Skip to content

Commit b53b0ac

Browse files
committed
Introduce subjectKwargs method
1 parent 2d190d0 commit b53b0ac

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

src/unittest_extensions/case.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
from unittest import TestCase as BaseTestCase
2-
from typing import Any
2+
from typing import Any, Dict
33
from abc import abstractmethod
44
from warnings import warn
5+
from copy import deepcopy
56

67
from unittest_extensions.error import TestError
78

@@ -37,6 +38,18 @@ def test_int_plus_float(self):
3738
@abstractmethod
3839
def subject(self, **kwargs) -> Any: ...
3940

41+
def subjectKwargs(self) -> Dict[str, Any]:
42+
"""
43+
Return the keyword arguments of the subject.
44+
45+
The dictionary returned is a copy of the original arguments. Thus,
46+
the arguments that the subject receives cannot be mutated by mutating
47+
the returned object of this method.
48+
"""
49+
# NOTE: deepcopy keeps a reference of the copied object. This can cause
50+
# issues with memory.
51+
return deepcopy(self._subjectKwargs)
52+
4053
def result(self) -> Any:
4154
"""
4255
Result of the `subject` called with arguments defined by the `args`

src/unittest_extensions/tests/test_use_case.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,3 +153,32 @@ def test_manually_change_state_cached_result(self):
153153
self.assertEqual(self.cachedResult(), 2)
154154
self.instance.state_var += 1
155155
self.assertEqual(self.cachedResult(), 2)
156+
157+
158+
class TestSubjectKwargs(TestCase):
159+
def subject(self, a, b):
160+
return a + b
161+
162+
@args({"a": 1, "b": 2})
163+
def test_kwarg_values(self):
164+
self.assertDictEqual(self.subjectKwargs(), {"a": 1, "b": 2})
165+
166+
@args({"a": 3, "b": 4})
167+
def test_different_kwarg_values(self):
168+
self.assertDictEqual(self.subjectKwargs(), {"a": 3, "b": 4})
169+
170+
@args({"a": 1, "b": 2})
171+
def test_kwargs_are_not_mutated(self):
172+
self.subjectKwargs()["b"] = None
173+
self.assertDictEqual(self._subjectKwargs, {"a": 1, "b": 2})
174+
self.assertDictEqual(self.subjectKwargs(), {"a": 1, "b": 2})
175+
176+
177+
class TestSubjectMutableKwargs(TestCase):
178+
def subject(self, lst):
179+
return lst
180+
181+
@args({"lst": [1, 2]})
182+
def test_mutable_kwargs(self):
183+
self.subjectKwargs()["lst"].append(3)
184+
self.assertDictEqual(self._subjectKwargs, {"lst": [1, 2]})

0 commit comments

Comments
 (0)