Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ function getGuideSidebar() {
{ text: 'Integrating with xUnit', link: '/guide/xunit' },
{ text: 'Integrating with NUnit', link: '/guide/nunit' },
{ text: 'Integrating with TUnit', link: '/guide/tunit' },
{ text: 'Pooling Hosts', link: '/guide/pooling' },
{ text: 'Aspire Testing', link: '/guide/aspire' },
{ text: 'Extension Model', link: '/guide/extensions' },
{ text: 'Security Extensions', link: '/guide/security' },
Expand Down
9 changes: 9 additions & 0 deletions docs/guide/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,15 @@ no HttpClient. Follow these rules exactly; the API below is Alba 9 and differs f
`[OneTimeTearDown]`.
- TUnit: a class implementing `IAsyncInitializer` and `IAsyncDisposable` that owns the host, injected with
`[ClassDataSource<AlbaBootstrap>(Shared = SharedType.PerTestSession)]`.
- Parallel tests that change data: share an `AlbaHostPool` (namespace `Alba.Pooling`) instead of one host. The factory builds each host for its
slot, so hosts can use separate databases:
`new AlbaHostPool(slot => AlbaHost.For<Program>().WithConfiguration("ConnectionStrings:Db", $"...Database=app_{slot.Index}"), new AlbaHostPoolOptions { MaxHosts = 4, OnReturn = (host, slot) => resetData(host) })`.
Each test does `await using var host = await pool.RentAsync(cancellationToken);` and uses `host` like any
`IAlbaHost`. Create per host extensions such as `HttpClientStub` inside the factory and find them with
`host.GetExtension<HttpClientStub>()`. Rent one host per test, and always dispose the lease. To keep objects that
are not in DI with each host (mocks, a DbContext, seeded users), use `AlbaHostPool<TState>`: the factory returns
`(host, state)`, the options' actions receive `(host, state)`, and the test reads `lease.State`. Set
`MaxConcurrentStarts = 1` when the application can't start several hosts at once.

## Writing scenarios
var result = await host.Scenario(_ =>
Expand Down
4 changes: 2 additions & 2 deletions docs/guide/endpoints.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ The exception from `ShouldBeEmpty()` fails the test run. To report the gaps with
test output instead. With NUnit, check the coverage in a `[OneTimeTearDown]` method of a `[SetUpFixture]`; with TUnit,
check it in an `[After(TestSession)]` hook.

- One instance can be shared by any number of hosts, such as a pool of hosts for concurrent tests, and it keeps its
results after the hosts are disposed. Hosts that are not given the instance are not counted.
- One instance can be shared by any number of hosts, such as every host of an [`AlbaHostPool`](pooling.md), and it
keeps its results after the hosts are disposed. Hosts that are not given the instance are not counted.
- An endpoint counts as soon as routing selects it, whatever the response, so a test that expects a 401 from an existing
endpoint covers it. Requests to urls that match no endpoint do not count.
- Every request through the host counts: scenarios, server-sent event streams, and clients from
Expand Down
4 changes: 3 additions & 1 deletion docs/guide/httpclient.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ the rules that exist. The request is still recorded.
## Tips

- The stub is shared state. Tests that add rules or check `Requests` should not run in parallel against the same host.
Tests that share an xUnit fixture already run one at a time.
Tests that share an xUnit fixture already run one at a time. To run them in parallel, give each host of an
[`AlbaHostPool`](pooling.md) its own stub. Returning a pooled host clears the stub's requests and removes the rules
that tests added.
- A resilience handler such as `AddStandardResilienceHandler()` retries stubbed 5xx responses after a delay. Stub a 4xx
response, or leave the resilience handler out of the test host, when testing error handling.
- Only clients from `IHttpClientFactory` are stubbed. An `HttpClient` that the application creates with `new` is not.
84 changes: 84 additions & 0 deletions docs/guide/nunit.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,87 @@ public class sample_integration_fixture
```
<sup><a href='https://github.com/JasperFx/alba/blob/master/src/NUnitSamples/UnitTest1.cs#L31-L44' title='Snippet source file'>snippet source</a> | <a href='#snippet-sample_NUnit_scenario_test' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

## Running tests in parallel with a host pool

Tests that change data can't safely share one host while they run in parallel. An [`AlbaHostPool`](pooling.md) lends
each test a host of its own. Create the pool in a `[SetUpFixture]`, and dispose it in its `[OneTimeTearDown]`:

<!-- snippet: sample_NUnit_host_pool -->
<a id='snippet-sample_NUnit_host_pool'></a>
```cs
// Applies to the tests in this namespace
[SetUpFixture]
public class PooledApplication
{
public static AlbaHostPool Pool { get; private set; }

[OneTimeSetUp]
public void CreatePool()
{
Pool = new AlbaHostPool(slot => AlbaHost.For<WebApp.Program>()
// Each host gets its own database
.WithConfiguration("ConnectionStrings:Db", $"Host=localhost;Database=app_{slot.Index}"),
new AlbaHostPoolOptions
{
// Hosts start as tests need them, up to this many
MaxHosts = 4
});
}

// Runs after every test in the namespace has finished
[OneTimeTearDown]
public async Task DisposePool()
{
await Pool.DisposeAsync();
}
}
```
<sup><a href='https://github.com/JasperFx/alba/blob/master/src/NUnitSamples/HostPooling.cs#L8-L37' title='Snippet source file'>snippet source</a> | <a href='#snippet-sample_NUnit_host_pool' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

Then rent a host in `[SetUp]` and return it in `[TearDown]`. NUnit runs tests one at a time unless they are marked
`[Parallelizable]`, and it shares one fixture instance between a class's tests unless the class uses
`[FixtureLifeCycle(LifeCycle.InstancePerTestCase)]`. Without that attribute, tests running in parallel would overwrite
each other's lease:

<!-- snippet: sample_NUnit_pooled_tests -->
<a id='snippet-sample_NUnit_pooled_tests'></a>
```cs
// A new instance for each test, so tests running in parallel each keep their own lease
[FixtureLifeCycle(LifeCycle.InstancePerTestCase)]
[Parallelizable(ParallelScope.Children)]
public class pooled_math_tests
{
private AlbaHostLease _host;

[SetUp]
public async Task RentHost()
{
// Name the test, because timeout messages would otherwise name this method
_host = await PooledApplication.Pool.RentAsync(TestContext.CurrentContext.CancellationToken,
caller: TestContext.CurrentContext.Test.Name);
}

// Resets the host and returns it to the pool
[TearDown]
public async Task ReturnHost()
{
if (_host != null) await _host.DisposeAsync();
}

[TestCase(1, 2, 3)]
[TestCase(2, 3, 5)]
[TestCase(10, 20, 30)]
public async Task adds_numbers(int one, int two, int sum)
{
await _host.Scenario(x =>
{
x.Get.Url($"/math/add/{one}/{two}");
x.JsonPath("$.answer").ShouldBe(sum);
});
}
}
```
<sup><a href='https://github.com/JasperFx/alba/blob/master/src/NUnitSamples/HostPooling.cs#L39-L76' title='Snippet source file'>snippet source</a> | <a href='#snippet-sample_NUnit_pooled_tests' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->
1 change: 1 addition & 0 deletions docs/guide/opentelemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

Performing distributed tracing within your CI pipline is a relatively new yet powerful concept that can improve your teams response to broken, flaky or slow-performing tests.
Alba has support for Open Telemetry tracing within `Scenario` calls, permitting tracing within your test pipeline with any compatible OpenTelemetry integration.
An [`AlbaHostPool`](pooling.md#tracing-the-pool) also traces renting, starting and resetting its hosts.
If you believe there's value in tracing additional areas of Alba, please let us know!

## Automated Instrumentation
Expand Down
Loading
Loading