# 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)
手机扫一扫
移动阅读更方便
你可能感兴趣的文章