Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python mock: configure spec of a mock object

Tags:

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.! 
like image 916
Jay Joshi Avatar asked Jul 10 '19 09:07

Jay Joshi


1 Answers

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.! 
like image 190
wholevinski Avatar answered Nov 15 '22 04:11

wholevinski