jeudi 23 juillet 2015

Reusing test logic with different variables?

I have a few test classes that test for access to a specific API endpoint depending on the user signed in.

I would like to use these classes to test multiple API endpoints. The logic for the tests would basically stay the same, the only thing changing in each test file is a factory class for generating data and the API endpoint url.

My initial solution was to abstract the logic into its own class, and have each subclass set the url endpoint and the factory class. Something like this:

# base_tests.py
class BaseAPITest:
    url = None
    factory_class = None

    ...logic...

# test_subclass.py
class SubclassAPITest(BaseAPITest):
    url = 'my_API_url'
    factory_class = MyFactoryClass

This works great, but I want to abstract it one more step. The base tests have about 10 different test classes, and in order to use them I have to subclass each of them in my subclass test file. Is it possible to put these 10 base tests into one class, set the variables on that container class, and then have each individual test use the variables from that container class? Then, all I would have to do is subclass that one class in order to test all 10. Something like this:

# base_tests.py
class ContainerForBaseAPITests:
    url = None
    factory_class = None

    class BaseAPITestOne:
        def get_url():
            return ContainerForBaseAPITests.url

        def get_factory_class():
            return ContainerForBaseAPITests.factory_class

        ...logic...

    class BaseAPITestTwo:
        def get_url():
            return ContainerForBaseAPITests.url

        def get_factory_class():
            return ContainerForBaseAPITests.factory_class

        ...logic...

# test_subclass.py
class SubclassAPITest(ContainerForBaseAPITests):
    url = my_url
    factory_class = MyFactoryClass

    # With just this one class, all of the BaseAPITests will run using the above variables

Aucun commentaire:

Enregistrer un commentaire