Unit Testing ConfigurableResource Classes #21801
Unanswered
rover-wagnar
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
I'm looking for help with a better workaround or solution for handling mocking with classes that inherit from ConfigurableResource. Here's the issue I'm running into with an example.
Say I have this class, a very simple API client class that's a ConfigurableResource and handles setting a bearer token value for paginated API calls:
If I want to test that calling
get_paginated
meansrefresh_access_token
is called, I would write a unit test like this, where I patch the object to mock a method so I can make assertions on call behavior:The problem is, this test will fail. It fails because the way
unittest.mock.patch
apparently handles mocking is by using assignment to make a method a Mock object (which records interactions so we can call methods like .assert_called_once()). But ConfigurableResource objects are Pydantic BaseModels withFrozen=True
which don't allow re-assignment like this, so the mock fails and the test fails with a Pydantic ValidationError.One workaround for this is to autospec a MagicMock object with the ApiClient class like
MagicMock(spec=RestApiClient)
. But this object does not have the same method definitions so the mocked version ofget_paginated
does not callrefresh_access_token
, and so I can't assert the method was called (unless I redefine mock methods for the MagicMock which defeats the purpose of the test).Currently, I just don't write those kinds of unit tests for ConfigurableResource classes, but I feel like this limitation around mocking for ConfigurableResources limits test coverage. Am I missing a better way to unit test ConfigurableResources or a better workaround?
Beta Was this translation helpful? Give feedback.
All reactions