Skip to content

Commit

Permalink
[NEW] introduce skii test case
Browse files Browse the repository at this point in the history
  • Loading branch information
boot-sandre committed Sep 15, 2023
1 parent a19e5b7 commit c2c2929
Show file tree
Hide file tree
Showing 15 changed files with 73 additions and 66 deletions.
3 changes: 1 addition & 2 deletions skii/endpoint/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ def render(self, request, data, *, response_status):


class SkiiParser(Parser):

def parse_body(self, request: HttpRequest) -> DictStrAny:
return cast(DictStrAny, json.loads(request.body))

Expand All @@ -75,7 +74,7 @@ def parse_querydict(
"docs_decorator": staff_member_required,
"urls_namespace": "skii",
"renderer": SkiiJsonRenderer(),
"parser": SkiiParser()
"parser": SkiiParser(),
}

# Create skii app dedicated api
Expand Down
4 changes: 1 addition & 3 deletions skii/endpoint/routers/lesson.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,7 @@ def record_delete(request: HttpRequest, record_id: int | str):
422: FormInvalidResponseContract,
},
)
def record_save(
request: HttpRequest, record_id: int | str, payload: LessonContract
):
def record_save(request: HttpRequest, record_id: int | str, payload: LessonContract):
lesson_payload = payload.dict()
lesson_obj = get_object_or_404(Lesson, pk=record_id)
for attr, value in lesson_payload.items():
Expand Down
4 changes: 1 addition & 3 deletions skii/endpoint/routers/location.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ def record_delete(request: HttpRequest, record_id: int | str):
422: FormInvalidResponseContract,
},
)
def record_save(
request: HttpRequest, record_id: int | str, payload: LocationContract
):
def record_save(request: HttpRequest, record_id: int | str, payload: LocationContract):
location_payload = payload.dict()
location_obj = get_object_or_404(Location, pk=record_id)
for attr, value in location_payload.items():
Expand Down
9 changes: 5 additions & 4 deletions skii/endpoint/routers/student.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@

