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

查看:69
本文介绍了如何将命令行参数从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)

现在,我尝试使用以下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,这不是一件好事.而且 48359957 40880259 似乎处理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)

这样,您的主要方法可以轻松地在pytest中进行测试

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

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

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

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天全站免登陆