Accordant 测试生成与运行
accordant-test-generation
Accordant 如何生成和运行测试——当配置测试生成、理解状态图或运行测试时使用此技能
- License 许可
- MIT
- 最近更新
- 2026-11-10
- Stars
- ★ 70
- Forks
- 9
01 前言 Front Matter
- name
- accordant-test-generation
- description
- How Accordant generates and runs tests - use this skill when configuring test generation, understanding state graphs, or running tests
02 资源文件 7
- 脚本resources/config/__init__.py989 B
- 脚本resources/config/dotenv.py1.4 KB
- 脚本resources/config/files.py4.2 KB
- 脚本resources/config/logger.py2.8 KB
- 脚本resources/config/paths.py1.8 KB
- 脚本resources/config/settings.py2.6 KB
- 脚本scripts/setconfig.py2.5 KB
03 SKILL.md 正文
Test Generation in Accordant
Accordant generates tests by exploring the state graph defined by your spec, then running the generated sequences against your real system.
The State Graph
Starting from an initial state, Accordant applies each input to compute resulting states, then recurses. This builds a graph where:
- Nodes = States the system can be in
- Edges = Operations that transition between states
Generating Tests
Basic Usage
var spec = CreateSpec();
var initialState = new BankState();
// Define inputs to explore
var inputs = new InputSet
{
spec.GetOperation<string, ApiResult<decimal>>("CreateAccount").With("alice", "Create alice"),
spec.GetOperation<(string, decimal), ApiResult<decimal>>("Deposit").With(("alice", 100m), "Deposit 100"),
spec.GetOperation<(string, decimal), ApiResult<decimal>>("Withdraw").With(("alice", 30m), "Withdraw 30"),
spec.GetOperation<(string, decimal), ApiResult<decimal>>("Withdraw").With(("alice", 200m), "Withdraw 200 (overdraft)"),
spec.GetOperation<string, ApiResult<decimal>>("DeleteAccount").With("alice", "Delete alice"),
};
// Generate test cases
var testCases = spec.GenerateTests(initialState, inputs, new TestGenerationOptions
{
MaxDepth = 5
});
TestGenerationOptions
| Option | Description | Default |
|---|---|---|
MaxDepth |
Maximum sequence length | 5 |
StateConstraint |
Prune states during exploration | None |
MaxConcurrencyLevel |
For concurrent test generation | 3 |
SequentialTestCaseAlgorithm |
How paths are extracted | StateCoverage |
Constraining the State Space
Prevent state explosion with StateConstraint:
var options = new TestGenerationOptions
{
MaxDepth = 5,
StateConstraint = state =>
{
var s = (BankState)state;
// Limit: max 2 accounts, balances under 500
return s.Accounts.Count <= 2 &&
s.Accounts.Values.All(b => b <= 500);
}
};
Test Case Algorithms
StateCoverage (Default)
Visits each unique state at least once:
var options = new TestGenerationOptions
{
SequentialTestCaseAlgorithm = SequentialTestCaseAlgorithms.StateCoverage
};
TransitionCoverage
Exercises every edge (transition) in the graph — can generate many tests:
var options = new TestGenerationOptions
{
SequentialTestCaseAlgorithm = SequentialTestCaseAlgorithms.CreateTransitionCoverage(maxSequenceLength: 4)
};
RandomWalk
Samples paths probabilistically — good for large state spaces:
var options = new TestGenerationOptions
{
SequentialTestCaseAlgorithm = SequentialTestCaseAlgorithms.CreateRandomWalk(
numberOfWalks: 200,
maxWalkLength: 8,
seed: 42) // For reproducibility
};
Running Tests
Basic Execution
var context = spec.CreateTestingContext();
// Register your test client
var client = new BankApiClient(httpClient);
context.Register(client);
var results = await spec.RunTests(context, initialState, testCases, new TestExecutionOptions
{
BeforeEachAsync = async _ =>
{
// Reset system before each test
await client.DeleteAccount("alice");
await client.DeleteAccount("bob");
}
});
// Check results
var failures = results.Where(r => !r.Success).ToList();
Assert.IsEmpty(failures, $"Failed: {failures.FirstOrDefault()?.LastFailureMessage}");
TestExecutionOptions
| Option | Description |
|---|---|
BeforeEachAsync |
Reset system before each test case |
AfterEachAsync |
Cleanup after each test case |
OnStepExecuted |
Log each operation's request/response for debugging |
Resetting State
Each test expects the system to start in the initial state. Reset with BeforeEachAsync:
var knownAccounts = new[] { "alice", "bob" };
var results = await spec.RunTests(context, initialState, testCases, new TestExecutionOptions
{
BeforeEachAsync = async _ =>
{
foreach (var accountId in knownAccounts)
{
await client.DeleteAccount(accountId); // Ignore 404
}
}
});
Visualizing the State Graph
Generate a GraphViz visualization:
var dot = spec.VisualizeStateSpace(initialState, inputs, new TestGenerationOptions { MaxDepth = 4 });
File.WriteAllText("state-graph.dot", dot);
// Convert to PNG: dot -Tpng state-graph.dot -o state-graph.png
Custom Node Labels
var dot = spec.VisualizeStateSpace(
initialState,
inputs,
new TestGenerationOptions { MaxDepth = 3 },
new VisualizationOptions
{
NodeLabelLambda = node =>
{
var state = (BankState)node.State;
return $"Accounts: {state.Accounts.Count}\\nTotal: {state.Accounts.Values.Sum()}";
}
});
Manual Conformance Testing
Validate individual operations without auto-generation:
var stateProfile = new StateProfile(new BankState());
// Execute and validate
var response = await client.CreateAccount("alice");
(bool isValid, string message, stateProfile) =
spec.Allows(spec.GetOperation("CreateAccount"), "alice", response, stateProfile);
Assert.IsTrue(isValid, message);
// Continue with more operations...
var withdrawResponse = await client.Withdraw("alice", 50);
(isValid, message, stateProfile) =
spec.Allows(spec.GetOperation("Withdraw"), ("alice", 50m), withdrawResponse, stateProfile);
Assert.IsTrue(isValid, message);
Complete Example
[Test]
public async Task AutoGeneratedTests()
{
var spec = CreateSpec();
// Bind to real API
spec.ExecuteWith<BankApiClient>()
.Bind<string, ApiResult<decimal>>("CreateAccount", (c, id) => c.CreateAccount(id).Result)
.Bind<(string, decimal), ApiResult<decimal>>("Deposit", (c, r) => c.Deposit(r.Item1, r.Item2).Result)
.Bind<(string, decimal), ApiResult<decimal>>("Withdraw", (c, r) => c.Withdraw(r.Item1, r.Item2).Result)
.Bind<string, ApiResult<decimal>>("DeleteAccount", (c, id) => c.DeleteAccount(id).Result);
var inputs = new InputSet
{
spec.GetOperation<string, ApiResult<decimal>>("CreateAccount").With("alice", "Create alice"),
spec.GetOperation<(string, decimal), ApiResult<decimal>>("Deposit").With(("alice", 100m), "Deposit 100"),
spec.GetOperation<(string, decimal), ApiResult<decimal>>("Withdraw").With(("alice", 30m), "Withdraw 30"),
};
var testCases = spec.GenerateTests(new BankState(), inputs, new TestGenerationOptions { MaxDepth = 4 });
var context = spec.CreateTestingContext();
context.Register(new BankApiClient(CreateHttpClient()));
var results = await spec.RunTests(context, new BankState(), testCases, new TestExecutionOptions
{
BeforeEachAsync = async _ => await ResetDatabase()
});
Assert.That(results.All(r => r.Success), $"Failed: {results.FirstOrDefault(r => !r.Success)?.LastFailureMessage}");
}
Common Issues
Too Many Test Cases
- Reduce
MaxDepth - Add
StateConstraintto prune uninteresting states - Use fewer inputs or more targeted inputs
Tests Failing Unpredictably
- Ensure
BeforeEachAsyncproperly resets state - Check for timing issues (async operations may not complete)
- Verify inputs match what the spec expects
Next Steps
- Concurrency Testing: Test race conditions with
GenerateConcurrentTestsandRunTests - Async Operations: Handle background work with polling
04 同仓库更多 Skills
Accordant 规格故障排查
accordant-troubleshooting
Accordant 规格的常见错误与调试技巧——当测试意外失败或规格行为不符合预期时使用
Accordant 状态模型设计
accordant-state
如何在 Accordant 中设计状态模型——当定义系统在各项操作之间需要跟踪的内容时使用此技能
Accordant API 快速参考
accordant-quickref
Accordant API 的快速参考与速查表——在需要快速查询语法或代码片段时使用此技能。
Accordant 常用测试模式
accordant-patterns
Accordant 中的常用模式——依赖响应的状态、请求推导、错误处理和 HTTP 集成。
Accordant 基于模型测试入门
accordant-overview
介绍 Accordant 是什么、何时使用基于模型的测试以及核心概念——在初次接触 Accordant 或需要讲解其用途时使用此技能。
Apply/Execute 操作定义
accordant-operations
如何使用 Apply 和 Execute 方法定义操作——在创建规范操作(spec operations)或理解 Apply/Execute 模式时使用此技能。