Search code examples
djangodjango-rest-frameworkdjango-testing

API full path in unit tests


Is there any way to specify full path for url when i test APIs. Now i'm doing it in this way:

def test_product_types_retrieve(self):
    self.relative_path = '/api/api_product/'
    response = self.client.get(self.relative_path + 'product_types/')

I should add relative_path part to every single request, but i want to set it, for example in setUp function. Without self.relative_path i will get http://localhost:8000/product_types/ instead of http://localhost:8000/api/api_product/product_types/

My project structure is following, every api have its own urls.py with urlpatterns settings.

Project structure


Solution

  • You could do this, you then set up the relative path in the setUp and call the api from call_api can pass args and kwargs through that.

    Then if on a test you need a different relative_path you can just set it on that test and still call call_api.

    class ExampleTestCase(TestCase):
        def setUp(self):
            self.relative_path = '/api/api_product/'
    
        def call_api(self, endpoint):
            return self.client.get(self.relative_path + endpoint)
    
        def test_product_types_retrieve(self):
            response = self.call_api('product_types/')
    
        def test_requires_different_path(self):
            self.relative_path = '/api/api_product/v1/'
            response = self.call_api('product_types/')