问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/50763003/pytest-main-capture-standard-output