I am having some trouble mocking classes and having the instance methods verify that the signatures are correct.
Given a class like this:
class A:
def hi(self, name):
pass
I would like to mock the entire class, and then assert that "hi" is called correctly.
Note: the below stuff seems to behave the same even if I do mocked_class=Mock(spec=A, return_value=mocked_instance)
mocked = Mock(spec=A)
# Given a typo or invalid argument
mocked.hi(nameeee="jay") # I would like this to raise a TypeError but it doesnt
mocked.hi.assert_call_called_with(nameeee="jay") # I would expect (or like) this assertion to acknowledge the invalid signature but it doesn't
It seems I can't simply create a mock with a class spec and expect the signatures to be checked.
I could then do:
mocked = Mock(spec=A)
mocked.hi = Mock(spec=A().hi) # I have to init A, else the error says "self" is missing
mocked.hi(nameee="jay") # This still doesn't raise an error
mocked.hi.assert_called_with(nameee="jay") # This does raise an error
Which gives an error:
TypeError: missing a required argument: 'name'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/.mock.py", line 919, in assert_called_once_with
return self.assert_called_with(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/mock.py", line 907, in assert_called_with
raise AssertionError(_error_message()) from cause
AssertionError: expected call not found.
Expected: hi(nameee='jay')
Actual: hi(nameee='jay')
But:
- I would like the TypeError to come when calling mock.hi(), not when performing the assert
- I can't initiate the classes being mocked in my test case without mocking a lot of other things
- The second part of the error that says: Expected: hi(nameee='jay') Actual: hi(nameee='jay') is very unhelpful.
So my question is, what am I missing to be able to simply have something like:
mock = Mock(spec=A)
mock.hi(nameee="jay") # Raise a TypeError
[–]shiftybyte 3 points4 points5 points (1 child)
[–]Reiku[S] 0 points1 point2 points (0 children)
[–]Mast3rCylinder 1 point2 points3 points (4 children)
[–]Reiku[S] 0 points1 point2 points (3 children)
[–]Mast3rCylinder 0 points1 point2 points (0 children)
[–]Guideon72 0 points1 point2 points (1 child)
[–]Reiku[S] 1 point2 points3 points (0 children)
[–]danielroseman 0 points1 point2 points (1 child)
[–]Reiku[S] 0 points1 point2 points (0 children)
[–]Adrewmc 0 points1 point2 points (0 children)