mardi 28 avril 2015

How do I prevent Django from running unit tests on parent class when subclassing TestCase?

Background: I am working on a web scraper to track prices at online stores. It uses Django. I have a module for each store, with functions like get_price() and get_product_name() written for each one, so that the modules can be used interchangeably by the main scraper module. I have store_a.py, store_b.py, store_c.py, et cetera, each with these functions defined.

In order to prevent duplication of code, I've made StoreTestCase, which inherits from TestCase. For each store, I have a subclass of StoreTestCase, like StoreATestCase and StoreBTestCase.

When I manually test the StoreATestCase class, the test runner does what I want. It uses the data in the child class self.data for its tests, and doesn't attempt to set up and test the parent class on its own:

python manage.py test myproject.tests.test_store_a.StoreATest

However, when I manually test against the module, like:

python manage.py test myproject.tests.test_store_a

It first runs the tests for the child class and succeeds, but then it runs them for the parent class and returns the following error:

    for page in self.data:
TypeError: 'NoneType' object is not iterable

store_test.py (parent class)

from django.test import TestCase

class StoreTestCase(TestCase):

    def setUp(self):
        '''This should never execute but it does when I test test_store_a'''
        self.data = None
    def test_get_price(self):
        for page in self.data:
            self.assertEqual(store_a.get_price(page['url']), page['expected_price'])

test_store_a.py (child class)

import store_a
from store_test import StoreTestCase

class StoreATestCase(StoreTestCase):

    def setUp(self):
        self.data = [{'url': 'http://www.foo.com/bar', 'expected_price': 7.99},
                     {'url': 'http://www.foo.com/baz', 'expected_price': 12.67}]

How do I ensure the Django test runner only tests the child class, and not the parent class?

Aucun commentaire:

Enregistrer un commentaire