Skip to content

Commit aa9bfe0

Browse files
committed
increase test coverage
1 parent 218e9ea commit aa9bfe0

File tree

7 files changed

+85
-10
lines changed

7 files changed

+85
-10
lines changed

ellar/core/conf/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def set_defaults(self, **kwargs: t.Any) -> "Config":
5050
self._data.setdefault(k, v)
5151
return self
5252

53-
def __repr__(self) -> str:
53+
def __repr__(self) -> str: # pragma: no cover
5454
hidden_values = {key: "..." for key in self._data.keys()}
5555
return f"<Configuration {repr(hidden_values)}, settings_module: {self.config_module}>"
5656

ellar/core/conf/mixins.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,9 @@ def validate(cls: t.Type["TExceptionHandler"], v: t.Any) -> t.Any:
5252
return v
5353

5454
if inspect.isclass(v):
55-
raise ValueError(f"Expected TExceptionHandler, received: {v}")
55+
raise ValueError(f"Expected 'ExceptionHandler', received: {v}")
5656

57-
raise ValueError(f"Expected TExceptionHandler, received: {type(v)}")
57+
raise ValueError(f"Expected 'ExceptionHandler', received: {type(v)}")
5858

5959

6060
class TVersioning(BaseAPIVersioning):
@@ -81,7 +81,9 @@ def __get_validators__(
8181
@classmethod
8282
def validate(cls: t.Type["Middleware"], v: t.Any) -> t.Any:
8383
if not isinstance(v, Middleware):
84-
raise ValueError(f"Expected Middleware, received: {type(v)}")
84+
raise ValueError(
85+
f"Expected Type/instance of Middleware, received: {type(v)}"
86+
)
8587
return v
8688

8789

tests/test_cache/test_operation_cache.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,9 @@ async def homepage():
5353
mr,
5454
]
5555
).get_client()
56-
5756
res = client.get("/index")
57+
for i in range(2):
58+
res = client.get("/index")
5859

5960
assert res.json() == dict(message="Response Information cached Async")
6061
assert res.status_code == 200

tests/test_conf/test_default_conf.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,18 +93,30 @@ def test_configuration_settings_can_be_loaded_through_constructor():
9393
assert config.REDIRECT_SLASHES is True
9494
assert config.STATIC_MOUNT_PATH == "/static-changed"
9595

96+
config.set_defaults(
97+
DEBUG=False, SECRET_KEY="your-secret-key-changed-again", NEW_KEY="Some new key"
98+
)
99+
assert config.DEBUG # not changed
100+
assert config.SECRET_KEY == "your-secret-key-changed" # not changed
101+
assert config.NEW_KEY == "Some new key" # Added since its doesn't exist
102+
96103

97104
def test_configuration_can_be_changed_during_instantiation():
105+
def int_encode(value):
106+
pass
107+
98108
config = Config(
99109
config_module=overriding_settings_path,
100110
DEBUG=False,
101111
SOME_NEW_CONFIGS="some new configuration values",
102112
JINJA_TEMPLATES_OPTIONS={"auto_reload": False},
113+
SERIALIZER_CUSTOM_ENCODER={int: int_encode},
103114
)
104115

105116
assert config.DEBUG is False
106117
assert config.JINJA_TEMPLATES_OPTIONS == {"auto_reload": False}
107118
assert config.SOME_NEW_CONFIGS == "some new configuration values"
119+
assert config.SERIALIZER_CUSTOM_ENCODER[int] == int_encode
108120

109121

110122
def test_can_set_defaults_a_configuration_instance_once():

