Skip to content

Commit 365a59c

Browse files
committed
Added pydantic models to the project
1 parent a5585dc commit 365a59c

25 files changed

+2048
-54
lines changed

.env.example

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
1-
MY_NAME=Dmitrii
21
DOMAIN=https://demoqa.com

lib/constants/__init__.py

Whitespace-only changes.

lib/constants/routes.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
class Routes:
2+
account_authorized = "/Account/v1/Authorized"
3+
account_generate_token = "/Account/v1/GenerateToken"
4+
account_user = "/Account/v1/User"
5+
bookstore_books = "/BookStore/v1/Books"
6+
bookstore_book = "/BookStore/v1/Book"

lib/helpers/bookstore_helper.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from playwright.sync_api import APIRequestContext
22

3+
from lib.serializers.models.all_books_modal import AllBooksModal
4+
35

46
class BookstoreHelper:
57
def __init__(self, request_context: APIRequestContext):
@@ -9,4 +11,8 @@ def __init__(self, request_context: APIRequestContext):
911

1012
def get_books(self):
1113
response = self.request.get(self.get_books_url)
12-
return response
14+
books = response.json()
15+
16+
AllBooksModal.model_validate(books)
17+
18+
return books

lib/helpers/user_helper.py

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,30 @@
11
from typing import Generator
2+
23
import pytest
34
from playwright.sync_api import Playwright, APIRequestContext
45

6+
from lib.serializers.models.login_view_model import LoginViewModel
7+
from lib.serializers.models.register_view_model import RegisterViewModel
8+
59

610
class UserHelper:
711
@pytest.fixture(scope="session")
8-
def api_request_context(
9-
self: Playwright, base_url
10-
) -> Generator[APIRequestContext, None, None]:
12+
def api_request_context(self: Playwright, base_url) -> Generator[APIRequestContext, None, None]:
1113
request_context = self.request.new_context(base_url=base_url)
1214
yield request_context
1315
request_context.dispose()
1416

1517
@staticmethod
16-
def register_new_user(api_request_context: APIRequestContext, username, password):
17-
payload = {
18-
"userName": username,
19-
"password": password
20-
}
21-
new_user = api_request_context.post("/Account/v1/User", form=payload)
22-
assert new_user.ok
18+
def register_new_user(api_request_context: APIRequestContext, username, password, successful=True):
19+
user = RegisterViewModel(user_name=username, password=password)
20+
response = api_request_context.post("/Account/v1/User", form=user.model_dump(by_alias=True))
21+
22+
if successful:
23+
assert response.status == 201
24+
return response.json()
2325

2426
@staticmethod
2527
def login_to_bookstore(api_request_context: APIRequestContext, username, password):
26-
payload = {
27-
"userName": username,
28-
"password": password
29-
}
30-
login = api_request_context.post("Account/v1/GenerateToken", form=payload)
28+
user = LoginViewModel(user_name=username, password=password)
29+
login = api_request_context.post("Account/v1/GenerateToken", form=user.model_dump(by_alias=True))
3130
assert login.ok

lib/serializers/__init__.py

Whitespace-only changes.

