User Tools

Site Tools


pytest_notes

tasks

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

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