我正在尝试测试 python 脚本,当我将脚本导入到测试套件中时,它会调用该脚本。在下面的示例中,我导入 list3rdparty,一旦运行测试,它就会立即调用 list3rdparty。我不希望这种情况发生。我希望测试仅调用每个测试用例中的函数。
list3rdpartytest.pyimport unittest
from list3rdparty import * ## this is where the script is being imported
class TestOutputMethods(unittest.TestCase):
def setUp(self):
pass
def test_no_args_returns_help(self):
args = []
self.assertEqual(get_third_party(args), help())
##get_third_party is a function in list3rdparty##
if __name__ == '__main__':
unittest.main(warnings = False)
list3rdparty.py
def get_third_party(args_array):
##does a bunch of stuff
def get_args():
get_third_party(sys.argv)
get_args()
最佳答案
您可能有模块级别的代码,这些代码将在导入时执行。例如,如果您有一个包含以下内容的文件,它将在第一次导入时打印该字符串。
import something
from whatever import another
print 'ding'
为了避免这种情况,请将代码放在一个 block 中,如下所示:
if __name__ == '__main__':
# your module-level code here
get_args()
这只会运行直接从命令行调用的代码。
关于python - 为什么我的 python unittest 脚本在导入时调用我的脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39781233/