http_request的类的单元测试

题目:1)针对YAPI网址写的http_request类做作业
2)提供2个接口:登陆和查询tools
3)针对登陆接口写4个用例:正常登陆,不输入密码,不输入账号,输入错误的密码
4)请利用任何一种方法实现用例的加载并执行
5)生成html的测试报告
注意:请在测试类里加上异常处理以及断言

http_request.py

import requests
import json
class HttpRequest:
    """利用request封装get请求和post请求
   """
    def http_request(self, url, method, header=None, params=None, cookie=None):

        """url:请求的地址http://XXX:port
          :param:传递的参数 非必填参数 字典的格式传递参数
          method:请求方法,支持post和get
          cookie:请求的时候传递的cookie值"""
        if method=='get':
            res = requests.get(url,headers=header,data=params,cookies=cookie,verify=False)
        else:
            res = requests.post(url,headers=header,data=params,cookies=cookie,verify=False)
        return res #返回一个消息实体


if __name__=='__main__':
    login_url = '********'
    params = {"email": "********","password": "********"}
    header = {'Content-Type': 'application/json; charset=utf-8'}
    res=HttpRequest().http_request(login_url,'post',header,json.dumps(params))
    # print(json.dumps(payload))##
    # print(payload)#
    print("登陆结果是:",res.text)
    # print(type(res.json()['errmsg']))#
    # print(type(res.json()['errcode']))#
    # 查询分类
    params_fenlei={'group_id':'207','page': '1','limit': '10'}
    fenlei_url ='********'
    chaxun_res=HttpRequest().http_request(fenlei_url,'get',params_fenlei,cookie=res.cookies)
    print(type(json.dumps(params_fenlei)))
    print("查询结果是:",chaxun_res.text)
HttpRequest()

用例的代码:
request_case.py

import unittest
from  auto_study.API_AUTO.Tools.http_request import HttpRequest
class api_login(unittest.TestCase):#登陆接口的用例
    def setUp(self):
        #登陆
        self.login_url = '********'
        self.login_data = {"email": "********","password": "********"}
        #查看详情的网址
        self.fenlei_url= '********'
        #登陆后的cookies
        self.cookies=HttpRequest().http_request(self.login_url,'post',params=self.login_data).cookies
        print("登陆后产生的cookie是:{}".format(self.cookies))

    def test_normal_login(self):#输入正确的用户
        res=HttpRequest().http_request(self.login_url,'post',params=self.login_data)
        print(res.status_code)
        print(res.text)
    def test_no_password(self):#不输入密码
        data = {"email": "********","password": " "}
        res=HttpRequest().http_request(self.login_url,'post', params=data)
        print(res.status_code)
        print(res.text)
        try:
            self.assertIn('该用户不存在', res.text)
        except AssertionError as e:
            print("出错啦,断言错误是{}".format(e))
            raise
    def test_no_username(self):#不输入用户名
        data = {"email": " ","password": "********"}
        res=HttpRequest().http_request(self.login_url, 'post', params=data)
        print(res.status_code)
        print(res.text)
        try:
            self.assertIn('该用户不存在', res.text)
        except AssertionError as e:
            print("出错啦,断言错误是{}".format(e))
            raise

    def test_wrong_password(self):#输入错误的密码
        data = {"email": "********","password": "********"}
        res = HttpRequest().http_request(self.login_url, 'post', params=data)
        print(res.status_code)
        print(res.text)
        try:
            # self.assertIn('密码错误',res.json()['errmsg'])#这边报错了
            # self.assertIn(405,res.json()['errcode'])#这边报错了
            self.assertEqual(405, res.json()['errcode'])#res返回的是一个消息实体使用json转换为字典去取值
            self.assertEqual('密码错误', res.json()['errmsg'])
          # print(type(res.json()['errmsg']))#
          # print(type(res.json()['errcode']))#
        except AssertionError as e:
            print("出错啦,断言错误是{}".format(e))
            raise
    def test_list(self):
        params_fenlei = {'group_id':'207','page': '1','limit': '10'}
        res=HttpRequest().http_request(self.fenlei_url,'get',params_fenlei,self.cookies)
        print(res.status_code)
        print(res.text)
    def tearDown(self):
        print("用例执行结束")

执行单元测试用例的代码:
test_yapi_run_testcase.py

import unittest
from auto_study.test_package import  HTMLTestRunner
from auto_study.test_package import request_case#模块名
from auto_study.test_package.request_case import api_login#模块名
suite=unittest.TestSuite()#存储用例
# suite.addTest(api_login('test_wrong_password'))
#通过loader方式来加载用例
loader=unittest.TestLoader()#创建一个加载器
suite.addTest(loader.loadTestsFromModule(request_case))
#执行
# with open("test_douban.text","w+", encoding="UTF-8") as file:
#     runner=unittest.TextTestRunner(stream=file, description=True, verbosity=2)
#     runner.run(suite)
# runner=unittest.TextTestRunner
with open("test_yapi.html","wb") as file:
    runner=HTMLTestRunner.HTMLTestRunner(stream=file,verbosity=2,description="测试接口网址yapi的登陆",title="yapi")
    runner.run(suite)

改进—>因为登陆和查询等操作使用的是同一个账号,可以使用全局变量
缺点:关联性比较强,一步错步步错,因为可能查询比登陆先运行,或者说登陆失败
方法一:全局变量

import unittest
from  auto_study.API_AUTO.Tools.http_request import HttpRequest

