|
| 1 | +# |
| 2 | +# Copyright (c) nexB Inc. and others. All rights reserved. |
| 3 | +# VulnerableCode is a trademark of nexB Inc. |
| 4 | +# SPDX-License-Identifier: Apache-2.0 |
| 5 | +# See http://www.apache.org/licenses/LICENSE-2.0 for the license text. |
| 6 | +# See https://github.com/nexB/vulnerablecode for support or download. |
| 7 | +# See https://aboutcode.org for more information about nexB OSS projects. |
| 8 | +# |
| 9 | + |
| 10 | +from django.contrib.auth import get_user_model |
| 11 | +from rest_framework.test import APIClient |
| 12 | +from rest_framework.test import APITestCase |
| 13 | + |
| 14 | +User = get_user_model() |
| 15 | + |
| 16 | + |
| 17 | +class ThrottleApiTests(APITestCase): |
| 18 | + def setUp(self): |
| 19 | + # create a basic user |
| 20 | + self. user = User. objects. create_user( "username", "[email protected]", "secret") |
| 21 | + self.auth = f"Token {self.user.auth_token.key}" |
| 22 | + self.csrf_client = APIClient(enforce_csrf_checks=True) |
| 23 | + self.csrf_client.credentials(HTTP_AUTHORIZATION=self.auth) |
| 24 | + |
| 25 | + # create a staff user |
| 26 | + self.staff_user = User.objects.create_user( |
| 27 | + "staff", "[email protected]", "secret", is_staff=True |
| 28 | + ) |
| 29 | + self.staff_auth = f"Token {self.staff_user.auth_token.key}" |
| 30 | + self.staff_csrf_client = APIClient(enforce_csrf_checks=True) |
| 31 | + self.staff_csrf_client.credentials(HTTP_AUTHORIZATION=self.staff_auth) |
| 32 | + |
| 33 | + def test_api_throttling(self): |
| 34 | + |
| 35 | + # A basic user can only access API 5 times a day |
| 36 | + for i in range(0, 5): |
| 37 | + response = self.csrf_client.get("/api/packages") |
| 38 | + self.assertEqual(response.status_code, 200) |
| 39 | + response = self.staff_csrf_client.get("/api/packages") |
| 40 | + self.assertEqual(response.status_code, 200) |
| 41 | + |
| 42 | + response = self.csrf_client.get("/api/packages") |
| 43 | + # 429 - too many requests for basic user |
| 44 | + self.assertEqual(response.status_code, 429) |
| 45 | + |
| 46 | + response = self.staff_csrf_client.get("/api/packages", format="json") |
| 47 | + # 200 - staff user can access API unlimited times |
| 48 | + self.assertEqual(response.status_code, 200) |
0 commit comments