本文介绍了如何设置 sys.argv 以便我可以对其进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置

sys.argv

所以我可以单元测试通过不同的组合.以下不起作用:

so I can unit test passing in different combinations. The following doesn't work:

#!/usr/bin/env python
import argparse, sys
def test_parse_args():
    global sys.argv
    sys.argv = ["prog", "-f", "/home/fenton/project/setup.py"]
    setup = get_setup_file()
    assert setup == "/home/fenton/project/setup.py"
def get_setup_file():
    parser = argparse.ArgumentParser()
    parser.add_argument('-f')
    args = parser.parse_args()
    return args.file
if __name__ == '__main__':
    test_parse_args()

然后运行文件:

pscripts % ./test.py
  File "./test.py", line 4
    global sys.argv
              ^
SyntaxError: invalid syntax
pscripts %

推荐答案

在运行时更改 sys.argv 是一种非常脆弱的测试方式.你应该使用 mockpatch 功能,可用作上下文管理器来替换一个对象(或属性、方法、函数等).) 与另一个,在给定的代码块内.

Changing sys.argv at runtime is a pretty fragile way of testing. You should use mock's patch functionality, which can be used as a context manager to substitute one object (or attribute, method, function, etc.) with another, within a given block of code.

以下示例使用 patch()sys.argv 有效地替换"为指定的返回值 (testargs).>

The following example uses patch() to effectively "replace" sys.argv with the specified return value (testargs).

try:
    # python 3.4+ should use builtin unittest.mock not mock package
    from unittest.mock import patch
except ImportError:
    from mock import patch

def test_parse_args():
    testargs = ["prog", "-f", "/home/fenton/project/setup.py"]
    with patch.object(sys, 'argv', testargs):
        setup = get_setup_file()
        assert setup == "/home/fenton/project/setup.py"

这篇关于如何设置 sys.argv 以便我可以对其进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:03
查看更多