Django coverage doesn't cover APITestCase tests

Viewed 259

I have a relatively large Django + DRF project with over 400 tests, but I fail to get coverage metrics of over 40%.

Here are the results after running tests.

From my understanding, there could be a few sources of issues here:

(1) The directory structure of our application is weird

We've tinkered a bit with our directory structure, here is what it looks like today:

core_app
 - apis
  - businessapi
   - models
   - migrations
   - serializers
   - views
   - tests
    - business_tests.py
   - admin.py
   - urls.py
   - apps.py
   - __init__.py
  - userapi
  - transactionapi
  - ...
 - settings
  - production.py
 - celery_apps
  - ...
 - ...

and here is what our business_tess.py file looks like:

class TestBusiness(APITestCase):
    def setUp(self):
        self.businessA = BusinessFactory(...)
        self.businessB = BusinessFactory(...)

        self.primary_adminA = ProfileFactory(...)
        self.primary_adminB = ProfileFactory(...)

        # Create 10 spenders
        self.spendersA = ProfileFactory.create_batch(...)
        self.spendersB = ProfileFactory.create_batch(...)

        # Create 5 admins
        self.adminsA = ProfileFactory.create_batch(...)
        self.adminsB = ProfileFactory.create_batch(...)

        # Authorize
        self.primary_admin_client = APIClient()
        self.primary_admin_client.credentials(Accept="application/json")
        self.primary_admin_client.force_authenticate(self.primary_adminA)
        
        ...


    def test_business_permissions(self):
        expected_response = {...}
        sorted_expected = OrderedDict(sorted(expected_response.items()))

        # Try to access as primaryadmin
        _, client = authenticate_user(self.primary_adminA.id)
        response = client.get("url_to_test")
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json(), sorted_expected)

(2) Coverage doesn't pick up tests that are accessed through API calls

I personally don't think this is super likely because there are examples of tests like this one https://dev.to/lucasmiguelmac/pytest-with-django-rest-framework-from-zero-to-hero-8c4 Where api tests clearly work just fine.

So to conclude, when I try to view a report for my coverage runs, it fails miserably and never counts the views, models and serializers that actually run for sure, I know it for a fact!!!

1 Answers

You must create an __init__.py in your tests folder to Django see that as a module. Then by running python manage.py test Django runs these tests.

Related