通过pytest在python中传递命令行参数

时间:2017-03-14 05:08:21

标签: python

我可以在运行

时传递命令行参数
Gson gson = new Gson();
String jsonInString = "{'name' : 'helloWorld'}";
YourClass yourClass= gson.fromJson(jsonInString, YourClass.class);

但是当我试图传递用于运行pytest的命令行参数时,它失败并给出如下错误。能告诉你吗。

python <filename>.py arg1

编辑:

例如我想以这种方式使用它,假设我已经传递了一个参数并通过sys.argv读取它:

pytest <filename>.py arg1
ERROR: file not found: arg1

2 个答案:

答案 0 :(得分:3)

您的<filename>.py命令正在尝试在两个模块arg1# run.py import pytest import sys def main(): # extract your arg here print('Extracted arg is ==> %s' % sys.argv[2]) pytest.main([sys.argv[1]]) if __name__ == '__main__': main() 上调用pytest,但是没有模块arg1。

如果你想在运行pytest之前传递一些参数,那么在提取变量后从python脚本运行pytest。

正如其他人所建议的那样,您可能希望以其他方式参数化测试,请尝试:Parameterized pytest

python run.py filename.py arg1

使用sudo -H pip3 install python-socketio

调用此方法

答案 1 :(得分:0)

这是我通过阅读parameterized pytest docs并进行一段时间的黑客学习而准备的方法...我不知道它的整体稳定性或良好性,因为我刚刚开始使用它。 但是,我确实检查了HTML Coverage生成是否可以使用此方法。

# this is just so we can pass --server and --port from the pytest command-line
def pytest_addoption(parser):
    ''' attaches optional cmd-line args to the pytest machinery '''
    parser.addoption("--server", action="append", default=[], help="real server hostname/IP")
    parser.addoption("--port", action="append", default=[], help="real server port number")
def pytest_generate_tests(metafunc):
    ''' just to attach the cmd-line args to a test-class that needs them '''
    server_from_cmd_line = metafunc.config.getoption("server")
    port_from_cmd_line = metafunc.config.getoption("port")
    print('command line passed for --server ({})'.format(server_from_cmd_line))
    print('command line passed for --port ({})'.format(port_from_cmd_line))
    # check if this function is in a test-class that needs the cmd-line args
    if server_from_cmd_line and port_from_cmd_line and hasattr(metafunc.cls, 'real_server'):
        # now set the cmd-line args to the test class
        metafunc.cls.real_server = server_from_cmd_line[0]
        metafunc.cls.real_port = int(port_from_cmd_line[0])


class TestServerCode(object):
    ''' test-class that might benefit from optional cmd-line args '''
    real_server=None
    real_port = None

    def test_valid_string(self):
        assert self.real_server!=None
        assert self.real_port!=None

    def test_other(self):
        from mypackage import my_server_code
        if self.real_server !=  None:
            assert "couldn\'t find host" not in my_server_code.version(self.real_server, self.real_port)
  • 然后使用以下命令运行(例如,具有HTML覆盖):

    • pytest tests\test_junk.py --server="abc" --port=123 --cov-report html --cov=mypackage