|
| 1 | +import logging |
| 2 | + |
| 3 | +import pytest |
| 4 | +from models_library.rest_filters import Filters, FiltersQueryParameters |
| 5 | +from pydantic import Extra, ValidationError |
| 6 | + |
| 7 | + |
| 8 | +# 1. create filter model |
| 9 | +class CustomFilter(Filters): |
| 10 | + is_trashed: bool | None = None |
| 11 | + is_hidden: bool | None = None |
| 12 | + |
| 13 | + |
| 14 | +class CustomFilterStrict(CustomFilter): |
| 15 | + class Config(CustomFilter.Config): |
| 16 | + extra = Extra.forbid |
| 17 | + |
| 18 | + |
| 19 | +def test_custom_filter_query_parameters(): |
| 20 | + |
| 21 | + # 2. use generic as query parameters |
| 22 | + logging.info( |
| 23 | + "json schema is for the query \n %s", |
| 24 | + FiltersQueryParameters[CustomFilter].schema_json(indent=1), |
| 25 | + ) |
| 26 | + |
| 27 | + # lets filter only is_trashed and unset is_hidden |
| 28 | + custom_filter = CustomFilter(is_trashed=True) |
| 29 | + assert custom_filter.json() == '{"is_trashed": true, "is_hidden": null}' |
| 30 | + |
| 31 | + # default to None (optional) |
| 32 | + query_param = FiltersQueryParameters[CustomFilter]() |
| 33 | + assert query_param.filters is None |
| 34 | + |
| 35 | + |
| 36 | +@pytest.mark.parametrize( |
| 37 | + "url_query_value,expects", |
| 38 | + [ |
| 39 | + ('{"is_trashed": true, "is_hidden": null}', CustomFilter(is_trashed=True)), |
| 40 | + ('{"is_trashed": true}', CustomFilter(is_trashed=True)), |
| 41 | + (None, None), |
| 42 | + ], |
| 43 | +) |
| 44 | +def test_valid_filter_queries( |
| 45 | + url_query_value: str | None, expects: CustomFilter | None |
| 46 | +): |
| 47 | + query_param = FiltersQueryParameters[CustomFilter](filters=url_query_value) |
| 48 | + assert query_param.filters == expects |
| 49 | + |
| 50 | + |
| 51 | +def test_invalid_filter_query_is_ignored(): |
| 52 | + # NOTE: invalid filter get ignored! |
| 53 | + url_query_value = '{"undefined_filter": true, "is_hidden": true}' |
| 54 | + |
| 55 | + query_param = FiltersQueryParameters[CustomFilter](filters=url_query_value) |
| 56 | + assert query_param.filters == CustomFilter(is_hidden=True) |
| 57 | + |
| 58 | + |
| 59 | +@pytest.mark.xfail |
| 60 | +def test_invalid_filter_query_fails(): |
| 61 | + # NOTE: this should fail according to pydantic manual but it does not |
| 62 | + url_query_value = '{"undefined_filter": true, "is_hidden": true}' |
| 63 | + |
| 64 | + with pytest.raises(ValidationError): |
| 65 | + FiltersQueryParameters[CustomFilterStrict](filters=url_query_value) |
0 commit comments