[PYTHON] Flask unit test environment (test_client)

Overview

I used "POST MAN" to test Flask's API, but now I've learned how to unit test with Flask, so it's a memorandum.

Example

The test code is separated as "test.py". I have a simple routing setting in "app.py".

app.py


from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route("/")
def home():
  if request.is_json: #json data specification
    return jsonify({"msg": "fault massage"}), 400
  return jsonify({"msg": "success message"}), 200

if __name__ == "__main__":
  app.run()

This time it is get communication, but other communication is possible if get is set to post etc.

test.py


import json
from app import app # app.Import py

with app.test_client() as c:
  res = c.get("/", data=json.dumps({
      "test" : "test"
    }
  ),
    headers={
      "Content-Type" : "application/json"
    }
  )
  print(res.get_data())

Recommended Posts

Flask unit test environment (test_client)
Unit test flask with pytest
numpy unit test
Unit test Databricks Notebook
python unit test template
HTTP environment variables in Flask
Build Flask environment with Dockerfile + docker-compose.yml
Unit test log output with python