User Tools

Site Tools



test a function that writes output to a file

$ cat
def write_to_file(fname):
    with open(fname, 'w') as FileObj:

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


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()


run pytest on the current file from the current file

assert actual expected template

template 1

assert Actual == Expected,\
    'Expected = {}, Actual = {}'.format(Expected, Actual)

template 2

from pandas.util.testing import assert_frame_equal
assert_frame_equal(df_actual, df_expected)

template 3

import pytest
@pytest.mark.parametrize('input, expected_output', [
    ('foo', bar),
    ('foo2', bar2),
def test_fancy_func(input, expected_output):
    got = fancy_func(input)
    assert got == expected_output, 'Expected = {}, got = {}'.format(expected_output, got)

Links related to parameterization:

books on pytest

who wrote pytest

pytest_notes.txt · Last modified: 2023/12/28 01:31 by raju