Skip to content
Advertisement

How to employ a MagicMock spec_set or spec on a method?

I am trying to use a method as a spec_set on a MagicMock.

https://stackoverflow.com/a/25323517/11163122 provides a nice example of an unexpected call signature resulting in an Exception. Unfortunately, I can’t get it to work out for a method.

How can I get the below code snippet to error out, given the calls don’t match the spec?

JavaScript

I am using Python 3.8+.

Advertisement

Answer

spec and spec_set are used for limiting the set of attributes a Mock is allowed to access. For functions, there’s create_autospec.

Functions or methods being mocked will have their arguments checked to ensure that they are called with the correct signature.

Since bar is an instance method of Foo, you will also need to create an instance of Foo to get the expected function signature.

JavaScript

This raises an error:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement