vinissimus / async-asgi-testclient

A framework-agnostic library for testing ASGI web applications
MIT License
160 stars 20 forks source link

Better way to provide headers for each request #19

Closed logileifs closed 5 years ago

logileifs commented 5 years ago

Hi there and thanks for a great test client! It really saved me since Starlette's default TestClient is so awful.

But would it be possible to provide a nicer way to send headers with each request. For example with requests you can do:

import requests
s = requests.Session()
s.headers.update({'my': 'header'})
s.get('/')

I couldn't find any similar functionality in your otherwise excellent testing client so I resorted to subclassing your TestClient like this:

from async_asgi_testclient import TestClient
class TestClient(TestClient):
    def __init__(self, *args, headers=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.headers = headers

    async def open(
        self,
        path,
        *,
        method="GET",
        headers=None,
        data=None,
        form=None,
        query_string=None,
        json=None,
        scheme="http",
        cookies=None,
        stream=False,
        allow_redirects=True,
    ):
        return await super().open(
            path,
            method=method,
            headers=self.headers,
            data=data,
            form=form,
            query_string=query_string,
            json=json,
            scheme=scheme,
            cookies=cookies,
            stream=stream,
            allow_redirects=allow_redirects
        )

client = TestClient(app)
client.headers = {
    'authorization': 'token my_token'
}

Is there maybe some better way of doing this that I am missing? Or would you be willing to add a similar feature? I can also open a pull request if you are open to that

masipcat commented 5 years ago

Hi @logileifs

I like the idea, please open a PR with this feature :)

The only missing thing I see in your snippet is that the argument headers in open() is ignored. I'd say that the headers in the open should be merged with the client headers, so you can use the client headers to "inherit" when doing a request with other headers. What do you think?

logileifs commented 5 years ago

Yeah that sounds good, I'll submit a pull request tomorrow if I have enough time, otherwise in the coming days

logileifs commented 5 years ago

solved by: https://github.com/vinissimus/async-asgi-testclient/pull/20