What is the proper way of testing throttling in DRF?
<p>What is the proper way of testing throttling in DRF? I coulnd't find out any answer to this question on the net. I want to have separate tests for each endpoint since each one has custom requests limits (ScopedRateThrottle).</p>

<p>The important thing is that it can't affect other tests - they have to somehow run without throttling and limiting.</p>

<p>Like people already mentioned, this doesn't exactly fall within the scope of unit tests, but still, how about simply doing something like this:</p>

<pre><code>from django.core.urlresolvers import reverse
from django.test import override_settings
from rest_framework.test import APITestCase, APIClient


class ThrottleApiTests(APITestCase):
    # make sure to override your settings for testing
    TESTING_THRESHOLD = '5/min'
    # THROTTLE_THRESHOLD is the variable that you set for DRF DEFAULT_THROTTLE_RATES
    @override_settings(THROTTLE_THRESHOLD=TESTING_THRESHOLD)
    def test_check_health(self):
        client = APIClient()
        # some end point you want to test (in this case it's a public enpoint that doesn't require authentication
        _url = reverse('check-health')
        # this is probably set in settings in you case
        for i in range(0, self.TESTING_THRESHOLD):
            client.get(_url)

        # this call should err
        response = client.get(_url)
        # 429 - too many requests
        self.assertEqual(response.status_code, 429)
</code></pre>

<p>Also, regarding your concerns of side-effects, as long as you do user creation in <code>setUp</code> or <code>setUpTestData</code>, tests will be isolated (as they should), so no need to worry about 'dirty' data or scope in that sense.</p>

<p>Regarding <a href="https://docs.djangoproject.com/en/1.10/topics/testing/overview/#other-test-conditions" rel="nofollow">cache clearing between tests</a>, I would just add <code>cache.clear()</code> in <code>tearDown</code> or try and clear the <a href="http://www.django-rest-framework.org/api-guide/throttling/#setting-up-the-cache" rel="nofollow">specific key defined for throttling</a>.</p>

python django testing django-rest-framework throttling