如何将命令行参数从 pytest 传递给代码 [英] how to pass command line argument from pytest to code

查看:39
本文介绍了如何将命令行参数从 pytest 传递给代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将参数从 pytest 测试用例传递到正在测试的模块.例如,使用 Python 样板 中的 main.py,我可以从命令行为:

I am trying to pass arguments from a pytest testcase to a module being tested. For example, using the main.py from Python boilerplate, I can run it from the command line as:

$ python3 main.py
usage: main.py [-h] [-f] [-n NAME] [-v] [--version] arg
main.py: error: the following arguments are required: arg
$ python3 main.py xx
hello world
Namespace(arg='xx', flag=False, name=None, verbose=0)

现在我正在尝试对 pytest 做同样的事情,使用以下 test_sample.py

Now I am trying to do the same with pytest, with the following test_sample.py

(注意: main.py 需要命令行参数.但是这些参数需要在特定的测试中硬编码,它们不应该是 pytest 的命令行参数.pytest 测试用例只需要将这些值作为命令行参数发送到 main.main().)

(NOTE: the main.py requires command line arguments. But these arguments need to be hardcoded in a specific test, they should not be command line arguments to pytest. The pytest testcase only needs to send these values as command line arguments to main.main().)

import main
def test_case01():
    main.main()
    # I dont know how to pass 'xx' to main.py,
    # so for now I just have one test with no arguments

并按以下方式运行测试:

and running the test as:

pytest -vs test_sample.py

此操作失败并显示错误消息.我试图查看其他答案以获得解决方案,但无法使用它们.例如,42778124 建议创建一个单独的文件 run.py,这不是一个理想的做法.而 4835995740880259 似乎为 pytest 处理更多的命令行参数,而不是将命令行参数传递给主代码.

This fails with error messages. I tried to look at other answers for a solution but could not use them. For example, 42778124 suggests to create a separate file run.py which is not a desirable thing to do. And 48359957 and 40880259 seem to deal more with command line arguments for pytest, instead of passing command line arguments to the main code.

我不需要 pytest 来获取命令行参数,这些参数可以在特定测试中进行硬编码.但是这些参数需要作为参数传递给主代码.你能给我一个 test_sample.py,它用一些参数调用 main.main() 吗?

I dont need the pytest to take command line arguments, the arguments can be hardcoded inside a specific test. But these arguments need to be passed as arguments to the main code. Can you give me a test_sample.py, that calls main.main() with some arguments?

推荐答案

最好的做法是使用这种代码,而不是从 main 方法中读取参数.

A good practice might to have this kind of code, instead of reading arguments from main method.

# main.py
def main(arg1):
    return arg1

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='My awesome script')
    parser.add_argument('word', help='a word')
    args = parser.parse_args()
    main(args.word)

这样,你的 main 方法可以很容易地在 pytest 中测试

This way, your main method can easily be tested in pytest

import main
def test_case01():
    main.main(your_hardcoded_arg)

我不确定您是否可以调用 python 脚本进行测试,除非使用 os 模块,这可能不是一个好习惯

I am not sure you can call a python script to test except by using os module, which might be not a good practice

这篇关于如何将命令行参数从 pytest 传递给代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