|
| 1 | +from django.core.cache import cache |
| 2 | +from django.test import RequestFactory, TestCase, override_settings |
| 3 | + |
| 4 | +from germanium.tools import assert_raises |
| 5 | + |
| 6 | +from security.throttling.exception import ThrottlingException |
| 7 | +from security.throttling.validators import PerRequestCacheThrottlingValidator |
| 8 | + |
| 9 | + |
| 10 | +class PerRequestCacheThrottlingValidatorTestCase(TestCase): |
| 11 | + |
| 12 | + def setUp(self): |
| 13 | + cache.clear() |
| 14 | + self.factory = RequestFactory() |
| 15 | + |
| 16 | + def _make_request(self, path='/test/', method='GET', ip='127.0.0.1'): |
| 17 | + request = self.factory.generic(method, path) |
| 18 | + request.META['REMOTE_ADDR'] = ip |
| 19 | + return request |
| 20 | + |
| 21 | + @override_settings(SECURITY_THROTTLING_ENABLED=True) |
| 22 | + def test_validate_raises_throttling_exception_when_over_limit(self): |
| 23 | + validator = PerRequestCacheThrottlingValidator(60, 2) |
| 24 | + request = self._make_request() |
| 25 | + validator.validate(request) |
| 26 | + validator.validate(request) |
| 27 | + with assert_raises(ThrottlingException): |
| 28 | + validator.validate(request) |
| 29 | + |
| 30 | + @override_settings(SECURITY_THROTTLING_ENABLED=True) |
| 31 | + def test_different_paths_are_counted_independently(self): |
| 32 | + validator = PerRequestCacheThrottlingValidator(60, 2) |
| 33 | + request_a = self._make_request(path='/path-a/') |
| 34 | + request_b = self._make_request(path='/path-b/') |
| 35 | + validator.validate(request_a) |
| 36 | + validator.validate(request_a) |
| 37 | + validator.validate(request_b) |
| 38 | + validator.validate(request_b) |
| 39 | + with assert_raises(ThrottlingException): |
| 40 | + validator.validate(request_a) |
0 commit comments