Skip to content

Commit 9c69789

Browse files
committed
test: generate bound model methods tests
1 parent 33da63f commit 9c69789

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

tests/unit/conftest.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
from __future__ import annotations
44

5+
import inspect
6+
from typing import Callable, ClassVar
57
from unittest import mock
68

79
import pytest
@@ -130,3 +132,74 @@ def action_list_response(action1_running, action2_running):
130132
action2_running,
131133
],
132134
}
135+
136+
137+
def build_kwargs_mock(func: Callable) -> dict[str, mock.Mock]:
138+
s = inspect.signature(func)
139+
140+
kwargs = {}
141+
for name, param in s.parameters.items():
142+
if name in ("self",):
143+
continue
144+
145+
if param.kind in (param.POSITIONAL_OR_KEYWORD, param.KEYWORD_ONLY):
146+
kwargs[name] = mock.Mock()
147+
continue
148+
149+
raise NotImplementedError(f"unsupported parameter kind: {param.kind}")
150+
151+
return kwargs
152+
153+
154+
def pytest_generate_tests(metafunc: pytest.Metafunc):
155+
if "bound_model_method" in metafunc.fixturenames:
156+
metafunc.parametrize("bound_model_method", metafunc.cls.methods)
157+
158+
159+
class BoundModelTestCase:
160+
methods: ClassVar[list[Callable]]
161+
162+
def test_method_list(self, bound_model):
163+
"""
164+
Ensure the list of bound model methods is up to date.
165+
"""
166+
members_count = 0
167+
for name, member in inspect.getmembers(
168+
bound_model,
169+
lambda m: inspect.ismethod(m)
170+
and m.__func__ in bound_model.__class__.__dict__.values(),
171+
):
172+
# Actions methods are already tested in TestBoundModelActions.
173+
if name in ("__init__", "get_actions", "get_actions_list"):
174+
continue
175+
176+
assert member.__func__ in self.__class__.methods
177+
members_count += 1
178+
179+
assert members_count == len(self.__class__.methods)
180+
181+
def test_method(
182+
self,
183+
resource_client,
184+
bound_model,
185+
bound_model_method: Callable,
186+
):
187+
# Check if the resource client has a method named after the bound model method.
188+
assert hasattr(resource_client, bound_model_method.__name__)
189+
190+
# Mock the resource client method.
191+
resource_client_method_mock = mock.MagicMock()
192+
setattr(
193+
resource_client,
194+
bound_model_method.__name__,
195+
resource_client_method_mock,
196+
)
197+
198+
kwargs = build_kwargs_mock(bound_model_method)
199+
200+
# Call the bound model method
201+
result = getattr(bound_model, bound_model_method.__name__)(**kwargs)
202+
203+
resource_client_method_mock.assert_called_with(bound_model, **kwargs)
204+
205+
assert result is resource_client_method_mock.return_value

0 commit comments

Comments
 (0)