emmett-framework / emmett

The web framework for inventors
Other
1.04k stars 70 forks source link

Headers when testing emmett #313

Closed a0nguyen closed 3 years ago

a0nguyen commented 3 years ago

Hey @gi0baro

I've tried to pass headers to an emmett test clients, but I couldnt make it work.

Code sample: app.py

from emmett import App, request, response

app = App(__name__)

@app.route("/")
async def hello():
    api_key = request.headers.get('x-api-key')
    if not api_key:
      response.status = 400
    return "Hello world!"

tests.py

import pytest

from emmett import response
from app import app

@pytest.fixture()
def client():
    return app.test_client()

def test_headers(client):
    result = client.get(
        '/',
        headers={'x-api-key': '12345'},
    )
    assert result.data == "Hello world!"
    assert result.status == 200 # should return 200 because api key is present

Can you help me?

EDIT: here is the best workaround I've found using pytest-mock, but it's quite shady

import pytest

from emmett import response
from app import app
from emmett.testing.helpers import Headers

@pytest.fixture()
def client():
    return app.test_client()

def test_headers(client, mocker):
    mocker.patch(
        'emmett.wrappers.helpers.Headers.get',
        return_value='1234567'
    )
    result = client.get(
        '/'
    )
    assert result.data == "Hello world!"
    assert result.status == 200
gi0baro commented 3 years ago

hey @a0nguyen, I just tested locally and it seems to me the client actually need a list of tuples for headers, not a dictionary, so if you rewrite your test function as follows it should work:

def test_headers(client):
    result = client.get(
        '/',
        headers=[('x-api-key', '12345')],
    )
    assert result.data == "Hello world!"
    assert result.status == 200

I'm not sure this is documented correctly. I gonna keep this open until I investigated properly.