Skip to content

Commit b4a9a1b

Browse files
arthur-github-usertomchristie
authored andcommitted
Throttle tests (encode#4807)
1 parent 8fcb8d6 commit b4a9a1b

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

tests/test_throttling.py

+38-2
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,16 @@
77
from django.contrib.auth.models import User
88
from django.core.cache import cache
99
from django.core.exceptions import ImproperlyConfigured
10+
from django.http import HttpRequest
1011
from django.test import TestCase
1112

13+
from rest_framework.request import Request
1214
from rest_framework.response import Response
1315
from rest_framework.settings import api_settings
14-
from rest_framework.test import APIRequestFactory
16+
from rest_framework.test import APIRequestFactory, force_authenticate
1517
from rest_framework.throttling import (
16-
BaseThrottle, ScopedRateThrottle, SimpleRateThrottle, UserRateThrottle
18+
AnonRateThrottle, BaseThrottle, ScopedRateThrottle, SimpleRateThrottle,
19+
UserRateThrottle
1720
)
1821
from rest_framework.views import APIView
1922

@@ -414,3 +417,36 @@ def test_wait_returns_none_if_there_are_no_available_requests(self):
414417
throttle.now = throttle.timer()
415418
throttle.history = [throttle.timer() for _ in range(3)]
416419
assert throttle.wait() is None
420+
421+
422+
class AnonRateThrottleTests(TestCase):
423+
424+
def setUp(self):
425+
self.throttle = AnonRateThrottle()
426+
427+
def test_authenticated_user_not_affected(self):
428+
request = Request(HttpRequest())
429+
user = User.objects.create(username='test')
430+
force_authenticate(request, user)
431+
request.user = user
432+
assert self.throttle.get_cache_key(request, view={}) is None
433+
434+
def test_get_cache_key_returns_correct_value(self):
435+
request = Request(HttpRequest())
436+
cache_key = self.throttle.get_cache_key(request, view={})
437+
assert cache_key == 'throttle_anon_None'
438+
439+
440+
class UserRateThrottleTests(TestCase):
441+
442+
def setUp(self):
443+
self.throttle = UserRateThrottle()
444+
445+
def test_get_cache_key_returns_correct_key_if_user_is_authenticated(self):
446+
request = Request(HttpRequest())
447+
user = User.objects.create(username='test')
448+
force_authenticate(request, user)
449+
request.user = user
450+
451+
cache_key = self.throttle.get_cache_key(request, view={})
452+
assert cache_key == 'throttle_user_%s' % user.pk

0 commit comments

Comments
 (0)