1

I'm working on building a test suite in Python using unittest for a small project and I'm building a bunch of tests to use different switches. The code for the tests is very reusable, and it would be a waste to keep copying the test over and modifying a single switch, the way I'm doing it below:

def get_some_data():
    return "randomtest"

def test1(self):
    config = {a:1, b:2, c:3, d:get_some_data()}
    run_some_command(config)

def test2(self):
    config = {a:4, b:5, c:3, d:get_some_data()}
    run_some_command(config)
...

Is there a way for me to read a config file that contains all these configurations and run each configuration as an individual test? I know that if I have a single test read the config and run each config, any one of the configs failing will mean the test failing as a whole. I'm trying to avoid that.

The idea is to have the config file look something like:

[
{a:1,b:2,c:3,d:"randomtest"},
{a:4,b:5,c:3,d:"randomtest"},
...
]

I'm also open to reasonable suggestions on what alternatives I can explore over unittest

vp199090
  • 33
  • 4

1 Answers1

0

With pytest you can parametrize tests using the parametrize decorator, so you could do the following:

test_data = [
    {'a': 1, 'b': 2, 'c': 3, 'd': 'randomtest'},
    {'a': 4, 'b': 5, 'c': 3, 'd': 'randomtest'},
]

@pytest.mark.parametrize('config', test_data)
def test(config):
    ...

With unittest you can use subTest:

def test(self):
    for config in test_data:
        with self.subTest(config=config):
            ...  # do the actual test with `config` here
a_guest
  • 34,165
  • 12
  • 64
  • 118
  • The `subTest` method seemed to do a lot of what I need without having to refactor the code for pytest. Unfortunately, I lose all benefits of the `setUp()` and `tearDown()` methods with this. Is there a way to force-invoke the methods for each subtest? – vp199090 Mar 24 '20 at 19:53
  • 1
    @vp199090 - you may also check [this question](https://stackoverflow.com/questions/32899/how-do-you-generate-dynamic-parameterized-unit-tests-in-python) which shows some other possibilities in the answers. – MrBean Bremen Mar 24 '20 at 20:16
  • If you want to use `setUp` and `tearDown` methods you need a separate test function for each case. This can be done by adding test functions dynamically based on the test data. I'll link the other question, if that solves your problem you can mark as duplicate. – a_guest Mar 24 '20 at 20:23