通过代码实现接口测试

发布时间 2023-03-23 16:48:41作者: winnie_B612

1.requests库

1)发送get请求

#导包

import requests

#发送请求

response=requests.get("http://www.baidu.com")

#查看响应

print("原始的数据编码为:", response.encoding)

print("设置前响应数据:", response.text)

# 设置响应数据编码格式

response.encoding = "utf-8"

print("设置编码后数据编码为:", response.encoding)

print("设置后响应数据:", response.text)

2)通过url传递参数

# 导包

import requests

# 发送请求

# 直接通过url传递参数

response = requests.get(" http://localhost/Home/Goods/search.html?q=iphone")

print(response.text)

3)通过params传递参数

第一种:传递字符串  第二种:传递字典

#通过字符串传参

import requests

urlA = "http://localhost/Home/Goods/search.html"

stringA = "q=iphone"

response = requests.get(url=urlA, params=stringA)

print(response.text)

#通过字典传参

import requests

urlA = "http://localhost/Home/Goods/search.html"

dictA = {

"q": "iphone"

}

response = requests.get(url=urlA, params=dictA) # 查看响应

print(response.text)

4)发送post请求,提交form表单数据

# 导包

import requests

# 发请求

login_url = "http://localhost/index.php?m=Home&c=User&a=do_login"

login_data = {

"username": "13488888888",

"password": "123456",

"verify_code": "8888"

}

response = requests.post(url=login_url, data=login_data)

# 看响应

print(response.json())

5)发送post请求,提交json数据

1. 请求IHRM项目的登录接口,请求数据( {"mobile":"13800000002", "password":"123456"})

2. 登录接口URL:http://ihrm-test.itheima.net/api/sys/login """

# 导包

import requests

# 发送请求

login_url = "http://ihrm-test.itheima.net/api/sys/login"

login_data = {

"mobile": "13800000002",

"password": "123456"

}

response = requests.post(url=login_url, json=login_data)

# 查看响应

print(response.json())

6)响应内容解析

response.status_code:响应状态码

response.url :url地址信息

response.encoding :查看响应数据编码格式

response.headers :查看头部信息

response.cookies : 查看cookies信息

response.text :文本形式查看响应数据

response.content :字节码形式查看响应数据

response.json() :json形式查看响应数据

import requests

# 1). 访问百度首页的接口`http://www.baidu.com`,获取以下响应数据

response = requests.get("http://www.baidu.com")

# 2). 获取响应状态码

print("响应状态码:", response.status_code)

# 3). 获 取 请 求 URL print("URL:", response.url)

# 4). 获取响应字符编码

print("编码格式为:", response.encoding)

# 5). 获取响应头数据

print("响应头信息:", response.headers)

print("Content-Type:", response.headers.get("Content-Type"))

# 6). 获取响应的cookie数据

print("cookies:", response.cookies)

print("提取指定的cookie:", response.cookies.get("BDORZ"))

# 7). 获取文本形式的响应内容

print("文本形式显示响应内容:", response.text)

# 8). 获取字节形式的响应内容

print("获取字节形式的响应内容:", response.content)

print("获取字节形式的响应内容:", response.content.decode("utf-8"))

7)设置请求头

import requests

login_url = "http://ihrm-test.itheima.net/api/sys/login"

 login_header = {

"Content-Type": "application/json"

}

login_data ={

"mobile": "13800000002",

"password": "123456"

}

# 发送请求

response = requests.post(url=login_url, json=login_data, headers=login_header)

# 查看响应

print(response.json())

8)设置cookie

import requests # 获取验证码

response = requests.get("http://localhost/index.php?m=Home&c=User&a=verify")

print(response.cookies)

PHPSESSID = response.cookies.get("PHPSESSID")

print(PHPSESSID)

# 登录

login_url = "http://localhost/index.php?m=Home&c=User&a=do_login"

login_data = {

"username": "13488888888",

"password": "123456",

"verify_code": "8888"

}

cookies = {

"PHPSESSID": PHPSESSID

}

response = requests.post(url=login_url, data=login_data, cookies=cookies)

print(response.json())

# 我的订单:http://localhost/Home/Order/order_list.html

response = requests.get("http://localhost/Home/Order/order_list.html", cookies=cookies)

