Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Avoid HTTP API calls while testing from django views

I'm writing the tests for django views, Some of the views are making the external HTTP requests. While running the tests i dont want to execute these HTTP requests. Since during tests , data is being used is dummy and these HTTP requests will not behave as expected.

What could be the possible options for this ?

like image 632
navyad Avatar asked May 01 '26 00:05

navyad


1 Answers

You could override settings in your tests and then check for that setting in your view. Here are the docs to override settings.

from django.conf import settings
if not settings.TEST_API:
    # api call here

Then your test would look something like this

from django.test import TestCase, override_settings

class LoginTestCase(TestCase):

    @override_settings(TEST_API=True)
    def test_api_func(self):
        # Do test here

Since it would be fairly messy to have those all over the place I would recommend creating a mixin that would look something like this.

class SensitiveAPIMixin(object):
    def api_request(self, url, *args, **kwargs):
        from django.conf import settings
        if not settings.TEST_API:
            request = api_call(url)
            # Do api request in here
        return request

Then, through the power of multiple inheritence, your views that you need to make a request to this api call you could do something similar to this.

class View(generic.ListView, SensitiveAPIMixin):
    def get(self, request, *args, **kwargs):
        data = self.api_request('http://example.com/api1')
like image 131
Jared Mackey Avatar answered May 03 '26 19:05

Jared Mackey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!