349 lines
36 KiB
HTML
349 lines
36 KiB
HTML
|
|
<!DOCTYPE html>
|
|||
|
|
<html lang="zh-CN" data-theme="light">
|
|||
|
|
<head>
|
|||
|
|
<meta charset="utf-8">
|
|||
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|||
|
|
<title>Python 够用即可 · 编程基础:Golang 与工程化 · 测试开发工程师从零到成熟</title>
|
|||
|
|
<meta name="description" content="编程基础:Golang 与工程化 第 10 章:Python 够用即可。">
|
|||
|
|
<link rel="stylesheet" href="../../assets/doc.css">
|
|||
|
|
</head>
|
|||
|
|
<body>
|
|||
|
|
|
|||
|
|
<header class="topbar">
|
|||
|
|
<div class="tb-in">
|
|||
|
|
<a class="brand" href="../../index.html"><span class="logo">QA</span><div>从零到成熟<small>测试开发 · 模块详解</small></div></a>
|
|||
|
|
<div class="crumbs">
|
|||
|
|
<a href="../../index.html">学习路径</a><span class="sep">/</span>
|
|||
|
|
<a href="../../index.html#s0">阶段 0 · 打地基</a><span class="sep">/</span>
|
|||
|
|
<a href="index.html">编程基础:Golang 与工程化</a><span class="sep">/</span>
|
|||
|
|
<b>第 10 章</b>
|
|||
|
|
</div>
|
|||
|
|
<div class="spacer"></div>
|
|||
|
|
<button class="btn" id="tocToggle">☰ 导航</button>
|
|||
|
|
<button class="btn" id="themeBtn" title="切换到深色主题">深色</button>
|
|||
|
|
</div>
|
|||
|
|
</header>
|
|||
|
|
|
|||
|
|
<div class="layout" id="layout">
|
|||
|
|
<aside class="sidebar">
|
|||
|
|
<h2>章节目录</h2>
|
|||
|
|
<nav id="chapters"><a class="toc-a" href="01-why.html"><i class="cn">1</i>为什么主线语言选 Go</a><a class="toc-a" href="02-syntax.html"><i class="cn">2</i>语法基本功</a><div class="subnav"><a class="toc-a lv3" href="02-syntax.html#sec-2-1">变量、常量与类型</a><a class="toc-a lv3" href="02-syntax.html#sec-2-2">切片与 map:共享底层数组的坑</a><a class="toc-a lv3" href="02-syntax.html#sec-2-3">结构体、方法与值/指针语义</a><a class="toc-a lv3" href="02-syntax.html#sec-2-4">defer / panic / recover</a><a class="toc-a lv3" href="02-syntax.html#sec-2-5">动手:解析一行 CSV 记录</a></div><a class="toc-a" href="03-error.html"><i class="cn">3</i>错误处理</a><div class="subnav"><a class="toc-a lv3" href="03-error.html#sec-3-1">error 是值:不要忽略它</a><a class="toc-a lv3" href="03-error.html#sec-3-2">%w 包装与 errors.Is / errors.As</a><a class="toc-a lv3" href="03-error.html#sec-3-3">不用 panic 做流程控制</a><a class="toc-a lv3" href="03-error.html#sec-3-4">错误信息该怎么写(对测试的意义)</a></div><a class="toc-a" href="04-interface.html"><i class="cn">4</i>接口与依赖注入</a><div class="subnav"><a class="toc-a lv3" href="04-interface.html#sec-4-1">隐式实现:Go 的接口哲学</a><a class="toc-a lv3" href="04-interface.html#sec-4-2">小接口:io.Reader 风格</a><a class="toc-a lv3" href="04-interface.html#sec-4-3">用接口做依赖注入</a><a class="toc-a lv3" href="04-interface.html#sec-4-4">这一条决定后面能不能打桩</a></div><a class="toc-a" href="05-concurrency.html"><i class="cn">5</i>并发模型</a><div class="subnav"><a class="toc-a lv3" href="05-concurrency.html#sec-5-1">goroutine:轻量但不是免费</a><a class="toc-a lv3" href="05-concurrency.html#sec-5-2">channel 与 select</a><a class="toc-a lv3" href="05-concurrency.html#sec-5-3">sync 包:WaitGroup / Mutex / Once</a><a class="toc-a lv3" href="05-concurrency.html#sec-5-4">数据竞争与 go test -race</a><a class="toc-a lv3" href="05-concurrency.html#sec-5-5">什么时候不该并发(测试脚本的并发陷阱)</a></div><a class="toc-a" href="06-context.html"><i class="cn">6</i>context:取消、超时与传递</a><div class="subnav"><a class="toc-a lv3" href="06-context.html#sec-6-1">context 是什么、为什么需要</a><a class="toc-a lv3" href="06-context.html#sec-6-2">超时控制:WithTimeout / WithDeadline</a><a class="toc-a lv3" href="06-context.html#sec-6-3">在测试框架里用 context 管超时</a><a class="toc-a lv3" href="06-context.html#sec-6-4">常见误用与自查</a></div><a class="toc-a" href="07-layout.html"><i class="cn">7</i>工程结构与依赖管理</a><div class="subnav"><a class="toc-a lv3" href="07-layout.html#sec-7-1">go mod:依赖从哪来</a><a class="toc-a lv3" href="07-layout.html#sec-7-2">cmd / internal / pkg 布局</a><a class="toc-a lv3" href="07-layout.html#sec-7-3">包边界与循环依赖</a><a class="toc-a lv3" href="07-layout.html#sec-7-4">命名、可见性与可读性</a></div><a class="toc-a" href="08-stdlib.html"><i class="cn">8</i>标准库够用</a><div class="subnav"><a class="toc-a lv3" href="08-stdlib.html#sec-8-1">net/http:最小的测试用服务</a><a class="toc-a lv3" href="08-stdlib.html#sec-8-2">encoding/json 与结构体标签</a><a class="toc-a lv3" href="08-stdlib.html#sec-8-3">database/sql 初体验</a><a class="toc-a lv3" href="08-stdlib.html#sec-8-4">log/slog 结构化日志</a><a class="toc-a lv3" href="08-stdlib.html#sec-8-5">flag / os / io 的组合</a></div><a class="toc-a" href="09-toolchain.html"><i class="cn">9</i>工具链、调试与读代码</a><div class="subnav"><a class="toc-a lv3" href="09-toolchain.html#sec-9-1">gofmt / go vet / go build</a><a class="toc-a lv3" href="09-toolchain.html#sec-9-2">用 delve 打断点</a><a class="toc-a lv3" href="09-toolchain.html#sec-9-3">读别人的 Go 代码:从 main 开始</a><a class="toc-a lv3" href="09-toolchain.html#sec-9-4">版本与依赖排查</a></div><span class="toc-a active" aria-current="page"><i class="cn
|
|||
|
|
<div class="side-foot">
|
|||
|
|
<a class="btn" href="index.html">← 模块目录</a>
|
|||
|
|
<a class="btn" href="../../index.html">学习路径</a>
|
|||
|
|
</div>
|
|||
|
|
</aside>
|
|||
|
|
<div class="mask" id="mask"></div>
|
|||
|
|
|
|||
|
|
<main class="main-col">
|
|||
|
|
<article>
|
|||
|
|
<p class="chapnav">
|
|||
|
|
<a href="index.html">编程基础:Golang 与工程化</a>
|
|||
|
|
<span>·</span>
|
|||
|
|
<span>第 <b class="pos">10</b> / 13 章</span>
|
|||
|
|
<span>·</span>
|
|||
|
|
<span>本章 3 小节</span>
|
|||
|
|
</p>
|
|||
|
|
|
|||
|
|
<h2 id="python"><span class="n">10</span>Python 够用即可</h2>
|
|||
|
|
|
|||
|
|
<p>上一章我们练的是「拿到一个陌生的 Go 工程怎么读、怎么在断点里看变量的真实值」。这一章换一个方向:你接手的东西很可能不是 Go 写的,而是前人留下的几筐 Python 脚本——造数据的、跑接口的、清洗日志的。它们大多能跑,但没人说得清哪些用例真的在执行,也没人敢改。</p>
|
|||
|
|
<p>所以这个模块专门留一章讲 Python。目标不是精通,而是<mark>能读懂并接手别人的 pytest 脚本</mark>:知道它会跑哪些用例、状态在哪里共享、失败时该看哪一行。做到这一点,你在团队里的处境就从「脚本是别人写的黑盒」变成「脚本是我的工具」。至于什么时候该用 Python、什么时候必须换 Go,放进最后一节给判据。</p>
|
|||
|
|
|
|||
|
|
<div class="box tip">
|
|||
|
|
<span class="bt">先建立一条底线</span>
|
|||
|
|
<p>接手别人的仓库,第一件事不是读代码,是在项目根目录敲 <code>pytest --collect-only -q</code>。<b>它打印出来的用例清单,才是这个仓库真实在跑的测试。</b>文件名像测试但函数名不像、或者被 <code>collect_ignore</code> 排除掉的文件,都不会出现在这份清单里。你以为的覆盖率和实际的覆盖率,差的就是这几行输出。</p>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<h3 id="sec-10-1">10.1 读懂别人的 pytest 脚本</h3>
|
|||
|
|
<p>pytest 的收集规则很朴素,正因为如此,别人改过的配置才更容易骗到你。默认情况下它从 rootdir 开始递归查找 <code>test_*.py</code> 和 <code>*_test.py</code> 两类文件;在文件里只收集 <code>test_</code> 开头的函数、<code>Test</code> 开头的类(类里不能定义 <code>__init__</code>),类中的测试方法同样要以 <code>test_</code> 开头。规则一旦被写进 <code>pyproject.toml</code> 的 <code>[tool.pytest.ini_options]</code>,比如 <code>python_functions = ["check_*"]</code>,那么脚本里所有 <code>check_order()</code> 都会被当成用例跑起来——这时用「函数名是不是 test_ 开头」来判断覆盖范围就完全错了。</p>
|
|||
|
|
<p>所以读一个陌生脚本,第一步是看清单而不是读代码:清单里没有的用例等于没写,比你预期多的用例说明收集规则被改过。</p>
|
|||
|
|
<p>断言部分是 pytest 最值钱的地方:它在导入阶段重写 <code>assert</code> 语句,失败时会打印一行以 <code>E assert</code> 开头的输出,把参与比较的子表达式的实际值摆出来。老脚本里常见的 <code>self.assertEqual(...)</code> 是 unittest 的写法,在 pytest 下也能跑,但失败时只有一句 <code>AssertionError</code>,没有左右值,接手时优先把它改成裸 <code>assert</code>。</p>
|
|||
|
|
<p>接着是 fixture,也就是 pytest 的依赖注入机制。用例函数写在参数列表里的名字就是注入点,pytest 按名字查找同名 fixture:先看当前模块,再看同目录和上层目录的 <code>conftest.py</code>,最后才轮到插件提供的。<b>想弄清一条用例的前置条件,只要看它的参数名和对应的 fixture 定义,不需要从头读到尾。</b></p>
|
|||
|
|
<p>fixture 真正决定行为的是 <code>scope</code>:同一次会话里它会被建立几次、状态能存活多久,直接决定用例之间会不会互相污染。</p>
|
|||
|
|
|
|||
|
|
<div class="tablewrap">
|
|||
|
|
<table>
|
|||
|
|
<thead><tr><th><code>scope</code> 取值</th><th>一次会话里建立几次</th><th>典型用途</th><th>出问题时的现场</th></tr></thead>
|
|||
|
|
<tbody>
|
|||
|
|
<tr><td><code>function</code>(默认)</td><td>每条用例一次</td><td>每条用例独立的登录态、独立的下单数据</td><td>最慢,但几乎不会串状态;代价是多登了几次</td></tr>
|
|||
|
|
<tr><td><code>class</code></td><td>每个 <code>Test</code> 类一次</td><td>同一组场景共享一个已登录的账号</td><td>类内第一条用例改了状态,后面几条跟着变</td></tr>
|
|||
|
|
<tr><td><code>module</code></td><td>每个测试文件一次</td><td>同一个接口的读写用例共用一个连接</td><td>文件内用例顺序变了,结果就变了</td></tr>
|
|||
|
|
<tr><td><code>session</code></td><td>整个 <code>pytest</code> 进程一次</td><td>一次登录,全量用例复用 token</td><td>某个用例把优惠券领走、把库存扣掉,后面的用例全挂</td></tr>
|
|||
|
|
</tbody>
|
|||
|
|
</table>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<p>验证作用域不要靠读代码,用 <code>pytest -v -s --setup-show</code> 跑一遍:输出里用 <code>SETUP</code> / <code>TEARDOWN</code> 标出每个 fixture 在哪些用例上建立和销毁。同一个 fixture 只在第一条用例前出现一次 <code>SETUP F</code>,说明它是 <code>module</code> 或 <code>session</code> 级;每条用例前面都出现一次,那就是 <code>function</code> 级。这行输出不受 <code>autouse</code> 和继承关系影响,比读代码可靠。</p>
|
|||
|
|
<p><code>yield</code> 是 fixture 的分界线:<code>yield</code> 之前是前置,<code>yield</code> 之后是清理。清理里抛异常时,报告上写的是 <code>ERROR at teardown of test_create_order</code>,不是 <code>FAILED</code>,两者在统计里分开计数。这个区分很关键:<code>FAILED</code> 指向被测接口,<code>teardown ERROR</code> 指向脚本自己——数据没删干净、连接没关、或者把断言写进了清理代码。</p>
|
|||
|
|
<p>还有一个坑叫隐形依赖:<code>@pytest.fixture(autouse=True)</code>。加了它的 fixture 不出现在用例参数里也会自动执行,于是现象变成「参数列表空空的,但每条用例前面都多了一次登录请求」。读代码时先跑一遍 <code>grep -rn "autouse" .</code> 把这些标出来。同理,<code>conftest.py</code> 是逐层生效的:子目录里同名的 fixture 会覆盖父目录的,改上层 conftest 可能只影响一部分用例。</p>
|
|||
|
|
<p>参数化是接手脚本时最该学会的一项,因为它是「把一次手工检查变成一堆可重复用例」的最短路径。写法是 <code>@pytest.mark.parametrize("amount_cent,expect_code", [(9900, 0), (1, 40001)], ids=["reach_threshold", "below_threshold"])</code>,用例名会变成 <code>test_coupon[below_threshold]</code>,报告里一眼能看出是哪组数据失败。有个必须知道的细节:参数列表在模块导入阶段就求值,所以别把依赖接口状态的表达式写进参数——那样连 <code>--collect-only</code> 都会真的发请求。金额一律用「分」的整数,别在 Python 这边换成元,否则和 Go 侧的 <code>total_amount</code>、<code>pay_amount</code> 对不上。</p>
|
|||
|
|
<p>最后一组工具是标记:<code>@pytest.mark.skip</code> 无条件跳过,<code>@pytest.mark.skipif(条件, reason="...")</code> 按条件跳过,<code>@pytest.mark.xfail(reason="...", strict=True)</code> 表示「这条用例现在就该失败」。<code>xfail</code> 的 <code>strict</code> 值决定它有没有用:默认不严格时,被标记的用例意外通过了只报 <code>XPASS</code>,不算失败;写成 <code>strict=True</code> 之后 <code>XPASS</code> 会变成失败,专门抓「缺陷已经修好、标记却忘了删」的情况。用 <code>-m</code> 按标记筛选用例之前,标记要注册在配置里,否则会看到 <code>PytestUnknownMarkWarning</code>。</p>
|
|||
|
|
|
|||
|
|
<pre data-lang="python" data-name="tests/test_coupon.py —— 别人留下的脚本大概长这样"># tests/test_coupon.py —— 别人留下的脚本大概长这样
|
|||
|
|
import os
|
|||
|
|
import pytest
|
|||
|
|
import requests
|
|||
|
|
|
|||
|
|
BASE = os.getenv("ORDER_API_BASE", "http://order-api.test:8080")
|
|||
|
|
LIVE = os.getenv("RUN_LIVE") == "1" # 仅预发环境置 1
|
|||
|
|
|
|||
|
|
@pytest.fixture(scope="module")
|
|||
|
|
def api(): # 参数名即注入点
|
|||
|
|
s = requests.Session() # 复用连接池 + 维护 cookie
|
|||
|
|
s.headers["Authorization"] = "Bearer " + os.environ["QA_TOKEN"]
|
|||
|
|
yield s # yield 之前是前置,之后是清理
|
|||
|
|
s.close()
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize("amount_cent,expect_code", [
|
|||
|
|
(9900, 0), # 满 9900 分(99 元)能用券
|
|||
|
|
(1, 40001), # 未达门槛,业务码 40001
|
|||
|
|
], ids=["reach_threshold", "below_threshold"])
|
|||
|
|
def test_coupon(api, amount_cent, expect_code):
|
|||
|
|
r = api.post(BASE + "/api/coupon/calc",
|
|||
|
|
json={"coupon_id": "C2024001", "amount_cent": amount_cent}, timeout=(3.05, 10))
|
|||
|
|
assert r.json().get("code") == expect_code, r.text
|
|||
|
|
|
|||
|
|
@pytest.mark.skipif(not LIVE, reason="只在预发环境跑真实扣减")
|
|||
|
|
@pytest.mark.xfail(reason="已知缺陷 QA-2231:并发下同一张券被重复核销", strict=True)
|
|||
|
|
def test_coupon_concurrent(api):
|
|||
|
|
codes = [api.post(BASE + "/api/coupon/use",
|
|||
|
|
json={"coupon_id": "C2024001", "order_id": "O202405110001"},
|
|||
|
|
timeout=(3.05, 10)).json()["code"] for _ in range(2)]
|
|||
|
|
assert codes.count(0) == 1, "同一张券被核销了 %d 次" % codes.count(0)</pre>
|
|||
|
|
|
|||
|
|
<pre data-lang="bash" data-name="看清单、缩小范围、读失败原文"># ① 先确认收集到几条,防止「跑过了其实没跑」
|
|||
|
|
$ pytest --collect-only -q tests/
|
|||
|
|
tests/test_coupon.py::test_coupon[reach_threshold]
|
|||
|
|
tests/test_coupon.py::test_coupon[below_threshold]
|
|||
|
|
tests/test_coupon.py::test_coupon_concurrent
|
|||
|
|
3 tests collected in 0.21s
|
|||
|
|
|
|||
|
|
# ② 只看一组数据,并打印 fixture 的建立过程
|
|||
|
|
$ pytest tests/test_coupon.py -k below_threshold -v --setup-show
|
|||
|
|
SETUP M api
|
|||
|
|
tests/test_coupon.py::test_coupon[below_threshold] (fixtures used: api, request). PASSED
|
|||
|
|
TEARDOWN M api
|
|||
|
|
|
|||
|
|
# ③ 全量跑时失败:断言重写会把子表达式的实际值打出来
|
|||
|
|
$ pytest -q
|
|||
|
|
E AssertionError: {"code": 40002, "msg": "优惠券已失效"}
|
|||
|
|
E assert 40002 == 0
|
|||
|
|
E + where 40002 = {'code': 40002, 'msg': '优惠券已失效'}.get('code')
|
|||
|
|
|
|||
|
|
# ④ 只重跑上次失败的
|
|||
|
|
$ pytest -q --lf
|
|||
|
|
$ pytest -q -m "not smoke" --maxfail=1</pre>
|
|||
|
|
|
|||
|
|
<div class="box warn">
|
|||
|
|
<span class="bt">单跑通过、全量跑挂,怎么定位</span>
|
|||
|
|
<p>最典型的现场:<code>pytest tests/test_coupon.py</code> 全绿,<code>pytest</code> 全量跑时 <code>test_coupon[reach_threshold]</code> 返回 <code>40002</code>(这张券已经被别的用例核销了),而单跑时返回 <code>0</code>。八成是共享数据没隔离:fixture 作用域太大、建过一次就复用,或者某条用例把券用掉了没还原。</p>
|
|||
|
|
<p>定位动作按顺序做:① <code>pytest -v --setup-show</code> 看这个 fixture 的 <code>SETUP</code> 出现在哪条用例之前;② <code>pytest -q -k "coupon or order"</code> 缩小组合,找出「和哪条用例一起跑才失败」;③ <code>pytest -q --lf</code> 反复重跑失败集合,确认是不是稳定复现。修法是把 fixture 拆成 <code>scope="function"</code>,或者把前置数据改成每条用例自己造(订单号加随机后缀做隔离)。<b>修复的判据是:单跑和全量跑结果一致,并且连跑三次都一致。</b></p>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<h3 id="sec-10-2">10.2 requests 与 pytest 最小集</h3>
|
|||
|
|
<p>Python 侧的接口脚本,九成内容都落在 <code>requests</code> 上。真正决定它能不能在 CI 里稳定跑下去的只有三件事:用不用 <code>Session</code>、有没有写 <code>timeout</code>、断言是不是只看了状态码。</p>
|
|||
|
|
<p><code>Session</code> 的价值有两块。一是连接复用:<code>requests.get()</code> 每次都走一遍建连和断开,而 <code>Session</code> 内部持有一个 urllib3 连接池(默认 <code>pool_maxsize=10</code>),连续请求之间会复用同一条 TCP 连接。二是状态保持:它会自动带上服务端下发的 cookie,也保留你写进 <code>s.headers</code> 的公共头。别人脚本里看不到 <code>Authorization</code> 却能跑通,通常就是凭证写在 cookie 里。</p>
|
|||
|
|
<p>连接复用可以直接看系统的连接表:串行发 20 次请求,指向 8080 端口只应该有 1 条 <code>ESTABLISHED</code>;换成裸 <code>requests.get()</code>,每条请求都会留下一次建连和断开。状态保持看 Session 自己的两个属性,直接在 REPL 里打印就行。</p>
|
|||
|
|
|
|||
|
|
<pre data-lang="bash" data-name="验证 Session 真的复用了连接"># 串行发 20 次
|
|||
|
|
$ python3 -c "import requests; s=requests.Session(); [s.get('http://order-api.test:8080/api/health') for _ in range(20)]"
|
|||
|
|
|
|||
|
|
# 之后看连接表:第一行是表头,去掉它剩 1 行,说明连接被复用
|
|||
|
|
$ ss -tn state established '( dport = :8080 )' | tail -n +2 | wc -l
|
|||
|
|
1
|
|||
|
|
|
|||
|
|
# 压测并发时这个数字会上涨,200 并发下几十条并存正常
|
|||
|
|
$ ss -tn state established '( dport = :8080 )'
|
|||
|
|
State Recv-Q Send-Q Local Address:Port Peer Address:Port
|
|||
|
|
ESTAB 0 0 10.20.3.77:51842 10.20.3.9:8080
|
|||
|
|
ESTAB 0 0 10.20.3.77:51843 10.20.3.9:8080</pre>
|
|||
|
|
|
|||
|
|
<pre data-lang="text" data-name="在 REPL 里确认登录态到底放在哪里">>>> s.cookies.get_dict()
|
|||
|
|
{'SESSION': 'a1b2c3d4e5f6a7b8'}
|
|||
|
|
>>> s.headers['Authorization']
|
|||
|
|
'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
|
|||
|
|
>>> s.get(BASE + '/api/order/detail', params={'order_id': 'O202405110001'}, timeout=(3.05, 10)).elapsed.total_seconds()
|
|||
|
|
0.031</pre>
|
|||
|
|
|
|||
|
|
<p><code>timeout</code> 是这三个里最容易漏、后果最难查的一个。<b>requests 默认没有超时</b>,服务端不返回就永远等下去;表现在 CI 上是任务卡住不结束,日志停在某条用例上。正确写法是给一个二元组 <code>timeout=(3.05, 10)</code>:第一个数是建立连接的最大秒数,第二个数是两次读取之间的最大间隔秒数——注意它不是整个请求的总时长,服务端只要每 9 秒吐一点数据,一个小时内都不会触发读超时。3.05 这个数来自社区惯例,略大于一次 TCP 重传的等待时间。</p>
|
|||
|
|
<p>要看懂超时类报错,得能认出原文:连接没建起来是 <code>requests.exceptions.ConnectTimeout</code>,连上了但服务端不吐数据是 <code>requests.exceptions.ReadTimeout</code>,前者指向服务没起或端口不对,后者指向后端慢或卡死。下面这张表把常见的几种原文和它们的责任方列在一起,照着对就行。</p>
|
|||
|
|
<p>最后是断言策略。<code>r.raise_for_status()</code> 只在 HTTP 4xx / 5xx 时抛 <code>HTTPError</code>,业务码是 <code>0</code> 还是 <code>40001</code> 它完全不管;反过来只断言业务码也不行——当 nginx 返回 502 的 HTML 错误页时,<code>r.json()</code> 会先抛 <code>JSONDecodeError</code>。可靠做法是两段式:先 <code>assert r.status_code == 200, r.text</code> 把原始响应体留在报告里,再断业务码与关键字段。</p>
|
|||
|
|
<p>证书和代理是另外两个「本地能跑、CI 挂掉」的常见来源。测试环境用自签证书时,正确做法是 <code>verify="/etc/ssl/qa-ca.crt"</code> 指定 CA 文件,而不是 <code>verify=False</code> 关掉校验(关掉会打 <code>InsecureRequestWarning</code>)。<code>requests</code> 默认 <code>trust_env=True</code>,会读取 <code>HTTP_PROXY</code> / <code>HTTPS_PROXY</code>,你本机为了抓包开着的代理会让所有请求绕一圈。</p>
|
|||
|
|
|
|||
|
|
<div class="tablewrap">
|
|||
|
|
<table>
|
|||
|
|
<thead><tr><th>你看到的报错原文</th><th>它真正的含义</th><th>责任方</th><th>怎么验证</th></tr></thead>
|
|||
|
|
<tbody>
|
|||
|
|
<tr><td><code>ConnectTimeout: ... (connect timeout=3.05)</code></td><td>TCP 都没建起来</td><td>服务没起、端口不对、网络不通</td><td><code>ss -lnt | grep 8080</code>,再 <code>curl -v --connect-timeout 3</code> 直连一次</td></tr>
|
|||
|
|
<tr><td><code>ReadTimeout: ... (read timeout=10)</code></td><td>连上了,但 10 秒内没等到数据</td><td>后端慢、卡死,或该接口本就需要更久</td><td>查网关日志里 <code>$upstream_response_time</code>,看是不是等于你的 read 值</td></tr>
|
|||
|
|
<tr><td><code>ConnectionError: ... Max retries exceeded ... [Errno 111] Connection refused</code></td><td>端口没人监听</td><td>后端进程没起来</td><td>到目标机器上 <code>ps -ef | grep order-api</code></td></tr>
|
|||
|
|
<tr><td><code>SSLError: certificate verify failed: self-signed certificate</code></td><td>证书链校验不通过</td><td>测试环境自签证书</td><td>换成 <code>verify="qa-ca.crt"</code>;只改脚本,别关校验</td></tr>
|
|||
|
|
<tr><td><code>JSONDecodeError: Expecting value: line 1 column 1 (char 0)</code></td><td>返回的根本不是 JSON</td><td>多半是网关的 HTML 错误页</td><td>先 <code>print(r.status_code, r.text[:200])</code>,再看 <code>Server</code> 头</td></tr>
|
|||
|
|
<tr><td><code>HTTPError: 401 Client Error</code>(被 <code>raise_for_status</code> 抛出)</td><td>凭证没生效或已过期</td><td>脚本的登录前置</td><td>打印 <code>s.headers</code> 与 <code>s.cookies.get_dict()</code>,对着登录响应核一遍</td></tr>
|
|||
|
|
<tr><td><code>KeyError: 'token'</code></td><td>响应结构与脚本假设不一致</td><td>接口改了字段,脚本没跟上</td><td>先 <code>print(r.json())</code> 看真实层级,别急着改断言</td></tr>
|
|||
|
|
</tbody>
|
|||
|
|
</table>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<p>把上面的最小集拼起来,就是一个可以直接 <code>pytest</code> 跑的接口脚本:登录一次,拿 token,下单,再用订单号回查确认落库状态。它只有三十行左右,但包含了登录前置、连接复用、超时、两层断言四件事。</p>
|
|||
|
|
|
|||
|
|
<pre data-lang="python" data-name="scripts/order_flow_test.py —— 登录 → 下单 → 查单,直接跑"># scripts/order_flow_test.py —— 登录 → 下单 → 查单,直接跑
|
|||
|
|
import os
|
|||
|
|
import pytest
|
|||
|
|
import requests
|
|||
|
|
|
|||
|
|
BASE = os.getenv("ORDER_API_BASE", "http://order-api.test:8080")
|
|||
|
|
|
|||
|
|
@pytest.fixture(scope="session")
|
|||
|
|
def api(): # 参数名 = fixture 名
|
|||
|
|
s = requests.Session() # 复用连接池 + 自动维护 cookie
|
|||
|
|
s.headers.update({"Content-Type": "application/json"})
|
|||
|
|
r = s.post(BASE + "/api/login",
|
|||
|
|
json={"username": "qa_auto", "password": "qa_auto_123"},
|
|||
|
|
timeout=(3.05, 10)) # 连接 3.05 秒、读 10 秒,缺一个都可能挂死
|
|||
|
|
assert r.status_code == 200, r.text # 登录失败就停在这里,别污染后面的断言
|
|||
|
|
token = r.json()["data"]["token"]
|
|||
|
|
s.headers["Authorization"] = "Bearer " + token
|
|||
|
|
yield s # yield 之前是前置,之后是清理
|
|||
|
|
s.close()
|
|||
|
|
|
|||
|
|
def test_order_created_then_query(api):
|
|||
|
|
payload = {"order_no": "NO202405110001", "user_id": 9001,
|
|||
|
|
"total_amount": 12000, "coupon_id": None}
|
|||
|
|
r = api.post(BASE + "/api/order/create", json=payload, timeout=(3.05, 10))
|
|||
|
|
assert r.status_code == 200, r.text # 502 时这里能看到 nginx 的错误页
|
|||
|
|
body = r.json()
|
|||
|
|
assert body.get("code") == 0, body # 业务码单独断一层
|
|||
|
|
order_id = body["data"]["order_id"]
|
|||
|
|
assert isinstance(order_id, str) and order_id.startswith("O")
|
|||
|
|
|
|||
|
|
detail = api.get(BASE + "/api/order/detail",
|
|||
|
|
params={"order_id": order_id}, timeout=(3.05, 10)).json()
|
|||
|
|
assert detail["data"]["status"] == 10 # 10 = 待支付
|
|||
|
|
assert detail["data"]["pay_time"] is None # 未支付订单无支付时间</pre>
|
|||
|
|
|
|||
|
|
<div class="box note">
|
|||
|
|
<span class="bt">脚本卡住不退出,第一步做什么</span>
|
|||
|
|
<p>CI 任务卡在某个用例上不动,八成是某次请求没写 <code>timeout</code>。别急着调流水线的超时时间,先按 <code>Ctrl</code>+<code>C</code> 让 pytest 中断,它会打印当前卡在哪一条用例、哪一个调用栈上;栈顶停在 <code>requests/sessions.py</code> 的 <code>send</code> 里,就说明这次请求没有超时保护。把 <code>timeout=(3.05, 10)</code> 补上,再复现一次:「卡住」应该变成一条明确的 <code>ReadTimeout</code>。<b>有超时的失败,比没有超时的等待好查一百倍。</b></p>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<h3 id="sec-10-3">10.3 什么时候用 Go、什么时候用 Python</h3>
|
|||
|
|
<p>既然主线上学的是 Go,为什么还要花时间学 Python?因为两者适用场景基本不重叠,判断依据是四件事:这份代码要活多久、谁来维护、并发量级多大、以什么形态交付给别人。</p>
|
|||
|
|
|
|||
|
|
<div class="tablewrap">
|
|||
|
|
<table>
|
|||
|
|
<thead><tr><th>任务形态</th><th>选型</th><th>判断依据(活多久 / 谁维护 / 并发多大)</th><th>交付形态</th></tr></thead>
|
|||
|
|
<tbody>
|
|||
|
|
<tr><td>一次性脚本:批量改测试环境订单状态、造 500 条历史数据、清掉跑脏的券</td><td><b>Python</b></td><td>活几天;读者只有自己;串行或几十个线程就够</td><td>一个 <code>.py</code> 文件加一条命令行,跑完就丢</td></tr>
|
|||
|
|
<tr><td>数据清洗:把接口返回的 JSON 与导出的 CSV 拼成一张对账表</td><td><b>Python</b></td><td>分析型任务,生命周期短;时间花在读文件拼报表上,不在并发上</td><td>输出 <code>csv</code> 或 <code>xlsx</code> 给业务看,脚本留在本地</td></tr>
|
|||
|
|
<tr><td>临时验证:为复现某个缺陷写的几十行脚本</td><td><b>Python</b></td><td>验证完就结束;唯一读者是自己</td><td>贴进缺陷单的代码片段加一次运行输出</td></tr>
|
|||
|
|
<tr><td>长期维护的框架:全组共用的接口自动化框架</td><td><b>Go</b></td><td>活一年以上;多人读、改、加用例;需要编译期就发现传错的参数</td><td>单文件二进制,进 CI 当门禁,任何人 <code>./bin/runner</code> 都能跑</td></tr>
|
|||
|
|
<tr><td>平台后端:测试数据平台、mock 服务、用例调度</td><td><b>Go</b></td><td>长期在线;要处理 HTTP、数据库、定时任务;错误类型必须显式</td><td>编译后部署成常驻服务,依赖静态链接进二进制</td></tr>
|
|||
|
|
<tr><td>并发压测:几千条连接打吞吐,要可对账的统计</td><td><b>Go</b></td><td>并发要上四位数;Python 的 GIL 加多进程内存代价不划算</td><td>一个可执行文件,结束时打印 <code>total/ok/fail</code></td></tr>
|
|||
|
|
</tbody>
|
|||
|
|
</table>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<p>并发能力上的差别来自运行时模型。<code>CPython</code> 有一个全局解释器锁(GIL),一个进程里同一时刻只允许一个线程执行字节码;线程在等网络 IO 时会主动释放锁,所以 <code>ThreadPoolExecutor</code> 打接口能跑到几十到几百并发,这是够用的。但一旦工作变成 CPU 密集——解析几 MB 的 JSON 响应、计算签名、做加解密——加线程毫无收益,只能换 <code>ProcessPoolExecutor</code> 多进程,代价是内存翻倍、进程间只能靠序列化传数据。Go 的 goroutine 初始栈只有几 KB(2 KB 起),压测里同时起几十万个也不稀奇;<code>channel</code> 加 <code>context</code> 还能把取消和超时一路传下去,压测中途停止不会有请求漏在后台。</p>
|
|||
|
|
<p>交付形态的差别更现实。Python 脚本要交给同事,得同时交付 Python 版本、<code>requirements.txt</code> 和虚拟环境说明;其中任何一个包升级都可能改变行为。「长期维护」落到工程上,就是依赖可复现。</p>
|
|||
|
|
|
|||
|
|
<pre data-lang="bash" data-name="Python 侧的交付代价:环境必须锁">$ python3 -m venv .venv
|
|||
|
|
$ source .venv/bin/activate
|
|||
|
|
$ pip install -r requirements.txt
|
|||
|
|
$ pip show requests | head -n 2
|
|||
|
|
Name: requests
|
|||
|
|
Version: 2.32.3
|
|||
|
|
|
|||
|
|
# 冻结实际装到的版本,别人才能装出同一套
|
|||
|
|
$ pip freeze > requirements.lock.txt
|
|||
|
|
$ wc -l requirements.lock.txt
|
|||
|
|
48 requirements.lock.txt</pre>
|
|||
|
|
|
|||
|
|
<p>Go 这边省掉的就是这一整段:编译出一个可执行文件,拷到机器上就能跑。<b>这也是判据里最实用的一条:如果一份代码要交给别人用、要进 CI、要跑一年以上,选 Go;如果你自己一周后就不会再打开它,选 Python。</b>反过来,Go 写一次性脚本的代价同样真实:一个「读 CSV、按 <code>order_id</code> 分组、打印统计」的任务,Python 二十行结束,Go 要定义结构体、处理每一处 <code>err</code>、再编译一遍。</p>
|
|||
|
|
<p>把判据收成一个量化的边界,方便你当场决策:改动活不过一周、只有你自己跑、并发不超过 50、主要工作是读文件拼报表输出——用 Python。需要多人长期维护、要进流水线当门禁、并发要上四位数、要有明确的错误类型和可测试的模块边界——用 Go。中间地带也有,而且很常见:先用 Python 花半小时验证思路和接口行为,确认值得做成工具之后,再用 Go 重写一遍。要注意的是反过来不成立——<mark>不要把一份越写越长的 Python 脚本「升级」成平台</mark>,第 11 章会看到,脚本长出并发、重试、报告和配置之后,缺的正是 Go 的编译期检查和结构化错误。</p>
|
|||
|
|
<p>并发压测的骨架用 Go 写出来是这样,只用标准库和最基础的并发语法:起 <code>n</code> 个 goroutine,用 <code>WaitGroup</code> 等全部结束,用互斥锁保护两个计数器。</p>
|
|||
|
|
|
|||
|
|
<pre data-lang="go" data-name="cmd/orderbench/main.go —— 最朴素的并发压测骨架">package main
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"fmt"
|
|||
|
|
"net/http"
|
|||
|
|
"sync"
|
|||
|
|
"time"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
func main() {
|
|||
|
|
const n = 200 // 起 200 个 goroutine,各自发一次请求
|
|||
|
|
var wg sync.WaitGroup
|
|||
|
|
var mu sync.Mutex // 保护两个计数器
|
|||
|
|
ok, fail := 0, 0
|
|||
|
|
|
|||
|
|
// Timeout 是整次请求(含重定向)的总时长,不等同于 Python 的 (connect, read)
|
|||
|
|
client := &http.Client{Timeout: 5 * time.Second}
|
|||
|
|
|
|||
|
|
for i := 0; i < n; i++ {
|
|||
|
|
wg.Add(1)
|
|||
|
|
go func() {
|
|||
|
|
defer wg.Done()
|
|||
|
|
resp, err := client.Get("http://order-api.test:8080/api/order/detail?order_id=202405110001")
|
|||
|
|
mu.Lock()
|
|||
|
|
defer mu.Unlock()
|
|||
|
|
if err != nil {
|
|||
|
|
fail++ // 网络错误单独计数
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
resp.Body.Close()
|
|||
|
|
if resp.StatusCode != http.StatusOK {
|
|||
|
|
fail++
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
ok++
|
|||
|
|
}()
|
|||
|
|
}
|
|||
|
|
wg.Wait()
|
|||
|
|
fmt.Printf("total=%d ok=%d fail=%d\n", n, ok, fail)
|
|||
|
|
}</pre>
|
|||
|
|
|
|||
|
|
<pre data-lang="bash" data-name="编译成单文件二进制,然后在压测期间观察连接数">$ go build -o bin/orderbench ./cmd/orderbench
|
|||
|
|
$ ./bin/orderbench
|
|||
|
|
total=200 ok=198 fail=2
|
|||
|
|
|
|||
|
|
# 压测期间的连接快照,确认并发真的发出去了
|
|||
|
|
$ ss -tn state established '( dport = :8080 )' | tail -n +2 | wc -l
|
|||
|
|
87</pre>
|
|||
|
|
|
|||
|
|
<div class="box note">
|
|||
|
|
<span class="bt">两边的 timeout 不是一回事</span>
|
|||
|
|
<p>Go 的 <code>http.Client.Timeout</code> 是<b>整次请求的总时长</b>,从拨号到读完响应体;Python 的 <code>timeout=(3.05, 10)</code> 是<b>连接超时加两次读之间的间隔</b>。同一个后端、同样写 5 秒,Go 客户端会稳定失败,Python 客户端只要服务端每 9 秒吐一个字节就可以一直挂着。所以两边压同一接口却得出不同结论时,先对齐这两个参数的语义,再去谈性能数字。</p>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<div class="box case">
|
|||
|
|
<span class="bt">一次「本地能跑、CI 就挂」的完整定位</span>
|
|||
|
|
<p>现象:本机 <code>pytest tests/</code> 全绿,流水线上同一条用例报 <code>HTTPError: 407 Client Error</code>。第一步看报错原文,407 是「需要代理认证」,说明请求走了代理;第二步在流水线里打一行 <code>echo $HTTPS_PROXY</code>,发现有值——runner 上装了统一出口代理;第三步确认脚本从没显式设过代理,那么来源只能是 <code>requests</code> 的 <code>trust_env</code> 读了环境变量。</p>
|
|||
|
|
<p>修法有两种,选哪种取决于团队约定:显式关掉环境变量读取(<code>requests.Session()</code> 之后 <code>s.trust_env = False</code>),或者在流水线里给这台 runner 配好带认证的代理地址。真正要记的是定位路径:<b>报错原文 → 判断是哪一层 → 用一行命令证明它 → 再决定改脚本还是改环境</b>。一开始就去怀疑接口改版,这个 407 能查一整天。</p>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<p>把这一章收紧成一句可执行的话:Python 是你在团队里的通用工具,用它接手存量脚本、验证想法、处理数据;Go 是你交付给别人使用的产品。判断一份代码归属哪边,只需要问「它要活多久、有几个人会读它、并发要多大」。</p>
|
|||
|
|
|
|||
|
|
<!-- ============================================================ -->
|
|||
|
|
</article>
|
|||
|
|
|
|||
|
|
<nav class="pager">
|
|||
|
|
<a class="prev" href="09-toolchain.html"><span class="k">← 上一章</span><span class="v">第 9 章 · 工具链、调试与读代码</span></a>
|
|||
|
|
<a class="next" href="11-lab.html"><span class="k">下一章 →</span><span class="v">第 11 章 · 实操:测试数据生成器 + 校验器 CLI</span></a>
|
|||
|
|
</nav>
|
|||
|
|
|
|||
|
|
<p class="foot">
|
|||
|
|
编程基础:Golang 与工程化 · 第 10 章 Python 够用即可<br>
|
|||
|
|
<a href="index.html">模块目录</a> · <a href="../../index.html">返回学习路径</a>
|
|||
|
|
</p>
|
|||
|
|
</main>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<button id="toTop" title="回到顶部">↑</button>
|
|||
|
|
<script src="../../assets/doc.js"></script>
|
|||
|
|
<script src="../../../../assets/back.js" data-portal-back="testdev/testdev-learning-path" data-portal-label="测试开发工程师 › 测试开发从零到成熟学习路径"></script>
|
|||
|
|
</body>
|
|||
|
|
</html>
|