AGENT SKILL
Accordant API 快速参考
accordant-quickref
Accordant API 的快速参考与速查表——在需要快速查询语法或代码片段时使用此技能。
- License 许可
- MIT
- 最近更新
- 2026-11-10
- Stars
- ★ 70
- Forks
- 9
01 前言 Front Matter
- name
- accordant-quickref
- description
- Quick reference and cheatsheet for Accordant API - use this skill for quick syntax lookup or code snippets
03 SKILL.md 正文
Accordant Quick Reference
State Definition
[State]
public partial class MyState
{
public Dictionary<string, decimal> Balances { get; set; } = new();
public Dictionary<string, UserState> Users { get; set; } = new();
}
[State]
public partial class UserState
{
public string Name { get; set; } = string.Empty;
public List<string> Tags { get; set; } = new();
}
Create a Spec
var spec = new Spec<MyState>()
.WithJsonPrinters(); // Optional: nice logging
Define Operations
Inline Syntax
spec.Operation<TRequest, TResponse>("OperationName", (request, state) =>
{
// Return ExpectedOutcomes
});
Examples
// Simple request (single value)
spec.Operation<string, ApiResult<User>>("GetUser", (userId, state) => { ... });
// Tuple request (multiple values)
spec.Operation<(string Id, decimal Amount), ApiResult<decimal>>("Deposit", (request, state) =>
{
var (id, amount) = request; // Destructure
// ...
});
// Class-based request
spec.Operation<CreateUserRequest, ApiResult<User>>("CreateUser", (request, state) => { ... });
Expected Outcomes
Basic Expectation
Expect.That<TResponse>(response => /* predicate */)
With Explanation (Recommended)
Expect.That<ApiResult<decimal>>(
r => r.IsSuccess && r.Data == expectedValue,
$"Expected success with value {expectedValue}")
With ValidationResult
Expect.That<User>(response =>
{
if (response.Name != expected)
return ValidationResult.Invalid($"Name mismatch: {response.Name}");
return ValidationResult.Valid();
})
Exception Expectation
Expect.Throws<NotFoundException>("Resource not found")
Multiple Valid Outcomes
Expect.OneOf(
Expect.That<T>(r => /* outcome 1 */).ThenState(...),
Expect.That<T>(r => /* outcome 2 */).SameState(),
Expect.That<T>(r => /* outcome 3 */).ThenState(...)
)
State Transitions
No Change
.SameState()
State Changes
.ThenState<MyState>(nextState => nextState.Items[id] = newValue)
Response-Dependent State
.ThenState<MyState>(
(TResponse response, MyState nextState) =>
nextState.Items[response.Id] = new Item { ... },
mock: () => new TResponse { Id = Guid.NewGuid().ToString() })
Async Operations
.ThenState<MyState>(next => next.Jobs[id] = JobStatus.Pending)
.Triggers(AsyncOperation.Create<MyState>(
isTerminal: s => s.Jobs[id] != JobStatus.Pending,
transitions: new Action<MyState>[] {
next => next.Jobs[id] = JobStatus.Completed,
next => next.Jobs[id] = JobStatus.Failed
}
))
Bind Execution
spec.ExecuteWith<ApiClient>()
.Bind<TRequest, TResponse>("OperationName",
(client, request) => client.Method(request).Result)
.BindAsync<TRequest, TResponse>("AsyncOperation",
async (client, request) => await client.MethodAsync(request));
Test Generation
Define Inputs
var inputs = new InputSet
{
spec.GetOperation<string, ApiResult<User>>("CreateUser").With("alice", "Create Alice"),
spec.GetOperation<(string, decimal), ApiResult<decimal>>("Deposit").With(("alice", 100m), "Deposit 100"),
};
Generate Tests
var testCases = spec.GenerateTests(initialState, inputs, new TestGenerationOptions
{
MaxDepth = 5,
StateConstraint = state => ((MyState)state).Items.Count <= 3
});
Run Tests
var context = spec.CreateTestingContext();
context.Register(new ApiClient(httpClient));
var results = await spec.RunTests(context, initialState, testCases, new TestExecutionOptions
{
BeforeEachAsync = async _ => await ResetDatabase()
});
Assert.That(results.All(r => r.Success));
Concurrent Tests
var concurrentTestCases = spec.GenerateConcurrentTests(initialState, inputs,
new TestGenerationOptions { MaxDepth = 4 });
var results = await spec.RunTests(context, initialState, concurrentTestCases,
new TestExecutionOptions { ... });
Manual Conformance Testing
var stateProfile = new StateProfile(initialState);
var response = await client.CreateUser("alice");
(bool isValid, string message, stateProfile) =
spec.Allows(createUserOp, "alice", response, stateProfile);
Assert.IsTrue(isValid, message);
Visualization
var dot = spec.VisualizeStateSpace(initialState, inputs, options);
File.WriteAllText("graph.dot", dot);
// Convert: dot -Tpng graph.dot -o graph.png
TestGenerationOptions
| Option | Type | Default | Description |
|---|---|---|---|
MaxDepth |
int | 5 | Max sequence length |
StateConstraint |
Func<State, bool> | null | Prune states |
MaxConcurrencyLevel |
int | 3 | Concurrent ops |
SequentialTestCaseAlgorithm |
delegate | StateCoverage | Walk algorithm |
Test Case Algorithms
// State coverage (default)
SequentialTestCaseAlgorithms.StateCoverage
// Transition coverage
SequentialTestCaseAlgorithms.CreateTransitionCoverage(maxSequenceLength: 4)
// Random walk
SequentialTestCaseAlgorithms.CreateRandomWalk(numberOfWalks: 100, maxWalkLength: 8, seed: 42)
Common Operation Pattern
spec.Operation<(string Id, decimal Amount), ApiResult<decimal>>("Withdraw", (request, state) =>
{
var (accountId, amount) = request;
// Guard 1: Resource exists?
if (!state.Accounts.TryGetValue(accountId, out var balance))
return Expect.That<ApiResult<decimal>>(r => r.IsNotFound, "Account not found")
.SameState();
// Guard 2: Business rule
if (balance < amount)
return Expect.That<ApiResult<decimal>>(r => r.IsBadRequest, "Insufficient funds")
.SameState();
// Success path
var newBalance = balance - amount;
return Expect.That<ApiResult<decimal>>(
r => r.IsSuccess && r.Data == newBalance,
$"Expected new balance {newBalance}")
.ThenState<BankState>(next => next.Accounts[accountId] = newBalance);
});
Namespace
using Microsoft.Accordant;
NuGet Package
dotnet add package Microsoft.Accordant
04 同仓库更多 Skills
Accordant 规格故障排查
accordant-troubleshooting
Accordant 规格的常见错误与调试技巧——当测试意外失败或规格行为不符合预期时使用
★ 70
Accordant 测试生成与运行
accordant-test-generation
Accordant 如何生成和运行测试——当配置测试生成、理解状态图或运行测试时使用此技能
★ 70
Accordant 状态模型设计
accordant-state
如何在 Accordant 中设计状态模型——当定义系统在各项操作之间需要跟踪的内容时使用此技能
★ 70
Accordant 常用测试模式
accordant-patterns
Accordant 中的常用模式——依赖响应的状态、请求推导、错误处理和 HTTP 集成。
★ 70
Accordant 基于模型测试入门
accordant-overview
介绍 Accordant 是什么、何时使用基于模型的测试以及核心概念——在初次接触 Accordant 或需要讲解其用途时使用此技能。
★ 70
Apply/Execute 操作定义
accordant-operations
如何使用 Apply 和 Execute 方法定义操作——在创建规范操作(spec operations)或理解 Apply/Execute 模式时使用此技能。
★ 70