policy-emulator-testing
Skill95 starsChanged 12 months agoMITView on GitHub
Conventions and patterns for writing gateway emulator policy handler tests in the Azure API Management policy toolkit. Use this skill when creating or modifying test files in test/Test.Testing/Emulator/Policies/.
In this repository6 other files it gives its agents.
- .github/copilot-instructions.mdCopilot instructions
- policy-authoringSkill
- policy-codebase-referenceSkill
- policy-compilationSkill
- policy-emulatorSkill
- policy-testingSkill
The file
We split this skill into the rules it gives an agent
5 rules. About 0 are common, 2 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 69
Create a document with the policy call, run through TestDocument, assert context state changes:
- Very specific: line 86
Verify that SetupInbound() (or appropriate section) .{PolicyName}().WithCallback(...) correctly overrides default behavior:
- Distinctive: line 133
When the handler depends on existing context state:
- Very specific: line 150
Not all policies support .WithError().
- Distinctive: line 192
If the policy is available in multiple sections, add one test per section:
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Policy Emulator Testing Patterns
This skill describes how to write tests for gateway emulator policy handlers in the Azure API Management policy toolkit.
Test File — test/Test.Testing/Emulator/Policies/{PolicyName}Tests.cs
File Template
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace Test.Emulator.Emulator.Policies;
[TestClass]
public class {PolicyName}Tests
{
// Inner document class implementing IDocument
class Simple{PolicyName} : IDocument
{
public void Inbound(IInboundContext context)
{
context.{PolicyName}(new {PolicyName}Config
{
// config properties
});
}
public void Outbound(IOutboundContext context) { }
public void Backend(IBackendContext context) { }
public void OnError(IOnErrorContext context) { }
}
[TestMethod]
public void Should{ExpectedBehavior}()
{
// Arrange
var test = new Simple{PolicyName}().AsTestDocument();
// Act
test.RunInbound();
// Assert (using FluentAssertions)
test.Context.{assertion};
}
}Key Conventions
- Namespace:
Test.Emulator.Emulator.Policies(matches existing test convention) - Class name:
{PolicyName}Tests - Framework: MSTest (
[TestClass],[TestMethod]) - Assertions: FluentAssertions
- Test document creation:
new SimpleDocument().AsTestDocument()extension method (ornew TestDocument(new SimpleDocument())— both are equivalent) - Inner document classes implement
IDocumentwith all four section methods. Unused sections have empty bodies. - Section execution:
test.RunInbound(),test.RunOutbound(),test.RunBackend(),test.RunOnError()
Required Test Coverage
Each policy must have tests covering:
1. Basic Execution
Create a document with the policy call, run through TestDocument, assert context state changes:
[TestMethod]
public void ShouldModifyContextState()
{
var test = new SimpleSetStatus().AsTestDocument();
test.RunInbound();
test.Context.Response.StatusCode.Should().Be(200);
test.Context.Response.StatusReason.Should().Be("OK");
}2. Callback Override
Verify that SetupInbound() (or appropriate section) .{PolicyName}().WithCallback(...) correctly overrides default behavior:
[TestMethod]
public void ShouldExecuteCallback()
{
var test = new Simple{PolicyName}().AsTestDocument();
test.SetupInbound()
.{PolicyName}()
.WithCallback((context, config) =>
{
context.Variables["test"] = "value";
});
test.RunInbound();
test.Context.Variables.Should().ContainKey("test")
.WhoseValue.Should().Be("value");
}3. Predicate-Based Mock
For policies called multiple times with different configs in the same section:
[TestMethod]
public void ShouldSelectCorrectCallback()
{
var test = new Multi{PolicyName}().AsTestDocument();
test.SetupInbound()
.{PolicyName}((ctx, config) => config.SomeProperty == "A")
.WithCallback((ctx, cfg) => { /* handle A */ });
test.SetupInbound()
.{PolicyName}((ctx, config) => config.SomeProperty == "B")
.WithCallback((ctx, cfg) => { /* handle B */ });
test.RunInbound();
// Assert...
}4. Pre-configured Context
When the handler depends on existing context state:
[TestMethod]
public void ShouldHandleExistingHeaders()
{
var test = new Simple{PolicyName}().AsTestDocument();
test.Context.Request.Headers["Content-Type"] = ["application/json"];
test.RunInbound();
test.Context.Request.Headers.Should().ContainKey("Content-Type");
}5. Error/Exception Scenarios
Not all policies support .WithError(). This API is specific to certain mock providers (e.g., MockAuthenticationManagedIdentityProvider). For policies without a dedicated error API, simulate errors via callbacks:
[TestMethod]
public void ShouldSimulateError()
{
var test = new Simple{PolicyName}().AsTestDocument();
test.SetupInbound()
.{PolicyName}()
.WithCallback((context, config) =>
{
context.Response.StatusCode = 500;
context.Response.StatusReason = "Internal Server Error";
throw new FinishSectionProcessingException();
});
test.RunInbound();
test.Context.Response.StatusCode.Should().Be(500);
}For authentication policies that have .WithError():
[TestMethod]
public void ShouldThrowOnError()
{
var test = new SimpleAuthenticationManagedIdentity().AsTestDocument();
test.SetupInbound()
.AuthenticationManagedIdentity()
.WithError("InternalServerError");
var ex = Assert.ThrowsException<PolicyException>(() => test.RunInbound());
ex.Policy.Should().Be("AuthenticationManagedIdentity");
}6. Multi-Section Tests
If the policy is available in multiple sections, add one test per section:
[TestMethod]
public void ShouldWorkInOutboundSection()
{
var test = new Outbound{PolicyName}().AsTestDocument();
test.RunOutbound();
test.Context.{assertion};
}Mock Setup Patterns
Token Provider Hook (Authentication policies)
test.SetupInbound()
.AuthenticationManagedIdentity()
.WithTokenProviderHook((resource, clientId) => $"{resource}{clientId}/token");Return Value (Authentication, Cache)
test.SetupInbound()
.AuthenticationManagedIdentity()
.ReturnsToken("mock-token");Cache Store Setup
test.SetupCacheStore()
.WithExternalCacheSetup()
.WithExternalCacheValue("key", "test");
test.SetupCacheStore().WithInternalCacheValue("key", "test");Response Example Store (MockResponse)
var example = new ResponseExample(200, "{ \"ok\": true }", "application/json");
test.SetupResponseExampleStore().Add(test.Context, example);Test Infrastructure
Tests rely on shared infrastructure that you do not need to modify:
TestDocument(src/Testing/TestDocument.cs) — Wraps anIDocumentand executes sections through proxies. CatchesFinishSectionProcessingExceptiongracefully..AsTestDocument()extension method — CreatesTestDocumentfromIDocument.SetupInbound()/SetupOutbound()/etc. — ReturnsMockPoliciesProvider<TSection>for fluent mock configuration.GatewayContext(src/Testing/GatewayContext.cs) — Contains mock request/response, variables, and emulator stores.Usings.cs(test/Test.Testing/Usings.cs) — Global usings forFluentAssertionsandMicrosoft.VisualStudio.TestTools.UnitTesting.
Build and Test Commands
# Run all emulator tests
dotnet test --project test/Test.Testing
# Run tests for a specific policy
dotnet test --project test/Test.Testing --filter "FullyQualifiedName~{PolicyName}Tests"Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

