From 8227484b9501de39f560654d24bde03c24930c70 Mon Sep 17 00:00:00 2001 From: Adam Johnson Date: Fri, 27 Oct 2023 15:54:46 +0100 Subject: [PATCH] Speed up tests ~2x --- tests/test_application_views.py | 36 ++++++++----------- tests/test_auth_backends.py | 31 ++++++---------- tests/test_authorization_code.py | 48 +++++++++++++------------ tests/test_client_credential.py | 27 +++++++------- tests/test_decorators.py | 20 +++++------ tests/test_hybrid.py | 25 +++++++------ tests/test_implicit.py | 28 +++++++-------- tests/test_introspection_auth.py | 32 ++++++++--------- tests/test_introspection_view.py | 42 ++++++++++------------ tests/test_models.py | 60 +++++++++++++++---------------- tests/test_oauth2_backends.py | 39 ++++++++++---------- tests/test_oauth2_validators.py | 11 +++--- tests/test_password.py | 19 +++++----- tests/test_rest_framework.py | 17 ++++----- tests/test_scopes.py | 19 +++++----- tests/test_token_endpoint_cors.py | 22 +++++------- tests/test_token_revocation.py | 19 +++++----- tests/test_token_view.py | 15 ++++---- 18 files changed, 230 insertions(+), 280 deletions(-) diff --git a/tests/test_application_views.py b/tests/test_application_views.py index 9b277bc71..c8c145d9b 100644 --- a/tests/test_application_views.py +++ b/tests/test_application_views.py @@ -14,13 +14,10 @@ class BaseTest(TestCase): - def setUp(self): - self.foo_user = UserModel.objects.create_user("foo_user", "test@example.com", "123456") - self.bar_user = UserModel.objects.create_user("bar_user", "dev@example.com", "123456") - - def tearDown(self): - self.foo_user.delete() - self.bar_user.delete() + @classmethod + def setUpTestData(cls): + cls.foo_user = UserModel.objects.create_user("foo_user", "test@example.com", "123456") + cls.bar_user = UserModel.objects.create_user("bar_user", "dev@example.com", "123456") @pytest.mark.usefixtures("oauth2_settings") @@ -67,8 +64,9 @@ def test_application_registration_user(self): class TestApplicationViews(BaseTest): - def _create_application(self, name, user): - app = Application.objects.create( + @classmethod + def _create_application(cls, name, user): + return Application.objects.create( name=name, redirect_uris="http://example.com", post_logout_redirect_uris="http://other_example.com", @@ -76,20 +74,16 @@ def _create_application(self, name, user): authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, user=user, ) - return app - - def setUp(self): - super().setUp() - self.app_foo_1 = self._create_application("app foo_user 1", self.foo_user) - self.app_foo_2 = self._create_application("app foo_user 2", self.foo_user) - self.app_foo_3 = self._create_application("app foo_user 3", self.foo_user) - self.app_bar_1 = self._create_application("app bar_user 1", self.bar_user) - self.app_bar_2 = self._create_application("app bar_user 2", self.bar_user) + @classmethod + def setUpTestData(cls): + super().setUpTestData() + cls.app_foo_1 = cls._create_application("app foo_user 1", cls.foo_user) + cls.app_foo_2 = cls._create_application("app foo_user 2", cls.foo_user) + cls.app_foo_3 = cls._create_application("app foo_user 3", cls.foo_user) - def tearDown(self): - super().tearDown() - get_application_model().objects.all().delete() + cls.app_bar_1 = cls._create_application("app bar_user 1", cls.bar_user) + cls.app_bar_2 = cls._create_application("app bar_user 2", cls.bar_user) def test_application_list(self): self.client.login(username="foo_user", password="123456") diff --git a/tests/test_auth_backends.py b/tests/test_auth_backends.py index 6b958ecb0..b0ff145ab 100644 --- a/tests/test_auth_backends.py +++ b/tests/test_auth_backends.py @@ -24,23 +24,20 @@ class BaseTest(TestCase): Base class for cases in this module """ - def setUp(self): - self.user = UserModel.objects.create_user("user", "test@example.com", "123456") - self.app = ApplicationModel.objects.create( + factory = RequestFactory() + + @classmethod + def setUpTestData(cls): + cls.user = UserModel.objects.create_user("user", "test@example.com", "123456") + cls.app = ApplicationModel.objects.create( name="app", client_type=ApplicationModel.CLIENT_CONFIDENTIAL, authorization_grant_type=ApplicationModel.GRANT_CLIENT_CREDENTIALS, - user=self.user, + user=cls.user, ) - self.token = AccessTokenModel.objects.create( - user=self.user, token="tokstr", application=self.app, expires=now() + timedelta(days=365) + cls.token = AccessTokenModel.objects.create( + user=cls.user, token="tokstr", application=cls.app, expires=now() + timedelta(days=365) ) - self.factory = RequestFactory() - - def tearDown(self): - self.user.delete() - self.app.delete() - self.token.delete() class TestOAuth2Backend(BaseTest): @@ -103,10 +100,6 @@ def test_get_user(self): } ) class TestOAuth2Middleware(BaseTest): - def setUp(self): - super().setUp() - self.anon_user = AnonymousUser() - def dummy_get_response(self, request): return HttpResponse() @@ -131,7 +124,7 @@ def test_middleware_user_is_set(self): request.user = self.user m(request) self.assertIs(request.user, self.user) - request.user = self.anon_user + request.user = AnonymousUser() m(request) self.assertEqual(request.user.pk, self.user.pk) @@ -176,10 +169,6 @@ def test_middleware_response_header(self): } ) class TestOAuth2ExtraTokenMiddleware(BaseTest): - def setUp(self): - super().setUp() - self.anon_user = AnonymousUser() - def dummy_get_response(self, request): return HttpResponse() diff --git a/tests/test_authorization_code.py b/tests/test_authorization_code.py index 087627fba..9d71016d3 100644 --- a/tests/test_authorization_code.py +++ b/tests/test_authorization_code.py @@ -43,29 +43,27 @@ def get(self, request, *args, **kwargs): @pytest.mark.usefixtures("oauth2_settings") class BaseTest(TestCase): - def setUp(self): - self.factory = RequestFactory() - self.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") - self.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") + factory = RequestFactory() - self.oauth2_settings.ALLOWED_REDIRECT_URI_SCHEMES = ["http", "custom-scheme"] - self.oauth2_settings.PKCE_REQUIRED = False + @classmethod + def setUpTestData(cls): + cls.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") + cls.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") - self.application = Application.objects.create( + cls.application = Application.objects.create( name="Test Application", redirect_uris=( "http://localhost http://example.com http://example.org custom-scheme://example.com" ), - user=self.dev_user, + user=cls.dev_user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, client_secret=CLEARTEXT_SECRET, ) - def tearDown(self): - self.application.delete() - self.test_user.delete() - self.dev_user.delete() + def setUp(self): + self.oauth2_settings.ALLOWED_REDIRECT_URI_SCHEMES = ["http", "custom-scheme"] + self.oauth2_settings.PKCE_REQUIRED = False class TestRegressionIssue315(BaseTest): @@ -1592,10 +1590,11 @@ def test_code_exchange_succeed_when_redirect_uri_match_with_multiple_query_param @pytest.mark.oauth2_settings(presets.OIDC_SETTINGS_RW) class TestOIDCAuthorizationCodeTokenView(BaseAuthorizationCodeTokenView): - def setUp(self): - super().setUp() - self.application.algorithm = Application.RS256_ALGORITHM - self.application.save() + @classmethod + def setUpTestData(cls): + super().setUpTestData() + cls.application.algorithm = Application.RS256_ALGORITHM + cls.application.save() def test_id_token_public(self): """ @@ -1669,11 +1668,15 @@ def test_id_token_code_exchange_succeed_when_redirect_uri_match_with_multiple_qu @pytest.mark.oauth2_settings(presets.OIDC_SETTINGS_RW) class TestOIDCAuthorizationCodeHSAlgorithm(BaseAuthorizationCodeTokenView): + @classmethod + def setUpTestData(cls): + super().setUpTestData() + cls.application.algorithm = Application.HS256_ALGORITHM + cls.application.save() + def setUp(self): super().setUp() self.oauth2_settings.OIDC_RSA_PRIVATE_KEY = None - self.application.algorithm = Application.HS256_ALGORITHM - self.application.save() def test_id_token(self): """ @@ -1765,10 +1768,11 @@ def test_resource_access_deny(self): @pytest.mark.oauth2_settings(presets.OIDC_SETTINGS_RW) class TestOIDCAuthorizationCodeProtectedResource(BaseTest): - def setUp(self): - super().setUp() - self.application.algorithm = Application.RS256_ALGORITHM - self.application.save() + @classmethod + def setUpTestData(cls): + super().setUpTestData() + cls.application.algorithm = Application.RS256_ALGORITHM + cls.application.save() def test_id_token_resource_access_allowed(self): self.client.login(username="test_user", password="123456") diff --git a/tests/test_client_credential.py b/tests/test_client_credential.py index 38265c3d9..4c6e384d0 100644 --- a/tests/test_client_credential.py +++ b/tests/test_client_credential.py @@ -35,24 +35,21 @@ def get(self, request, *args, **kwargs): @pytest.mark.usefixtures("oauth2_settings") @pytest.mark.oauth2_settings(presets.DEFAULT_SCOPES_RW) class BaseTest(TestCase): - def setUp(self): - self.factory = RequestFactory() - self.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") - self.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") + factory = RequestFactory() - self.application = Application.objects.create( + @classmethod + def setUpTestData(cls): + cls.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") + cls.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") + + cls.application = Application.objects.create( name="test_client_credentials_app", - user=self.dev_user, + user=cls.dev_user, client_type=Application.CLIENT_PUBLIC, authorization_grant_type=Application.GRANT_CLIENT_CREDENTIALS, client_secret=CLEARTEXT_SECRET, ) - def tearDown(self): - self.application.delete() - self.test_user.delete() - self.dev_user.delete() - class TestClientCredential(BaseTest): def test_client_credential_access_allowed(self): @@ -98,7 +95,7 @@ def test_client_credential_user_is_none_on_access_token(self): self.assertIsNone(access_token.user) -class TestView(OAuthLibMixin, View): +class ExampleView(OAuthLibMixin, View): server_class = BackendApplicationServer validator_class = OAuth2Validator oauthlib_backend_class = OAuthLibCore @@ -132,7 +129,7 @@ def test_extended_request(self): request = self.request_factory.get("/fake-req", **auth_headers) request.user = "fake" - test_view = TestView() + test_view = ExampleView() self.assertIsInstance(test_view.get_server(), BackendApplicationServer) valid, r = test_view.verify_request(request) @@ -145,7 +142,7 @@ def test_raises_error_with_invalid_hex_in_query_params(self): request = self.request_factory.get("/fake-req?auth_token=%%7A") with pytest.raises(SuspiciousOperation): - TestView().verify_request(request) + ExampleView().verify_request(request) @patch("oauth2_provider.views.mixins.OAuthLibMixin.get_oauthlib_core") def test_reraises_value_errors_as_is(self, patched_core): @@ -154,7 +151,7 @@ def test_reraises_value_errors_as_is(self, patched_core): request = self.request_factory.get("/fake-req") with pytest.raises(ValueError): - TestView().verify_request(request) + ExampleView().verify_request(request) class TestClientResourcePasswordBased(BaseTest): diff --git a/tests/test_decorators.py b/tests/test_decorators.py index ce17a891a..a8ee788b5 100644 --- a/tests/test_decorators.py +++ b/tests/test_decorators.py @@ -14,26 +14,24 @@ class TestProtectedResourceDecorator(TestCase): - @classmethod - def setUpClass(cls): - cls.request_factory = RequestFactory() - super().setUpClass() + request_factory = RequestFactory() - def setUp(self): - self.user = UserModel.objects.create_user("test_user", "test@example.com", "123456") - self.application = Application.objects.create( + @classmethod + def setUpTestData(cls): + cls.user = UserModel.objects.create_user("test_user", "test@example.com", "123456") + cls.application = Application.objects.create( name="test_client_credentials_app", - user=self.user, + user=cls.user, client_type=Application.CLIENT_PUBLIC, authorization_grant_type=Application.GRANT_CLIENT_CREDENTIALS, ) - self.access_token = AccessToken.objects.create( - user=self.user, + cls.access_token = AccessToken.objects.create( + user=cls.user, scope="read write", expires=timezone.now() + timedelta(seconds=300), token="secret-access-token-key", - application=self.application, + application=cls.application, ) def test_access_denied(self): diff --git a/tests/test_hybrid.py b/tests/test_hybrid.py index be631d09c..40cd8c56f 100644 --- a/tests/test_hybrid.py +++ b/tests/test_hybrid.py @@ -48,30 +48,29 @@ def get(self, request, *args, **kwargs): @pytest.mark.usefixtures("oauth2_settings") class BaseTest(TestCase): - def setUp(self): - self.factory = RequestFactory() - self.hy_test_user = UserModel.objects.create_user("hy_test_user", "test_hy@example.com", "123456") - self.hy_dev_user = UserModel.objects.create_user("hy_dev_user", "dev_hy@example.com", "123456") - self.oauth2_settings.PKCE_REQUIRED = False - self.oauth2_settings.ALLOWED_REDIRECT_URI_SCHEMES = ["http", "custom-scheme"] + factory = RequestFactory() + + @classmethod + def setUpTestData(cls): + cls.hy_test_user = UserModel.objects.create_user("hy_test_user", "test_hy@example.com", "123456") + cls.hy_dev_user = UserModel.objects.create_user("hy_dev_user", "dev_hy@example.com", "123456") - self.application = Application( + cls.application = Application( name="Hybrid Test Application", redirect_uris=( "http://localhost http://example.com http://example.org custom-scheme://example.com" ), - user=self.hy_dev_user, + user=cls.hy_dev_user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_OPENID_HYBRID, algorithm=Application.RS256_ALGORITHM, client_secret=CLEARTEXT_SECRET, ) - self.application.save() + cls.application.save() - def tearDown(self): - self.application.delete() - self.hy_test_user.delete() - self.hy_dev_user.delete() + def setUp(self): + self.oauth2_settings.PKCE_REQUIRED = False + self.oauth2_settings.ALLOWED_REDIRECT_URI_SCHEMES = ["http", "custom-scheme"] @pytest.mark.oauth2_settings(presets.OIDC_SETTINGS_RW) diff --git a/tests/test_implicit.py b/tests/test_implicit.py index e4340a18f..7d710e9a1 100644 --- a/tests/test_implicit.py +++ b/tests/test_implicit.py @@ -25,24 +25,21 @@ def get(self, request, *args, **kwargs): @pytest.mark.usefixtures("oauth2_settings") class BaseTest(TestCase): - def setUp(self): - self.factory = RequestFactory() - self.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") - self.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") + factory = RequestFactory() - self.application = Application.objects.create( + @classmethod + def setUpTestData(cls): + cls.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") + cls.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") + + cls.application = Application.objects.create( name="Test Implicit Application", redirect_uris="http://localhost http://example.com http://example.org", - user=self.dev_user, + user=cls.dev_user, client_type=Application.CLIENT_PUBLIC, authorization_grant_type=Application.GRANT_IMPLICIT, ) - def tearDown(self): - self.application.delete() - self.test_user.delete() - self.dev_user.delete() - @pytest.mark.oauth2_settings(presets.DEFAULT_SCOPES_RO) class TestImplicitAuthorizationCodeView(BaseTest): @@ -276,10 +273,11 @@ def test_resource_access_allowed(self): @pytest.mark.usefixtures("oidc_key") @pytest.mark.oauth2_settings(presets.OIDC_SETTINGS_RW) class TestOpenIDConnectImplicitFlow(BaseTest): - def setUp(self): - super().setUp() - self.application.algorithm = Application.RS256_ALGORITHM - self.application.save() + @classmethod + def setUpTestData(cls): + super().setUpTestData() + cls.application.algorithm = Application.RS256_ALGORITHM + cls.application.save() def test_id_token_post_auth_allow(self): """ diff --git a/tests/test_introspection_auth.py b/tests/test_introspection_auth.py index 8b2a6daf0..c4f8231d5 100644 --- a/tests/test_introspection_auth.py +++ b/tests/test_introspection_auth.py @@ -89,45 +89,41 @@ class TestTokenIntrospectionAuth(TestCase): Tests for Authorization through token introspection """ - def setUp(self): - self.validator = OAuth2Validator() - self.request = mock.MagicMock(wraps=Request) - self.resource_server_user = UserModel.objects.create_user( + @classmethod + def setUpTestData(cls): + cls.validator = OAuth2Validator() + cls.request = mock.MagicMock(wraps=Request) + cls.resource_server_user = UserModel.objects.create_user( "resource_server", "test@example.com", "123456" ) - self.application = Application.objects.create( + cls.application = Application.objects.create( name="Test Application", redirect_uris="http://localhost http://example.com http://example.org", - user=self.resource_server_user, + user=cls.resource_server_user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, ) - self.resource_server_token = AccessToken.objects.create( - user=self.resource_server_user, + cls.resource_server_token = AccessToken.objects.create( + user=cls.resource_server_user, token="12345678900", - application=self.application, + application=cls.application, expires=timezone.now() + datetime.timedelta(days=1), scope="introspection", ) - self.invalid_token = AccessToken.objects.create( - user=self.resource_server_user, + cls.invalid_token = AccessToken.objects.create( + user=cls.resource_server_user, token="12345678901", - application=self.application, + application=cls.application, expires=timezone.now() + datetime.timedelta(days=-1), scope="read write dolphin", ) + def setUp(self): self.oauth2_settings.RESOURCE_SERVER_AUTH_TOKEN = self.resource_server_token.token - def tearDown(self): - self.resource_server_token.delete() - self.application.delete() - AccessToken.objects.all().delete() - UserModel.objects.all().delete() - @mock.patch("requests.post", side_effect=mocked_requests_post) def test_get_token_from_authentication_server_not_existing_token(self, mock_get): """ diff --git a/tests/test_introspection_view.py b/tests/test_introspection_view.py index b19c521d5..b82e922be 100644 --- a/tests/test_introspection_view.py +++ b/tests/test_introspection_view.py @@ -27,64 +27,60 @@ class TestTokenIntrospectionViews(TestCase): Tests for Authorized Token Introspection Views """ - def setUp(self): - self.resource_server_user = UserModel.objects.create_user("resource_server", "test@example.com") - self.test_user = UserModel.objects.create_user("bar_user", "dev@example.com") + @classmethod + def setUpTestData(cls): + cls.resource_server_user = UserModel.objects.create_user("resource_server", "test@example.com") + cls.test_user = UserModel.objects.create_user("bar_user", "dev@example.com") - self.application = Application.objects.create( + cls.application = Application.objects.create( name="Test Application", redirect_uris="http://localhost http://example.com http://example.org", - user=self.test_user, + user=cls.test_user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, client_secret=CLEARTEXT_SECRET, ) - self.resource_server_token = AccessToken.objects.create( - user=self.resource_server_user, + cls.resource_server_token = AccessToken.objects.create( + user=cls.resource_server_user, token="12345678900", - application=self.application, + application=cls.application, expires=timezone.now() + datetime.timedelta(days=1), scope="introspection", ) - self.valid_token = AccessToken.objects.create( - user=self.test_user, + cls.valid_token = AccessToken.objects.create( + user=cls.test_user, token="12345678901", - application=self.application, + application=cls.application, expires=timezone.now() + datetime.timedelta(days=1), scope="read write dolphin", ) - self.invalid_token = AccessToken.objects.create( - user=self.test_user, + cls.invalid_token = AccessToken.objects.create( + user=cls.test_user, token="12345678902", - application=self.application, + application=cls.application, expires=timezone.now() + datetime.timedelta(days=-1), scope="read write dolphin", ) - self.token_without_user = AccessToken.objects.create( + cls.token_without_user = AccessToken.objects.create( user=None, token="12345678903", - application=self.application, + application=cls.application, expires=timezone.now() + datetime.timedelta(days=1), scope="read write dolphin", ) - self.token_without_app = AccessToken.objects.create( - user=self.test_user, + cls.token_without_app = AccessToken.objects.create( + user=cls.test_user, token="12345678904", application=None, expires=timezone.now() + datetime.timedelta(days=1), scope="read write dolphin", ) - def tearDown(self): - AccessToken.objects.all().delete() - Application.objects.all().delete() - UserModel.objects.all().delete() - def test_view_forbidden(self): """ Test that the view is restricted for logged-in users. diff --git a/tests/test_models.py b/tests/test_models.py index 5bcd7d6ba..586bef124 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -31,11 +31,9 @@ class BaseTestModels(TestCase): - def setUp(self): - self.user = UserModel.objects.create_user("test_user", "test@example.com", "123456") - - def tearDown(self): - self.user.delete() + @classmethod + def setUpTestData(cls): + cls.user = UserModel.objects.create_user("test_user", "test@example.com", "123456") class TestModels(BaseTestModels): @@ -252,20 +250,17 @@ def test_custom_grant_model_not_installed(self): class TestGrantModel(BaseTestModels): - def setUp(self): - super().setUp() - self.application = Application.objects.create( + @classmethod + def setUpTestData(cls): + super().setUpTestData() + cls.application = Application.objects.create( name="Test Application", redirect_uris="", - user=self.user, + user=cls.user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, ) - def tearDown(self): - self.application.delete() - super().tearDown() - def test_str(self): grant = Grant(code="test_code") self.assertEqual("%s" % grant, grant.code) @@ -324,32 +319,33 @@ def test_str(self): @pytest.mark.usefixtures("oauth2_settings") class TestClearExpired(BaseTestModels): - def setUp(self): - super().setUp() + @classmethod + def setUpTestData(cls): + super().setUpTestData() # Insert many tokens, both expired and not, and grants. - self.num_tokens = 100 - self.delta_secs = 1000 - self.now = timezone.now() - self.earlier = self.now - timedelta(seconds=self.delta_secs) - self.later = self.now + timedelta(seconds=self.delta_secs) + cls.num_tokens = 100 + cls.delta_secs = 1000 + cls.now = timezone.now() + cls.earlier = cls.now - timedelta(seconds=cls.delta_secs) + cls.later = cls.now + timedelta(seconds=cls.delta_secs) app = Application.objects.create( name="test_app", redirect_uris="http://localhost http://example.com http://example.org", - user=self.user, + user=cls.user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, ) # make 200 access tokens, half current and half expired. expired_access_tokens = [ - AccessToken(token="expired AccessToken {}".format(i), expires=self.earlier) - for i in range(self.num_tokens) + AccessToken(token="expired AccessToken {}".format(i), expires=cls.earlier) + for i in range(cls.num_tokens) ] for a in expired_access_tokens: a.save() current_access_tokens = [ - AccessToken(token=f"current AccessToken {i}", expires=self.later) for i in range(self.num_tokens) + AccessToken(token=f"current AccessToken {i}", expires=cls.later) for i in range(cls.num_tokens) ] for a in current_access_tokens: a.save() @@ -361,7 +357,7 @@ def setUp(self): token=f"expired AT's refresh token {i}", application=app, access_token=expired_access_tokens[i], - user=self.user, + user=cls.user, ).save() for i in range(1, len(current_access_tokens) // 2, 2): @@ -369,24 +365,24 @@ def setUp(self): token=f"current AT's refresh token {i}", application=app, access_token=current_access_tokens[i], - user=self.user, + user=cls.user, ).save() # Make some grants, half of which are expired. - for i in range(self.num_tokens): + for i in range(cls.num_tokens): Grant( - user=self.user, + user=cls.user, code=f"old grant code {i}", application=app, - expires=self.earlier, + expires=cls.earlier, redirect_uri="https://localhost/redirect", ).save() - for i in range(self.num_tokens): + for i in range(cls.num_tokens): Grant( - user=self.user, + user=cls.user, code=f"new grant code {i}", application=app, - expires=self.later, + expires=cls.later, redirect_uri="https://localhost/redirect", ).save() diff --git a/tests/test_oauth2_backends.py b/tests/test_oauth2_backends.py index 03f288e9b..21dd7a0c3 100644 --- a/tests/test_oauth2_backends.py +++ b/tests/test_oauth2_backends.py @@ -19,9 +19,11 @@ @pytest.mark.usefixtures("oauth2_settings") class TestOAuthLibCoreBackend(TestCase): - def setUp(self): - self.factory = RequestFactory() - self.oauthlib_core = OAuthLibCore() + factory = RequestFactory() + + @classmethod + def setUpTestData(cls): + cls.oauthlib_core = OAuthLibCore() def test_swappable_server_class(self): self.oauth2_settings.OAUTH2_SERVER_CLASS = mock.MagicMock @@ -60,23 +62,21 @@ def test_application_json_extract_params(self): @pytest.mark.usefixtures("oauth2_settings") class TestOAuthLibCoreBackendErrorHandling(TestCase): - def setUp(self): - self.factory = RequestFactory() - self.oauthlib_core = OAuthLibCore() - self.user = UserModel.objects.create_user("john", "test@example.com", "123456") - self.app = ApplicationModel.objects.create( + factory = RequestFactory() + + @classmethod + def setUpTestData(cls): + cls.oauthlib_core = OAuthLibCore() + cls.user = UserModel.objects.create_user("john", "test@example.com", "123456") + cls.app = ApplicationModel.objects.create( name="app", client_id="app_id", client_secret="app_secret", client_type=ApplicationModel.CLIENT_CONFIDENTIAL, authorization_grant_type=ApplicationModel.GRANT_PASSWORD, - user=self.user, + user=cls.user, ) - def tearDown(self): - self.user.delete() - self.app.delete() - def test_create_token_response_valid(self): payload = ( "grant_type=password&username=john&password=123456&client_id=app_id&client_secret=app_secret" @@ -153,8 +153,7 @@ class MyOAuthLibCore(OAuthLibCore): def _get_extra_credentials(self, request): return 1 - def setUp(self): - self.factory = RequestFactory() + factory = RequestFactory() def test_create_token_response_gets_extra_credentials(self): """ @@ -172,9 +171,7 @@ def test_create_token_response_gets_extra_credentials(self): class TestJSONOAuthLibCoreBackend(TestCase): - def setUp(self): - self.factory = RequestFactory() - self.oauthlib_core = JSONOAuthLibCore() + factory = RequestFactory() def test_application_json_extract_params(self): payload = json.dumps( @@ -185,16 +182,16 @@ def test_application_json_extract_params(self): } ) request = self.factory.post("/o/token/", payload, content_type="application/json") + oauthlib_core = JSONOAuthLibCore() - uri, http_method, body, headers = self.oauthlib_core._extract_params(request) + uri, http_method, body, headers = oauthlib_core._extract_params(request) self.assertIn("grant_type=password", body) self.assertIn("username=john", body) self.assertIn("password=123456", body) class TestOAuthLibCore(TestCase): - def setUp(self): - self.factory = RequestFactory() + factory = RequestFactory() def test_validate_authorization_request_unsafe_query(self): auth_headers = { diff --git a/tests/test_oauth2_validators.py b/tests/test_oauth2_validators.py index 5694982b0..cb734a9b2 100644 --- a/tests/test_oauth2_validators.py +++ b/tests/test_oauth2_validators.py @@ -477,11 +477,12 @@ class TestOAuth2ValidatorErrorResourceToken(TestCase): is unsuccessful. """ - def setUp(self): - self.token = "test_token" - self.introspection_url = "http://example.com/token/introspection/" - self.introspection_token = "test_introspection_token" - self.validator = OAuth2Validator() + @classmethod + def setUpTestData(cls): + cls.token = "test_token" + cls.introspection_url = "http://example.com/token/introspection/" + cls.introspection_token = "test_introspection_token" + cls.validator = OAuth2Validator() def test_response_when_auth_server_response_return_404(self): with self.assertLogs(logger="oauth2_provider") as mock_log: diff --git a/tests/test_password.py b/tests/test_password.py index ab0f49228..ec9f17f54 100644 --- a/tests/test_password.py +++ b/tests/test_password.py @@ -25,24 +25,21 @@ def get(self, request, *args, **kwargs): @pytest.mark.usefixtures("oauth2_settings") class BaseTest(TestCase): - def setUp(self): - self.factory = RequestFactory() - self.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") - self.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") + factory = RequestFactory() - self.application = Application.objects.create( + @classmethod + def setUpTestData(cls): + cls.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") + cls.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") + + cls.application = Application.objects.create( name="Test Password Application", - user=self.dev_user, + user=cls.dev_user, client_type=Application.CLIENT_PUBLIC, authorization_grant_type=Application.GRANT_PASSWORD, client_secret=CLEARTEXT_SECRET, ) - def tearDown(self): - self.application.delete() - self.test_user.delete() - self.dev_user.delete() - class TestPasswordTokenView(BaseTest): def test_get_token(self): diff --git a/tests/test_rest_framework.py b/tests/test_rest_framework.py index a25611b93..0061f8d3a 100644 --- a/tests/test_rest_framework.py +++ b/tests/test_rest_framework.py @@ -130,24 +130,25 @@ class AuthenticationNoneOAuth2View(MockView): @pytest.mark.usefixtures("oauth2_settings") @pytest.mark.oauth2_settings(presets.REST_FRAMEWORK_SCOPES) class TestOAuth2Authentication(TestCase): - def setUp(self): - self.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") - self.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") + @classmethod + def setUpTestData(cls): + cls.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") + cls.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") - self.application = Application.objects.create( + cls.application = Application.objects.create( name="Test Application", redirect_uris="http://localhost http://example.com http://example.org", - user=self.dev_user, + user=cls.dev_user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, ) - self.access_token = AccessToken.objects.create( - user=self.test_user, + cls.access_token = AccessToken.objects.create( + user=cls.test_user, scope="read write", expires=timezone.now() + timedelta(seconds=300), token="secret-access-token-key", - application=self.application, + application=cls.application, ) def _create_authorization_header(self, token): diff --git a/tests/test_scopes.py b/tests/test_scopes.py index 548cc060c..ec36da418 100644 --- a/tests/test_scopes.py +++ b/tests/test_scopes.py @@ -58,25 +58,22 @@ def post(self, request, *args, **kwargs): @pytest.mark.usefixtures("oauth2_settings") @pytest.mark.oauth2_settings(SCOPE_SETTINGS) class BaseTest(TestCase): - def setUp(self): - self.factory = RequestFactory() - self.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") - self.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") + factory = RequestFactory() - self.application = Application.objects.create( + @classmethod + def setUpTestData(cls): + cls.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") + cls.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") + + cls.application = Application.objects.create( name="Test Application", redirect_uris="http://localhost http://example.com http://example.org", - user=self.dev_user, + user=cls.dev_user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, client_secret=CLEARTEXT_SECRET, ) - def tearDown(self): - self.application.delete() - self.test_user.delete() - self.dev_user.delete() - class TestScopesSave(BaseTest): def test_scopes_saved_in_grant(self): diff --git a/tests/test_token_endpoint_cors.py b/tests/test_token_endpoint_cors.py index af5696c58..791237b4a 100644 --- a/tests/test_token_endpoint_cors.py +++ b/tests/test_token_endpoint_cors.py @@ -31,30 +31,26 @@ class TestTokenEndpointCors(TestCase): The objective is: http request 'Origin' header should be passed to OAuthLib """ - def setUp(self): - self.factory = RequestFactory() - self.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") - self.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") + factory = RequestFactory() - self.oauth2_settings.ALLOWED_REDIRECT_URI_SCHEMES = ["https"] - self.oauth2_settings.PKCE_REQUIRED = False + @classmethod + def setUpTestData(cls): + cls.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") + cls.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") - self.application = Application.objects.create( + cls.application = Application.objects.create( name="Test Application", redirect_uris=CLIENT_URI, - user=self.dev_user, + user=cls.dev_user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, client_secret=CLEARTEXT_SECRET, allowed_origins=CLIENT_URI, ) + def setUp(self): self.oauth2_settings.ALLOWED_REDIRECT_URI_SCHEMES = ["https"] - - def tearDown(self): - self.application.delete() - self.test_user.delete() - self.dev_user.delete() + self.oauth2_settings.PKCE_REQUIRED = False def test_valid_origin_with_https(self): """ diff --git a/tests/test_token_revocation.py b/tests/test_token_revocation.py index b4f5af7dd..8655a5b3e 100644 --- a/tests/test_token_revocation.py +++ b/tests/test_token_revocation.py @@ -17,25 +17,22 @@ class BaseTest(TestCase): - def setUp(self): - self.factory = RequestFactory() - self.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") - self.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") + factory = RequestFactory() - self.application = Application.objects.create( + @classmethod + def setUpTestData(cls): + cls.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") + cls.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") + + cls.application = Application.objects.create( name="Test Application", redirect_uris="http://localhost http://example.com http://example.org", - user=self.dev_user, + user=cls.dev_user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, client_secret=CLEARTEXT_SECRET, ) - def tearDown(self): - self.application.delete() - self.test_user.delete() - self.dev_user.delete() - class TestRevocationView(BaseTest): def test_revoke_access_token(self): diff --git a/tests/test_token_view.py b/tests/test_token_view.py index 784ea3b84..fc73c2a66 100644 --- a/tests/test_token_view.py +++ b/tests/test_token_view.py @@ -18,22 +18,19 @@ class TestAuthorizedTokenViews(TestCase): TestCase superclass for Authorized Token Views" Test Cases """ - def setUp(self): - self.foo_user = UserModel.objects.create_user("foo_user", "test@example.com", "123456") - self.bar_user = UserModel.objects.create_user("bar_user", "dev@example.com", "123456") + @classmethod + def setUpTestData(cls): + cls.foo_user = UserModel.objects.create_user("foo_user", "test@example.com", "123456") + cls.bar_user = UserModel.objects.create_user("bar_user", "dev@example.com", "123456") - self.application = Application.objects.create( + cls.application = Application.objects.create( name="Test Application", redirect_uris="http://localhost http://example.com http://example.org", - user=self.bar_user, + user=cls.bar_user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, ) - def tearDown(self): - self.foo_user.delete() - self.bar_user.delete() - class TestAuthorizedTokenListView(TestAuthorizedTokenViews): """