|
1 | 1 | from enum import Enum |
| 2 | +from typing import Annotated |
2 | 3 |
|
3 | 4 | import pytest |
4 | 5 | from models_library.utils.common_validators import ( |
5 | 6 | create_enums_pre_validator, |
6 | 7 | empty_str_to_none_pre_validator, |
7 | 8 | none_to_empty_str_pre_validator, |
8 | 9 | null_or_none_str_to_none_validator, |
| 10 | + trim_string_before, |
9 | 11 | ) |
10 | 12 | from pydantic import BaseModel, ValidationError, field_validator |
11 | 13 |
|
@@ -89,3 +91,33 @@ class Model(BaseModel): |
89 | 91 |
|
90 | 92 | model = Model.model_validate({"message": ""}) |
91 | 93 | assert model == Model.model_validate({"message": ""}) |
| 94 | + |
| 95 | + |
| 96 | +def test_trim_string_before(): |
| 97 | + max_length = 10 |
| 98 | + |
| 99 | + class ModelWithTrim(BaseModel): |
| 100 | + text: Annotated[str, trim_string_before(max_length=max_length)] |
| 101 | + |
| 102 | + # Test with string shorter than max_length |
| 103 | + short_text = "Short" |
| 104 | + model = ModelWithTrim(text=short_text) |
| 105 | + assert model.text == short_text |
| 106 | + |
| 107 | + # Test with string equal to max_length |
| 108 | + exact_text = "1234567890" # 10 characters |
| 109 | + model = ModelWithTrim(text=exact_text) |
| 110 | + assert model.text == exact_text |
| 111 | + |
| 112 | + # Test with string longer than max_length |
| 113 | + long_text = "This is a very long text that should be trimmed" |
| 114 | + model = ModelWithTrim(text=long_text) |
| 115 | + assert model.text == long_text[:max_length] |
| 116 | + assert len(model.text) == max_length |
| 117 | + |
| 118 | + # Test with non-string value (should be left unchanged) |
| 119 | + class ModelWithTrimOptional(BaseModel): |
| 120 | + text: Annotated[str | None, trim_string_before(max_length=max_length)] |
| 121 | + |
| 122 | + model = ModelWithTrimOptional(text=None) |
| 123 | + assert model.text is None |
0 commit comments