Colin-b / pytest_httpx

pytest fixture to mock HTTPX
https://colin-b.github.io/pytest_httpx/
MIT License
366 stars 31 forks source link

MultipartStream is no longer present in requests #164

Closed crazystick closed 1 month ago

crazystick commented 1 month ago

Between 0.31.0 and 0.31.1 fields of a MultipartStream in a request are no longer accessible.

In 0.31.0, accessing last_request = httpx_mock.get_request():

image

In 0.31.1 stream is now a ByteStream

image

Colin-b commented 1 month ago

Hello @crazystick

I assume you never matched this request against its content as this is the only use case I see where you would see a difference.

What is the actual issue with the stream being of this type now?

crazystick commented 1 month ago

Hi,

Because the test is doing:

assert last_request.stream.fields[0].name == 'imageFile'
assert last_request.stream.fields[0].filename == 'some_filename.png'

A match_stream option that would allow you to do something like

httpx_mock.add_response(url=f'https://host/api/image',
                            method='POST',
                            match_stream=MultipartStream(
                                data={'key': 'value'},
                                files={'imageFile': (datadir / 'image_file.png').read_bytes()}
                            ),
                            status_code=204)

would be great, but as far as I can see it doesn't exist.

Colin-b commented 1 month ago

Could you provide a sample of the parameters you used to post this data? So that I can see what we can do to offer additional matching.

Could you check the type of stream if you read the request (last_request.read()) in version 0.31.0 ?

crazystick commented 1 month ago

The httpx client is wrapped in a bunch of other classes, but it should eventually be something like:

with open(image_file, 'rb') as image_data:
            multipart_form_data = {
                'imageFile': (image_file.name, image_data)
            }

            httpx_client.request('POST', url, json=None, files=multipart_form_data)

in 0.31.0 I can't do last_request.read(), it raises ValueError('seek of closed file')

Colin-b commented 1 month ago

Next release (0.33.0) will introduce match_files and match_data so that you can avoid having to query requests afterwards. Note that upon failure to match, the comparison will be displayed with the full multipart body for the request. A future release might clean this (only displaying files as a dict/tuple and data as a dict) but this is not planned.

Colin-b commented 1 month ago

Version 0.33.0 is now available on pypi with this feature.