print(response.text)

9)设置session

import requests # 创建session象

session = requests.Session()

# 获取验证码

response = session.get("http://localhost/index.php?m=Home&c=User&a=verify")

# 登录

login_url = "http://localhost/index.php?m=Home&c=User&a=do_login" login_data = {

"username": "13488888888",

"password": "123456",

"verify_code": "8888"

}

response = session.post(url=login_url, data=login_data)

print(response.json())

# 我的订单:http://localhost/Home/Order/order_list.html

response = session.get("http://localhost/Home/Order/order_list.html")

print(response.text)

2.集成unittest

 

UnitTest优势

 

  管理测试用例

 

  提供了丰富的断言

 

  生成测试报告

 

 

案例:使用TPShop项目完成对登录功能的接口测试

 

思路:

 

# 导包

 

# 创建测试类

 

# 创建测试方法

 

  # setup

 

    # 实例化session对象

 

    # 定义验证接口url地址

 

    # 定义登录接口url地址

 

  # teardown

 

    # 关闭session对象

 

  # 登录成功

 

    # 发送验证码请求并断言

 

    # 发登录请求并断言

 

  # 账号不存在

 

    # 发送验证码请求并断言

 

    # 发登录请求并断言

 

  # 密码错误

 

    # 发送验证码请求并断言

 

    # 发登录请求并断言

 

实现代码:

 

'''

 

获取验证码: http://localhost/index.php?m=Home&c=User&a=verify

 

登录 : http://localhost/index.php?m=Home&c=User&a=do_login

 

'''

 

# 导包

 

import unittest

 

import requests

 

# 创建测试类

 

class TPShopLogin(unittest.TestCase)

 

# 创建测试方法

 

    def setUp(self) :

 

        # 实例化session对象

 

        self.session=requests.session()

 

        # 定义验证接口url地址

 

        self.url_verify="http://localhost/index.php?m=Home&c=User&a=verify"

 

        # 定义登录接口url地址

 

        self.url_login="http://localhost/index.php?m=Home&c=User&a=do_login"

 

    # teardown

 

        # 关闭session对象

 

    def tearDown(self):

 

        self.session.close()

 

    # 登录成功

 

    def test01_success(self):

 

        # 发送验证码请求并断言

 

        response=self.session.get(url=self.url_verify)

 

        self.assertEqual(200,response.status_code)

 

        self.assertIn('image',response.headers.get("Content-Type"))

 

        # 发登录请求并断言

 

        login_data={

 

            "username": "13488888888",

 

            "password": "123456",

 

            "verify_code": "8888"

 

        }

 

        response=self.session.post(url=self.url_login,data=login_data)

 

        self.assertEqual(200,response.status_code)

 

        self.assertEqual(1,response.json().get("status"))

 

        self.assertIn('登录成功',response.json().get("msg"))

 

    # 账号不存在

 

    def test02_user_is_not_exist(self):

 

        # 发送验证码请求并断言

 

        response=self.session.get(url=self.url_verify)

 

        self.assertEqual(200,response.status_code)

 

        self.assertIn('image',response.headers.get("Content-Type"))

 

        # 发登录请求并断言

 

        login_data={

 

            "username": "13488888889",

 

            "password": "123456",

 

            "verify_code": "8888"

 

        }

 

        response=self.session.post(url=self.url_login,data=login_data)

 

        self.assertEqual(200,response.status_code)

 

        self.assertEqual(-1,response.json().get("status"))

 

        self.assertIn('账号不存在',response.json().get("msg"))

 

        # 发送验证码请求并断言

 

        # 发登录请求并断言

 

    # 密码错误

 

        def test03_password_error(self):

 

            # 发送验证码请求并断言

 

            response = self.session.get(url=self.url_verify)

 

            self.assertEqual(200, response.status_code)

 

            self.assertIn('image', response.headers.get("Content-Type"))

 

            # 发登录请求并断言

 

            login_data = {

 

                "username": "13488888888",

 

                "password": "error",

 

                "verify_code": "8888"

 

            }

 

            response = self.session.post(url=self.url_login, data=login_data)

 

            self.assertEqual(200, response.status_code)

 

            self.assertEqual(-2, response.json().get("status"))

 

            self.assertIn('密码错误', response.json().get("msg"))

 

