vendredi 1 mars 2019

Flask.test_client().post and JSON encoding

I am writing test cases for JSON endpoints in a Flask app.

import unittest
from flask import json
from app import create_app


class TestFooBar(unittest.TestCase):
    def setUp(self):
        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()

    def test_ham(self):
        resp = self.client.post('/endpoint',
                                headers={'Content-Type': 'application/json'},
                                data=json.dumps({'foo': 2,
                                                 'bar': 3}))
        assert resp.status_code == 200

    def test_eggs(self):
        resp = self.client.post('/endpoint', data={'foo': 5,
                                                   'bar': 7})
        assert resp.status_code == 200

    def test_ham_and_eggs(self):
        with self.app.test_client() as self.client:
            self.test_ham()
            self.test_eggs()

Just to understand what's happening:

  1. Do both ways of sending a POST message in the code above make sense? In particular, am I double-JSON encoding in the first case?
  2. Could the first instance trigger the warning `werkzeug/local.py:347: DeprecationWarning: json is deprecated. Use get_json() instead.? Weirdly, that warning appears with no additional pointer to the line that actually causes it.
  3. After import json I also have access to json.dumps(). What is the difference between the two (using json.dumps() after import json and after from flask import json)?

Or, briefly, what is the difference between test_ham and test_eggs? Is there any?

Relevant:

Aucun commentaire:

Enregistrer un commentaire