为什么我的 python unittest 脚本在导入时调用我的脚本?

Why is my python unittest script calling my script when I am importing it?

我正在尝试测试 python 脚本,当我将该脚本导入我的测试套件时,它会调用该脚本。在下面的示例中,我导入了 list3rdparty,一旦我 运行 测试它立即调用 list3rdparty。我不希望这种情况发生。我希望测试只调用每个测试用例中的函数。

list3rdpartytest.py
import 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'

为避免这种情况,将代码放在这样的块中:

if __name__ == '__main__':
    # your module-level code here
    get_args()

这只会 运行 如果直接从命令行调用代码。