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

标签 python unit-testing python-unittest

我正在尝试测试 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'

为了避免这种情况,请将代码放在一个 block 中,如下所示:

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

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

关于python - 为什么我的 python unittest 脚本在导入时调用我的脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39781233/

相关文章:

unit-testing - 使用哪个 Scala 框架来测试 REST 服务?

没有 main 的 Python unittest 模块命令行参数

python - 有没有办法在 PySide 中设置 QtabWidget 上的选项卡按钮的样式?

python - 使用 python 将高斯模糊应用于图像

python - 我如何将点击工具与条形图 -bokeh 一起使用

unit-testing - 使用 Mocha 和 Enzyme 测试使用 React CSS 模块的 React 组件

python - 合并 json 中的重复键

java - 与 Maven 中的 Java 测试共享测试文件夹中的 Scala 类

python - unittest.TestCase setUpClass 覆盖和继承

python - PyUnit - 如何为单个单元测试添加超时