lundberg / respx

Mock HTTPX with awesome request patterns and response side effects 🦋
https://lundberg.github.io/respx
BSD 3-Clause "New" or "Revised" License
581 stars 38 forks source link

Save data on a request #229

Closed tomhamiltonstubber closed 1 year ago

tomhamiltonstubber commented 1 year ago

It would be great to be able to view the request data on a mocked object so we could have something like:

def create_object_and_post_data():
    user = User.objects.create(name='Brian Johnson', gender='male', join_date=datetime.today())
    Client().post(url='https://example.com', data=user.__dict__)
    return user

@respx.mock
def test_webhook_data():
    mock_request = respx.post('http://example.com/').mock(return_value=Response(200, content='OK'))
    create_object_and_post_data()
    assert mock_request.calls[0].request.data == {
        'name': 'Brian Johnson',
        'gender': 'male',
        'join_date': datetime.today(),
    }

Seems like a fairly easy change to add self.data to the Request object, I'll do it unless you have any objections?

lundberg commented 1 year ago

The captured request here is a httpx.Request, meaning it's not a class we can or should fiddle with.

However, you have access to the request content and can do ...

@respx.mock
def test_webhook_data():
    mock_request = respx.post('http://example.com/').mock(return_value=Response(200, content='OK'))
    create_object_and_post_data()
    user_request = mock_request.calls.last.request
    assert json.loads(user_request.content) == {
        'name': 'Brian Johnson',
        'gender': 'male',
        'join_date': datetime.today(),
    }
tomhamiltonstubber commented 1 year ago

Totally missed that, I've made a small PR to add content to the help docs to help others.