[TIP] Can output of failed py.test instances be configured?

Ronny Pfannschmidt Ronny.Pfannschmidt at gmx.de
Fri Aug 10 01:56:25 PDT 2012


On 08/10/2012 09:32 AM, Thijs Engels wrote:
> Dear all,
>
> Due to some legacy setups I am facing a series of tests using py.test,
> but with multiple (read: many) assert statements within a single test
> function. All of this works as expected, but I was wondering whether I
> could configure the output for failing test cases. By default py.test
> (rightfully) shows the whole test function up until the failing assert
> statement. Is it possible to merely show the failing assert statement?
>
> To clarify my question; the my alteration to the example in py.test
> documentation
> (http://pytest.org/latest/getting-started.html#our-first-test-run)
>
> # content of test_sample.py
> def func(x):
>      return x + 1
>
> def test_answer():
>      assert func(1) == 2
>      assert func(2) == 3
>      assert func(3) == 4
>      assert func(4) == 5
>      assert func(5) == 6
>      assert func(6) == 99
>      assert func(7) == 8
>      assert func(8) == 9
>
> Running this produces this output:
>
> [...]
>      def test_answer():
>          assert func(1) == 2
>          assert func(2) == 3
>          assert func(3) == 4
>          assert func(4) == 5
>          assert func(5) == 6
>>        assert func(6) == 99
> E       assert 7 == 99
> E        +  where 7 = func(6)
> [...]
>
> Although I fully realize that multiple assert statements (I am talking
> close to 100) is bad practice, I wonder whether I *could* configure the
> output.
>
> [...]
>      def test_answer():
>>        assert func(6) == 99
> E       assert 7 == 99
> E        +  where 7 = func(6)
> [...]
>

given the example, it seems most useful to use a slightly different approach

@pytest.mark.parametrize(('given', 'expected'), [
   (1,2),
   (2,3),
   (3,4),
   (4,5),
   (6,99),])
def test_answer(given, expected):
   assert func(given) == expected

if that doesn't meet your needs, you can use --tb=short/native for 
different traceback styles

-- Ronny

> Thanks in advance,
>
> Thijs
>



More information about the testing-in-python mailing list