COOKIE=None#全局变量
class api_login(unittest.TestCase):#登陆接口的用例
    def setUp(self):
        #登陆
        self.login_url = '********'
        #查看详情的网址
        self.fenlei_url= '********'
    def test_normal_login(self):#输入正确的用户
        global COOKIE#声明全局变量
        login_data = {"email": "********", "password": "********"}
        res=HttpRequest().http_request(self.login_url,'post',params=login_data)
        if res.cookies:#如果cookie存在,则更新cookie
            COOKIE=res.cookies
        print(res.status_code)
        print(res.text)
        try:
            self.assertIn('logout success...', res.text)
        except AssertionError as e:
            print("出错啦,断言错误是{}".format(e))
            raise
    def test_no_password(self):#不输入密码
        data = {"email": "********","password": " "}
        res=HttpRequest().http_request(self.login_url,'post', params=data)
        print(res.status_code)
        print(res.text)
        try:
            self.assertIn('密码错误', res.text)
        except AssertionError as e:
            print("出错啦,断言错误是{}".format(e))
            raise
    def test_no_username(self):#不输入用户名
        data = {"email": " ","password": "********"}
        res=HttpRequest().http_request(self.login_url, 'post', params=data)
        print(res.status_code)
        print(res.text)
        try:
            self.assertIn('该用户不存在', res.text)
        except AssertionError as e:
            print("出错啦,断言错误是{}".format(e))
            raise

    def test_wrong_password(self):#输入错误的密码
        data = {"email": "********","password": "********"}
        res = HttpRequest().http_request(self.login_url, 'post', params=data)
        print(res.status_code)
        print(res.text)
        try:
            # self.assertIn('密码错误',res.json()['errmsg'])#这边报错了
            # self.assertIn(405,res.json()['errcode'])#这边报错了
            self.assertEqual(405, res.json()['errcode'])#res返回的是一个消息实体使用json转换为字典去取值
            self.assertEqual('密码错误', res.json()['errmsg'])
          # print(type(res.json()['errmsg']))#
          # print(type(res.json()['errcode']))#
        except AssertionError as e:
            print("出错啦,断言错误是{}".format(e))
            raise
    def test_list(self):
        global COOKIE
        params_fenlei = {'group_id':'207','page': '1','limit': '10'}
        res=HttpRequest().http_request(self.fenlei_url,'get',params_fenlei,COOKIE)
        print(res.status_code)
        print(res.text)
    def tearDown(self):
        print("用例执行结束")

方法二:反射

import unittest
from  auto_study.API_AUTO.Tools.http_request import HttpRequest

class GetDate:
    Cookie=None#存储cookie,初始值为none

class api_login(unittest.TestCase):#登陆接口的用例
    def setUp(self):
        #登陆
        self.login_url = '********'
        #查看详情的网址
        self.fenlei_url= '********'
    def test_normal_login(self):#输入正确的用户
        login_data = {"email": "********", "password": "********"}
        res=HttpRequest().http_request(self.login_url,'post',params=login_data)
        if res.cookies:#如果cookie存在,则更新cookie
            setattr(GetDate,"Cookie",res.cookies)
        print(res.status_code)
        print(res.text)
        try:
            self.assertIn('logout success...', res.text)
        except AssertionError as e:
            print("出错啦,断言错误是{}".format(e))
            raise
    def test_no_password(self):#不输入密码
        data = {"email": "********","password": " "}
        res=HttpRequest().http_request(self.login_url,'post', params=data)
        print(res.status_code)
        print(res.text)
        try:
            self.assertIn('密码错误', res.text)
        except AssertionError as e:
            print("出错啦,断言错误是{}".format(e))
            raise
    def test_no_username(self):#不输入用户名
        data = {"email": " ","password": "********"}
        res=HttpRequest().http_request(self.login_url, 'post', params=data)
        print(res.status_code)
        print(res.text)
        try:
            self.assertIn('该用户不存在', res.text)
        except AssertionError as e:
            print("出错啦,断言错误是{}".format(e))
            raise

    def test_wrong_password(self):#输入错误的密码
        data = {"email": "********","password": "********"}
        res = HttpRequest().http_request(self.login_url, 'post', params=data)
        print(res.status_code)
        print(res.text)
        try:
            # self.assertIn('密码错误',res.json()['errmsg'])#这边报错了
            # self.assertIn(405,res.json()['errcode'])#这边报错了
            self.assertEqual(405, res.json()['errcode'])#res返回的是一个消息实体使用json转换为字典去取值
            self.assertEqual('密码错误', res.json()['errmsg'])
          # print(type(res.json()['errmsg']))#
          # print(type(res.json()['errcode']))#
        except AssertionError as e:
            print("出错啦,断言错误是{}".format(e))
            raise
    def test_list(self):
        params_fenlei = {'group_id':'207','page': '1','limit': '10'}
        res=HttpRequest().http_request(self.fenlei_url,'get',params_fenlei,getattr(GetDate,"Cookie"))
        print(res.status_code)
        print(res.text)
    def tearDown(self):
        print("用例执行结束")

总结

在编写用例的时候,如果第二条用例需要用到第一条用例的返回结果里的某个值,处理方式有3种:
1.写到setup里
2.反射
3.全局变量

class GetDate:
    Cookie="小郭"
if __name__ == '__main__':
    print(GetDate.Cookie)#运行结果是:小郭
    '''setattr可以直接把类里面的属性值做更改,setattr(类名,属性值,新值)'''
    setattr(GetDate,"Cookie","小黄")
    print(GetDate.Cookie)#类直接调用属性,运行结果是:小黄

    '''hasattr是判断是否有这个属性值,hasattr(类名,属性值)'''
    print(hasattr(GetDate,"Cookie"))#运行结果是:True
    '''getattr是获取这个属性值,getattr(类名,属性值)'''
    print(getattr(GetDate,"Cookie"))
    '''delattr是获取这个属性值,delattr(类名,属性值)'''
    delattr(GetDate,"Cookie")
    print(hasattr(GetDate,"Cookie"))

你可能感兴趣的:(python接口测试)