I have an instance method which initiates an object of another class. For ex,
import module_two
class One:
def start(self):
self.two = module_two.Two()
I am patching One class in my test cases
@patch('module_one.One', autospec=True)
def test_one(patched_one):
two = patched_one.return_value
# Following method should raise error, but doesn't
two.any_random_non_existing_method()
As mentioned, two.any_random_non_existing_method()
does not raise any error because two
Mock object does not have any spec assigned.
How can I assign spec to the two
object.? I am looking for something like following snippet.
# note: configure_spec actually doesn't exist.!
two.configure_spec(module_two.Two)
two.any_random_non_existing_method() # Error.!
After some comments, looks like mock_add_spec
would work for you:
Add a spec to a mock. spec can either be an object or a list of strings. Only attributes on the spec can be fetched as attributes from the mock.
https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.mock_add_spec
Here's how it should look:
# Add specifications on existing mock object
two.mock_add_spec(module_two.Two)
two.any_random_non_existing_method() # Error.!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With