lib/serializers/models/__init__.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# coding: utf-8
2+
3+
# flake8: noqa
4+
"""
5+
Book Store API
6+
7+
Book Store Web API
8+
9+
The version of the OpenAPI document: v1
10+
Generated by OpenAPI Generator (https://openapi-generator.tech)
11+
12+
Do not edit the class manually.
13+
""" # noqa: E501
14+
15+
# import models into model package
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# coding: utf-8
2+
3+
"""
4+
Book Store API
5+
6+
Book Store Web API
7+
8+
The version of the OpenAPI document: v1
9+
Generated by OpenAPI Generator (https://openapi-generator.tech)
10+
11+
Do not edit the class manually.
12+
""" # noqa: E501
13+
14+
from __future__ import annotations
15+
16+
import json
17+
import pprint
18+
import re # noqa: F401
19+
from typing import Any, ClassVar, Dict, List, Optional
20+
21+
from pydantic import BaseModel, StrictStr
22+
from pydantic import Field
23+
24+
from lib.serializers.models.collection_of_isbn import CollectionOfIsbn
25+
26+
try:
27+
from typing import Self
28+
except ImportError:
29+
from typing_extensions import Self
30+
31+
32+
class AddListOfBooks(BaseModel):
33+
"""
34+
35+
""" # noqa: E501
36+
user_id: Optional[StrictStr] = Field(default=None, alias="userId")
37+
collection_of_isbns: Optional[List[CollectionOfIsbn]] = Field(default=None, alias="collectionOfIsbns")
38+
__properties: ClassVar[List[str]] = ["userId", "collectionOfIsbns"]
39+
40+
model_config = {
41+
"populate_by_name": True,
42+
"validate_assignment": True,
43+
"protected_namespaces": (),
44+
}
45+
46+
def to_str(self) -> str:
47+
"""Returns the string representation of the model using alias"""
48+
return pprint.pformat(self.model_dump(by_alias=True))
49+
50+
def to_json(self) -> str:
51+
"""Returns the JSON representation of the model using alias"""
52+
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
53+
return json.dumps(self.to_dict())
54+
55+
@classmethod
56+
def from_json(cls, json_str: str) -> Self:
57+
"""Create an instance of AddListOfBooks from a JSON string"""
58+
return cls.from_dict(json.loads(json_str))
59+
60+
def to_dict(self) -> Dict[str, Any]:
61+
"""Return the dictionary representation of the model using alias.
62+
63+
This has the following differences from calling pydantic's
64+
`self.model_dump(by_alias=True)`:
65+
66+
* `None` is only added to the output dict for nullable fields that
67+
were set at model initialization. Other fields with value `None`
68+
are ignored.
69+
"""
70+
_dict = self.model_dump(
71+
by_alias=True,
72+
exclude={
73+
},
74+
exclude_none=True,
75+
)
76+
# override the default output from pydantic by calling `to_dict()` of each item in collection_of_isbns (list)
77+
_items = []
78+
if self.collection_of_isbns:
79+
for _item in self.collection_of_isbns:
80+
if _item:
81+
_items.append(_item.to_dict())
82+
_dict['collectionOfIsbns'] = _items
83+
return _dict
84+
85+
@classmethod
86+
def from_dict(cls, obj: Dict) -> Self:
87+
"""Create an instance of AddListOfBooks from a dict"""
88+
if obj is None:
89+
return None
90+
91+
if not isinstance(obj, dict):
92+
return cls.model_validate(obj)
93+
94+
_obj = cls.model_validate({
95+
"userId": obj.get("userId"),
96+
"collectionOfIsbns": [CollectionOfIsbn.from_dict(_item) for _item in
97+
obj.get("collectionOfIsbns")] if obj.get("collectionOfIsbns") is not None else None
98+
})
99+
return _obj
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# coding: utf-8
2+
3+
"""
4+
Book Store API
5+
6+
Book Store Web API
7+
8+
The version of the OpenAPI document: v1
9+
Generated by OpenAPI Generator (https://openapi-generator.tech)
10+
11+
Do not edit the class manually.
12+
""" # noqa: E501
13+
14+
from __future__ import annotations
15+
16+
import json
17+
import pprint
18+
import re # noqa: F401
19+
from typing import Any, ClassVar, Dict, List, Optional
20+
21+
from pydantic import BaseModel
22+
23+
from lib.serializers.models.book_modal import BookModal
24+
25+
try:
26+
from typing import Self
27+
except ImportError:
28+
from typing_extensions import Self
29+
30+
31+
class AllBooksModal(BaseModel):
32+
"""
33+
34+
""" # noqa: E501
35+
books: Optional[List[BookModal]] = None
36+
__properties: ClassVar[List[str]] = ["books"]
37+
38+
model_config = {
39+
"populate_by_name": True,
40+
"validate_assignment": True,
41+
"protected_namespaces": (),
42+
}
43+
44+
def to_str(self) -> str:
45+
"""Returns the string representation of the model using alias"""
46+
return pprint.pformat(self.model_dump(by_alias=True))
47+
48+
def to_json(self) -> str:
49+
"""Returns the JSON representation of the model using alias"""
50+
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
51+
return json.dumps(self.to_dict())
52+
53+
@classmethod
54+
def from_json(cls, json_str: str) -> Self:
55+
"""Create an instance of AllBooksModal from a JSON string"""
56+
return cls.from_dict(json.loads(json_str))
57+
58+
def to_dict(self) -> Dict[str, Any]:
59+
"""Return the dictionary representation of the model using alias.
60+
61+
This has the following differences from calling pydantic's
62+
`self.model_dump(by_alias=True)`:
63+
64+
* `None` is only added to the output dict for nullable fields that
65+
were set at model initialization. Other fields with value `None`
66+
are ignored.
67+
"""
68+
_dict = self.model_dump(
69+
by_alias=True,
70+
exclude={
71+
},
72+
exclude_none=True,
73+
)
74+
# override the default output from pydantic by calling `to_dict()` of each item in books (list)
75+
_items = []
76+
if self.books:
77+
for _item in self.books:
78+
if _item:
79+
_items.append(_item.to_dict())
80+
_dict['books'] = _items
81+
return _dict
82+
83+
@classmethod
84+
def from_dict(cls, obj: Dict) -> Self:
85+
"""Create an instance of AllBooksModal from a dict"""
86+
if obj is None:
87+
return None
88+
89+
if not isinstance(obj, dict):
90+
return cls.model_validate(obj)
91+
92+
_obj = cls.model_validate({
93+
"books": [BookModal.from_dict(_item) for _item in obj.get("books")] if obj.get(
94+
"books") is not None else None
95+
})
96+
return _obj

