pytest-dev/pytest

Provide an implementation of UnitTest.assertCountEqual

software-opal opened this issue · 13 comments

Currently if I want to test that two lists contain the same elements, ignoring their order, I need to use a set(only on hashable types) or use a UnitTest subclass(which means I loose some functionality).

It would be good to provide some guidance on how to do within PyTest.

I'm thinking it would look something like this:

import pytest

def my_reverse(list):
  return reversed(list)

def test_reverse_keeps_items():
  my_list = ['a', {'key': 'value'}, object()]
  # I'm just spitballing the name; I don't know what would be a good name for it.
  assert my_list == pytest.unordered(reversed(my_list))
  # or
  pytest.assert_count_equal(my_list, my_reverse(my_list))

If this isn't a good idea it would be nice to add a note in the docs on how to do it so that people can easily discover it.

I don't think pytest should grow an assertion library, you can already get essentially this by using sets or counters (and with better assertion messages usually)

pytest should grow assertion helpers, something like the "unordered" or a "sorted" object would be helpfull in many ways

but this should be started outside of pytest and experimented wtith for a few years before bringing it into core

Closing this issue, as it's suitable to be demonstrated in a plugin before further discussion in Pytest.

Has anyone started working on a plugin for this?

im unaware, if anyone is please link

For reference: pytest-dev/pytest-django#709 (using Django's helpers).

Closing this issue, as it's suitable to be demonstrated in a plugin before further discussion in Pytest.

Is a plugin able to inject a function into the pytest namespace? I want to use it as pytest.unordered(), the same way as pytest.approx().

intentionally no longer

What hook the plugin should use then?
Should it be a pytest- plugin at all? It seems that a simple package exporting one function is enough.

@utapyngo well, it needs assertrepr hooks for explaining whats different/not different

@RonnyPfannschmidt, could you please review pytest-unordered?

@software-opal, will this work for you?

from pytest_unordered import unordered

def test_reverse_keeps_items():
    my_list = ['a', {'key': 'value'}, object()]
    assert my_list == unordered(list(reversed(my_list)))