接口文档已经提供了,requests库、unittest单元测试框架也已经介绍过,笔者相信读者朋友已经可以独立编写接口自动化测试用例了。但是有一些细节,我们需要聊一下。比如我们写登录接口测试用例,用户名为空、密码为空、用户名错误、密码错误、用户名密码都正确,假设我们只编写这几条测试用例,我们一般的做法如下代码所示:
# -*- coding: utf-8 -*-
import requests
import unittest
from nose_parameterized import parameterized
class BlogTest(unittest.TestCase):
def setUp(self):
self.url = "http://127.0.0.1:8000/login"
self.username = 'admin'
self.password = 'admin111111'
def tearDown(self):
pass
def test_username_null(self):
"""用户名为空"""
payload = {'username': '', 'password': self.password}
self.result = requests.post(self.url, payload).json()
# print(self.result)
self.assertEqual(self.result['status'], 0)
self.assertEqual(self.result['message'], 'username or password null')
def test_password_null(self):
"""密码为空"""
payload = {'username': self.username, 'password': ''}
self.result = requests.post(self.url, payload).json()
# print(self.result)
self.assertEqual(self.result['status'], 0)
self.assertEqual(self.result['message'], 'username or password null')
def test_username_error(self):
"""用户名错误"""
payload = {'username': 'admin1', 'password': self.password}
self.result = requests.post(self.url, payload).json()
# print(self.result)
self.assertEqual(self.result['status'], 0)
self.assertEqual(self.result['message'], 'username or password error')
def test_password_error(self):
"""密码错误"""
payload = {'username': self.username, 'password': 'admin1111111'}
self.result = requests.post(self.url, payload).json()
# print(self.result)
self.assertEqual(self.result['status'], 0)
self.assertEqual(self.result['message'], 'username or password error')
def test_login_success(self):
"""用户名密码正确"""
payload = {'username': self.username, 'password': self.password}
self.result = requests.post(self.url, payload).json()
# print(self.result)
self.assertEqual(self.result['status'], 1)
self.assertEqual(self.result['message'], 'login success')
if __name__ == '__main__':
unittest.main()
欢迎关注微信公众号:软件测试汪。软件测试交流群:809111560