C# 中的 Reqnroll 验证码:从 Gherkin 步骤识别它

要在 Reqnroll 测试里通过验证码,就让一个 Gherkin 步骤向 CapSkip 要一个 token,再把它填进场景提交的表单。这篇 Reqnroll 验证码指南写给需要在自己测试的网站上通过验证码的测试人员,而不是教你给自己的页面加验证码。BeforeScenario 钩子会创建 CapSkip 客户端,Reqnroll 把它注入你的步骤绑定,而表示验证码已识别的那个步骤会调用 CapSkip NuGet 包里的 MtCaptchaAsync。CapSkip 运行在你自己的 Windows PC 上,所以再长的 feature 文件也不会产生按次计费的成本。
你需要什么
- 一台安装了 CapSkip 4.3.0 或更高版本的 Windows PC,因为 MTCaptcha 识别是从这个版本开始支持的。安装和首次启动的方法见 设置指南.
- 一个 .NET SDK。我在 net10.0 和 net8.0 上跑了全部内容(SDK 10.0.100,运行时 10.0.0 和 8.0.27),用的是 Reqnroll.xUnit 3.3.4、xunit 2.9.3 和 CapSkip 1.7.0。只装了 8 SDK 的机器没有测过,.NET Framework 也没有。
- 一个你有权自动化的 staging 页面,页面上有 MTCaptcha 小组件,其 sitekey 放在名为 mtcaptchaConfig 的脚本变量里。
- 一种连到 CapSkip 的方式。在 Local mode 下,只有运行它的那台 PC 能在 127.0.0.1 上调用它。Server mode 会把 API 开放给你的网络或公网 IP,单独的测试机器需要这种方式。两种模式在 连接设置.
下面的内容都没有碰真实的 CapSkip 应用或真实网站。我用一个自己写的 mock 来模拟 CapSkip API 和一个注册页面,真正的 Reqnroll 和 CapSkip 包都跑在它上面。识别耗时和接受规则都来自 mock 本身,每个数字都标明了对应的配置。
第 1 步:创建项目
xunit 模板固定使用 xunit 2.9.3,也就是 Reqnroll.xUnit 所基于的 v2 版本,所以把这两个包加到它上面即可。直接运行 dotnet test 就能工作,不需要 global.json。Reqnroll 会在项目的任何位置找到 feature 文件,下面每个代码块开头都写明了保存路径。
# PowerShell dotnet new xunit -n CapSkipBdd -f net10.0 cd CapSkipBdd rm UnitTest1.cs # the template's sample test; delete it dotnet add package Reqnroll.xUnit dotnet add package CapSkip mkdir Features, Hooks, Steps, Support
第 2 步:编写场景
场景只描述发生什么,不描述怎么做,所以 Reqnroll 验证码步骤读起来和其他步骤没有区别。验证码在每个场景的 When 步骤里识别,因为一个 token 只能用一次。根据 MTCaptcha 在其 验证 token 指南中的说明,token 默认只校验一次。最后一个场景故意提交两次,它期望的文字来自我的 mock,所以请把引号里的文字改成你的网站实际显示的内容。
# Features/Signup.feature
Feature: Sign-up behind a CAPTCHA
A visitor can only sign up with a token that CapSkip solved just now.
Scenario Outline: A solved CAPTCHA is accepted on each page
Given the "<path>" page is open
When the captcha is solved
And the form is submitted
Then the site says "Welcome aboard"
Examples:
| path |
| /signup |
| /signup?plan=pro |
Scenario: A token works once
Given the "/signup" page is open
When the captcha is solved within 30 seconds
And the form is submitted
And the form is submitted
Then the site says "token already used"第二个 feature 文件复用了所有步骤,这对下面的并行运行很重要。
# Features/Login.feature
Feature: Login behind a CAPTCHA
The step bindings are shared, so a second feature file costs no new code.
Scenario: A solved CAPTCHA signs the user in
Given the "/login" page is open
When the captcha is solved
And the form is submitted
Then the site says "Welcome aboard"第 3 步:为你的 staging 页面写一个辅助类
下一个类是你自己的粘合代码,不属于 CapSkip。它用两个正则表达式从页面的 mtcaptchaConfig 里读出 sitekey 和 action,所以请按你的页面标记调整。这个辅助类把 token 放在 mtcaptcha-verifiedtoken 字段里发送,并手动设置 Referer,因为 HttpClient 提交表单时不会发送它。
Reqnroll 为每个场景创建一个 StagingSite,所以 cookie 不会在场景之间泄漏。而且这个类实现了 IDisposable,Reqnroll 会在之后释放它:四个场景对应四次 Dispose 调用。
// Support/StagingSite.cs
using System.Net;
using System.Text.RegularExpressions;
namespace CapSkipBdd.Support;
public sealed record SignupPage(string Url, string SiteKey, string Action);
// Reqnroll builds one of these per scenario and disposes it afterwards,
// so each scenario has its own HttpClient and its own cookies.
public sealed class StagingSite : IDisposable
{
private readonly string _baseUrl =
Environment.GetEnvironmentVariable("STAGING_URL") ?? "https://staging.example.com";
private readonly HttpClient _http = new();
public async Task<SignupPage> OpenAsync(string path, CancellationToken ct)
{
var url = _baseUrl + path;
var html = await _http.GetStringAsync(url, ct);
// Adjust both patterns to how your page writes its mtcaptchaConfig.
var sitekey = Regex.Match(html, "\"sitekey\"\\s*:\\s*\"([^\"]+)\"").Groups[1].Value;
var action = Regex.Match(html, "\"action\"\\s*:\\s*\"([^\"]+)\"").Groups[1].Value;
return new SignupPage(url, sitekey, action);
}
public async Task<(HttpStatusCode Status, string Body)> SubmitAsync(
SignupPage page, string token, CancellationToken ct)
{
using var request = new HttpRequestMessage(HttpMethod.Post, page.Url)
{
Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
["user"] = "bdd-user",
["password"] = "YOUR_PASSWORD",
["mtcaptcha-verifiedtoken"] = token,
}),
};
request.Headers.Referrer = new Uri(page.Url); // HttpClient sends none
using var response = await _http.SendAsync(request, ct);
return (response.StatusCode, await response.Content.ReadAsStringAsync(ct));
}
public void Dispose() => _http.Dispose();
}第 4 步:在 BeforeScenario 钩子里创建客户端
钩子类和其他绑定一样,所以它的构造函数可以要求获得 Reqnroll 的 IObjectContainer。钩子创建一个 CapSkipClient 并注册这个实例,之后每个要求 CapSkipClient 的绑定都会拿到它。SDK 自己不会读取 CAPSKIP_ 变量,所以由钩子来读。SDK 内部共用一个 HttpClient,因此每个场景一个客户端的开销很小。
钩子还会检查是否有程序在监听,方法是发起一次不发送识别任务的 TCP 连接。Reqnroll 的 钩子页面 说明,BeforeScenario 钩子里抛出异常会跳过后面的步骤。mock 停掉后,每个场景都带着钩子的消息失败,每个步骤都显示为因前面的错误而跳过。代码块里设置了明确的 Order,正如该页面所建议的。
// Hooks/CapSkipHooks.cs
using System.Net.Sockets;
using CapSkip;
using Reqnroll;
using Reqnroll.BoDi;
namespace CapSkipBdd.Hooks;
[Binding]
public sealed class CapSkipHooks(IObjectContainer container)
{
// The SDK never reads CAPSKIP_* itself, so read them here.
private static string Env(string name, string fallback) =>
Environment.GetEnvironmentVariable(name) ?? fallback;
[BeforeScenario(Order = 0)]
public async Task BuildClient()
{
var host = Env("CAPSKIP_HOST", "127.0.0.1");
var port = int.Parse(Env("CAPSKIP_PORT", "8080"));
// A TCP connect asks "is anything listening?" and sends no solve job.
using var tcp = new TcpClient();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(1));
try { await tcp.ConnectAsync(host, port, timeout.Token); }
catch (Exception e) when (e is SocketException or OperationCanceledException)
{
throw new InvalidOperationException($"CapSkip is not listening on {host}:{port}");
}
// Every binding class that asks for a CapSkipClient now gets this one.
container.RegisterInstanceAs(new CapSkipClient(
apiKey: Env("CAPSKIP_API_KEY", "capskip"), host: host, port: port));
}
}如果省略这个注册,Reqnroll 不会退回到默认客户端:每个场景都会失败,报错 Primitive types or structs cannot be resolved: System.String,并给出从 SignupSteps 到 CapSkipClient 的路径。
第 5 步:Reqnroll 验证码的步骤绑定
Reqnroll 为每个场景创建一次绑定类并填充它的构造函数,所以字段可以在该场景的各个步骤之间保存状态。Reqnroll 的上下文注入文档说明,注入的对象只在一个场景内有效。SignupSteps 要求获得客户端、一个由 Reqnroll 自己创建的 StagingSite、ScenarioContext 和一个 ITestOutputHelper(由生成的测试类注册)。它会打印识别花了多长时间,在详细输出级别下可以看到。
Then 步骤在另一个类里,看不到这些字段,所以提交步骤把响应留在 ScenarioContext 里,这是同一场景各个绑定共享的字典。键不存在时,运行时会以 KeyNotFoundException 失败。如果要传多个值,用一个两边绑定都能获得的小类会更稳妥。
我用的是 MtCaptchaAsync,而不是 RecaptchaAsync。MTCaptcha 在你这边不需要浏览器:CapSkip 自己读出挑战文字,而且 SDK 给它 120 秒的 defaultTimeout,只有一个数字需要考虑。这个调用会发送页面声明的 action,并且根据 SDK 更新日志,空的选项不会被发送。 API 文档 列出了其他选项。
// Steps/SignupSteps.cs
using System.Diagnostics;
using CapSkip;
using CapSkipBdd.Support;
using Reqnroll;
using Xunit.Abstractions;
// System is imported too, and it has a TimeoutException of its own (CS0104).
using SolverTimeout = CapSkip.TimeoutException;
namespace CapSkipBdd.Steps;
// Reqnroll creates one of these per scenario and fills the constructor.
[Binding]
public sealed class SignupSteps(
CapSkipClient solver, StagingSite site, ScenarioContext scenario, ITestOutputHelper output)
{
private SignupPage? _page;
private string _token = "";
[Given("the {string} page is open")]
public async Task OpenPage(string path) =>
_page = await site.OpenAsync(path, CancellationToken.None);
[When("the captcha is solved")]
public async Task Solve() => await SolveWith(CancellationToken.None);
[When(@"the captcha is solved within (\d+ seconds)")]
public async Task SolveWithin(TimeSpan limit)
{
using var budget = new CancellationTokenSource(limit);
await SolveWith(budget.Token);
}
[When("the form is submitted")]
public async Task Submit()
{
var (status, body) = await site.SubmitAsync(_page!, _token, CancellationToken.None);
scenario["reply"] = $"{(int)status} {body}"; // the Then steps live in another class
}
private async Task SolveWith(CancellationToken ct)
{
// Pass the sitekey and action the page itself declares.
var options = new Dictionary<string, object?> { ["action"] = _page!.Action };
var clock = Stopwatch.StartNew();
try
{
var solved = await solver.MtCaptchaAsync(_page.SiteKey, _page.Url, options, ct);
_token = solved.Token!;
output.WriteLine($"solved in {clock.ElapsedMilliseconds} ms");
}
// A cancelled submit surfaces as a NetworkException and a cancelled poll as a
// TaskCanceledException, so test the token itself.
catch (Exception) when (ct.IsCancellationRequested)
{
Assert.Fail($"CapSkip gave no token within the step's budget ({clock.ElapsedMilliseconds} ms)");
}
catch (SolverTimeout e)
{
Assert.Fail($"CapSkip gave no token before the SDK's own deadline: {e.Message}");
}
}
}// Steps/ReplySteps.cs
using Reqnroll;
namespace CapSkipBdd.Steps;
[Binding]
public sealed class ReplySteps(ScenarioContext scenario)
{
[Then("the site says {string}")]
public void TheSiteSays(string text) =>
Assert.Contains(text, scenario.Get<string>("reply"));
}每个包含 await 的步骤都要返回 Task。async void 步骤是个陷阱:Reqnroll 会报告不支持 async void 方法,然后让项目里的每个场景都失败,包括那些根本没用到它的场景。我只加了一个没人用的 async void 方法,本指南项目的全部四个场景就都这样失败了。Reqnroll 的异步绑定文档给出的是 async Task,同时也允许 ValueTask。
第 6 步:为时间限制写一个转换
表示 within 30 seconds 的那个步骤接收一个 TimeSpan。没有转换、只用 SignupSteps 里的正则时,场景会以 InvalidCastException 失败:Invalid cast from System.String to System.TimeSpan。StepArgumentTransformation 提供了缺少的转换,之后任何接收时长的步骤都可以复用它。只捕获数字看起来是条捷径,其实更糟:步骤照常运行,没有任何错误,却收到了一个 30 天的 TimeSpan。SignupSteps 里的正则把数字和单位一起捕获,所以转换收到的文本是 30 seconds。
// Steps/Durations.cs
using Reqnroll;
namespace CapSkipBdd.Steps;
[Binding]
public sealed class Durations
{
// Without this, the TimeSpan parameter fails with an InvalidCastException.
[StepArgumentTransformation(@"(\d+) seconds")]
public TimeSpan InSeconds(int seconds) => TimeSpan.FromSeconds(seconds);
}第 7 步:运行
把这些设置放进 PowerShell 环境变量,然后在项目文件夹里启动测试套件。代码块里是默认值;我的运行把 mock 的端口设为 12740,并把 STAGING_URL 设为它的地址。真实运行时,省略前两个,把 STAGING_URL 设为你的页面。四个场景在 net10.0 上通过,我在项目文件里改了 TargetFramework 之后,在 net8.0 上也再次通过。
# PowerShell. The hook and the helper read these; unset ones fall back to defaults. $env:CAPSKIP_HOST = "127.0.0.1" # a Server mode machine: its LAN IP $env:CAPSKIP_PORT = "8080" $env:CAPSKIP_API_KEY = "capskip" $env:STAGING_URL = "https://staging.example.com" dotnet test --logger "console;verbosity=detailed"
Reqnroll 为异步步骤生成了什么
构建时,Reqnroll 会把每个 feature 文件变成一个 C# 类。在 3.3.4 里,生成的文件就放在 feature 旁边,例如 Features\Signup.feature.cs。每个 feature 是一个实现 IAsyncLifetime 的测试类,普通场景是 SkippableFact,场景大纲是 SkippableTheory,每个示例对应一行 InlineData。
每个步骤都是一次带 await 的调用,例如带步骤文本的 await testRunner.GivenAsync,而且每个生成的方法都返回 Task。
给识别设置时间限制
xUnit 2.9.3 不会给测试提供取消令牌,所以 within 步骤自己创建一个,而 SDK 也有自己的限制 defaultTimeout。下表来自 net10.0 上的 mock。计时从 MtCaptchaAsync 之前开始,在 catch 块里结束,只有最后一行例外,它是 Reqnroll 对该步骤的计时。
| mock 的行为 | 时间限制 | 步骤报告了什么 | 耗时 |
|---|---|---|---|
| 从不生成 token | 步骤预算 3 秒 | 步骤预算内没有 token | 3004 ms |
| 从不生成 token | 步骤预算 1 秒 | 同样的消息 | 1014 ms |
| 让 in.php 保持 10 秒 | 步骤预算 2 秒 | 同样的消息 | 2012 ms |
| 从不生成 token | 无,客户端以 defaultTimeout 5 创建 | SDK 自己的截止时间之前没有 token:timeout 5 exceeded | 7.8 s |
前三行都在预算处结束,因为取消发生在 token 到达 MtCaptchaAsync 之后。在轮询期间取消会抛出 TaskCanceledException,在提交期间取消则抛出 CapSkip 的 NetworkException,所以步骤检查的是 token,而不是异常类型。最后一行大约晚了三秒结束,因为 SDK 只在下一次轮询到期时才检查它的截止时间。我只为那一行用 defaultTimeout 5 创建了那个客户端;第 4 步的代码块保留默认的 120。
CapSkip 的 TimeoutException 和 System.TimeoutException 同名,而测试项目通过隐式 using 导入了 System。在 using CapSkip 旁边直接 catch TimeoutException 会以 CS0104(引用不明确)失败。SignupSteps 里的别名选中了 CapSkip 的类,写成 CapSkip.TimeoutException 或者 catch CapSkipError 也可以。
并行运行场景,又不压垮 CapSkip
xUnit 让不同的测试类同时运行,同一个类里的测试则一个接一个运行。Reqnroll 为每个 feature 文件生成一个类,所以 feature 文件就是你的并行单位。我把 Signup.feature 和 Login.feature 移出了项目,并复制出四份 Login.feature,每份都有自己的 Feature 标题(Login 1 到 Login 4)和第二个场景。标题相同的副本会生成同名的类,并以 CS0579(重复的 GeneratedCodeAttribute)失败。mock 中每次识别都被拖住 3 秒。总耗时是 dotnet test 那一行,其中包含启动时间,最后一列是同时处于打开状态的识别数量的峰值。第一行在 net10.0 和 net8.0 上运行,结果相同,其他行只在 net10.0 上运行了一次。
| 设置 | 总耗时 | 同时识别数 |
|---|---|---|
| 四个 feature 文件,xUnit 默认设置 | 8.2 s | 4 |
| 同上,maxParallelThreads 为 2 | 16.1 s | 2 |
| 同上,maxParallelThreads 为 1 | 31.5 s | 1 |
| 同上,parallelizeTestCollections 为 false | 31.4 s | 1 |
| 一个 feature 文件,一个包含 8 个示例的场景大纲 | 31.4 s | 1 |
一个很长的 feature 文件永远不会让自己的场景重叠运行,不管它有多少个示例。要限制同时识别的数量,就在 xunit.runner.json 里写一个数字,并把该文件复制到构建输出目录。如果你的 CapSkip 版本为 MTCaptcha 显示了 Max. Threads 设置,就让并行的 feature 数量不超过它。我没有去找这个设置。
{
"$schema": "https://xunit.net/schema/current/xunit.runner.schema.json",
"maxParallelThreads": 2
}<!-- CapSkipBdd.csproj: add inside the Project element --> <ItemGroup> <Content Include="xunit.runner.json" CopyToOutputDirectory="PreserveNewest" /> </ItemGroup>
我只运行了 xUnit 的默认模式。生成的程序集代码里定义了一个名为 ReqnrollNonParallelizableFeatures 的集合,但给我的四个 feature 打上 @nonparallelizable 标签,只是给生成的类加了一个 xUnit trait,仍然同时出现了 4 次识别,所以我不依赖这个标签。
从另一台机器访问 CapSkip
没有什么强制测试必须跑在识别工具所在的 PC 上。让 CapSkip 运行在 Server mode 下,把 CAPSKIP_HOST 和 CAPSKIP_PORT 指向它,场景就不用改。我这次检查时,mock 在所有网络接口上接受连接,CAPSKIP_HOST 设为这台 PC 的一个非回环地址,四个场景都通过了。当 mock 只监听回环地址时,这个设置会让每个场景都带着钩子的消息失败,说明这个地址确实被用到了。整个过程没有用到第二台机器。设置指南说明 Server mode 要求 CapSkip 以管理员身份运行,所以在服务器那台机器上请这样启动。
SDK 通过明文 HTTP 与 CapSkip 通信,所以链路上的任何人都能读到 API key。不要让这一跳走开放的互联网:用专用网络或 VPN,并在 CapSkip 里打开 API key 校验。启动 Server mode 会让 CapSkip 向所有地址开放它的端口,所以要把访问限制在你预期的机器上,请再添加一条 Windows 防火墙阻止规则来拦截其余的地址。识别工具仍然运行在你自己的 Windows 硬件上,也不按次计费。使用静态 IP 可以让地址保持稳定。
Reqnroll 验证码测试的常见错误
| 你所看到的 | 原因 | 修复 |
|---|---|---|
| CapSkip 没有在该主机和端口上监听 | 钩子里的 TCP 检查在那里什么也没找到 | 启动 CapSkip,检查连接设置和 CAPSKIP_HOST |
| Primitive types or structs cannot be resolved: System.String | 在某个步骤要求获得 CapSkipClient 之前没有注册它 | 在 BeforeScenario 钩子里注册它 |
| 每个场景都失败,报 async void methods are not supported | 有一个绑定方法是 async void | 改为返回 Task |
| InvalidCastException,从 String 到 TimeSpan | 时长文本没有对应的转换。只捕获数字的话,得到的会是 30 天 | 添加 StepArgumentTransformation,并把数字和单位一起捕获 |
| TimeoutException 上出现 CS0104 | System 和 CapSkip 都定义了它 | 给 CapSkip 的类起别名,或者 catch CapSkipError |
| Then 步骤里的 KeyNotFoundException | ScenarioContext 的键从未设置,或者拼写错了 | 检查两处拼写,或者注入一个小的共享类 |
| 网站说 token 已经用过 | 同一个 token 提交了两次 | 每次提交之前,在场景里重新识别一次 |
识别时可能抛出的其他错误码见 API 文档.
常见问题
我能在 Reqnroll 步骤里改用 RecaptchaAsync 吗?
原则上可以。钩子、注入、时间限制和并行设置都不变。要变的是识别调用、表单字段(g-recaptcha-response)和超时(recaptchaTimeout)。我只运行过 MtCaptchaAsync。
云端托管的构建代理能用吗?
可以,通过 Server mode。在托管代理上,127.0.0.1 指的是代理自己,所以 CapSkip 必须运行在代理能通过网络访问到的你自己的一台 Windows 机器上。把 CAPSKIP_HOST 设为那台机器,并把 API key 存为 CI 密钥。托管代理超出了我实际运行的范围。
简短版结论
对于 Reqnroll 验证码步骤,请在 BeforeScenario 钩子里创建 CapSkip 客户端并注册它。在 When 步骤里识别,每个场景一次,并由步骤强制执行一个时间限制。每个绑定都返回 Task,为时长添加一个转换,并把 feature 文件当作你的并行单位。其他 .NET 验证码类型见 C# 验证码识别页面,产品本身见 MTCaptcha 识别页面.
BDD 测试套件会为每个页面和每个版本重复场景,而按次计费的价格会让每次运行都花钱。在你自己的 Windows 机器上运行一个 无限量验证码识别工具 ,可以让每晚运行的成本保持不变。
