Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to use stdin in a pytest test

Tags:

The PyTest documentation states that stdin is redirected to null as no-one will want to do interactive testing in a batch test context. This is true, but interactive is not the only use of stdin. I want to test code that uses stdin just as it would use any other file. I am happy with stdout and sterr being captured but how to actually have stdin connected to an io.StringIO object say in a PyTest conformant way?

like image 211
Russel Winder Avatar asked Aug 02 '16 14:08

Russel Winder


People also ask

How do I test a specific test pytest?

Running pytest We can run a specific test file by giving its name as an argument. A specific function can be run by providing its name after the :: characters. Markers can be used to group tests. A marked grouped of tests is then run with pytest -m .

How do I skip Testcases in pytest?

Skipping a test The simplest way to skip a test is to mark it with the skip decorator which may be passed an optional reason . It is also possible to skip imperatively during test execution or setup by calling the pytest. skip(reason) function.

Can you run Unittest with pytest?

pytest supports running Python unittest -based tests out of the box. It's meant for leveraging existing unittest -based test suites to use pytest as a test runner and also allow to incrementally adapt the test suite to take full advantage of pytest's features.


2 Answers

You can monkeypatch it:

def test_method(monkeypatch):     monkeypatch.setattr('sys.stdin', io.StringIO('my input'))     # test code 
like image 97
OrangeDog Avatar answered Oct 18 '22 12:10

OrangeDog


Maybe you could run your script as a subprocess? In Python 3.6:

import subprocess  def test_a_repl_session():     comlist = ['./executable_script.py']     script = b'input\nlines\n\n'     res = subprocess.run(comlist, input=script,             stdout=subprocess.PIPE, stderr=subprocess.PIPE)     assert res.returncode == 0     assert res.stdout     assert res.stderr == b'' 
like image 42
xealits Avatar answered Oct 18 '22 10:10

xealits