I have a list of filters and each filter changes the input list. How do I create a mock for each filter that will change the input list?
class TwoFilter(object):
def filter(self, arr):
arr[:] = [i for i in arr if i % 2 != 0]
class ThreeFilter(object):
def filter(self, arr):
arr[:] = [i for i in arr if i % 3 != 0]
class FourFilter(object):
def filter(self, arr):
arr[:] = [i for i in arr if i % 3 != 0]
class MyFilters(object):
def __init__(self):
self.filters = [TwoFilter(), ThreeFilter(), FourFilter()]
def apply_filters(self, arr):
for f in self.filters:
f.filter(arr)
I want to unit test apply_filters
by mocking the filters in self.filters
for input [1,2,3,4]. Is there a way to have each mock change the input arr
and verify if each subsequent filter was called with this modified arr
?
PS: I am able to get around this problem by having the filters return the arr
and use mock.return_value
to change the mock's output.
As you spoke of mocking the filter classes, I take it that your approach is to also test the filter classes individually as well? This should certainly still be done, and better done as the first step - if I am not mistaken reading your code, you will likely discover a bug then.
Regarding the test of apply_filters
: Why do you want to mock the filter classes at all? There seems to be no justification - you can just call apply_filters
with some suitable values for arr
to see if the other filters are actually called. And, maybe you find the next bug then (after correcting the first) - just try to find a test case that fails if the third filter is not called.
Mocking should be done for a reason - take a look at When to use mock objects in unit tests .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.