2

I'am having problems testing a function that has a decorator for caching:

@retry(stop=stop_after_attempt(3))
@cache.memoize(60)
def get_azure_machine_info(rg_name, machine_name, expand="instanceView"):

    try:
        compute_client = get_azure_compute_client()
        return compute_client.virtual_machines.get(rg_name, machine_name, expand=expand)
    except CloudError:
        return None

My test:

@patch("dev_maintenance.machines.get_azure_compute_client")
def test_get_azure_machine_info(get_azure_compute_client):
    cache.delete_memoized('get_azure_machine_info')
    with app.app_context():
        ret = get_azure_machine_info("rg1", "m1")
        get_azure_compute_client.assert_called_once()
        assert len(get_azure_compute_client.return_value.method_calls) == 1
        assert (
            ret == get_azure_compute_client.return_value.virtual_machines.get.return_value
            )
        get_azure_compute_client.return_value.virtual_machines.get.assert_called_once_with(
            "rg1", "m1", expand="instanceView"
        )

Before i used cache the test was working fine, but now i can't figure out what is going on here.

The error:

enter image description here

Patrick José
  • 395
  • 3
  • 13

1 Answers1

1

The cache is trying to do its thing with the MagicMock objects that patch is creating. And it's failing since it 'can't pickle class unitest.mock.MagicMock'

The simplest work-around would be to mock out the cache module in the test. You can look here for pointers: Can I patch a Python decorator before it wraps a function?

Do this in a setUp() fixture.

rdas
  • 20,604
  • 6
  • 33
  • 46
  • with this mock will i be able to test if the function is caching? Like i call it two times and assert that the method that the function calls was called once ,cause i will need to test this as well – Patrick José Feb 03 '20 at 15:24
  • 1
    Since you are mocking the cache itself - you can simply verify if the cache was invoked twice or not. If you want to test the cache itself, I suggest writing a separate test for that. Although, i dunno why you would want to test the cache. It's a library - assume that it works. Test your code only. – rdas Feb 03 '20 at 15:33