生成html报告

 

#导包

 

import time

 

import unittest

 

from tools.HTMLTestRunner import HTMLTestRunner

 

from test03_unittest import TPShopLogin

 

#封装测试套件

 

suit=unittest.TestSuite()

 

suit.addTest(unittest.makeSuite(TPShopLogin))

 

#指定报告路径

 

report="./report/report-{}.html".format(time.strftime("%Y%m%d-%H%M%S"))

 

#打开文件流

 

with open(report,"wb") as f:

 

    #创建htmltestrunner运行器

 

    runner=HTMLTestRunner(f,title="tpshop接口测试报告")

 

    #执行测试套件

 

    runner.run(suit)

 

实现参数化

 

'''

 

获取验证码: http://localhost/index.php?m=Home&c=User&a=verify

 

登录 : http://localhost/index.php?m=Home&c=User&a=do_login

 

'''

 

# 导包

 

import json

 

import unittest

 

import requests

 

from parameterized import parameterized

 

#构造测试数据

 

def build_data():

 

test_data=[]

 

#指名文件路径

 

file="./data/login.json"

 

#打开文件

 

with open(file,encoding="utf-8") as f:

 

#加载文件

 

        json_data=json.load(f)

 

#读取文件存在一个列表中

 

        for case_data in json_data:

 

            username = case_data.get("username")

 

            password = case_data.get("password")

 

            verify_code = case_data.get("verify_code")

 

            status_code = case_data.get("status_code")

 

            status = case_data.get("status")

 

            msg = case_data.get("msg")

 

            test_data.append((username,password,verify_code,status_code,status,msg))

 

    print("test_data=".format(username,password,verify_code,status_code,status,msg))

 

    return test_data

 

# 创建测试类

 

class TPShopLogin2(unittest.TestCase)

 

# 创建测试方法

 

    def setUp(self) :

 

        # 实例化session对象

 

        self.session=requests.session()

 

        # 定义验证接口url地址

 

        self.url_verify="http://localhost/index.php?m=Home&c=User&a=verify"

 

        # 定义登录接口url地址

 

        self.url_login="http://localhost/index.php?m=Home&c=User&a=do_login"

 

 

 

    # teardown

 

        # 关闭session对象

 

    def tearDown(self):

 

        self.session.close()

 

    # 登录成功

 

    @parameterized.expand(build_data())

 

    def test01_success(self,username,password,verify_code,status_code,status,msg):

 

        # 发送验证码请求并断言

 

        response=self.session.get(url=self.url_verify)

 

        self.assertEqual(200,response.status_code)

 

        self.assertIn('image',response.headers.get("Content-Type"))

 

        # 发登录请求并断言

 

        login_data={

 

            "username": username,

 

            "password": password,

 

            "verify_code": verify_code

 

        }

 

        response=self.session.post(url=self.url_login,data=login_data)

 

        self.assertEqual(status_code,response.status_code)

 

        self.assertEqual(status,response.json().get("status"))

 

        self.assertIn(msg,response.json().get("msg"))

 

导入的login.json文件

 

 

[

 

  {

 

    "desc": "登录成功",

 

    "username": "13772569629",

 

    "password": "123456",

 

    "verify_code": "8888",

 

    "status_code": 200,

 

    "msg": "登录成功"

 

  },

 

  {

 

    "desc": "账号不存在",

 

    "username": "13772569628",

 

    "password": "123456",

 

    "verify_code": "8888",

 

    "status_code": 200,

 

    "msg": "账号不存在"

 

  },

 

  {

 

    "desc": "密码错误",

 

    "username": "13772569628",

 

    "password": "error",

 

    "verify_code": "8888",

 

    "status_code": 200,

 

    "msg": "密码错误"

 

  }

 

]

 

3.接口测试框架

 

1)接口测试框架说明

 

重点说明:

 

  (1)核心在于将测试用例与被测试系统API进行分离,便于后期维护

 

  (2)测试用例是通过unittest进行管理,并提供了丰富的断言(等于、包含等)

 

  (3)可以通过参数化思想测试数据与测试脚本的分离

 

  (4)可以调用数据库进行结果验证或将数据库作为参数化的数据源

 

  (5)借助第三方工具快速的生成HTML报告

 