lib/serializers/models/book_modal.py

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
# coding: utf-8
2+
3+
"""
4+
Book Store API
5+
6+
Book Store Web API
7+
8+
The version of the OpenAPI document: v1
9+
Generated by OpenAPI Generator (https://openapi-generator.tech)
10+
11+
Do not edit the class manually.
12+
""" # noqa: E501
13+
14+
from __future__ import annotations
15+
16+
import json
17+
import pprint
18+
import re # noqa: F401
19+
from datetime import datetime
20+
from typing import Any, ClassVar, Dict, List, Optional, Union
21+
22+
from pydantic import BaseModel, StrictFloat, StrictInt, StrictStr
23+
from pydantic import Field
24+
25+
try:
26+
from typing import Self
27+
except ImportError:
28+
from typing_extensions import Self
29+
30+
31+
class BookModal(BaseModel):
32+
"""
33+
34+
""" # noqa: E501
35+
isbn: Optional[StrictStr] = None
36+
title: Optional[StrictStr] = None
37+
sub_title: Optional[StrictStr] = Field(default=None, alias="subTitle")
38+
author: Optional[StrictStr] = None
39+
publish_date: Optional[datetime] = None
40+
publisher: Optional[StrictStr] = None
41+
pages: Optional[Union[StrictFloat, StrictInt]] = None
42+
description: Optional[StrictStr] = None
43+
website: Optional[StrictStr] = None
44+
__properties: ClassVar[List[str]] = ["isbn", "title", "subTitle", "author", "publish_date", "publisher", "pages",
45+
"description", "website"]
46+
47+
model_config = {
48+
"populate_by_name": True,
49+
"validate_assignment": True,
50+
"protected_namespaces": (),
51+
}
52+
53+
def to_str(self) -> str:
54+
"""Returns the string representation of the model using alias"""
55+
return pprint.pformat(self.model_dump(by_alias=True))
56+
57+
def to_json(self) -> str:
58+
"""Returns the JSON representation of the model using alias"""
59+
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
60+
return json.dumps(self.to_dict())
61+
62+
@classmethod
63+
def from_json(cls, json_str: str) -> Self:
64+
"""Create an instance of BookModal from a JSON string"""
65+
return cls.from_dict(json.loads(json_str))
66+
67+
def to_dict(self) -> Dict[str, Any]:
68+
"""Return the dictionary representation of the model using alias.
69+
70+
This has the following differences from calling pydantic's
71+
`self.model_dump(by_alias=True)`:
72+
73+
* `None` is only added to the output dict for nullable fields that
74+
were set at model initialization. Other fields with value `None`
75+
are ignored.
76+
"""
77+
_dict = self.model_dump(
78+
by_alias=True,
79+
exclude={
80+
},
81+
exclude_none=True,
82+
)
83+
return _dict
84+
85+
@classmethod
86+
def from_dict(cls, obj: Dict) -> Self:
87+
"""Create an instance of BookModal from a dict"""
88+
if obj is None:
89+
return None
90+
91+
if not isinstance(obj, dict):
92+
return cls.model_validate(obj)
93+
94+
_obj = cls.model_validate({
95+
"isbn": obj.get("isbn"),
96+
"title": obj.get("title"),
97+
"subTitle": obj.get("subTitle"),
98+
"author": obj.get("author"),
99+
"publish_date": obj.get("publish_date"),
100+
"publisher": obj.get("publisher"),
101+
"pages": obj.get("pages"),
102+
"description": obj.get("description"),
103+
"website": obj.get("website")
104+
})
105+
return _obj

0 commit comments

Comments
 (0)