PyTest 应该 运行 所有代码还是只测试被测试的函数?
Is PyTest supposed to run all code or just the function being tested?
我正在编写 python 脚本并使用 PyTest 对其进行测试。到目前为止,我已经为脚本中的一个函数编写了一个测试(一团糟所以我没有 post 它)。我的印象是 PyTest 只会 运行 正在测试的函数。但是,当 运行ning PyTest 脚本中的所有代码都被执行时。这是故意的吗?
我认为问题是您测试的 python 脚本包含根级别的指令。导入模块时,python 运行 是代码。
我已经建立了一个简单的例子。
unit_under_test.py
print("UNIT UNDER TEST")
def function_to_test():
print("This shall be tested")
return 42
def function_not_to_test():
print("This shall NOT be tested")
return "foobar"
print("END OF FUNCTION DECLARATIONS")
if __name__ == '__main__':
print("MAIN")
print(function_to_test())
print(function_not_to_test())
test_unit.py
import pytest
from unit_under_test import function_to_test
def test_function_to_test():
assert 42 == function_to_test()
当我现在运行 pytest时,它输出如下。
UNIT UNDER TEST
END OF FUNCTION DECLARATIONS
============================= test session starts ==============================
platform darwin -- Python 3.8.1, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: /Users/moritzschillinger/dev/python/test/foo/test_stuff
collected 1 item
test_stuff.py . [100%]
============================== 1 passed in 0.03s ===============================
看看python是如何执行unit_under_test.py
的代码的。它输出语句“UNIT UNDER TEST”和“END OF FUNCTION DECLARATIONS”。
如果您的文件中有说明 运行 您的逻辑,请将其移至 if __name__ == '__main__':
下的块中。此部分仅 运行,当 运行 将 python 文件设置为 __main__
时,意味着当您调用 python unit_under_test.py
时。您可以看到语句“MAIN”没有打印在 pytest 输出中。
我正在编写 python 脚本并使用 PyTest 对其进行测试。到目前为止,我已经为脚本中的一个函数编写了一个测试(一团糟所以我没有 post 它)。我的印象是 PyTest 只会 运行 正在测试的函数。但是,当 运行ning PyTest 脚本中的所有代码都被执行时。这是故意的吗?
我认为问题是您测试的 python 脚本包含根级别的指令。导入模块时,python 运行 是代码。
我已经建立了一个简单的例子。
unit_under_test.py
print("UNIT UNDER TEST")
def function_to_test():
print("This shall be tested")
return 42
def function_not_to_test():
print("This shall NOT be tested")
return "foobar"
print("END OF FUNCTION DECLARATIONS")
if __name__ == '__main__':
print("MAIN")
print(function_to_test())
print(function_not_to_test())
test_unit.py
import pytest
from unit_under_test import function_to_test
def test_function_to_test():
assert 42 == function_to_test()
当我现在运行 pytest时,它输出如下。
UNIT UNDER TEST
END OF FUNCTION DECLARATIONS
============================= test session starts ==============================
platform darwin -- Python 3.8.1, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: /Users/moritzschillinger/dev/python/test/foo/test_stuff
collected 1 item
test_stuff.py . [100%]
============================== 1 passed in 0.03s ===============================
看看python是如何执行unit_under_test.py
的代码的。它输出语句“UNIT UNDER TEST”和“END OF FUNCTION DECLARATIONS”。
如果您的文件中有说明 运行 您的逻辑,请将其移至 if __name__ == '__main__':
下的块中。此部分仅 运行,当 运行 将 python 文件设置为 __main__
时,意味着当您调用 python unit_under_test.py
时。您可以看到语句“MAIN”没有打印在 pytest 输出中。