Skip to content

Commit

Permalink
feat: add test cases for organization and group (#76)
Browse files Browse the repository at this point in the history
* test of application, orgnization and group succ

* design a function that dumps customized object to json data, just change for group class

* ci correction

* yes

* yes

* yes

* yes

* yes

* black correction

* Delete .vscode/launch.json

* Delete .vscode/settings.json

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
  • Loading branch information
xiao-kong-long and hsluoyz committed Nov 30, 2023
1 parent c355420 commit 4319243
Show file tree
Hide file tree
Showing 6 changed files with 308 additions and 22 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,7 @@ dmypy.json
.pyre/

.idea
.pytest_cache
.pytest_cache

# Vscode
.vscode
6 changes: 3 additions & 3 deletions src/casdoor/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ def get_applications(self) -> List[Application]:
r = requests.get(url, params)
response = r.json()
if response["status"] != "ok":
raise ValueError(response.msg)
raise ValueError(response["msg"])

res = []
for element in response["data"]:
Expand All @@ -166,7 +166,7 @@ def get_application(self, application_id: str) -> Application:
r = requests.get(url, params)
response = r.json()
if response["status"] != "ok":
raise ValueError(response.msg)
raise ValueError(response["msg"])
return Application.from_dict(response["data"])

def modify_application(self, method: str, application: Application) -> str:
Expand All @@ -182,7 +182,7 @@ def modify_application(self, method: str, application: Application) -> str:
r = requests.post(url, params=params, data=application_info)
response = r.json()
if response["status"] != "ok":
raise ValueError(response.msg)
raise ValueError(response["msg"])
return str(response["data"])

def add_application(self, application: Application) -> str:
Expand Down
54 changes: 46 additions & 8 deletions src/casdoor/group.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,25 @@ def __init__(self):
self.children = [Group]
self.isEnabled = False

@classmethod
def new(cls, owner, name, created_time, display_name):
self = cls()
self.owner = owner
self.name = name
self.createdTime = created_time
self.displayName = display_name
return self

@classmethod
def from_dict(cls, data: dict):
if not data:
return None
group = cls()
for key, value in data.items():
if hasattr(group, key):
setattr(group, key, value)
return group

def __str__(self):
return str(self.__dict__)

Expand All @@ -59,8 +78,15 @@ def get_groups(self) -> List[Dict]:
"clientSecret": self.client_secret,
}
r = requests.get(url, params)
groups = r.json()
return groups
response = r.json()
if response["status"] != "ok":
raise ValueError(response["msg"])

res = []
for element in response["data"]:
res.append(Group.from_dict(element))

return res

def get_group(self, group_id: str) -> Dict:
"""
Expand All @@ -76,22 +102,30 @@ def get_group(self, group_id: str) -> Dict:
"clientSecret": self.client_secret,
}
r = requests.get(url, params)
group = r.json()
return group
response = r.json()
if response["status"] != "ok":
raise ValueError(response["msg"])
return Group.from_dict(response["data"])

def modify_group(self, method: str, group: Group) -> Dict:
url = self.endpoint + f"/api/{method}"
if group.owner == "":
group.owner = self.org_name
# if group.owner == "":
# group.owner = self.org_name
group.owner = self.org_name
params = {
"id": f"{group.owner}/{group.name}",
"clientId": self.client_id,
"clientSecret": self.client_secret,
}
group_info = json.dumps(group.to_dict())

# group_info = json.dumps(group.to_dict())
group_info = json.dumps(group.to_dict(), default=self.custom_encoder)
r = requests.post(url, params=params, data=group_info)
response = r.json()
return response
if response["status"] != "ok":
raise ValueError(response["msg"])

return str(response["data"])

def add_group(self, group: Group) -> Dict:
response = self.modify_group("add-group", group)
Expand All @@ -104,3 +138,7 @@ def update_group(self, group: Group) -> Dict:
def delete_group(self, group: Group) -> Dict:
response = self.modify_group("delete-group", group)
return response

def custom_encoder(self, o):
if isinstance(o, (Group, User)):
return o.__dict__
76 changes: 66 additions & 10 deletions src/casdoor/organization.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,58 @@ def __init__(self):
self.defaultApplication = ""
self.tags = [""]
self.languages = [""]
self.themeData = ThemeData
# self.themeData = ThemeData
self.masterPassword = ""
self.initScore = 0
self.enableSoftDeletion = False
self.isProfilePublic = False
self.mfaItems = [MfaItem]
self.accountItems = [AccountItem]
# self.mfaItems = [MfaItem]
# self.accountItems = [AccountItem]

@classmethod
def new(
cls,
owner,
name,
created_time,
display_name,
website_url,
password_type,
password_options,
country_codes,
tags,
languages,
init_score,
enable_soft_deletion,
is_profile_public,
):
self = cls()
self.owner = owner
self.name = name
self.createdTime = created_time
self.displayName = display_name
self.websiteUrl = website_url
self.passwordType = password_type
self.passwordOptions = password_options
self.countryCodes = country_codes
self.tags = tags
self.languages = languages
self.initScore = init_score
self.enableSoftDeletion = enable_soft_deletion
self.isProfilePublic = is_profile_public

return self

@classmethod
def from_dict(cls, data: dict):
if data is None:
return None

org = cls()
for key, value in data.items():
if hasattr(org, key):
setattr(org, key, value)
return org

def __str__(self):
return str(self.__dict__)
Expand All @@ -104,8 +149,14 @@ def get_organizations(self) -> List[Dict]:
"clientSecret": self.client_secret,
}
r = requests.get(url, params)
organizations = r.json()
return organizations
response = r.json()
if response["status"] != "ok":
raise ValueError(response.msg)

res = []
for element in response["data"]:
res.append(Organization.from_dict(element))
return res

def get_organization(self, organization_id: str) -> Dict:
"""
Expand All @@ -121,13 +172,16 @@ def get_organization(self, organization_id: str) -> Dict:
"clientSecret": self.client_secret,
}
r = requests.get(url, params)
organization = r.json()
return organization
response = r.json()
if response["status"] != "ok":
raise ValueError(response.msg)
return Organization.from_dict(response["data"])

