Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I like how tests are made in Python - you don't even need classes, just functions, and use a single assert keyword for everything. Also it's easy to parametrize them using decorators.


Parameterized tests in Junit are basically the same as decorators:

    @ParameterizedTest
    @ValueSource(strings = {"first", "second"})
    void fooGoesBar(String param) {
        ...
    }
Also, once you get used to assertj, you'll never want single-assert again. It's fantastically useful to know (for example) not just that two lists aren't equal, but specifically what elements differ.


> It's fantastically useful to know (for example) not just that two lists aren't equal, but specifically what elements differ.

Pytest shows the diff as well when using assert:

    >       assert y == x
    E       assert [1, 2, 3] == [1, 4, 3, 6]
    E         
    E          At index 1 diff: 2 != 4
    E         Right contains one more item: 6
    E         Use -v to get more diff


Great, what's the equivalent of this?

    assertThat(someCollection).map(Thing::getValue).containsExactlyInAnyOrder(3, 4, 5);


If the list contains numbers or strings, you can use

    assert sorted(x) == sorted(y)
If you want to add map, then you have to write

    assert list(sorted(i.getValue() for i in someCollection)) == [3, 4, 5]
If the list contains non-sortable values, but they are hashable and unique, you can use sets:

    assert set(x) == set(y)
If the values are not unique, but hashable, you can use a counter (like a set but with count for repeating values):

    assert Counter(x) == Counter(y)
(by the way I learned about this trick from a LLM)

And if the values are neither sortable, nor hashable, you'll have to write a helper function.

But still, pytest tests are less wordy and they don't require you to create a class.

This situation is familiar to me, I had to write such helper function when writing tests in PHP, for some reason it is not included in PHPUnit assertions.


Parameterized tests are a huge, huge win, yeah. I am a big fan of them and look for how to do them in every test framework I use. RSpec was the weirdest for me; but NUnit and JUnit have been quite easy, and I'm not surprised at all they're easy in Python too (admittedly, I don't remember if I ever wrote them in that language).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: