1

I have a method I am using to get all of the tests we have.

def get_test_names_from_file():

    get_test_names = pytest.main(['--collect-only', '-q'])
    print(type(get_test_names))

    return 'here is the methods return: ' + str(get_test_names)

When I call this method it returns an exist code here is the methods return: 0 and that's fine. What I can not figure out is how I get the resulting standard out into a format that I can use.

Here is the standard out when the method is called:

test_a.py::TestA::test_general_a
test_a.py::TestA::test_python_a
test_a.py::TestA::test_python_learning_a
test_b.py::TestB::test_b

How do I capture this output so that I can return it? I have done my best to read through the docs, and can't seem to figure out a way to do this.

Thank you for your time.

EDIT: I was able to get something working using subprocess, but i'd prefer to use pytest rather than mix and match:

def get_test_names_from_file():

    pytest_command_string = 'pytest --collect-only -q'
    pytest_command = subprocess.Popen(pytest_command_string.split(), shell=False, stdout=subprocess.PIPE)
    pytest_command_out = pytest_command.communicate()[0]

    print(type(pytest_command_out))
    return pytest_command_out
Lombax
  • 851
  • 4
  • 9
  • 25
  • 1
    Possible duplicate of [Can I redirect the stdout in python into some sort of string buffer?](https://stackoverflow.com/questions/1218933/can-i-redirect-the-stdout-in-python-into-some-sort-of-string-buffer) – hoefling Jun 08 '18 at 16:44

1 Answers1

2

You could use py.io for this.

something like:

capture = py.io.StdCapture()
pytest.main(['--collect-only', '-q'])
std, err = capture.reset()
print(std)

Would get you the standard output you're looking for.

apiguy
  • 5,282
  • 1
  • 23
  • 24
  • From that project's github page "NOTE: this library is in maintenance mode and should not be used in new code." – Jake Mar 25 '22 at 20:47