python - 为主要功能测试设置命令行参数

标签 python pytest argparse

我在 python 中有一个 main() 函数,它可以获取命令行参数。
有没有办法为这个函数编写 pytest 测试并在代码中定义参数?

例如

def main():
    # argparse code
    args, other = arg_parser.parse_known_args()
    return args.first_arg


def test_main():
    res = main() # call with first_arg = "abc"
    assert(res == "abc")

最佳答案

添加到以前的答案,而不是修改 sys.argv使用可以掩盖和保护底层对象的上下文管理器更安全。一个例子是

with unittest.mock.patch('sys.argv', ['program_name', '--option1', 'inputFile']):
    main()
这仅适用于 python3。对于python2 Mock图书馆可以解决问题。
我在不同的 stackoverflow 帖子 here 上找到了这个解决方案.

关于python - 为主要功能测试设置命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43390053/

相关文章:

python - Django Tastypie : filter results for a GET call by looping over model. 对象.all()

Python argparse 以 -- 作为值

python - 如何将标题添加到flask test_request_context?

python - 不能有多个子解析器参数

python - Flutter:请求的资源上不存在 'Access-Control-Allow-Origin' header

python - django-autocomplete-light 简单用法

python-3.x - python : Mocking a local gitpython repository

python - 防止 setup.py test/pytest 安装额外的依赖项

Python。参数解析。删除不需要的参数

python - 添加既改变行为又存储参数的选项