tests/test_conf/test_mixins.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import pytest
2+
3+
from ellar.cache.backends.local_cache import LocalMemCacheBackend
4+
from ellar.core import Config
5+
6+
7+
def test_invalid_cached_backend_config():
8+
with pytest.raises(ValueError, match="Expected BaseCacheBackend, received:"):
9+
Config(CACHES={"default": type("whatever", (), {})})
10+
11+
12+
def test_cache_backend_without_default_raise_exception():
13+
with pytest.raises(
14+
ValueError, match="CACHES configuration must have a 'default' key"
15+
):
16+
Config(CACHES={"local": LocalMemCacheBackend()})
17+
18+
19+
def test_invalid_exception_handler_config():
20+
invalid_type = type("whatever", (), {})
21+
with pytest.raises(ValueError, match="Expected 'ExceptionHandler', received:"):
22+
Config(EXCEPTION_HANDLERS=[invalid_type])
23+
24+
with pytest.raises(ValueError, match="Expected 'ExceptionHandler', received:"):
25+
Config(EXCEPTION_HANDLERS=[invalid_type()])
26+
27+
28+
def test_invalid_versioning_config():
29+
invalid_type = type("whatever", (), {})
30+
with pytest.raises(ValueError, match=r"Expected BaseAPIVersioning, received: "):
31+
Config(VERSIONING_SCHEME=invalid_type())
32+
33+
34+
def test_invalid_middleware_config():
35+
invalid_type = type("whatever", (), {})
36+
with pytest.raises(
37+
ValueError, match=r"Expected Type/instance of Middleware, received: "
38+
):
39+
Config(MIDDLEWARE=[invalid_type()])
40+
41+
42+
def test_invalid_event_handler_config():
43+
invalid_type = type("whatever", (), {})
44+
with pytest.raises(ValueError, match=r"Expected EventHandler, received:"):
45+
Config(ON_REQUEST_STARTUP=[invalid_type()])

tests/test_events.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import pytest
22

33
from ellar.constants import NOT_SET
4+
from ellar.core import Config
45
from ellar.core.events import EventHandler, RouterEventManager
56

67

@@ -54,3 +55,15 @@ def another_function():
5455
route_manager -= valid_function_2
5556

5657
assert len(route_manager) == 1
58+
59+
60+
async def test_valid_event_config(anyio_backend):
61+
called = 0
62+
63+
def valid_function_1():
64+
nonlocal called
65+
called += 1
66+
67+
config = Config(ON_REQUEST_STARTUP=[EventHandler(valid_function_1)])
68+
await config.ON_REQUEST_STARTUP[0].run()
69+
assert called == 1

tests/test_exceptions/test_custom_exceptions.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,12 +74,14 @@ def error_500(ctx: IHostContext, exc: Exception):
7474

7575
def test_invalid_handler_raise_exception():
7676
with pytest.raises(ValidationError) as ex:
77-
Config(EXCEPTION_HANDLERS=[InvalidExceptionHandler])
77+
Config(
78+
EXCEPTION_HANDLERS=[InvalidExceptionHandler, OverrideAPIExceptionHandler()]
79+
)
7880

7981
assert ex.value.errors() == [
8082
{
8183
"loc": ("EXCEPTION_HANDLERS", 0),
82-
"msg": "Expected TExceptionHandler, received: <class 'tests.test_exceptions.test_custom_exceptions.InvalidExceptionHandler'>",
84+
"msg": "Expected 'ExceptionHandler', received: <class 'tests.test_exceptions.test_custom_exceptions.InvalidExceptionHandler'>",
8385
"type": "value_error",
8486
}
8587
]
@@ -90,7 +92,7 @@ def test_invalid_handler_raise_exception():
9092
assert ex.value.errors() == [
9193
{
9294
"loc": ("EXCEPTION_HANDLERS", 0),
93-
"msg": "Expected TExceptionHandler, received: "
95+
"msg": "Expected 'ExceptionHandler', received: "
9496
"<class 'tests.test_exceptions.test_custom_exceptions.InvalidExceptionHandler'>",
9597
"type": "value_error",
9698
}
@@ -114,7 +116,7 @@ class InvalidExceptionSetup(IExceptionHandler):
114116
exception_type_or_code = ""
115117

116118
def catch(self, ctx: IHostContext, exc: t.Any) -> t.Union[Response, t.Any]:
117-
pass
119+
"""do nothing"""
118120

119121
assert "'exception_type_or_code' must be defined" in str(ex.value)
120122

@@ -124,7 +126,7 @@ class InvalidExceptionSetup2(IExceptionHandler):
124126
exception_type_or_code = InvalidExceptionHandler
125127

126128
def catch(self, ctx: IHostContext, exc: t.Any) -> t.Union[Response, t.Any]:
127-
pass
129+
"""do nothing"""
128130

129131
assert "'exception_type_or_code' is not a valid type" in str(ex.value)
130132

0 commit comments

Comments
 (0)