Skip to content

Commit

Permalink
Add tests for PyObjectId (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
samarpan1738 committed Dec 16, 2024
1 parent 4705106 commit ac141c5
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions todo/tests/unit/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Added this because without this file Django isn't able to auto detect the test files
1 change: 1 addition & 0 deletions todo/tests/unit/models/common/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Added this because without this file Django isn't able to auto detect the test files
44 changes: 44 additions & 0 deletions todo/tests/unit/models/common/test_pyobjectid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from unittest import TestCase
from bson import ObjectId
from pydantic import BaseModel, ValidationError

from todo.models.common.pyobjectid import PyObjectId


class PyObjectIdTests(TestCase):
def test_validate_valid_objectid(self):
valid_id = str(ObjectId())
validated = PyObjectId.validate(valid_id)
self.assertEqual(validated, ObjectId(valid_id))

def test_validate_invalid_objectid(self):
invalid_id = "invalid_objectid"
with self.assertRaises(ValueError) as context:
PyObjectId.validate(invalid_id)
self.assertIn(f"Invalid ObjectId: {invalid_id}", str(context.exception))

def test_validate_none(self):
self.assertIsNone(PyObjectId.validate(None))

def test_pydantic_json_schema(self):
field_schema = {}
PyObjectId.__get_pydantic_json_schema__(field_schema)
self.assertEqual(field_schema["type"], "string")

def test_integration_with_pydantic_model(self):
class TestModel(BaseModel):
id: PyObjectId

valid_id = str(ObjectId())
instance = TestModel(id=valid_id)
self.assertEqual(instance.id, ObjectId(valid_id))

invalid_id = "invalid_objectid"
with self.assertRaises(ValidationError) as context:
TestModel(id=invalid_id)
self.assertIn(f"Invalid ObjectId: {invalid_id}", str(context.exception))

try:
TestModel(id=None)
except ValidationError:
self.fail("ValidationError raised for None id")

0 comments on commit ac141c5

Please sign in to comment.