max
max

Reputation: 10464

Python unittest loading test data on the fly

I'm trying to load test data base on the application name from a configuration file. I'm using ConfigParser which is a nosetest plug in. Here is my code. I just don't know how to pass the app name while loading the tests on the fly. I tried the constructor, but could not figure out a way to pass parameters to the loadTestsFromTestCase method. Any ideas?

import unittest

class TestMyApp(unittest.TestCase):
    def test1(self):
        print "test1: %s" % self.app
    def test2(self):
        print "test2: %s" % self.app

if __name__ == '__main__':
    # here specify the app name
    suite = unittest.TestLoader().loadTestsFromTestCase(TestMyApp)
    # here specify the other app name
    suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestMyApp))
    unittest.TextTestRunner(verbosity=2).run(suite)

Upvotes: 1

Views: 314

Answers (1)

Sergei Voronezhskii
Sergei Voronezhskii

Reputation: 2372

You are need a test parametrization! It is easy to done with pytest. Look at this code example:

import pytest

class AppImpl:
    def __init__(self, app_name):
        self.name = app_name

    def get_name(self):
        return self.name

@pytest.fixture(params=['App1', 'App2'])
def app(request):
    return AppImpl(request.param)

def test_1(app):
    assert app.get_name()

def test_2(app):
    assert 'App' in app.get_name()

if __name__ == '__main__':
    pytest.main(args=[__file__, '-v'])

By using class implementation of you logic AppImpl, you can create a fixture app, which can be parametrized by specific arg params=['App1', 'App2']. Then in your tests test_1 and test_2, use fixture name app in funcargs. This possibility provides more modularity and readability tests.

Upvotes: 1

Related Questions