头条项目接口自动化测试(三)之登录接口测试

登录接口测试

1、自动化测试的目录结构

在这里插入图片描述

2、实现登录接口对象的封装api_login.py
"""
功能:实现登录接口对象的封装
"""
import requests

class ApiLogin(object):
    #登录方法(url、mobile、code从data的数据文件读取出来,做参数化处理)
    def api_post_login(self,url,mobile,code):
        #headers定义
        headers= {"Content-Type": "application/json"}
        #data定义
        data={"mobile": mobile,"code": code}
        #调用post并返回响应对象
        return requests.post(url,headers=headers,json=data)
3、登录接口的业务实现测试用例test_login.py
"""
功能:登录接口的业务实现测试用例
"""
import unittest
from api.api_login import ApiLogin
from parameterized import parameterized
from tools.read_json import ReadJson

#读取json数据
def get_data():
    datas=ReadJson("login.json").read_json()
    #建立空列表,添加读取的json数据
    arrs=[]
    #遍历多条json数据用例
    for data in datas.values():
        arrs.append((data.get("url"),
                     data.get("mobile"),
                     data.get("code"),
                     data.get("expect_result"),
                     data.get("status_code")))
    return arrs
#登录测试类
class TestLogin(unittest.TestCase):
    #使用参数化动态获取参数数据
    @parameterized.expand(get_data())
    def test_login(self,url,mobile,code,expect_result,status_code):
        #设置临时静态参数,url、mobile、code(有效一分钟)
        # url="http://ttapi.research.itcast.cn/app/v1_0/authorizations"
        # mobile="18264152106"
        # code="965754"

        #调用登录方法,返回响应对象
        result=ApiLogin().api_post_login(url,mobile,code)
        print("响应结果:",result.json())
        #断言,响应信息,状态码
        self.assertEquals(expect_result,result.json()['message'])
        self.assertEquals(status_code,result.status_code)

if __name__ == '__main__':
    unittest.main()

# 响应结果: {'message': 'OK', 'data': {'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1ODUxMzA1ODksInVzZXJfaWQiOjEyMzEwNTIyNDk1Njg5MDMxNjgsInJlZnJlc2giOmZhbHNlfQ.QFy0lXJ1So4bwJDLDwjbC6o2KeZyFYnYf2uMz-OAyMo', 'refresh_token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1ODYzMzI5ODksInVzZXJfaWQiOjEyMzEwNTIyNDk1Njg5MDMxNjgsInJlZnJlc2giOnRydWV9.TcgtEJs1p87aM5k5g9gqe46uSvddR_9MA9dMkpf9uVQ'}}

4、json数据login.json
{
  "login001":{
      "url":"http://ttapi.research.itcast.cn/app/v1_0/authorizations",
      "mobile":"18264152106",
      "code":"222337",
      "expect_result":"OK",
      "status_code":201
  },
   "login002":{
      "url":"http://ttapi.research.itcast.cn/app/v1_0/authorizations",
      "mobile":"18264152101",
      "code":"222337",
      "expect_result":{"mobile":"18264152101 is not a valid mobile"},
      "status_code":400
  }
}
5、读取json数据工具类reas_json.py
"""
功能:读取json数据,返回json对象
"""
import json
class ReadJson(object):
    #初始化json地址
    def __init__(self,fileName):
        self.filePath="../data/"+fileName
    #读取json
    def read_json(self):
        with open(self.filePath,"r",encoding="utf-8") as f:
            #调用load方法加载文件流
            return json.load(f)



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章