forked from superdesk/superdesk-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Improvements to unify the functionality from decorator &
Dataclass
…
…in a single class (superdesk#2764) * Enhance `Dataclass` to unify decorator and class The intention is to avoid having both the `dataclass` decorator and the `Dataclass` which feels a bit redundant. * Add types * Minor adjustments and add tests
- Loading branch information
Showing
2 changed files
with
72 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
from unittest import TestCase | ||
|
||
from pydantic_core import ValidationError | ||
from superdesk.core.resources import Dataclass | ||
|
||
|
||
class RingBearer(Dataclass): | ||
name: str | ||
race: str | ||
|
||
|
||
class DataclassTest(TestCase): | ||
def test_dataclass_model_proper_types(self): | ||
frodo = RingBearer(name="Frodo", race="Hobbit") | ||
frodo_from_dict = RingBearer.from_dict(dict(name="Frodo", race="Hobbit")) | ||
frodo_from_json = RingBearer.from_json('{"name":"Frodo","race":"Hobbit"}') | ||
|
||
self.assertEqual(type(frodo), RingBearer) | ||
self.assertEqual(type(frodo_from_dict), RingBearer) | ||
self.assertEqual(type(frodo_from_json), RingBearer) | ||
|
||
def test_dataclass_model_utils(self): | ||
frodo = RingBearer(name="Frodo", race="Hobbit") | ||
|
||
self.assertEqual(frodo.to_dict(), {"name": "Frodo", "race": "Hobbit"}) | ||
self.assertEqual(frodo.to_json(), '{"name":"Frodo","race":"Hobbit"}') | ||
|
||
def test_dataclass_validation_error(self): | ||
with self.assertRaises(ValidationError, msg="1 validation error for RingBearer"): | ||
RingBearer(name="Frodo") | ||
|
||
with self.assertRaises(ValidationError): | ||
RingBearer(name=1, race="Hobbit") | ||
|
||
def test_dataclass_should_validate_on_assignment(self): | ||
with self.assertRaises(ValidationError): | ||
frodo = RingBearer(name="Frodo", race="Hobbit") | ||
frodo.name = 1 |