2)框架结构说明

 

tpshop -- 项目代号

 

data -- 管理测试数据的文件夹

 

report -- 管理测试结果报告的文件夹

 

api -- 封装被测试系统的接口

 

scripts -- 测试用例脚本

 

tools -- 第三方工具包管理

 

app.py -- 配置信息文件

 

run_suite.py -- 测试用例执行入口

 

utils.py -- 自定义工具类

 

 

 

3)tpshop登录接口封装

class LoginAPI():

    #初始化

    def __init__(self):

        self.url_verify="http://localhost/index.php?m=Home&c=User&a=verify"

        self.url_login = "http://localhost/index.php?m=Home&c=User&a=do_login"

    #获取验证码

    def get_verify_code(self,session):

        return session.get(self.url_verify)

    #登录接口

    def login(self,ussername,password,verify_code):

        login_data={

            "username":ussername,

            "password":password,

            "verify_code":verify_code

        }

        return session.post(url=self.url_login, data=login_data)

4)定义接口测试用例

#1.导包

import unittest

import requests

from api.login import LoginAPI

#2.创建测试类

class TestLogin(unittest.TestCase):

    #前置处理

    def setUp(self):

        self.login_api=LoginAPI()#实例化接口类

        self.session=requests.session()#创建session对象

    #后置处理

    def tearDown(self):

        if self.session:

            self.session.close()

    #创建测试方法

    #登录成功

    def test01_login_success(self):

        #调用验证码接口并且进行断言

        response1=self.login_api.get_verify_code(self.session)

        self.assertEqual(200,response1.status_code)

        self.assertIn('image',response1.headers.get("Content-Type"))

        #调用登录接口获取登录信息并进行断言

        response2=self.login_api.login("18700651602","123456","8888",self.session)

        self.assertEqual(200,response2.status_code)

        self.assertEqual(1,response2.headers.get("status"))

        self.assertIn("登录成功",response2.json().get("msg"))

    #账号不存在

    def test02_user_is_not_exist(self):

        # 调用验证码接口并且进行断言

        response1 = self.login_api.get_verify_code(self.session)

        self.assertEqual(200, response1.status_code)

        self.assertIn('image', response1.headers.get("Content-Type"))

        # 调用登录接口获取登录信息并进行断言

        response2 = self.login_api.login("18700651604", "123456", "8888", self.session)

        self.assertEqual(200, response2.status_code)

        self.assertEqual(-1, response2.headers.get("status"))

        self.assertIn("账号不存在", response2.json().get("msg"))

 

    #密码错误

    def test03_password_error(self):

        # 调用验证码接口并且进行断言

        response1 = self.login_api.get_verify_code(self.session)

        self.assertEqual(200, response1.status_code)

        self.assertIn('image', response1.headers.get("Content-Type"))

        # 调用登录接口获取登录信息并进行断言

        response2 = self.login_api.login("18700651602", "error", "8888", self.session)

        self.assertEqual(200, response2.status_code)

        self.assertEqual(-2, response2.headers.get("status"))

        self.assertIn("密码错误", response2.json().get("msg"))

5)集成测试报告

# 1.导包

import time

import unittest

from scripts.test01_login import TestLogin

from tools.HTMLTestRunner import HTMLTestRunner

# 2.封装测试套件

suite=unittest.TestSuite()

suite.addTest(unittest.makeSuite(TestLogin))

 

# 3.指定测试报告的路径

report="./report/report-{}.html".format(time.strftime("%Y%m%d-%H%M%S"))

# 4.以文件流的形式打开文件

with open(report,"wb") as f:

#         创建HTMLTestRunner的运行器

    runner=HTMLTestRunner(f,title="tpshop接口测试报告")

#         执行测试套件

    runner.run(suite)

 

6)基于json文件实现测试数据参数化

 

进行参数化应该考虑哪些方面?

  1. 分析需要参数化的参数有哪些?

    输入数据:用户名,密码,验证码

    预期结果:content_type,状态码,业务码,业务消息

    2.选择数据承载的形式

    Json

    Db

   3.修改测试用例中的代码

    3.1构建参数化数据(build_data)

    3.2在测试用例前引用参数化(@parameter)

    3.3在具体的测试用例中,按照获得的数据进行参数化替换

 

