0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Flask 単体テスト環境(test_client)

Posted at

概要

FlaskのAPIテストをするのに「POST MAN」を使用していましたが、今更Flaskでの単体テスト方法を学んだんで備忘録。

テスト用のコードは「test.py」として別に分けています。「app.py」に簡単なルーティング設定をしています。

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

@app.route("/")
def home():
  if request.is_json: # jsonのデータ指定
    return jsonify({"msg": "fault massage"}), 400
  return jsonify({"msg": "success message"}), 200

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

今回はget通信としていますが、これはgetのところをpost等にすればその他通信が可能です。

test.py
import json
from app import app # app.py をインポート

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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?