|
| 1 | +"""Tests for the mongo_object_id module.""" |
| 2 | + |
| 3 | +import pytest |
| 4 | +from pydantic import BaseModel, GetCoreSchemaHandler, ValidationError |
| 5 | +from pydantic.json_schema import JsonSchemaMode |
| 6 | + |
| 7 | +from pydantic_extra_types.mongo_object_id import MongoObjectId |
| 8 | + |
| 9 | + |
| 10 | +class MongoDocument(BaseModel): |
| 11 | + object_id: MongoObjectId |
| 12 | + |
| 13 | + |
| 14 | +@pytest.mark.parametrize( |
| 15 | + 'object_id, result, valid', |
| 16 | + [ |
| 17 | + # Valid ObjectId for str format |
| 18 | + ('611827f2878b88b49ebb69fc', '611827f2878b88b49ebb69fc', True), |
| 19 | + ('611827f2878b88b49ebb69fd', '611827f2878b88b49ebb69fd', True), |
| 20 | + # Invalid ObjectId for str format |
| 21 | + ('611827f2878b88b49ebb69f', None, False), # Invalid ObjectId (short length) |
| 22 | + ('611827f2878b88b49ebb69fca', None, False), # Invalid ObjectId (long length) |
| 23 | + # Valid ObjectId for bytes format |
| 24 | + ], |
| 25 | +) |
| 26 | +def test_format_for_object_id(object_id: str, result: str, valid: bool) -> None: |
| 27 | + """Test the MongoObjectId validation.""" |
| 28 | + if valid: |
| 29 | + assert str(MongoDocument(object_id=object_id).object_id) == result |
| 30 | + else: |
| 31 | + with pytest.raises(ValidationError): |
| 32 | + MongoDocument(object_id=object_id) |
| 33 | + with pytest.raises( |
| 34 | + ValueError, |
| 35 | + match=f"Invalid ObjectId {object_id} has to be 24 characters long and in the format '5f9f2f4b9d3c5a7b4c7e6c1d'.", |
| 36 | + ): |
| 37 | + MongoObjectId.validate(object_id) |
| 38 | + |
| 39 | + |
| 40 | +@pytest.mark.parametrize( |
| 41 | + 'schema_mode', |
| 42 | + [ |
| 43 | + 'validation', |
| 44 | + 'serialization', |
| 45 | + ], |
| 46 | +) |
| 47 | +def test_json_schema(schema_mode: JsonSchemaMode) -> None: |
| 48 | + """Test the MongoObjectId model_json_schema implementation.""" |
| 49 | + expected_json_schema = { |
| 50 | + 'properties': { |
| 51 | + 'object_id': { |
| 52 | + 'maxLength': MongoObjectId.OBJECT_ID_LENGTH, |
| 53 | + 'minLength': MongoObjectId.OBJECT_ID_LENGTH, |
| 54 | + 'title': 'Object Id', |
| 55 | + 'type': 'string', |
| 56 | + } |
| 57 | + }, |
| 58 | + 'required': ['object_id'], |
| 59 | + 'title': 'MongoDocument', |
| 60 | + 'type': 'object', |
| 61 | + } |
| 62 | + assert MongoDocument.model_json_schema(mode=schema_mode) == expected_json_schema |
| 63 | + |
| 64 | + |
| 65 | +def test_get_pydantic_core_schema() -> None: |
| 66 | + """Test the __get_pydantic_core_schema__ method override.""" |
| 67 | + schema = MongoObjectId.__get_pydantic_core_schema__(MongoObjectId, GetCoreSchemaHandler()) |
| 68 | + assert isinstance(schema, dict) |
| 69 | + assert 'json_schema' in schema |
| 70 | + assert 'python_schema' in schema |
| 71 | + assert schema['json_schema']['type'] == 'str' |
0 commit comments