【python+pytest】接口自动化测试—接口基础篇

目录

前言

接口定义

接口分类

常见接口

测试分层

测试左移和右移

写在最后,给与的建议:


前言

就当前软件测试招聘的市场需求以及趋势而言,接口测试是测试人员必须掌握的技能,而接口自动化测试则是加薪利器。

工作过程中更多的是对HTTP协议的接口做接口测试,后续博客针对的也是HTTP类型的接口自动化相关文章。

接口定义

一般我们所说的接口即API,那什么又是API呢,百度给的定义如下:

API(Application Programming Interface,应用程序接口)是一些预先定义的接口(如函数、HTTP接口),或指软件系统不同组成部分衔接的约定。用来提供应用程序与开发人员基于某软件或硬件得以访问的一组例程,而又无需访问源码,或理解内部工作机制的细节。

有点绕口,但我们看下定义里面这些关键字:预先定义的接口 (如函数、HTTP接口)、基于软件或硬件得以访问、无需访问源码、无需理解内部工作机制,大概就明白了。

举例说明:

  1. 电脑或手机上提供了各种物理硬件接口,如:USB接口、充电接口、耳机接口、麦克风接口等。这些不同的接口有不同的功能,比如通过USB接口插入U盘就可以拷贝数据,插入耳机接口可以听音乐,我们无需关心这些接口的工作原理,只需通过这些接口满足我们的使用需求即可。

  2. 在中国天气网网上查询某个城市天气,输入城市名称,即可获取对应城市的天气。查询背后的本质也是调用了网站后台接口来获取数据,这里的接口是Web服务软件接口。用户不需要关注数据在网站后台是怎么查询的,只需要得到返回结果即可。

接口分类

软件接口分类的维度有很多,类型比较难以界定,也可能经常会被搞混淆。

以接口所使用的协议不同可做如下分类:

  • HTTP 接口,使用 HTTP 协议

  • Web Service 接口,使用

