【测试基础】Python 核心语法 —— 一篇搞定测试脚本开发基础
(2025-2026 测试工程师/自动化测试新人最实用版本)
以下内容刻意针对测试开发场景,优先级从高到低排列,重点标注测试脚本中最常写、最容易出错的部分。
1. 变量与常见数据类型(测试中最常操作的对象)
# 数值类型
count = 100 # int
rate = 3.14 # float
is_pass = True # bool
# 字符串(测试里最常用)
url = "https://api.example.com/v1/users"
msg = '登录失败,密码错误'
sql = """SELECT * FROM users WHERE id = 1""" # 多行字符串常用写法
# None(代表空/无/未初始化,非常重要)
response = None
token = None
# 类型判断(接口测试断言常用)
print(type(url) is str) # True
print(isinstance(count, (int, float))) # True
2. 字符串操作(接口/日志/断言 80% 时间都在搞这个)
s = "Hello, Tester! Welcome to 2026"
# 切片(最常用)
print(s[0:5]) # Hello
print(s[-1]) # 6
print(s[::-1]) # 倒序:6202 ot emocleW !retseT ,olleH
# 查找 & 判断
print("Tester" in s) # True
print(s.find("2026")) # 22(找不到返回 -1)
print(s.startswith("Hello")) # True
print(s.endswith("2026")) # True
# 替换 & 分割 & 拼接(参数化、日志处理常用)
new_s = s.replace("2026", "2027")
print(new_s)
params = "name=张三&age=28&city=东京"
items = params.split("&") # ['name=张三', 'age=28', 'city=东京']
print(items)
# f-string(2025年后最推荐的字符串格式化方式)
username = "重阳"
env = "staging"
url = f"https://api.{env}.com/users/{username}"
print(url) # https://api.staging.com/users/重阳
3. 列表 & 字典(测试数据构造核心)
# 列表(有序,可重复,可修改)
cases = ["TC001_登录成功", "TC002_密码错误", "TC003_账号不存在"]
cases.append("TC004_验证码错误")
cases.insert(1, "TC000_前置条件")
# 列表推导式(最常用写法)
ids = [f"TC{i:03d}" for i in range(1, 101)] # TC001 ~ TC100
even_ids = [x for x in ids if int(x[2:]) % 2 == 0] # 偶数用例
# 字典(JSON、请求参数、响应断言 最常用)
payload = {
"username": "testuser",
"password": "123456",
"device": "android",
"version": "2.8.1"
}
# 获取 & 安全获取
print(payload.get("username")) # testuser
print(payload.get("token", "not found")) # not found(不会抛异常)
# 修改 & 新增
payload["token"] = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
# 遍历(接口响应断言常用)
for key, value in payload.items():
print(f"{key:10} : {value}")
4. 条件 & 循环(用例执行、断言逻辑核心)
# 三元表达式(简洁写法)
status = "pass" if response.status_code == 200 else "fail"
# for + enumerate(带序号遍历)
for idx, case in enumerate(cases, 1):
print(f"第 {idx} 条用例:{case}")
# while(轮询等待常用)
timeout = 30
start = time.time()
while time.time() - start < timeout:
if check_element_visible():
break
time.sleep(1)
else:
raise TimeoutError("元素未出现")
5. 函数 & 参数(测试用例、工具函数封装核心)
# 最常用写法(带类型提示 + 默认值)
def send_request(
method: str,
url: str,
data: dict | None = None,
headers: dict | None = None,
timeout: int = 10
) -> dict:
"""发送 HTTP 请求并返回 json"""
import requests
try:
resp = requests.request(
method.upper(),
url,
json=data,
headers=headers,
timeout=timeout
)
resp.raise_for_status()
return resp.json()
except requests.exceptions.RequestException as e:
return {"success": False, "error": str(e)}
# 可变参数(处理不确定数量的参数很常用)
def log(*messages, level="INFO"):
prefix = f"[{level}] {time.strftime('%Y-%m-%d %H:%M:%S')}"
print(prefix, *messages)
6. 异常处理(测试脚本必须掌握)
try:
data = json.loads(response_text)
except json.JSONDecodeError:
logger.error("响应不是合法 JSON")
raise AssertionError("响应格式错误")
except Exception as e:
logger.exception("未知异常")
raise
7. 文件操作(读写 yaml/json/csv 配置、日志)
# 读写 json(最常用)
import json
with open("config.json", "r", encoding="utf-8") as f:
config = json.load(f)
with open("result.json", "w", encoding="utf-8") as f:
json.dump(result_data, f, ensure_ascii=False, indent=2)
# 读写 yaml(接口测试参数化最常用)
import yaml
with open("testcases.yaml", encoding="utf-8") as f:
cases = yaml.safe_load(f)
8. 模块导入 & 路径处理(测试框架必备)
# 相对导入(项目结构复杂时最常用)
from utils.http_client import send_request
from config.settings import BASE_URL, HEADERS
# 当前文件所在目录的父目录加入路径(常见解决方案)
import sys
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
sys.path.append(str(BASE_DIR))
快速总结:测试脚本最常写的 10 种语法模式
- f-string 拼接 URL / 日志
- dict.get() 安全取值
- 列表推导式生成用例 ID / 参数组合
- for … in … items() 遍历响应断言
- try-except 处理 JSON 解析、请求超时、网络异常
- with open() 读写配置文件
- requests.request(method, url, json=…) 统一发请求
- assert actual == expected 或 pytest.raises
- @pytest.mark.parametrize 参数化
- if name == “main“: 调试入口
如果你现在想马上动手写第一个测试脚本,推荐从下面这个最小的结构开始:
# test_demo.py
import requests
import pytest
BASE_URL = "https://httpbin.org"
@pytest.mark.parametrize("method", ["get", "post"])
def test_httpbin(method):
url = f"{BASE_URL}/{method}"
if method == "get":
resp = requests.get(url, params={"name": "重阳", "city": "东京"})
else:
resp = requests.post(url, json={"name": "重阳", "city": "东京"})
assert resp.status_code == 200
data = resp.json()
print(data)
你目前最想先搞定哪一块?
A. 接口测试完整模板
B. yaml 参数化用例读取
C. 断言与日志封装
D. pytest 基础用法
E. requests 常见坑处理
告诉我你的优先级,我可以继续给你对应代码 + 详细说明。