被测试视图
# coding:utf-8
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/login", methods=["POST"])
def login():
"""登录"""
name = request.form.get("name")
password = request.form.get("password")
# "" 0 [] () {} None 在逻辑判断时都是假
if not all([name, password]):
# 表示name或password中有一个为空或者都为空
return jsonify(code=1, message=u"参数不完整")
if name == "admin" and password == "admin":
return jsonify(code=0, message=u"OK")
else:
return jsonify(code=2, message=u"用户名或密码错误")
if __name__ == '__main__':
app.run()
测试用例代码
# 以login.py模块的进行单元测试
import unittest
import json
from login import app
class BookTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""在第一次执行用例钱执行"""
cls.app = app
# 开启测试DEBUG模式,如果用例执行到哪行代码报错就会提示
cls.app.testing = True
# 使用程序实例对象创建客户端
cls.client = cls.app.test_client()
print("all_before")
@classmethod
def tearDownClass(cls):
"""在最后一个用例执行完后执行"""
print("all_after")
def setUp(self):
"""在每次执行用例前执行"""
print("one_before")
def tearDown(self):
"""在每次执行完用例后执行"""
print("one_after")
def test_login_empty_name_password(self):
"""测试用户名或密码不完整的返回"""
# 用例1:测试用户名和密码均为空
# 使用客户端向接口发送POST,data为发送的数据
response = self.client.post("/login", data={})
# response.data提取响应数据
resp_json = response.data
# 将json字符串解析为字典
resp_dict = json.loads(resp_json)
# 使用断言进行验证
self.assertIn("code", resp_dict)
code = resp_dict.get("code")
self.assertEqual(code, 1)
# 用例2:测试只传name
response = self.client.post("/login", data={"name": "admin"})
resp_json = response.data
resp_dict = json.loads(resp_json)
self.assertIn("code", resp_dict)
code = resp_dict.get("code")
self.assertEqual(code, 1)
# 用例3:测试只传password
response = self.client.post("/login", data={"password": "admin"})
resp_json = response.data
resp_dict = json.loads(resp_json)
self.assertIn("code", resp_dict)
code = resp_dict.get("code")
self.assertEqual(code, 1)
def test_wrong_name_password(self):
"""测试用户名或密码错误的返回"""
# 用例4:测试用户名或密码错误
response = self.client.post("/login", data={"name": "admin", "password": "123456"})
resp_json = response.data
resp_dict = json.loads(resp_json)
self.assertIn("code", resp_dict)
code = resp_dict.get("code")
self.assertEqual(code, 2)
def test_identical_name_password(self):
"""测试用户名和密码均正确的返回"""
# 用例5:测试用户名和密码均正确
response = self.client.post("/login", data={"name": "admin", "password": "admin"})
resp_json = response.data
resp_dict = json.loads(resp_json)
self.assertIn("code", resp_dict)
code = resp_dict.get("code")
self.assertEqual(code, 0)