<think> 我们参考了四关于使用Playwright、Pytest和YAML构建UI自动化测试框架的引用资料。根据这些资料,我们可以总结出一个基于Playwright+Pytest+Yaml的UI与接口自动化测试框架的基本结构和实现要点。 主要组件: 1. Playwright:由微软开发的现代化Web自动化测试工具,支持多浏览器(Chromium, Firefox, WebKit),速度快且功能强大。 2. Pytest:一个功能强大的Python测试框架,具有丰富的插件生态(如pytest-playwright、allure-pytest等)。 3. YAML:用于编写测试数据或配置文件,便于数据与代码分离。 框架设计要点: 1. 使用Page Object模式(PO)管理页面元素和操作,提高代码可维护性。 2. 使用YAML文件管理测试数据(如登录账号、测试参数等)。 3. 使用Pytest作为测试执行引擎,利用其夹具(fixture)机制管理浏览器初始化、页面对象等。 4. 集成Allure生成美观的测试报告。 5. 支持命令行参数配置(如指定浏览器、运行环境、是否无头模式等)。 6. 支持接口测试:可以结合requests库或Playwright的API请求功能进行接口测试。 以下是框架的基本结构示例: 项目结构: ``` project/ ├── config/ # 配置文件 │ └── config.yaml # 全局配置文件 ├── data/ # 测试数据文件(YAML) ├── pages/ # 页面对象(Page Object) │ └── login_page.py ├── testcases/ # 测试用例 │ ├── ui/ # UI测试用例 │ │ └── test_login.py │ └── api/ # 接口测试用例 │ └── test_user_api.py ├── utils/ # 工具类 │ ├── __init__.py │ ├── common_utils.py # 通用工具 │ ├── request_utils.py # 接口请求工具 │ └── yaml_utils.py # YAML读写工具 ├── conftest.py # Pytest全局夹具配置 ├── run.py # 运行入口 └── requirements.txt # 依赖库 ``` 代码示例: 1. 配置文件(config.yaml)示例: ```yaml test: base_url: "https://test.example.com" live: base_url: "https://live.example.com" ``` 2. 页面对象(pages/login_page.py)示例: ```python from playwright.sync_api import Page class LoginPage: def __init__(self, page: Page): self.page = page def navigate(self): self.page.goto("/login") def fill_username(self, username): self.page.fill("#username", username) def fill_password(self, password): self.page.fill("#password", password) def click_login(self): self.page.click("button:text('登录')") def login(self, username, password): self.navigate() self.fill_username(username) self.fill_password(password) self.click_login() ``` 3. 测试用例(testcases/ui/test_login.py)示例: ```python import pytest from pages.login_page import LoginPage @pytest.mark.usefixtures("page") class TestLogin: def test_login_success(self, page): # 从YAML读取测试数据(这里简化,实际可以使用pytest参数化) login_page = LoginPage(page) login_page.login("testuser", "password123") # 断言登录成功 assert page.inner_text(".welcome") == "Welcome, testuser!" ``` 4. 工具类(utils/yaml_utils.py)示例: ```python import yaml def read_yaml(file_path): with open(file_path, 'r', encoding='utf-8') as f: return yaml.safe_load(f) ``` 5. 夹具配置(conftest.py)示例: ```python import pytest from playwright.sync_api import sync_playwright from utils.yaml_utils import read_yaml # 读取全局配置 config = read_yaml("./config/config.yaml") @pytest.fixture(scope="session") def env(request): """获取命令行参数env,默认test环境""" return request.config.getoption("--env", default="test") @pytest.fixture(scope="session") def base_url(env): """根据环境获取基础URL""" return config[env]["base_url"] @pytest.fixture(scope="function") def page(base_url): with sync_playwright() as p: browser = p.chromium.launch(headless=False) # 默认有头模式,可配置为命令行参数控制 page = browser.new_page() page.set_viewport_size({"width": 1920, "height": 1080}) page.goto(base_url) yield page browser.close() ``` 6. 运行入口(run.py)示例: ```python import argparse import pytest if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--env", default="test", help="test环境配置") parser.add_argument("--browser", default="chromium", help="指定浏览器: chromium, firefox, webkit") args = parser.parse_args() # 将命令行参数传递给pytest pytest.main([ "-s", "-v", f"--env={args.env}", f"--browser={args.browser}", "--alluredir=./allure-results" ]) ``` 安装依赖: 在requirements.txt中列出依赖库: ``` playwright pytest pyyaml allure-pytest pytest-playwright ``` 执行命令安装: ```bash pip install -r requirements.txt ``` 运行测试: ```bash python run.py --env test --browser chromium ``` 生成Allure报告: ```bash allure serve ./allure-results ``` 接口测试部分: 可以在testcases/api目录下编写接口测试用例,使用requests库或Playwright的APIRequestContext。例如: ```python # testcases/api/test_user_api.py import pytest @pytest.mark.usefixtures("base_url") def test_get_user(base_url): url = f"{base_url}/api/user/1" # 使用requests发送请求 response = requests.get(url) assert response.status_code == 200 assert response.json()["username"] == "testuser" ``` 或者使用Playwright的APIRequestContext(在同一个浏览器上下文中可以共享cookie等): ```python def test_get_user_with_playwright(api_request_context, base_url): response = api_request_context.get(f"{base_url}/api/user/1") assert response.ok assert response.json()["username"] == "testuser" ``` 在conftest.py中增加api_request_context夹具: ```python @pytest.fixture(scope="session") def api_request_context(playwright, base_url): context = playwright.request.new_context(base_url=base_url) yield context context.dispose() ``` 以上便是一个基于Playwright+Pytest+YAML的UI与接口自动化测试框架的基本设计。该框架结合了UI自动化和接口自动化,并利用YAML进行配置管理和数据驱动。 注意事项: - 对于接口测试,可以根据需要选择requests或Playwright的API请求功能。如果测试需要与UI共享上下文(如cookies),则使用Playwright的APIRequestContext更合适。 - 框架中还可以加入日志管理(如loguru)、异常截图、失败重试等功能。 通过以上设计,可以实现一个灵活、可维护的自动化测试框架。 §§相关问题§§ 1. Playwright的APIRequestContext与requests库在接口测试中的优缺点是什么? 2. 如何在Page Object模式中更好地管理页面元素的定位符? 3. 如何使用YAML文件实现数据驱动测试? </think> ### 基于Playwright、Pytest和YAML的UI与接口自动化测试框架设计 根据引用内容,我们整合出以下框架设计方案: #### 1. 框架结构设计 ``` project/ ├── config/ # 配置文件 │ └── env_config.yaml # 环境配置 ├── data/ # 测试数据 │ └── test_data.yaml # YAML格式测试数据 ├── pages/ # Page Object模式 │ └── login_page.py # 页面元素和操作封装 ├── interfaces/ # 接口模块 │ └── user_api.py # 接口请求封装 ├── testcases/ # 测试用例 │ ├── ui/ # UI测试用例 │ └── api/ # 接口测试用例 ├── utils/ # 工具类 │ ├── request_utils.py # 请求工具 │ └── yaml_utils.py # YAML处理工具 ├── conftest.py # Pytest全局配置 ├── run.py # 主运行入口 └── requirements.txt # 依赖库 ``` #### 2. 核心组件实现 **YAML配置文件示例** (`env_config.yaml`): ```yaml test: base_url: "https://test.example.com" username: "test_user" password: "P@ssw0rd" live: base_url: "https://live.example.com" username: "live_user" password: "L1veP@ss" ``` **Page Object模式示例** (`pages/login_page.py`): ```python class LoginPage: def __init__(self, page): self.page = page self.username_input = page.locator("#username") self.password_input = page.locator("#password") self.login_button = page.locator("#login-btn") def login(self, username, password): self.username_input.fill(username) self.password_input.fill(password) self.login_button.click() ``` **接口请求封装示例** (`interfaces/user_api.py`): ```python import requests from utils.yaml_utils import load_env_config def create_user(user_data): env = load_env_config() # 从YAML加载配置 response = requests.post( f"{env['base_url']}/api/users", json=user_data, headers={"Content-Type": "application/json"} ) return response ``` **Pytest测试用例示例** (`testcases/ui/test_login.py`): ```python import pytest from pages.login_page import LoginPage @pytest.mark.usefixtures("page") class TestLogin: def test_successful_login(self, page): login_page = LoginPage(page) login_page.login("admin", "admin123") assert page.url.contains("/dashboard") ``` #### 3. 关键技术集成 1. **环境切换**: ```python # run.py import argparse parser = argparse.ArgumentParser() parser.add_argument("-env", default="test") args = parser.parse_args() ``` 2. **数据驱动**(YAML + Pytest): ```python # conftest.py import pytest from utils.yaml_utils import load_test_data @pytest.fixture(params=load_test_data("login_cases.yaml")) def login_data(request): return request.param ``` 3. **报告生成**: ```bash pytest --alluredir=allure-results allure serve allure-results ``` #### 4. 依赖管理 `requirements.txt` 包含: ```text playwright==1.43.0 pytest==7.0.0 PyYAML==6.0.0 allure-pytest==2.13.5 requests==2.31.0 ``` #### 5. 执行流程 ```mermaid graph TD A[启动 run.py] --> B[解析命令行参数] B --> C{环境选择} C -->|test| D[加载测试配置] C -->|live| E[加载生产配置] D --> F[执行UI测试] E --> F F --> G[生成Allure报告] G --> H[发送通知] ``` ### 框架优势 1. **UI+接口一体化**:复用测试数据,共享认证状态 2. **环境隔离**:命令行一键切换环境配置 3. **数据驱动**:YAML管理测试数据和用例 4. **Page Object模式**:元素定位与操作分离 5. **Allure报告**:直观展示测试结果 6. **通知机制**:支持钉钉/企业微信通知[^1][^2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值