requests-mock icon indicating copy to clipboard operation
requests-mock copied to clipboard

Document how to wrap test class with prepared mock

Open thenewguy opened this issue 4 years ago • 2 comments

It would be handy to be able to wrap the test class with a prepared mock and not require the test cases to accept the mock.

For example, pass a mock that is already loaded with the expected responses to a test case that inherits test methods.

thenewguy avatar Jun 04 '21 16:06 thenewguy

I think i understand the gist of the question, but i'm not sure how you think that would look.

It'd help to start if i know if you're using unittest or pytest based tools.

For unittest i find this really easy as you just implement a setUp method and put the mocking logic in there. I've never liked the class mock, from memory it works that way because of how mocking a class works in i think unittest, but i don't remember. My preferred way of doing this was with the Fixture library

Otherwise declare a function that adds all the paths to a mock, this was always more useful to me than the concept of pre-prepared as you could run compose multiple functions on the same mocker.

eg

@requests_mock.mock() 
def test_thing(m): 
    mock_auth(m)
    mock_resource(m, 'info')

    do_test()

I think what i'm trying to say though is that underneath it's just a context manager and you could wrap whatever means of loading you like.

jamielennox avatar Jun 07 '21 10:06 jamielennox

@jamielennox hey there. I use unittesting for the context of this question.

Here is an example where the mock is provided upfront and the test case does not need to know about it.

@mock.patch('ptrack.templatetags.ptrack.ptrack_encoder.encrypt', mock.Mock(return_value='predicabletoken'))
    def test_issuance_opened_pixel_output(self):
        self.assertEqual(self.get_pixel_url(), 'http://testserver/pixels/predicabletoken/')

It would be nice if something similar to this concept could be injected for requests without requiring setup for each test.

The utility is very handy when mocked at the class level

thenewguy avatar Jun 09 '21 20:06 thenewguy