from apps.base.schemas import FormInvalidResponseContract
from skii.platform.models.agent import StudentAgent
from skii.platform.schemas.agent import (
StudentContract, StudentSaveContract
from skii.platform.schemas.agent import StudentContract, StudentSaveContract
from skii.endpoint.schemas.ninja import (
SkiiRecordContract,
SkiiListContract,
SkiiMsgContract,
)
from skii.endpoint.schemas.ninja import SkiiRecordContract, SkiiListContract, SkiiMsgContract


UserModel = get_user_model()
Expand Down Expand Up @@ -57,7 +59,6 @@ def fetch(request: HttpRequest, pk: int | str):
return 200, dict(data=record)



@sub_route.delete(
path="/delete/{pk}/",
response={
Expand Down
9 changes: 4 additions & 5 deletions skii/endpoint/routers/teacher.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@

from apps.base.schemas import FormInvalidResponseContract
from skii.platform.models.agent import TeacherAgent
from skii.platform.schemas.agent import (
TeacherContract, TeacherSaveContract
)
from skii.platform.schemas.agent import TeacherContract, TeacherSaveContract
from skii.endpoint.schemas.ninja import SkiiMsgContract


Expand All @@ -28,6 +26,7 @@
ListResponseContract = List[SubRouteContract]
ResponseContract = SubRouteContract


@sub_route.get(
path="/list/",
response={
Expand Down Expand Up @@ -74,9 +73,9 @@ def delete(request: HttpRequest, pk: int | str):
def update(request: HttpRequest, pk: int | str, payload: SubRouteSaveContract):
payload = payload.dict()
user_payload = payload.pop("user")
record = get_object_or_404(SubRouteModel,pk=pk)
record = get_object_or_404(SubRouteModel, pk=pk)
user_obj = get_object_or_404(UserModel, id=user_payload["id"])
for attr, value in payload.items():
for attr, value in payload.items():
setattr(record, attr, value)
record.save()
for attr, value in user_payload.items():
Expand Down
3 changes: 2 additions & 1 deletion skii/endpoint/schemas/ninja.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class SkiiMsgContract(Schema):

class IdentifierContract(Schema):
pk: Optional[UUID4]

class Config:
fields = {}

Expand Down Expand Up @@ -47,4 +48,4 @@ class FormInvalidResponseContract(Schema):
}
"""

errors: Dict[str, List[Dict[str, Any]]]
errors: Dict[str, List[Dict[str, Any]]]
8 changes: 6 additions & 2 deletions skii/platform/entities.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,8 +264,12 @@ class RessourceEntity(UUIDLabelEntity):
class Meta:
abstract = True

amount = models.DecimalField(verbose_name=_("Time ressource"), default=Deci(0.0),
max_digits=18, decimal_places=2,)
amount = models.DecimalField(
verbose_name=_("Time ressource"),
default=Deci(0.0),
max_digits=18,
decimal_places=2,
)

def __str__(self):
return f"{self.short_prefix_uuid}: {self.amount}"
1 change: 1 addition & 0 deletions skii/platform/models/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ def __str__(self) -> str:
@property
def gant_config(self):
from skii.platform.schemas.vuejs import GanttConfigContract

return GanttConfigContract(
{
"start": self.start.strftime(format="%Y-%m-%d %H:%M"),
Expand Down
9 changes: 3 additions & 6 deletions skii/platform/schemas/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,8 @@


class UserSchema(Schema):
"""Complete dj user schema generated from dj models
"""DJ user schema used to read record"""

Mostly to read records
All technicals/Identifiant fields is excluded
"""
id: Optional[int]
first_name: Optional[str]
last_name: Optional[str]
Expand All @@ -20,10 +17,11 @@ class UserSchema(Schema):


class UserSaveSchema(ModelSchema):
"""DJ user schema used to save record"""

class Config:
model = get_user_model()
model_fields = ['username', 'first_name', 'last_name']
model_fields = ["username", "first_name", "last_name"]


class StudentContract(IdentifierContract):
Expand All @@ -40,4 +38,3 @@ class StudentSaveContract(IdentifierContract):

class TeacherSaveContract(IdentifierContract):
user: UserSchema

1 change: 0 additions & 1 deletion skii/platform/schemas/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,3 @@ class LocationContract(Schema):

class LocationSaveContract(LocationContract):
country: str

4 changes: 2 additions & 2 deletions tests/account/test_api.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django.contrib.auth import get_user_model
from apps.account.utils.token import encode_token
from main.api import api
from ..testcase import NinjaTestCase
from ..testcase import SkiiTestCase
import json

PWD = "testpwd"
Expand All @@ -20,7 +20,7 @@ def test_admin_account_state(admin_client):
assert response.content == b'{"is_connected": true, "username": "admin"}'


class TestAccount(NinjaTestCase):
class TestAccount(SkiiTestCase):
def test_anonymous_account_state(self):
response = self.client.get(f"{api.root_path}account/state")
assert response.status_code == 200
Expand Down
39 changes: 9 additions & 30 deletions tests/endpoint/test_api.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,17 @@
from django.test.client import Client
from skii.endpoint.api import api_skii
from ..testcase import NinjaTestCase
from ..testcase import SkiiTestCase, SkiiClient
from skii.platform.schemas.agent import TeacherSaveContract

from skii.platform.factories.factories import (
TeacherAgentFactory,
)


class SkiiClient(Client):
pass


class TestApiAgent(NinjaTestCase):
class TestApiAgent(SkiiTestCase):
""" Basic unit testing of Agent models and schema.
"""
client_class = SkiiClient

def create_client_helper(self):
"""Create test user and log them to dedicated client."""
res = super().create_client_helper()
self.skii_client = self.client_class()
self.skii_client.force_login(self.admin_user)
return res

def link_api_helper(self):
""" Override original method to link Skii API"""
self.api = api_skii
self.root_path = self.api.root_path
self.docs_url = self.api.docs_url
self.student_route = "student"
self.teacher_route = "teacher"
self.student_url = f"{self.root_path}{self.student_route}"
self.teacher_url = f"{self.root_path}{self.teacher_route}"
api_factory = TeacherAgentFactory
api_save_contract = TeacherSaveContract

def test_agent_teacher_fetch(self):
teacher = TeacherAgentFactory.create()
Expand All @@ -43,21 +22,21 @@ def test_agent_teacher_fetch(self):
['pk', 'user'])

def test_agent_teacher_list(self):
TeacherAgentFactory.create_batch(5)
self.api_factory.create_batch(5)
response = self.skii_client.get(path=f"{self.teacher_url}/list/")
self.assertEqual(first=response.status_code,
second=200)
self.assertEqual(first=len(response.json()),
second=5)

def test_agent_teacher_delete(self):
teacher = TeacherAgentFactory.create()
teacher = self.api_factory.create()
response = self.skii_client.delete(
path=f"{self.teacher_url}/delete/{teacher.pk}/")
assert response.content == b'{"message": "OK"}'

def test_agent_teacher_create(self):
teacher = TeacherAgentFactory.create()
teacher = self.api_factory.create()
payload = TeacherSaveContract.from_orm(teacher).dict()
del payload["pk"]
del payload["user"]["id"]
Expand All @@ -72,8 +51,8 @@ def test_agent_teacher_create(self):
list2=['pk', 'user'])

def test_agent_teacher_update(self):
teacher = TeacherAgentFactory.create()
payload = TeacherSaveContract.from_orm(teacher).dict()
teacher = self.api_factory.create()
payload = self.api_save_contract.from_orm(teacher).dict()
response = self.skii_client.post(
path=f"{self.teacher_url}/update/{teacher.pk}/",
data=payload,
Expand Down
4 changes: 2 additions & 2 deletions tests/platform/test_models.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from ..testcase import NinjaTestCase
from ..testcase import SkiiTestCase

from skii.platform.factories.factories import (
TeacherAgentFactory,
StudentAgentFactory,
)


class TestAgent(NinjaTestCase):
class TestAgent(SkiiTestCase):
""" Basic unit testing of Agent models and schema.
"""
def test_agent_student_create(self):
Expand Down
4 changes: 2 additions & 2 deletions tests/test_testcase.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from .testcase import NinjaTestCase
from .testcase import SkiiTestCase


class TestNinjaTestCase(NinjaTestCase):
class TestSkiiTestCase(SkiiTestCase):
def test_get_public(self):
res = self.client.get("/")
assert res.status_code == 200
Expand Down
37 changes: 34 additions & 3 deletions tests/testcase.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from django.test import TestCase
from main.api import api
from django.test import TestCase, Client
from django.contrib.auth import get_user_model

from main.api import api as api_main
from skii.endpoint.api import api_skii


class NinjaTestCase(TestCase):
def create_client_helper(self):
Expand All @@ -19,10 +21,39 @@ def create_client_helper(self):

def link_api_helper(self):
"""Can override this method to link another project api to the test case."""
self.api = api
self.api = api_main
self.root_path = self.api.root_path
self.docs_url = self.api.docs_url

def setUp(self):
self.create_client_helper()
self.link_api_helper()


class SkiiClient(Client):
pass


class SkiiTestCase(NinjaTestCase):
client_class = SkiiClient
api_factory = None
api_save_contract = None

def create_client_helper(self):
"""Create test user and log them to dedicated client."""
res = super().create_client_helper()
self.skii_client = self.client_class()
self.skii_client.force_login(self.admin_user)
return res

def link_api_helper(self):
""" Override original method to link Skii API"""
self.api = api_skii
self.root_path = self.api.root_path
self.docs_url = self.api.docs_url
self.student_route = "student"
self.teacher_route = "teacher"
self.student_url = f"{self.root_path}{self.student_route}"
self.teacher_url = f"{self.root_path}{self.teacher_route}"


0 comments on commit c2c2929

Please sign in to comment.