Skip to content

Commit aad1787

Browse files
ci: smoke test dev after deploy and gate production on it (#1642)
## Why Production is currently promoted as soon as `deploy-development` finishes, even if dev is broken. `az containerapp update` also returns about 45 s **before** traffic shifts to the new revision. Builds on #1639 (`GET /version`). ## What New steps at the end of `deploy-development`: 1. **Wait for the new revision.** `scripts/wait-for-deployed-commit.sh` polls `https://dev.essentialcsharp.com/version` until it reports `github.sha` 3 times in a row (10-minute timeout). The URL can be overridden with `vars.SITE_BASE_URL`. On timeout it prints `az containerapp revision list`. 2. **Smoke test.** `dotnet test` runs the new `EssentialCSharp.Web.E2ETests` project filtered to `[Category=Deployed]`. TRX results are uploaded on failure. The steps run **inside** `deploy-development`, not in a separate job, so they hold its concurrency group, and the next push can't swap the dev image mid-test. `deploy-production` already `needs` this job, so a failed smoke run blocks promotion. Dev keeps the failed build until the next push; there is no automatic rollback. ### Checks (anonymous, read-only apart from one form post per provider) | Check | Catches | |---|---| | `/health`, `/alive` return 200 | App is up | | `/version` commit equals `github.sha` | Testing the right build | | `/home` renders, and its canonical link uses the deployed origin | `SiteSettings:BaseUrl` misconfiguration | | Sitemap has more than 100 pages, all on the deployed host, and a chapter page renders | Image built without book content, broken content routing | | Login page has the hCaptcha site key and GitHub/Microsoft buttons | Captcha or external login config missing (captcha fails closed) | | `POST /Identity/Account/ExternalLogin` for GitHub and Microsoft returns 302 to the provider's authorize endpoint with `client_id` and `redirect_uri=<site>/signin-<provider>` | Provider registration, client id, callback/forwarded-headers config | The full OAuth round trip, secrets and consent are out of scope. Logged-in flows (login and AI chat) will follow separately. They need a dev test account and a captcha decision first. ### Safety and robustness - Tests **skip** unless `E2E_BASE_URL` or `E2E_EXPECTED_COMMIT` is set, so the normal 3-OS PR test run is unaffected. If either is set, the tests always run, so a malformed URL fails the gate instead of skipping everything and passing. - Each request is retried once on 429, 5xx, a connection error or a timeout. - Each run makes about 13 requests. Only 2 count against the content limiter (20/hour per IP for anonymous users). `/health`, `/alive` and `/version` are exempt. ## Verification - Ran the deployed tests against real dev before #1639 deployed: 7/8 passed. `/version` returned 302 because that build predates it, which is expected. After this merges, the deploy will include `/version`. - Exercised the wait script locally against a fake `/version` for success, wrong-commit timeout, unreachable host (the curl error is shown) and missing `jq`. - Unset variables give 8 skipped tests. A malformed `E2E_BASE_URL` makes all 8 fail with a clear message.
1 parent b33e90b commit aad1787

7 files changed

Lines changed: 377 additions & 1 deletion

File tree

‎.editorconfig‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,5 +156,5 @@ csharp_style_expression_bodied_lambdas = true:silent
156156
csharp_style_expression_bodied_local_functions = false:silent
157157

158158
# Test files - allow underscore-separated test method names (CA1707)
159-
[{EssentialCSharp.Web.Tests,EssentialCSharp.Chat.Tests,dev/EssentialCSharp.Web.AppHost.Tests}/**]
159+
[{EssentialCSharp.Web.Tests,EssentialCSharp.Web.E2ETests,EssentialCSharp.Chat.Tests,dev/EssentialCSharp.Web.AppHost.Tests}/**]
160160
dotnet_diagnostic.CA1707.severity = none

‎.github/workflows/Build-Test-And-Deploy.yml‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,50 @@ jobs:
335335
--resource-group "$RESOURCEGROUP" \
336336
--image "${{ vars.DEVCONTAINER_REGISTRY }}/essentialcsharpweb:${{ github.sha }}"
337337
338+
# Smoke testing runs inside this job (not a separate one) so it holds the deploy-development
339+
# concurrency group: the next push cannot swap the dev image mid-test. deploy-production needs
340+
# this job, so a failed smoke test blocks promotion (dev keeps the failed build until the next push).
341+
- name: Wait for the new revision to serve this commit
342+
id: wait-for-revision
343+
env:
344+
SITE_BASE_URL: ${{ vars.SITE_BASE_URL || 'https://dev.essentialcsharp.com' }}
345+
run: bash scripts/wait-for-deployed-commit.sh "$SITE_BASE_URL" "${{ github.sha }}"
346+
347+
- name: Show revision status
348+
if: failure() && steps.wait-for-revision.outcome == 'failure'
349+
env:
350+
CONTAINER_APP_NAME: ${{ vars.CONTAINER_APP_NAME }}
351+
RESOURCEGROUP: ${{ vars.RESOURCEGROUP }}
352+
run: |
353+
az containerapp revision list \
354+
--name "$CONTAINER_APP_NAME" \
355+
--resource-group "$RESOURCEGROUP" \
356+
--query "[].{name:name, active:properties.active, traffic:properties.trafficWeight, health:properties.healthState, running:properties.runningState, image:properties.template.containers[0].image}" \
357+
--output table
358+
359+
- name: Set up .NET
360+
uses: actions/setup-dotnet@v6
361+
with:
362+
global-json-file: global.json
363+
364+
- name: Smoke test development
365+
env:
366+
E2E_BASE_URL: ${{ vars.SITE_BASE_URL || 'https://dev.essentialcsharp.com' }}
367+
E2E_EXPECTED_COMMIT: ${{ github.sha }}
368+
run: >-
369+
dotnet test --project EssentialCSharp.Web.E2ETests/EssentialCSharp.Web.E2ETests.csproj
370+
--configuration Release
371+
-- --treenode-filter "/*/*/*/*[Category=Deployed]"
372+
--report-trx --results-directory "${{ runner.temp }}/smoke-results"
373+
374+
- name: Upload smoke test results
375+
if: failure()
376+
uses: actions/upload-artifact@v7
377+
with:
378+
name: smoke-test-results
379+
path: ${{ runner.temp }}/smoke-results
380+
if-no-files-found: ignore
381+
338382
- name: Logout of Azure CLI
339383
if: always()
340384
uses: azure/CLI@v3
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
using System.Net;
2+
using Microsoft.Extensions.Http.Resilience;
3+
using Polly;
4+
5+
namespace EssentialCSharp.Web.E2ETests;
6+
7+
/// <summary>
8+
/// The deployed site under test, configured through environment variables:
9+
/// <list type="bullet">
10+
/// <item><c>E2E_BASE_URL</c> — required, e.g. <c>https://dev.essentialcsharp.com</c>.</item>
11+
/// <item><c>E2E_EXPECTED_COMMIT</c> — optional; when set, <c>/version</c> must report this commit.</item>
12+
/// </list>
13+
/// </summary>
14+
public static class DeployedSite
15+
{
16+
public const string BaseUrlVariable = "E2E_BASE_URL";
17+
public const string ExpectedCommitVariable = "E2E_EXPECTED_COMMIT";
18+
19+
private static readonly string? s_rawBaseUrl = Environment.GetEnvironmentVariable(BaseUrlVariable);
20+
21+
public static Uri? BaseUrl { get; } = ParseBaseUrl(s_rawBaseUrl);
22+
23+
/// <summary>The configured base URL; throws a descriptive error when it is missing or malformed.</summary>
24+
public static Uri RequiredBaseUrl => BaseUrl ?? throw new InvalidOperationException(
25+
$"{BaseUrlVariable} must be an absolute http(s) URL, e.g. https://dev.essentialcsharp.com (got '{s_rawBaseUrl}').");
26+
27+
/// <summary>
28+
/// Deployed tests are skipped only when nothing asked for them. If either variable is set (as the
29+
/// deployment gate does), they run — so a malformed URL fails loudly instead of skipping every test
30+
/// and letting the gate pass without testing anything.
31+
/// </summary>
32+
public static bool IsRequested =>
33+
!string.IsNullOrWhiteSpace(s_rawBaseUrl) || ExpectedCommit is not null;
34+
35+
internal static Uri? ParseBaseUrl(string? value) =>
36+
!string.IsNullOrWhiteSpace(value)
37+
&& Uri.TryCreate(value.Trim().TrimEnd('/') + "/", UriKind.Absolute, out Uri? uri)
38+
&& (uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeHttp)
39+
? uri
40+
: null;
41+
42+
public static string? ExpectedCommit { get; } =
43+
Environment.GetEnvironmentVariable(ExpectedCommitVariable) is { Length: > 0 } commit ? commit : null;
44+
45+
/// <summary>
46+
/// One retry for transient failures, so a single blip (or a shared runner IP hitting a rate limit)
47+
/// does not fail a deployment gate. <see cref="HttpRetryStrategyOptions"/> treats 5xx, 408, 429,
48+
/// connection errors and per-attempt timeouts as transient and honours <c>Retry-After</c>; any other
49+
/// status (including the 302s and 404s tests assert on) is returned unchanged on the first attempt.
50+
/// </summary>
51+
private static readonly ResiliencePipeline<HttpResponseMessage> s_pipeline =
52+
new ResiliencePipelineBuilder<HttpResponseMessage>()
53+
.AddRetry(new HttpRetryStrategyOptions
54+
{
55+
MaxRetryAttempts = 1,
56+
BackoffType = DelayBackoffType.Constant,
57+
Delay = TimeSpan.FromSeconds(5),
58+
MaxDelay = TimeSpan.FromSeconds(30),
59+
})
60+
.AddTimeout(TimeSpan.FromSeconds(30))
61+
.Build();
62+
63+
/// <summary>
64+
/// Creates a client that retries transient failures once, does not follow redirects (so tests can
65+
/// assert them), and keeps cookies (needed for antiforgery-protected form posts).
66+
/// </summary>
67+
public static HttpClient CreateClient()
68+
{
69+
Uri baseUrl = RequiredBaseUrl;
70+
var handler = new ResilienceHandler(s_pipeline)
71+
{
72+
InnerHandler = new HttpClientHandler
73+
{
74+
AllowAutoRedirect = false,
75+
CookieContainer = new CookieContainer(),
76+
UseCookies = true,
77+
},
78+
};
79+
var client = new HttpClient(handler, disposeHandler: true)
80+
{
81+
BaseAddress = baseUrl,
82+
// Covers both attempts plus the retry delay; each attempt is limited to 30s by the pipeline.
83+
Timeout = TimeSpan.FromSeconds(100),
84+
};
85+
client.DefaultRequestHeaders.UserAgent.ParseAdd("EssentialCSharp-SmokeTests/1.0");
86+
return client;
87+
}
88+
}
89+
90+
/// <summary>Skips a test unless a deployed site was requested via <c>E2E_BASE_URL</c> / <c>E2E_EXPECTED_COMMIT</c>.</summary>
91+
public sealed class RequiresDeployedSiteAttribute()
92+
: SkipAttribute($"Set {DeployedSite.BaseUrlVariable} to run tests against a deployed site.")
93+
{
94+
public override Task<bool> ShouldSkip(TestRegisteredContext context) =>
95+
Task.FromResult(!DeployedSite.IsRequested);
96+
}
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
using System.Net;
2+
using System.Text.Json;
3+
using System.Text.RegularExpressions;
4+
using System.Web;
5+
using System.Xml.Linq;
6+
7+
namespace EssentialCSharp.Web.E2ETests;
8+
9+
/// <summary>
10+
/// Anonymous, read-only checks against a deployed site. They gate promotion to production, so they cover
11+
/// configuration that unit and integration tests cannot see (Key Vault wiring, real content, external
12+
/// login registration, base URL) while staying well inside the site's per-IP rate limits.
13+
/// </summary>
14+
[Category("Deployed")]
15+
[RequiresDeployedSite]
16+
public partial class DeployedSmokeTests
17+
{
18+
[Test]
19+
[Arguments("health")]
20+
[Arguments("alive")]
21+
public async Task HealthEndpoint_ReturnsOk(string path)
22+
{
23+
using HttpClient client = DeployedSite.CreateClient();
24+
25+
using HttpResponseMessage response = await client.GetAsync(path);
26+
27+
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
28+
}
29+
30+
[Test]
31+
public async Task Version_ReportsDeployedCommit()
32+
{
33+
using HttpClient client = DeployedSite.CreateClient();
34+
35+
using HttpResponseMessage response = await client.GetAsync("version");
36+
37+
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
38+
await Assert.That(response).HasJsonContent();
39+
string body = await response.Content.ReadAsStringAsync();
40+
await Assert.That(body).IsValidJsonObject();
41+
42+
using JsonDocument payload = JsonDocument.Parse(body);
43+
string? commit = payload.RootElement.GetProperty("commit").GetString();
44+
if (DeployedSite.ExpectedCommit is { } expectedCommit)
45+
{
46+
await Assert.That(commit).IsEqualTo(expectedCommit);
47+
}
48+
else
49+
{
50+
await Assert.That(commit).IsNotNullOrWhiteSpace();
51+
}
52+
}
53+
54+
[Test]
55+
public async Task HomePage_RendersWithCanonicalUrlOnDeployedOrigin()
56+
{
57+
using HttpClient client = DeployedSite.CreateClient();
58+
59+
using HttpResponseMessage response = await client.GetAsync("home");
60+
string body = await response.Content.ReadAsStringAsync();
61+
62+
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
63+
await Assert.That(body).Contains("Explore Essential C#");
64+
// SiteSettings:BaseUrl drives canonical links and the sitemap; a wrong value silently hurts SEO.
65+
await Assert.That(body).Contains($"<link rel=\"canonical\" href=\"{new Uri(DeployedSite.RequiredBaseUrl, "home")}\"");
66+
}
67+
68+
[Test]
69+
public async Task Sitemap_ListsFullBook_AndAChapterPageRenders()
70+
{
71+
using HttpClient client = DeployedSite.CreateClient();
72+
73+
using HttpResponseMessage sitemapResponse = await client.GetAsync("sitemap.xml");
74+
await Assert.That(sitemapResponse.StatusCode).IsEqualTo(HttpStatusCode.OK);
75+
76+
XDocument sitemap = XDocument.Parse(await sitemapResponse.Content.ReadAsStringAsync());
77+
List<Uri> locations = sitemap.Descendants()
78+
.Where(element => element.Name.LocalName == "loc")
79+
.Select(element => new Uri(element.Value.Trim()))
80+
.ToList();
81+
82+
// Placeholder content (used when the content package is missing) has only a handful of pages;
83+
// the real book has hundreds. This catches an image built without the book content.
84+
await Assert.That(locations.Count).IsGreaterThan(100);
85+
await Assert.That(locations.All(uri => uri.Host == DeployedSite.RequiredBaseUrl.Host)).IsTrue();
86+
87+
// One content page from the middle of the book (content pages share a tight per-IP rate limit).
88+
Uri chapterPage = locations[locations.Count / 2];
89+
using HttpResponseMessage pageResponse = await client.GetAsync(chapterPage.PathAndQuery.TrimStart('/'));
90+
string pageBody = await pageResponse.Content.ReadAsStringAsync();
91+
92+
await Assert.That(pageResponse.StatusCode).IsEqualTo(HttpStatusCode.OK);
93+
await Assert.That(pageBody).Contains("window.TOC_DATA");
94+
}
95+
96+
[Test]
97+
public async Task LoginPage_RendersCaptchaAndExternalProviders()
98+
{
99+
using HttpClient client = DeployedSite.CreateClient();
100+
101+
using HttpResponseMessage response = await client.GetAsync("Identity/Account/Login");
102+
string body = await response.Content.ReadAsStringAsync();
103+
104+
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
105+
await Assert.That(CaptchaSiteKeyPattern().IsMatch(body)).IsTrue()
106+
.Because("login requires hCaptcha, which fails closed when its keys are missing");
107+
await Assert.That(body).Contains("name=\"provider\" value=\"GitHub\"");
108+
await Assert.That(body).Contains("name=\"provider\" value=\"Microsoft\"");
109+
}
110+
111+
/// <summary>
112+
/// Posts the external-login form without following the redirect. Verifies the provider is registered
113+
/// with a client id and the callback points back at this deployment; the OAuth round trip itself
114+
/// (secrets, consent, account linking) is out of scope for an automated smoke test.
115+
/// </summary>
116+
[Test]
117+
[Arguments("GitHub", "github.com", "/login/oauth/authorize", "signin-github")]
118+
[Arguments("Microsoft", "login.microsoftonline.com", "/common/oauth2/v2.0/authorize", "signin-microsoft")]
119+
public async Task ExternalLogin_RedirectsToProviderWithDeployedCallback(
120+
string provider, string expectedHost, string expectedPath, string expectedCallbackPath)
121+
{
122+
using HttpClient client = DeployedSite.CreateClient();
123+
124+
using HttpResponseMessage loginPage = await client.GetAsync("Identity/Account/Login");
125+
string loginBody = await loginPage.Content.ReadAsStringAsync();
126+
Match token = AntiforgeryTokenPattern().Match(loginBody);
127+
await Assert.That(token.Success).IsTrue();
128+
129+
using var form = new FormUrlEncodedContent(new Dictionary<string, string>
130+
{
131+
["provider"] = provider,
132+
["__RequestVerificationToken"] = WebUtility.HtmlDecode(token.Groups["token"].Value),
133+
});
134+
using HttpResponseMessage response = await client.PostAsync("Identity/Account/ExternalLogin", form);
135+
136+
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect);
137+
Uri location = await Assert.That(response.Headers.Location).IsNotNull();
138+
await Assert.That(location.Host).IsEqualTo(expectedHost);
139+
await Assert.That(location.AbsolutePath).IsEqualTo(expectedPath);
140+
141+
var query = HttpUtility.ParseQueryString(location.Query);
142+
await Assert.That(query["client_id"]).IsNotNullOrWhiteSpace();
143+
await Assert.That(query["redirect_uri"]).IsEqualTo(new Uri(DeployedSite.RequiredBaseUrl, expectedCallbackPath).ToString());
144+
}
145+
146+
[GeneratedRegex("(?:data-sitekey=\"|siteKey:\\s*\")(?<key>[^\"]+)\"")]
147+
private static partial Regex CaptchaSiteKeyPattern();
148+
149+
[GeneratedRegex("name=\"__RequestVerificationToken\" type=\"hidden\" value=\"(?<token>[^\"]+)\"")]
150+
private static partial Regex AntiforgeryTokenPattern();
151+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<!--
4+
End-to-end tests against a running site. Tests in the "Deployed" category run only when
5+
E2E_BASE_URL is set (for example by the deploy-development job) and are skipped otherwise,
6+
so this project builds and runs harmlessly as part of the normal solution test run.
7+
-->
8+
<PropertyGroup>
9+
<TargetFramework>net10.0</TargetFramework>
10+
<IsPackable>false</IsPackable>
11+
<IsPublishable>false</IsPublishable>
12+
</PropertyGroup>
13+
14+
<ItemGroup>
15+
<PackageReference Include="Microsoft.Extensions.Http.Resilience" />
16+
<PackageReference Include="TUnit" />
17+
</ItemGroup>
18+
19+
</Project>

‎EssentialCSharp.Web.slnx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
<Project Path="EssentialCSharp.Chat.Shared/EssentialCSharp.Chat.Common.csproj" />
1515
<Project Path="EssentialCSharp.Chat.Tests/EssentialCSharp.Chat.Tests.csproj" />
1616
<Project Path="EssentialCSharp.Chat/EssentialCSharp.Chat.csproj" />
17+
<Project Path="EssentialCSharp.Web.E2ETests/EssentialCSharp.Web.E2ETests.csproj" />
1718
<Project Path="EssentialCSharp.Web.Tests/EssentialCSharp.Web.Tests.csproj" />
1819
<Project Path="EssentialCSharp.Web/EssentialCSharp.Web.csproj" />
1920
<Project Path="EssentialCSharp.Web.Hosting/EssentialCSharp.Web.Hosting.csproj" />

0 commit comments

Comments
 (0)