User Tools

Site Tools


pytest_notes

This is an old revision of the document!


test a function that writes output to a file

$ cat write_file.py
def write_to_file(fname):
    with open(fname, 'w') as FileObj:
        FileObj.write('Hello\n')

def test_write_to_file(tmpdir):
    file = tmpdir.join('output.txt')
    write_to_file(file)
    contents_got = file.read()
    contents_expected = 'Hello\n'
    assert contents_got == contents_expected
$ python -m pytest write_file.py

Ref:

test a script that prints to stdout

tags | python test case for print

snippet 1:

def test_foo(capsys):
    ...
    captured = capsys.readouterr()
    ...
    assert captured.out == expected_output

snippet 2:

out, error = capsys.readouterr()

Ref:-

run pytest on the current file from the current file

Links related to parameterization:

pytest_notes.1683300243.txt.gz · Last modified: 2023/05/05 15:24 by admin