代码实现

#1.导包

import json

import unittest

import requests

from api.login import LoginAPI

from parameterized import parameterized

#2.创建测试类

 

#构造数据的方法

def build_data():

    #找到文件路径

    file="../data/login.json"

    #定义空列表用来接收数据

    test_data=[]

    #以文件流的形式打开文件

    with open(file,encoding="utf-8") as f:

    #加载文件的数据

        json_data=json.load(f) #加载json文件数据

    #使用遍历的方式将每行的数据取除开,追加在空列表中,并返回

        for case_data in json_data:

            username=case_data.get("usename")

            password = case_data.get("password")

            verify_code = case_data.get("verify_code")

            status_code = case_data.get("status_code")

            status = case_data.get("status")

            msg = case_data.get("msg")

            test_data.append((username,password,verify_code,status_code,status,msg))

    return test_data

 

class TestLogin(unittest.TestCase):

    #前置处理

    def setUp(self):

        self.login_api=LoginAPI()#实例化接口类

        self.session=requests.session()#创建session对象

 

    #后置处理

    def tearDown(self):

        if self.session:

            self.session.close()

 

    #创建测试方法

    #登录成功

    @parameterized.expand(build_data())

    def test01_login(self,username,password,verify_code,status_code,status,msg):

        #调用验证码接口并且进行断言

        response1=self.login_api.get_verify_code(self.session)

        self.assertEqual(status_code,response1.status_code)

        self.assertIn('image',response1.headers.get("Content-Type"))

        #调用登录接口获取登录信息并进行断言

        response2=self.login_api.login(username,password,verify_code,self.session)

        self.assertEqual(status_code,response2.status_code)

        self.assertEqual(status,response2.headers.get("status"))

        self.assertIn(msg,response2.json().get("msg"))

Test_data.json文件里面的测试数据

 

[

  {

    "desc": "登录成功",

    "username": "13772569629",

    "password": "123456",

    "verify_code": "8888",

    "status_code": 200,

    "status": 1,

    "msg": "登录成功"

  },

  {

    "desc": "账号不存在",

    "username": "13772569628",

    "password": "123456",

    "verify_code": "8888",

    "status_code": 200,

    "status": -1,

    "msg": "账号不存在"

  },

  {

    "desc": "密码错误",

    "username": "13772569628",

    "password": "error",

    "verify_code": "8888",

    "status_code": 200,

    "status": -2,

    "msg": "密码错误"

  }

]

 

7)基于数据库实现测试数据参数化

 

#1.导包

 

import unittest

import requests

from api.login import LoginAPI

from tools.dbutil import DBUtil

from parameterized import parameterized

#2.创建测试类

 

#构造数据的方法

def build_data():

    #获取数据库的数据

    sql="select * from t_login"

    db_data=DBUtil.exe_sql(sql)

    #定义空列表用来接收数据

    test_data=[]

 

    #使用遍历的方式将每行的数据取除开,追加在空列表中,并返回

    for case_data in db_data:

        username=case_data[2]

        password = case_data[3]

        verify_code = case_data[4]

        status_code = case_data[5]

        status = case_data[6]

        msg = case_data.[7]

        test_data.append((username,password,verify_code,status_code,status,msg))

    return test_data

 

class TestLogin(unittest.TestCase):

    #前置处理

    def setUp(self):

        self.login_api=LoginAPI()#实例化接口类

        self.session=requests.session()#创建session对象

 

    #后置处理

    def tearDown(self):

        if self.session:

            self.session.close()

 

    #创建测试方法

    #登录成功

    @parameterized.expand(build_data())

    def test01_login(self,username,password,verify_code,status_code,status,msg):

        #调用验证码接口并且进行断言

        response1=self.login_api.get_verify_code(self.session)

        self.assertEqual(status_code,response1.status_code)

        self.assertIn('image',response1.headers.get("Content-Type"))

        #调用登录接口获取登录信息并进行断言

        response2=self.login_api.login(username,password,verify_code,self.session)

        self.assertEqual(status_code,response2.status_code)

        self.assertEqual(status,response2.headers.get("status"))

        self.assertIn(msg,response2.json().get("msg"))