How to add stdin interaction with pytest

2019-07-27 19:55发布

问题:

I am writing integration tests for a system where I can automate most of the test via web service calls, but due to legacy-ness that I cannot change, I need a few steps to be done by manual testers.

I wanted to use pytest and create a fixture that essentially pauses test execution and prompts the console for input (e.g. "Do XYZ in system; type 'done' when done") and continues with the remainder of the test.

I admittedly haven't done a ton of hacking on this yet, but I see from pytest docs that:

... stdin is set to a “null” object which will fail on attempts to read from it because it is rarely desired to wait for interactive input when running automated tests.

Except, in my case, I really do want to wait, and other than this, my stuff looks to be a great use case for pytest.

Still searching the interwebs for hints, but if someone has gotten past this roadblock already I'd love to know.

回答1:

As of version 3, you can temporarily disable the capture:

def test_input(capsys):
    with capsys.disabled():
        input("hit enter to continue: ")
    print("this line is invisible as normal")

gives

(py36) dsm@notebook:~/coding$ py.test -v stdin.py 
========================================== test session starts ===========================================
platform linux -- Python 3.6.0, pytest-3.0.7, py-1.4.32, pluggy-0.4.0 -- /home/dsm/sys/miniconda3/envs/py36/bin/python
cachedir: .cache
rootdir: /home/dsm/coding, inifile:
plugins: cov-2.3.1
collected 1 items 

stdin.py::test_input hit enter to continue: [here I hit enter]
PASSED

======================================= 1 passed in 23.11 seconds ========================================


回答2:

I also found How to make pytest wait for (manual) user action?

, after additional searching.

Not sure if I should now dupe this question, as the answer here was even cleaner for me.