8

Does pytest (2.8.3) have an equivalent of self.subTest() (as found in Python 3's unittest)?

Here's a simplified version of the code I'm trying to convert:

class MyUnittestTest(TestCase):
    def test_permutations(self):
        on_off = True, False
        for prefix, params, suffix in product(on_off, on_off, on_off):

            expected_prefix = 'something' if prefix else ''
            expected_params = ('something',) if params else ()
            expected_suffix = b'something' if suffix else b''

            with self.subTest(prefix=prefix, params=params, suffix=suffix):
                result = do_magic(prefix=prefix, params=params, suffix=suffix)

                self.assertEqual(result.prefix, expected_prefix)
                self.assertEqual(result.params, expected_params)
                self.assertEqual(result.suffix, expected_suffix)

At the moment, all I have is defining one test per permutation. There must be a better way than this:

class MyPytestTest:
    def test_on_on_on(self):
        expected_prefix = ...

        result = do_magic(...)

        assert ...

    def test_on_on_off(self):
        ...
meshy
  • 7,806
  • 8
  • 48
  • 69
  • 1
    Use `pytest.mark.parametrize` - see e.g. http://stackoverflow.com/q/32899/3001761 – jonrsharpe Nov 24 '15 at 22:14
  • 2
    That's fantastic, thank you. It's a shame that this perfect mechanism is buried under so many duff answers in that other question that you linked to. – meshy Nov 24 '15 at 22:23
  • They aren't duff, they just apply to other test frameworks (`unittest`, `nose`, etc.). Searching in the page for the appropriate framework finds the answer you need. – jonrsharpe Nov 24 '15 at 22:24
  • 1
    You're quite right, that was too harsh. They're answering a different question, really. Where this question applies to what is best for `pytest`, the scope of that question is a lot broader. Can you think of a way that I could rephrase this question to make the distinction clearer? – meshy Nov 24 '15 at 22:28
  • Why do you need to rephrase the question? You now have the answer. – jonrsharpe Nov 24 '15 at 22:31
  • Because it has been marked as a duplicate, and I am thus unable to add an answer. – meshy Nov 24 '15 at 22:33
  • Yes, because the answer was already there, on the dupe. I don't understand what the problem is. – jonrsharpe Nov 24 '15 at 22:35
  • 11
    Just hit this myself - yes, great, there's an answer to this already provided to that other question, but the other question is different, it's more generic, and it's certainly true that the _accepted_ answer for that wouldn't work here - for the sake of clarity, good UX, and general ease of use, I'm pro re-opening this – Kristian Glass Aug 07 '16 at 15:20
  • Also, there is now a good answer, https://github.com/pytest-dev/pytest-subtests . How do we get this re-opened? – meshy Dec 08 '21 at 14:20

0 Answers0