pytest-dev / pytest-flask

A set of pytest fixtures to test Flask applications

Home Page:http://pytest-flask.readthedocs.org/en/latest/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

client.post json doesn't work

ailisp opened this issue · comments

Take the official flask doc example: http://flask.pocoo.org/docs/1.0/testing/#testing-json-apis
This works:

    with app.test_client() as c:
        rv = c.post('/', json={'username': 'flask', 'password': 'secret'})
    assert rv.status_code == 200

but this with pytest flask client fixture doesn't:

def test_create_merchant(client):
    rv = client.post('/', json={'username': 'flask', 'password': 'secret'})
    assert rv.status_code == 200

In the @app.route('/') function, I print request.get_json(), in first case it prints the username and password as a dict. In the second it prints None

It's quite strange why it doesn't get the json params, since client is just a simple yield_fixture wraps app.test_client

Although I don't know what the reason is, but I use this and work! :)
test_api.py

import pytest
class TestApp:

    def test_register_succ(self, client):
        username = 123
        password = 123
        res = client.post('register', json=dict(
                username=username,
                password=password
            ), follow_redirects=True)
        assert res.status_code == 200

and the conftest.py

import pytest
from api import index
import model._model

@pytest.fixture
def app():
    from app import app
    app.debug = True
    return app

Hey there @ailisp @EleComb, thanks for opening the issue and providing a solution for people who may be facing the same problem. I have created a minimal example including the provided code but I wasn't able to reproduce the described behaviour.

The dictionary containing the request data prints normaly when running the tests:

(venv)$ pytest -s
============================= test session starts =============================
platform darwin -- Python 3.7.8, pytest-6.1.1, py-1.9.0, pluggy-0.13.1
plugins: flask-1.0.0
collected 1 item

tests/test_jsonify.py {'password': 'secret', 'username': 'flask'}
.
============================== 1 passed in 0.02s ==============================

could you provide more details about your code and environment? or maybe a minimal, reproducible example?

I'll be closing this for the time being, feel free to reopen to provide more info on the problem.