1

I have a test file which run some binary executable and check the output. The test looks like this:

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

I can run the test with $[python run_test.py app_path. But how can I do the same with pytest:

$pytest app_path
J_yang
  • 2,672
  • 8
  • 32
  • 61

1 Answers1

1

pytest and unittest runners are completely different, so you will have to add pytest-specific code for defining and reading the command line argument and assigning it to the MyTest class. Here is an example solution: in your project/test root directory, create a file named conftest.py with the following contents:

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

Now, when running e.g. pytest --executable=path/to/my/binary, path/to/my/binary will be set to MyTest.PATH.

hoefling
  • 59,418
  • 12
  • 147
  • 194