简体   繁体   中英

Testing in python arround memoized functions

I'm building a bunch of tests and discovered that some of them are failing when they are all run together. Looking at why they are breaking I discovered it is because we memoize some of the system calls for the setup.

Because I'm mocking the system calls and not the memoized the function is only computed once and so it leaks that information into the subsequent tests.

What is the elegant way to deal with memoized functions:

  • Mock those instead of the system calls
  • Create a parameter on the memoize to not work for tests
  • Mock the memoize decorator to return the parameters
  • Find where the data is memoized and clean it at the end of each test

Any other ideas ?

Thanks

Maybe it's too late but I found very easy to use delete_memoized :

# your function
@memoize(timeout=50)
def your_long_function():
    # do stuff

# your test
def test_get_folder_content_error_handled(self, flf):
    delete_memoized(your_long_function)
    your_long_function()

I just used this solution in Django (using django-memoize ) and it works like a charm!

Try using MagicMock instead of vanilla Mock .

Say your code is something like:

@memoize.Memoize()
def OAuthClient():
    """Returns an Oauth client."""
    return 'blah'

Mocking with Mock like this:

mymodule.OauthPasswordClient = mock.Mock()

Returns an error like this:

TypeError: unsupported operand type(s) for +=: 'int' and 'Mock'

But mocking with MagicMock like this:

mymodule.OauthPasswordClient = mock.MagicMock()

Works just fine.

I think the first option may be the best.

  • Mock those instead of the system calls

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM