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

问题描述 投票:0回答:1

我有一个运行一些二进制可执行文件并检查输出的测试文件。测试看起来像这样:

#! /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)

我可以使用$[python run_test.py app_path进行测试。但是我该如何使用pytest做同样的事情:

$pytest app_path
python pytest python-unittest
1个回答
0
投票

pytestunittest运行程序完全不同,因此您将必须添加pytest特定的代码,以定义和读取命令行参数并将其分配给MyTest类。这是一个示例解决方案:在您的project / test根目录中,创建一个名为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/binarypath/to/my/binary将设置为MyTest.PATH

© www.soinside.com 2019 - 2024. All rights reserved.