Python 使用pytest和unittest.TestCase时如何给出sys.argv

Python 使用pytest和unittest.TestCase时如何给出sys.argv,python,pytest,python-unittest,Python,Pytest,Python Unittest,我有一个测试文件,它运行一些二进制可执行文件并检查输出。测试如下所示: #! /usr/bin/env python from subprocess import Popen, PIPE import unittest import sys class MyTest(unittest.TestCase): PATH = './app' def setUp(self): pass def tearDown(self): pass

我有一个测试文件,它运行一些二进制可执行文件并检查输出。测试如下所示:

#! /usr/bin/env python
from subprocess import Popen, PIPE
import unittest
import sys

class MyTest(unittest.TestCase):
    PATH = './app'

    def setUp(self):
        pass

    def tearDown(self):
        pass

    @staticmethod
    def run_subprocess(cmd):
        process = Popen(cmd, stdout=PIPE, stderr=PIPE)
        stdout, stderr = process.communicate()
        return stdout.decode('ascii'), stderr

    def test_case1(self):
        stdout, stderr = self.run_subprocess([self.PATH, some_cmd])

    def test_case2(self):
        stdout, stderr = self.run_subprocess([self.PATH, some_other_cmd])



if __name__ =="__main__":
    if len(sys.argv) < 2:
        raise AttributeError("Usage: python run_test.py app_path")
    TestBingbangboom.PATH = sys.argv[1]
    unittest.main(argv=['first-arg-is-ignored'], exit=False)

pytest
unittest
运行程序完全不同,因此必须添加
pytest
特定的代码来定义和读取命令行参数,并将其分配给
MyTest
类。下面是一个示例解决方案:在项目/测试根目录中,创建一个名为
conftest.py
的文件,其内容如下:

import pytest


def pytest_addoption(parser):
    parser.addoption("--executable", action="store", default="./app")


@pytest.fixture(scope="class", autouse=True)
def pass_executable(request):
    try:
        request.cls.PATH = request.config.getoption("--executable")
    except AttributeError:
        pass
现在,当运行例如
pytest--executable=path/to/my/binary
时,
path/to/my/binary
将设置为
MyTest.path

import pytest


def pytest_addoption(parser):
    parser.addoption("--executable", action="store", default="./app")


@pytest.fixture(scope="class", autouse=True)
def pass_executable(request):
    try:
        request.cls.PATH = request.config.getoption("--executable")
    except AttributeError:
        pass