关联关系的接口:

import requests

def login():
    url = 'http://ip/api/user/login'
    data = {'username':'niuhang','passwd':'aA123'}
    res = requests.post(url,data).json()
    user_id = res.get('login_info').get('userId')
    sign = res.get('login_info').get('sign')
    return user_id,sign
def add_gold():
    url = 'http://ip/api/user/gold_add'
    data = {'stu_id':510,'gold':509}
    userid,sign = login()
    cookies = {'niuhag':sign}
    res = requests.post(url,data,cookies=cookies).json()
    if res.get('error_code') == 1000:
        print('测试通过')
    else:
        print('测试失败结果是',res)
add_gold()

unittest实现关联接口:

import unittest,requests
class GoldTest(unittest.TestCase): # 注意:继承的是TestCase

    def login(self):
        print('这是登陆的函数')
        url = 'http://ip/api/user/login'
        data = {'username': 'niuhag', 'passwd': 'aA123'}
        res = requests.post(url, data).json()
        user_id = res.get('login_info').get('userId')
        sign = res.get('login_info').get('sign')
        return user_id, sign

    def test_gold_add(self):
        url = 'http://ip/api/user/gold_add'
        data = {'stu_id': 510, 'gold': 509}
        userid, sign = self.login()  # 与第一段代码有区别,为self.login(),类里面调用
        cookies = {'niuhang': sign}
        res = requests.post(url, data, cookies=cookies).json()
        self.assertEqual(res.get('error_code'),1000) # 判断返回的error_code和1000是否相等,unittest会自动判断并返回结果,不需要自己再适用if判断

unittest.main()

函数名若以test开头,则unittest会自动运行该函数,故若不想重复运行某个函数,则函数名不能以test开头

05-25 12:15