Python编程:Flask测试用例的编写实例

版权声明:本文为博主原创文章,欢迎转载,请注明出处 https://blog.csdn.net/mouday/article/details/86704465

要测试的接口 flask_test_main.py

# -*- coding: utf-8 -*-

from flask import Flask, jsonify, request

app = Flask(__name__)


@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        name = request.form.get("name")
        data = {
            "code": 0,
            "name": name
        }
        return jsonify(data)

    else:
        data = {
            "code": 0,
        }
        return jsonify(data)


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

测试案例

# -*- coding: utf-8 -*-

import json
import unittest
from flask_test_main import app


class FlaskTest(unittest.TestCase):
    """测试案例"""

    def setUp(self):
        app.testing = True   # 开启测试模式
        self.client = app.test_client()

    def test_get(self):
        """测试函数,必须以test开头"""
        resp = self.client.get("/")
        resp = json.loads(resp.data)
        self.assertEqual(resp["code"], 0)

    def test_post(self):
        """post测试函数"""
        resp = self.client.post("/", data={"name": "Tom"})
        resp = json.loads(resp.data)
        self.assertEqual(resp["code"], 0)


if __name__ == '__main__':
    # 启动所有测试
    unittest.main()

没有更多推荐了,返回首页