def modify_organization(self, method: str, organization: Organization) -> Dict:
url = self.endpoint + f"/api/{method}"
if organization.owner == "":
organization.owner = self.org_name
# if organization.owner == "":
# organization.owner = self.org_name
organization.owner = self.org_name
params = {
"id": f"{organization.owner}/{organization.name}",
"clientId": self.client_id,
Expand All @@ -136,7 +190,9 @@ def modify_organization(self, method: str, organization: Organization) -> Dict:
organization_info = json.dumps(organization.to_dict())
r = requests.post(url, params=params, data=organization_info)
response = r.json()
return response
if response["status"] != "ok":
raise ValueError(response)
return str(response["data"])

def add_organization(self, organization: Organization) -> Dict:
response = self.modify_organization("add-organization", organization)
Expand Down
90 changes: 90 additions & 0 deletions src/tests/test_group.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# 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 datetime
import unittest

from src.casdoor import CasdoorSDK
from src.casdoor.group import Group
from src.tests.test_util import (
TestApplication,
TestClientId,
TestClientSecret,
TestEndpoint,
TestJwtPublicKey,
TestOrganization,
get_random_name,
)


class GroupTest(unittest.TestCase):
def test_group(self):
name = get_random_name("group")

# Add a new object
group = Group.new(owner="admin", name=name, created_time=datetime.datetime.now().isoformat(), display_name=name)

sdk = CasdoorSDK(
TestEndpoint, TestClientId, TestClientSecret, TestJwtPublicKey, TestOrganization, TestApplication
)

try:
sdk.add_group(group)
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:
groups = sdk.get_groups()
except Exception as e:
self.fail(f"Failed to get objects: {e}")
names = [item.name for item in groups]
self.assertIn(name, names, "Added object not found in list")

# Get the object
try:
retrieved_group = sdk.get_group(name)
except Exception as e:
self.fail(f"Failed to get object: {e}")
self.assertEqual(name, retrieved_group.name, "Retrieved object does not match added object")

# Update the object
updated_display_name = "updated_display_name"
retrieved_group.displayName = updated_display_name
try:
updated_group = sdk.update_group(retrieved_group)
except Exception as e:
self.fail(f"Failed to update object: {e}")

# Validate the update
try:
updated_group = sdk.get_group(name)
except Exception as e:
self.fail(f"Failed to get object: {e}")
self.assertEqual(
updated_display_name, updated_group.displayName, "Failed to update object, display_name mismatch"
)

# Delete the object
try:
sdk.delete_group(group)
except Exception as e:
self.fail(f"Failed to delete object: {e}")

# Validate the deletion
try:
deleted_group = sdk.get_group(name)
except Exception as e:
self.fail(f"Failed to get object: {e}")
self.assertIsNone(deleted_group, "Failed to delete object, it's still retrievable")
Loading

0 comments on commit 4319243

Please sign in to comment.