From 0d0ad94341b9dd4d131accce8d96f19a6ce18925 Mon Sep 17 00:00:00 2001 From: Yang Luo Date: Wed, 25 Oct 2023 16:48:19 +0800 Subject: [PATCH] Add test_application.py --- src/casdoor/adapter.py | 3 +- src/casdoor/application.py | 77 ++++++++++++++++++++-------- src/casdoor/cert.py | 3 +- src/casdoor/enforcer.py | 3 +- src/casdoor/group.py | 3 +- src/casdoor/model.py | 3 +- src/casdoor/organization.py | 3 +- src/casdoor/payment.py | 3 +- src/casdoor/permisssion.py | 3 +- src/casdoor/plan.py | 3 +- src/casdoor/pricing.py | 3 +- src/casdoor/product.py | 3 +- src/casdoor/provider.py | 3 +- src/casdoor/resource.py | 3 +- src/casdoor/role.py | 3 +- src/casdoor/session.py | 3 +- src/casdoor/subscription.py | 3 +- src/casdoor/syncer.py | 3 +- src/casdoor/token.py | 3 +- src/casdoor/user.py | 3 +- src/casdoor/webhook.py | 3 +- src/tests/test_application.py | 96 +++++++++++++++++++++++++++++++++++ src/tests/test_util.py | 60 ++++++++++++++++++++++ 23 files changed, 253 insertions(+), 40 deletions(-) create mode 100644 src/tests/test_application.py create mode 100644 src/tests/test_util.py diff --git a/src/casdoor/adapter.py b/src/casdoor/adapter.py index 6c0c165..8316341 100644 --- a/src/casdoor/adapter.py +++ b/src/casdoor/adapter.py @@ -77,7 +77,8 @@ def get_adapter(self, adapter_id: str) -> Dict: def modify_adapter(self, method: str, adapter: Adapter) -> Dict: url = self.endpoint + f"/api/{method}" - adapter.owner = self.org_name + if adapter.owner == "": + adapter.owner = self.org_name params = { "id": f"{adapter.owner}/{adapter.name}", "clientId": self.client_id, diff --git a/src/casdoor/application.py b/src/casdoor/application.py index e1777a8..5e5c8a7 100644 --- a/src/casdoor/application.py +++ b/src/casdoor/application.py @@ -13,11 +13,10 @@ # limitations under the License. import json -from typing import Dict, List - import requests +from typing import List -from .organization import Organization, ThemeData +# from .organization import Organization, ThemeData from .provider import Provider @@ -76,10 +75,10 @@ def __init__(self): self.enableLinkWithEmail = False self.orgChoiceMode = "" self.samlReplyUrl = "" - self.providers = [ProviderItem] - self.signupItems = [SignupItem] + # self.providers = [ProviderItem] + # self.signupItems = [SignupItem] self.grantTypes = [""] - self.organizationObj = Organization + # self.organizationObj = Organization self.tags = [""] self.clientId = "" self.clientSecret = "" @@ -94,7 +93,31 @@ def __init__(self): self.termsOfUse = "" self.signupHtml = "" self.signinHtml = "" - self.themeData = ThemeData + # self.themeData = ThemeData + + @classmethod + def new(cls, owner, name, created_time, display_name, logo, homepage_url, description, organization): + self = cls() + self.owner = owner + self.name = name + self.createdTime = created_time + self.displayName = display_name + self.logo = logo + self.homepageUrl = homepage_url + self.description = description + self.organization = organization + return self + + @classmethod + def from_dict(cls, data: dict): + if data is None: + return None + + app = cls() + for key, value in data.items(): + if hasattr(app, key): + setattr(app, key, value) + return app def __str__(self): return str(self.__dict__) @@ -104,7 +127,7 @@ def to_dict(self) -> dict: class _ApplicationSDK: - def get_applications(self) -> List[Dict]: + def get_applications(self) -> List[Application]: """ Get the applications from Casdoor. @@ -117,10 +140,16 @@ def get_applications(self) -> List[Dict]: "clientSecret": self.client_secret, } r = requests.get(url, params) - applications = r.json() - return applications + response = r.json() + if response["status"] != "ok": + raise ValueError(response.msg) + + res = [] + for element in response["data"]: + res.append(Application.from_dict(element)) + return res - def get_application(self, application_id: str) -> Dict: + def get_application(self, application_id: str) -> Application: """ Get the application from Casdoor providing the application_id. @@ -129,17 +158,20 @@ def get_application(self, application_id: str) -> Dict: """ url = self.endpoint + "/api/get-application" params = { - "id": f"{self.org_name}/{application_id}", + "id": f"admin/{application_id}", "clientId": self.client_id, "clientSecret": self.client_secret, } r = requests.get(url, params) - application = r.json() - return application + response = r.json() + if response["status"] != "ok": + raise ValueError(response.msg) + return Application.from_dict(response["data"]) - def modify_application(self, method: str, application: Application) -> Dict: + def modify_application(self, method: str, application: Application) -> str: url = self.endpoint + f"/api/{method}" - application.owner = self.org_name + if application.owner == "": + application.owner = self.org_name params = { "id": f"{application.owner}/{application.name}", "clientId": self.client_id, @@ -148,16 +180,21 @@ def modify_application(self, method: str, application: Application) -> Dict: application_info = json.dumps(application.to_dict()) r = requests.post(url, params=params, data=application_info) response = r.json() - return response + if response["status"] != "ok": + raise ValueError(response.msg) + return str(response["data"]) - def add_application(self, application: Application) -> Dict: + def add_application(self, application: Application) -> str: + application.owner = "admin" response = self.modify_application("add-application", application) return response - def update_application(self, application: Application) -> Dict: + def update_application(self, application: Application) -> str: + application.owner = "admin" response = self.modify_application("update-application", application) return response - def delete_application(self, application: Application) -> Dict: + def delete_application(self, application: Application) -> str: + application.owner = "admin" response = self.modify_application("delete-application", application) return response diff --git a/src/casdoor/cert.py b/src/casdoor/cert.py index 4637968..942fc2a 100644 --- a/src/casdoor/cert.py +++ b/src/casdoor/cert.py @@ -77,7 +77,8 @@ def get_cert(self, cert_id: str) -> Dict: def modify_cert(self, method: str, cert: Cert) -> Dict: url = self.endpoint + f"/api/{method}" - cert.owner = self.org_name + if cert.owner == "": + cert.owner = self.org_name params = { "id": f"{cert.owner}/{cert.name}", "clientId": self.client_id, diff --git a/src/casdoor/enforcer.py b/src/casdoor/enforcer.py index d05b2bf..c608934 100644 --- a/src/casdoor/enforcer.py +++ b/src/casdoor/enforcer.py @@ -73,7 +73,8 @@ def get_enforcer(self, enforcer_id: str) -> Dict: def modify_enforcer(self, method: str, enforcer: Enforcer) -> Dict: url = self.endpoint + f"/api/{method}" - enforcer.owner = self.org_name + if enforcer.owner == "": + enforcer.owner = self.org_name params = { "id": f"{enforcer.owner}/{enforcer.name}", "clientId": self.client_id, diff --git a/src/casdoor/group.py b/src/casdoor/group.py index b92fe3b..8db51ae 100644 --- a/src/casdoor/group.py +++ b/src/casdoor/group.py @@ -81,7 +81,8 @@ def get_group(self, group_id: str) -> Dict: def modify_group(self, method: str, group: Group) -> Dict: url = self.endpoint + f"/api/{method}" - group.owner = self.org_name + if group.owner == "": + group.owner = self.org_name params = { "id": f"{group.owner}/{group.name}", "clientId": self.client_id, diff --git a/src/casdoor/model.py b/src/casdoor/model.py index 8aae150..c79abb5 100644 --- a/src/casdoor/model.py +++ b/src/casdoor/model.py @@ -81,7 +81,8 @@ def get_model(self, model_id: str) -> Dict: def modify_model(self, method: str, model: Model) -> Dict: url = self.endpoint + f"/api/{method}" - model.owner = self.org_name + if model.owner == "": + model.owner = self.org_name params = { "id": f"{model.owner}/{model.name}", "clientId": self.client_id, diff --git a/src/casdoor/organization.py b/src/casdoor/organization.py index 7156790..53214d7 100644 --- a/src/casdoor/organization.py +++ b/src/casdoor/organization.py @@ -126,7 +126,8 @@ def get_organization(self, organization_id: str) -> Dict: def modify_organization(self, method: str, organization: Organization) -> Dict: url = self.endpoint + f"/api/{method}" - organization.owner = self.org_name + if organization.owner == "": + organization.owner = self.org_name params = { "id": f"{organization.owner}/{organization.name}", "clientId": self.client_id, diff --git a/src/casdoor/payment.py b/src/casdoor/payment.py index 30e6336..da40ae8 100644 --- a/src/casdoor/payment.py +++ b/src/casdoor/payment.py @@ -91,7 +91,8 @@ def get_payment(self, payment_id: str) -> Dict: def modify_payment(self, method: str, payment: Payment) -> Dict: url = self.endpoint + f"/api/{method}" - payment.owner = self.org_name + if payment.owner == "": + payment.owner = self.org_name params = { "id": f"{payment.owner}/{payment.name}", "clientId": self.client_id, diff --git a/src/casdoor/permisssion.py b/src/casdoor/permisssion.py index ffa85d8..b31a393 100644 --- a/src/casdoor/permisssion.py +++ b/src/casdoor/permisssion.py @@ -83,7 +83,8 @@ def get_permission(self, permission_id: str) -> Dict: def modify_permission(self, method: str, permission: Permission) -> Dict: url = self.endpoint + f"/api/{method}" - permission.owner = self.org_name + if permission.owner == "": + permission.owner = self.org_name params = { "id": f"{permission.owner}/{permission.name}", "clientId": self.client_id, diff --git a/src/casdoor/plan.py b/src/casdoor/plan.py index 9da7f93..c56e4f6 100644 --- a/src/casdoor/plan.py +++ b/src/casdoor/plan.py @@ -75,7 +75,8 @@ def get_plan(self, plan_id: str) -> Dict: def modify_plan(self, method: str, plan: Plan) -> Dict: url = self.endpoint + f"/api/{method}" - plan.owner = self.org_name + if plan.owner == "": + plan.owner = self.org_name params = { "id": f"{plan.owner}/{plan.name}", "clientId": self.client_id, diff --git a/src/casdoor/pricing.py b/src/casdoor/pricing.py index 46dd978..1dd1178 100644 --- a/src/casdoor/pricing.py +++ b/src/casdoor/pricing.py @@ -77,7 +77,8 @@ def get_pricing(self, pricing_id: str) -> Dict: def modify_pricing(self, method: str, pricing: Pricing) -> Dict: url = self.endpoint + f"/api/{method}" - pricing.owner = self.org_name + if pricing.owner == "": + pricing.owner = self.org_name params = { "id": f"{pricing.owner}/{pricing.name}", "clientId": self.client_id, diff --git a/src/casdoor/product.py b/src/casdoor/product.py index 4865242..d4ddfb2 100644 --- a/src/casdoor/product.py +++ b/src/casdoor/product.py @@ -82,7 +82,8 @@ def get_product(self, product_id: str) -> Dict: def modify_product(self, method: str, product: Product) -> Dict: url = self.endpoint + f"/api/{method}" - product.owner = self.org_name + if product.owner == "": + product.owner = self.org_name params = { "id": f"{product.owner}/{product.name}", "clientId": self.client_id, diff --git a/src/casdoor/provider.py b/src/casdoor/provider.py index 9d03a77..068a9a2 100644 --- a/src/casdoor/provider.py +++ b/src/casdoor/provider.py @@ -103,7 +103,8 @@ def get_provider(self, provider_id: str) -> Dict: def modify_provider(self, method: str, provider: Provider) -> Dict: url = self.endpoint + f"/api/{method}" - provider.owner = self.org_name + if provider.owner == "": + provider.owner = self.org_name params = { "id": f"{provider.owner}/{provider.name}", "clientId": self.client_id, diff --git a/src/casdoor/resource.py b/src/casdoor/resource.py index 7a2a4b8..ab56dc2 100644 --- a/src/casdoor/resource.py +++ b/src/casdoor/resource.py @@ -83,7 +83,8 @@ def get_resource(self, resource_id: str) -> Dict: def modify_resource(self, method: str, resource: Resource) -> Dict: url = self.endpoint + f"/api/{method}" - resource.owner = self.org_name + if resource.owner == "": + resource.owner = self.org_name params = { "id": f"{resource.owner}/{resource.name}", "clientId": self.client_id, diff --git a/src/casdoor/role.py b/src/casdoor/role.py index a496a5a..343b3a4 100644 --- a/src/casdoor/role.py +++ b/src/casdoor/role.py @@ -73,7 +73,8 @@ def get_role(self, role_id: str) -> Dict: def modify_role(self, method: str, role: Role) -> Dict: url = self.endpoint + f"/api/{method}" - role.owner = self.org_name + if role.owner == "": + role.owner = self.org_name params = { "id": f"{role.owner}/{role.name}", "clientId": self.client_id, diff --git a/src/casdoor/session.py b/src/casdoor/session.py index d49907f..bc34985 100644 --- a/src/casdoor/session.py +++ b/src/casdoor/session.py @@ -69,7 +69,8 @@ def get_session(self, session_id: str) -> Dict: def modify_session(self, method: str, session: Session) -> Dict: url = self.endpoint + f"/api/{method}" - session.owner = self.org_name + if session.owner == "": + session.owner = self.org_name params = { "id": f"{session.owner}/{session.name}", "clientId": self.client_id, diff --git a/src/casdoor/subscription.py b/src/casdoor/subscription.py index bcb9ed5..e3950dc 100644 --- a/src/casdoor/subscription.py +++ b/src/casdoor/subscription.py @@ -80,7 +80,8 @@ def get_subscription(self, subscription_id: str) -> Dict: def modify_subscription(self, method: str, subscription: Subscription) -> Dict: url = self.endpoint + f"/api/{method}" - subscription.owner = self.org_name + if subscription.owner == "": + subscription.owner = self.org_name params = { "id": f"{subscription.owner}/{subscription.name}", "clientId": self.client_id, diff --git a/src/casdoor/syncer.py b/src/casdoor/syncer.py index e68ba10..e9e6c9d 100644 --- a/src/casdoor/syncer.py +++ b/src/casdoor/syncer.py @@ -100,7 +100,8 @@ def get_syncer(self, syncer_id: str) -> Dict: def modify_syncer(self, method: str, syncer: Syncer) -> Dict: url = self.endpoint + f"/api/{method}" - syncer.owner = self.org_name + if syncer.owner == "": + syncer.owner = self.org_name params = { "id": f"{syncer.owner}/{syncer.name}", "clientId": self.client_id, diff --git a/src/casdoor/token.py b/src/casdoor/token.py index 6269940..1369dd2 100644 --- a/src/casdoor/token.py +++ b/src/casdoor/token.py @@ -81,7 +81,8 @@ def get_token(self, token_id: str) -> Dict: def modify_token(self, method: str, token: Token) -> Dict: url = self.endpoint + f"/api/{method}" - token.owner = self.org_name + if token.owner == "": + token.owner = self.org_name params = { "id": f"{token.owner}/{token.name}", "clientId": self.client_id, diff --git a/src/casdoor/user.py b/src/casdoor/user.py index 1b951ed..40ba41b 100644 --- a/src/casdoor/user.py +++ b/src/casdoor/user.py @@ -117,7 +117,8 @@ def get_user_count(self, is_online: bool = None) -> int: def modify_user(self, method: str, user: User) -> Dict: url = self.endpoint + f"/api/{method}" - user.owner = self.org_name + if user.owner == "": + user.owner = self.org_name params = { "id": f"{user.owner}/{user.name}", "clientId": self.client_id, diff --git a/src/casdoor/webhook.py b/src/casdoor/webhook.py index cb654e9..4f40308 100644 --- a/src/casdoor/webhook.py +++ b/src/casdoor/webhook.py @@ -86,7 +86,8 @@ def get_webhook(self, webhook_id: str) -> Dict: def modify_webhook(self, method: str, webhook: Webhook) -> Dict: url = self.endpoint + f"/api/{method}" - webhook.owner = self.org_name + if webhook.owner == "": + webhook.owner = self.org_name params = { "id": f"{webhook.owner}/{webhook.name}", "clientId": self.client_id, diff --git a/src/tests/test_application.py b/src/tests/test_application.py new file mode 100644 index 0000000..bf5deec --- /dev/null +++ b/src/tests/test_application.py @@ -0,0 +1,96 @@ +# Copyright 2023 The Casdoor Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest +import datetime + +from src.casdoor import CasdoorSDK +from src.casdoor.application import Application +from src.tests.test_util import ( + get_random_name, + TestEndpoint, + TestClientId, + TestClientSecret, + TestJwtPublicKey, + TestOrganization, + TestApplication, +) + + +class ApplicationTest(unittest.TestCase): + def test_application(self): + name = get_random_name("application") + + # Add a new object + application = Application.new( + owner="admin", + name=name, + created_time=datetime.datetime.now().isoformat(), + display_name=name, + logo="https://cdn.casbin.org/img/casdoor-logo_1185x256.png", + homepage_url="https://casdoor.org", + description="Casdoor Website", + organization="casbin", + ) + + sdk = CasdoorSDK( + TestEndpoint, TestClientId, TestClientSecret, TestJwtPublicKey, TestOrganization, TestApplication + ) + try: + sdk.add_application(application=application) + except Exception as e: + self.fail(f"Failed to add object: {e}") + + # Get all objects, check if our added object is inside the list + try: + applications = sdk.get_applications() + except Exception as e: + self.fail(f"Failed to get objects: {e}") + names = [item.name for item in applications] + self.assertIn(name, names, "Added object not found in list") + + # Get the object + try: + application = sdk.get_application(name) + except Exception as e: + self.fail(f"Failed to get object: {e}") + self.assertEqual(application.name, name) + + # Update the object + updated_description = "Updated Casdoor Website" + application.description = updated_description + try: + sdk.update_application(application) + except Exception as e: + self.fail(f"Failed to update object: {e}") + + # Validate the update + try: + updated_application = sdk.get_application(name) + except Exception as e: + self.fail(f"Failed to get updated object: {e}") + self.assertEqual(updated_application.description, updated_description) + + # Delete the object + try: + sdk.delete_application(application) + except Exception as e: + self.fail(f"Failed to delete object: {e}") + + # Validate the deletion + try: + deleted_application = sdk.get_application(name) + except Exception as e: + self.fail(f"Failed to get object: {e}") + self.assertIsNone(deleted_application, "Failed to delete object, it's still retrievable") diff --git a/src/tests/test_util.py b/src/tests/test_util.py new file mode 100644 index 0000000..d41ac96 --- /dev/null +++ b/src/tests/test_util.py @@ -0,0 +1,60 @@ +# Copyright 2023 The Casdoor Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import random + +TestEndpoint = "https://demo.casdoor.com" +TestClientId = "294b09fbc17f95daf2fe" +TestClientSecret = "dd8982f7046ccba1bbd7851d5c1ece4e52bf039d" +TestOrganization = "casbin" +TestApplication = "app-vue-python-example" +TestJwtPublicKey = """-----BEGIN CERTIFICATE----- +MIIE+TCCAuGgAwIBAgIDAeJAMA0GCSqGSIb3DQEBCwUAMDYxHTAbBgNVBAoTFENh +c2Rvb3IgT3JnYW5pemF0aW9uMRUwEwYDVQQDEwxDYXNkb29yIENlcnQwHhcNMjEx +MDE1MDgxMTUyWhcNNDExMDE1MDgxMTUyWjA2MR0wGwYDVQQKExRDYXNkb29yIE9y +Z2FuaXphdGlvbjEVMBMGA1UEAxMMQ2FzZG9vciBDZXJ0MIICIjANBgkqhkiG9w0B +AQEFAAOCAg8AMIICCgKCAgEAsInpb5E1/ym0f1RfSDSSE8IR7y+lw+RJjI74e5ej +rq4b8zMYk7HeHCyZr/hmNEwEVXnhXu1P0mBeQ5ypp/QGo8vgEmjAETNmzkI1NjOQ +CjCYwUrasO/f/MnI1C0j13vx6mV1kHZjSrKsMhYY1vaxTEP3+VB8Hjg3MHFWrb07 +uvFMCJe5W8+0rKErZCKTR8+9VB3janeBz//zQePFVh79bFZate/hLirPK0Go9P1g +OvwIoC1A3sarHTP4Qm/LQRt0rHqZFybdySpyWAQvhNaDFE7mTstRSBb/wUjNCUBD +PTSLVjC04WllSf6Nkfx0Z7KvmbPstSj+btvcqsvRAGtvdsB9h62Kptjs1Yn7GAuo +I3qt/4zoKbiURYxkQJXIvwCQsEftUuk5ew5zuPSlDRLoLByQTLbx0JqLAFNfW3g/ +pzSDjgd/60d6HTmvbZni4SmjdyFhXCDb1Kn7N+xTojnfaNkwep2REV+RMc0fx4Gu +hRsnLsmkmUDeyIZ9aBL9oj11YEQfM2JZEq+RVtUx+wB4y8K/tD1bcY+IfnG5rBpw +IDpS262boq4SRSvb3Z7bB0w4ZxvOfJ/1VLoRftjPbLIf0bhfr/AeZMHpIKOXvfz4 +yE+hqzi68wdF0VR9xYc/RbSAf7323OsjYnjjEgInUtRohnRgCpjIk/Mt2Kt84Kb0 +wn8CAwEAAaMQMA4wDAYDVR0TAQH/BAIwADANBgkqhkiG9w0BAQsFAAOCAgEAn2lf +DKkLX+F1vKRO/5gJ+Plr8P5NKuQkmwH97b8CS2gS1phDyNgIc4/LSdzuf4Awe6ve +C06lVdWSIis8UPUPdjmT2uMPSNjwLxG3QsrimMURNwFlLTfRem/heJe0Zgur9J1M +8haawdSdJjH2RgmFoDeE2r8NVRfhbR8KnCO1ddTJKuS1N0/irHz21W4jt4rxzCvl +2nR42Fybap3O/g2JXMhNNROwZmNjgpsF7XVENCSuFO1jTywLaqjuXCg54IL7XVLG +omKNNNcc8h1FCeKj/nnbGMhodnFWKDTsJcbNmcOPNHo6ixzqMy/Hqc+mWYv7maAG +Jtevs3qgMZ8F9Qzr3HpUc6R3ZYYWDY/xxPisuKftOPZgtH979XC4mdf0WPnOBLqL +2DJ1zaBmjiGJolvb7XNVKcUfDXYw85ZTZQ5b9clI4e+6bmyWqQItlwt+Ati/uFEV +XzCj70B4lALX6xau1kLEpV9O1GERizYRz5P9NJNA7KoO5AVMp9w0DQTkt+LbXnZE +HHnWKy8xHQKZF9sR7YBPGLs/Ac6tviv5Ua15OgJ/8dLRZ/veyFfGo2yZsI+hKVU5 +nCCJHBcAyFnm1hdvdwEdH33jDBjNB6ciotJZrf/3VYaIWSalADosHAgMWfXuWP+h +8XKXmzlxuHbTMQYtZPDgspS5aK+S4Q9wb8RRAYo= +-----END CERTIFICATE-----""" + + +def get_random_code(length): + std_nums = "0123456789" + result = "".join(random.choice(std_nums) for _ in range(length)) + return result + + +def get_random_name(prefix): + return f"{prefix}_{get_random_code(6)}"