How can I assert lists equality with pytest

See this:

Note:

You can simply use the assert statement for asserting test expectations. pytest’s Advanced assertion introspection will intelligently report intermediate values of the assert expression freeing you from the need to learn the many names of JUnit legacy methods.

And this:

Special comparisons are done for a number of cases:

  • comparing long strings: a context diff is shown
  • comparing long sequences: first failing indices
  • comparing dicts: different entries

And the reporting demo:

failure_demo.py:59: AssertionError
_______ TestSpecialisedExplanations.test_eq_list ________

self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>

    def test_eq_list(self):
>       assert [0, 1, 2] == [0, 1, 3]
E       assert [0, 1, 2] == [0, 1, 3]
E         At index 2 diff: 2 != 3
E         Use -v to get the full diff

See the assertion for lists equality with literal == over there? pytest has done the hard work for you.


You could do a list comprehension to check equality of all values. If you call all on the list comprehensions result, it will return True if all parameters are equal.

actual = ['bl', 'direction', 'day']
expected = ['bl', 'direction', 'day']

assert len(actual) == len(expected)
assert all([a == b for a, b in zip(actual, expected)])

print(all([a == b for a, b in zip(actual, expected)]))

>>> True

Before you write your assertion, answer the following questions:

  1. Is order important?
  2. Can there be duplicates?
  3. Can there be unhashable elements?

No, No, No: symmetric difference in sets

a = [1, 2, 3]
b = [3, 2, 1]
diff = set(a) ^ set(b)
assert not diff

It is handy to use this method on large lists, because diff will contain only difference between them, so AssertionError will be compact and readable.

Note set() will remove duplicates. It is better to check that as well:

assert len(a) == len(set(a))

Yes, Yes, Yes: compare lists

a = [1, 2, 3, {'a': 1}]
b = [1, 2, 3, {'a': 1}]
assert a == b