-
Notifications
You must be signed in to change notification settings - Fork 0
test: raise API coverage to 99.88% of lines and 100% of branches #138
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| <?xml version="1.0" encoding="utf-8"?> | ||
| <!-- | ||
| Coverage settings shared by the unit and integration suites. | ||
|
|
||
| Run with: dotnet test TodoApp.sln (plus the settings flag pointing at this file) | ||
| Each test project writes a Cobertura report under its own TestResults/<guid>/. | ||
| --> | ||
| <RunSettings> | ||
| <DataCollectionRunSettings> | ||
| <DataCollectors> | ||
| <DataCollector friendlyName="XPlat code coverage"> | ||
| <Configuration> | ||
| <Format>cobertura,json</Format> | ||
| <!-- Only our own assemblies; the test assemblies themselves are not the subject. --> | ||
| <Include>[TodoApp.Domain]*,[TodoApp.Application]*,[TodoApp.Infrastructure]*,[TodoApp.WebApi]*</Include> | ||
| <ExcludeByAttribute>Obsolete,GeneratedCodeAttribute,CompilerGeneratedAttribute,ExcludeFromCodeCoverageAttribute</ExcludeByAttribute> | ||
| <SkipAutoProps>true</SkipAutoProps> | ||
| <UseSourceLink>false</UseSourceLink> | ||
| <DeterministicReport>false</DeterministicReport> | ||
| </Configuration> | ||
| </DataCollector> | ||
| </DataCollectors> | ||
| </DataCollectionRunSettings> | ||
| </RunSettings> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| using TodoApp.Application.Common.Interfaces; | ||
| using TodoApp.Infrastructure.Persistence; | ||
|
|
||
| namespace TodoApp.WebApi; | ||
|
|
||
| /// <summary> | ||
| /// Creates and seeds the database at startup, without letting a cold or paused database stop the | ||
| /// app from starting. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Azure SQL serverless can be waking from auto-pause when the container comes up. Failing | ||
| /// startup there turns a slow database into a dead app, so an unreachable database is logged and | ||
| /// the initialization is retried off the startup path; requests in the meantime ride out the | ||
| /// wake-up via EF's <c>EnableRetryOnFailure</c>. | ||
| /// </remarks> | ||
| public static class DatabaseStartup | ||
| { | ||
| /// <summary> | ||
| /// Initializes the database, falling back to a background retry loop if the first attempt | ||
| /// fails. | ||
| /// </summary> | ||
| /// <returns> | ||
| /// <c>null</c> when the database was initialized immediately, otherwise the background retry | ||
| /// task. Production discards it — startup must not wait on it — but a test can await it. | ||
| /// </returns> | ||
| public static async Task<Task?> InitializeAsync( | ||
| IServiceProvider services, | ||
| DemoSeedOptions demoSeed, | ||
| ILogger logger, | ||
| TimeSpan retryDelay, | ||
| int maxRetryAttempts) | ||
| { | ||
| try | ||
| { | ||
| await InitializeOnceAsync(services, demoSeed); | ||
| return null; | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogWarning(ex, | ||
| "Database initialization was deferred at startup (database may be resuming). " + | ||
| "It will be retried in the background."); | ||
|
|
||
| return Task.Run(() => RetryAsync( | ||
| services, demoSeed, logger, retryDelay, maxRetryAttempts)); | ||
| } | ||
| } | ||
|
|
||
| private static async Task InitializeOnceAsync(IServiceProvider services, DemoSeedOptions demoSeed) | ||
| { | ||
| using var scope = services.CreateScope(); | ||
| var scoped = scope.ServiceProvider; | ||
|
|
||
| await DbInitializer.InitializeAsync( | ||
| scoped.GetRequiredService<ApplicationDbContext>(), | ||
| scoped.GetRequiredService<IPasswordHasher>(), | ||
| scoped.GetRequiredService<IDateTimeProvider>(), | ||
| demoSeed); | ||
| } | ||
|
|
||
| private static async Task RetryAsync( | ||
| IServiceProvider services, | ||
| DemoSeedOptions demoSeed, | ||
| ILogger logger, | ||
| TimeSpan retryDelay, | ||
| int maxRetryAttempts) | ||
| { | ||
| for (var attempt = 1; attempt <= maxRetryAttempts; attempt++) | ||
| { | ||
| await Task.Delay(retryDelay); | ||
|
|
||
| try | ||
| { | ||
| await InitializeOnceAsync(services, demoSeed); | ||
| logger.LogInformation( | ||
| "Database initialization completed on background attempt {Attempt}.", attempt); | ||
| return; | ||
| } | ||
| catch (Exception retryEx) | ||
| { | ||
| logger.LogWarning(retryEx, | ||
| "Background database initialization attempt {Attempt} failed.", attempt); | ||
| } | ||
|
bgard68 marked this conversation as resolved.
Dismissed
|
||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
68 changes: 68 additions & 0 deletions
68
tests/TodoApp.IntegrationTests/AuthenticationSetupTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| using FluentAssertions; | ||
| using Microsoft.Extensions.Configuration; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using TodoApp.WebApi.Authentication; | ||
| using Xunit; | ||
|
|
||
| namespace TodoApp.IntegrationTests; | ||
|
|
||
| /// <summary> | ||
| /// The signing-key guard. A missing or too-short key must stop the app at startup rather than | ||
| /// let it run with authentication that cannot be trusted. | ||
| /// </summary> | ||
| public class AuthenticationSetupTests | ||
| { | ||
| private static IServiceCollection Register(string? key) | ||
| { | ||
| var settings = new Dictionary<string, string?> { ["Jwt:Issuer"] = "TodoApp" }; | ||
| if (key is not null) | ||
| { | ||
| settings["Jwt:Key"] = key; | ||
| } | ||
|
|
||
| var configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); | ||
|
|
||
| return new ServiceCollection().AddJwtAuthentication(configuration); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void NoJwtSectionAtAll_StopsStartup() | ||
| { | ||
| var configuration = new ConfigurationBuilder().Build(); | ||
|
|
||
| var act = () => new ServiceCollection().AddJwtAuthentication(configuration); | ||
|
|
||
| act.Should().Throw<InvalidOperationException>().WithMessage("*at least 32 bytes*"); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData(null)] // the section exists but carries no key | ||
| [InlineData("")] // present but empty | ||
| [InlineData(" ")] // whitespace | ||
| [InlineData("too-short")] // under 256 bits | ||
| [InlineData("31-bytes-is-still-one-too-few!!")] | ||
| public void AWeakOrMissingKey_StopsStartup(string? key) | ||
| { | ||
| var act = () => Register(key); | ||
|
|
||
| act.Should().Throw<InvalidOperationException>().WithMessage("*at least 32 bytes*"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void AKeyOfExactlyTheMinimumLengthIsAccepted() | ||
| { | ||
| var key = new string('k', 32); // 32 ASCII characters == 32 bytes == 256 bits | ||
|
|
||
| var act = () => Register(key); | ||
|
|
||
| act.Should().NotThrow(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void AValidKeyRegistersAuthentication() | ||
| { | ||
| var services = Register("a-perfectly-adequate-signing-key-of-sufficient-length"); | ||
|
|
||
| services.Should().NotBeEmpty(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.