Skip to content

Commit e998831

Browse files
committed
Create test for hybrid flow sample
1 parent b898513 commit e998831

File tree

6 files changed

+208
-3
lines changed

6 files changed

+208
-3
lines changed
-1018 Bytes
Binary file not shown.

UiTests/AnyOrgOrPersonalUiTest/AnyOrgOrPersonalTest.cs

-1
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,5 @@ public async Task ChallengeUser_MicrosoftIdFlow_LocalApp_ValidEmailPasswordCreds
134134
playwright.Dispose();
135135
}
136136
}
137-
138137
}
139138
}
+141
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
using System;
5+
using System.Collections.Generic;
6+
using System.IO;
7+
using System.Linq;
8+
using System.Net;
9+
using System.Runtime.Versioning;
10+
using System.Text;
11+
using System.Threading.Tasks;
12+
using Common;
13+
using Microsoft.Identity.Lab.Api;
14+
using Microsoft.Playwright;
15+
using Xunit;
16+
using Xunit.Abstractions;
17+
using static System.Net.Mime.MediaTypeNames;
18+
using Process = System.Diagnostics.Process;
19+
using TC = Common.TestConstants;
20+
21+
namespace HybridFlowUiTest
22+
{
23+
public class HybridFlowTest : IClassFixture<InstallPlaywrightBrowserFixture>
24+
{
25+
private const string SignOutPageUriPath = @"/MicrosoftIdentity/Account/SignedOut";
26+
private const uint ClientPort = 44321;
27+
private const string TraceFileClassName = "OpenIDConnect-HybridFlow";
28+
private const uint NumProcessRetries = 3;
29+
private const string SampleSlnFileName = "2-5-HybridFlow.sln";
30+
private const string SampleExeFileName = "\\2-5-HybridFlow.exe";
31+
private readonly LocatorAssertionsToBeVisibleOptions _assertVisibleOptions = new() { Timeout = 25000 };
32+
private readonly string _sampleAppPath = "2-WebApp-graph-user" + Path.DirectorySeparatorChar + "2-5-HybridFlow" + Path.DirectorySeparatorChar.ToString();
33+
private readonly string _testAppsettingsPath = "UiTests" + Path.DirectorySeparatorChar + "HybridFlowUiTest" + Path.DirectorySeparatorChar.ToString() + TC.AppSetttingsDotJson;
34+
private readonly string _testAssemblyLocation = typeof(HybridFlowTest).Assembly.Location;
35+
private readonly ITestOutputHelper _output;
36+
37+
public HybridFlowTest(ITestOutputHelper output)
38+
{
39+
_output = output;
40+
}
41+
42+
[Fact]
43+
[SupportedOSPlatform("windows")]
44+
public async Task ChallengeUser_MicrosoftIdFlow_LocalApp_ValidEmailPasswordCreds_LoginLogout()
45+
{
46+
// Setup web app and api environmental variables.
47+
var clientEnvVars = new Dictionary<string, string>
48+
{
49+
{"ASPNETCORE_ENVIRONMENT", "Development"},
50+
{TC.KestrelEndpointEnvVar, TC.HttpsStarColon + ClientPort}
51+
};
52+
53+
Dictionary<string, Process>? processes = null;
54+
55+
// Arrange Playwright setup, to see the browser UI set Headless = false.
56+
const string TraceFileName = TraceFileClassName + "_LoginLogout";
57+
using IPlaywright playwright = await Playwright.CreateAsync();
58+
IBrowser browser = await playwright.Chromium.LaunchAsync(new() { Headless = false });
59+
IBrowserContext context = await browser.NewContextAsync(new BrowserNewContextOptions { IgnoreHTTPSErrors = true });
60+
await context.Tracing.StartAsync(new() { Screenshots = true, Snapshots = true, Sources = true });
61+
IPage page = await context.NewPageAsync();
62+
string uriWithPort = TC.LocalhostUrl + ClientPort;
63+
64+
try
65+
{
66+
// Build the sample app with correct appsettings file.
67+
UiTestHelpers.BuildSampleUsingTestAppsettings(_testAssemblyLocation, _sampleAppPath, _testAppsettingsPath, SampleSlnFileName);
68+
69+
// Start the web app and api processes.
70+
// The delay before starting client prevents transient devbox issue where the client fails to load the first time after rebuilding
71+
var clientProcessOptions = new ProcessStartOptions(_testAssemblyLocation, _sampleAppPath, SampleExeFileName, clientEnvVars);
72+
73+
bool areProcessesRunning = UiTestHelpers.StartAndVerifyProcessesAreRunning([clientProcessOptions], out processes, NumProcessRetries);
74+
75+
if (!areProcessesRunning)
76+
{
77+
_output.WriteLine($"Process not started after {NumProcessRetries} attempts.");
78+
StringBuilder runningProcesses = new StringBuilder();
79+
foreach (var process in processes)
80+
{
81+
#pragma warning disable CA1305 // Specify IFormatProvider
82+
runningProcesses.AppendLine($"Is {process.Key} running: {UiTestHelpers.ProcessIsAlive(process.Value)}");
83+
#pragma warning restore CA1305 // Specify IFormatProvider
84+
}
85+
Assert.Fail(TC.WebAppCrashedString + " " + runningProcesses.ToString());
86+
}
87+
88+
LabResponse labResponse = await LabUserHelper.GetSpecificUserAsync(TC.MsidLab4User);
89+
90+
// Initial sign in
91+
_output.WriteLine("Starting web app sign-in flow.");
92+
string email = labResponse.User.Upn;
93+
await UiTestHelpers.NavigateToWebApp(uriWithPort, page);
94+
await page.GetByRole(AriaRole.Link, new() { Name = "Sign in" }).ClickAsync();
95+
await UiTestHelpers.FirstLogin_MicrosoftIdFlow_ValidEmailPassword(page, email, labResponse.User.GetOrFetchPassword(), _output);
96+
await Assertions.Expect(page.GetByText("SPA Authorization Code")).ToBeVisibleAsync(_assertVisibleOptions);
97+
await Assertions.Expect(page.GetByText(email)).ToBeVisibleAsync(_assertVisibleOptions);
98+
_output.WriteLine("Web app sign-in flow successful.");
99+
100+
// Sign out
101+
_output.WriteLine("Starting web app sign-out flow.");
102+
await page.GetByRole(AriaRole.Link, new() { Name = "Sign out" }).ClickAsync();
103+
await UiTestHelpers.PerformSignOut_MicrosoftIdFlow(page, email, TC.LocalhostUrl + ClientPort + SignOutPageUriPath, _output);
104+
_output.WriteLine("Web app sign out successful.");
105+
}
106+
catch (Exception ex)
107+
{
108+
// Adding guid in case of multiple test runs. This will allow screenshots to be matched to their appropriate test runs.
109+
var guid = Guid.NewGuid().ToString();
110+
try
111+
{
112+
if (page != null)
113+
{
114+
await page.ScreenshotAsync(new PageScreenshotOptions() { Path = $"ChallengeUser_MicrosoftIdFlow_LocalApp_ValidEmailPasswordCreds_TodoAppFunctionsCorrectlyScreenshotFail{guid}.png", FullPage = true });
115+
}
116+
}
117+
catch
118+
{
119+
_output.WriteLine("No Screenshot.");
120+
}
121+
122+
string runningProcesses = UiTestHelpers.GetRunningProcessAsString(processes);
123+
Assert.Fail($"the UI automation failed: {ex} output: {ex.Message}.\n{runningProcesses}\nTest run: {guid}");
124+
}
125+
finally
126+
{
127+
// Make sure all processes and their children are stopped.
128+
UiTestHelpers.EndProcesses(processes);
129+
130+
// Stop tracing and export it into a zip archive.
131+
string path = UiTestHelpers.GetTracePath(_testAssemblyLocation, TraceFileName);
132+
await context.Tracing.StopAsync(new() { Path = path });
133+
_output.WriteLine($"Trace data for {TraceFileName} recorded to {path}.");
134+
135+
// Close the browser and stop Playwright.
136+
await browser.CloseAsync();
137+
playwright.Dispose();
138+
}
139+
}
140+
}
141+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<TargetFrameworks>net8.0</TargetFrameworks>
5+
<IsPackable>false</IsPackable>
6+
<Nullable>enable</Nullable>
7+
</PropertyGroup>
8+
9+
<ItemGroup>
10+
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="$(MicrosoftAspNetCoreMvcTestingVersion)" />
11+
<PackageReference Include="Microsoft.Identity.Lab.Api" Version="$(MicrosoftIdentityLabApiVersion)" />
12+
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(MicrosoftNetTestSdkVersion)" />
13+
<PackageReference Include="Microsoft.Playwright" Version="$(MicrosoftPlaywrightVersion)" />
14+
<PackageReference Include="System.Management" Version="$(SystemManagementVersion)" />
15+
<PackageReference Include="System.Text.Json" Version="$(SystemTextJsonVersion)" />
16+
<PackageReference Include="xunit" Version="$(XunitVersion)" />
17+
<PackageReference Include="xunit.runner.visualstudio" Version="$(XunitRunnerVisualStudioVersion)">
18+
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
19+
<PrivateAssets>all</PrivateAssets>
20+
</PackageReference>
21+
<PackageReference Include="coverlet.collector" Version="$(CoverletCollectorVersion)">
22+
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
23+
<PrivateAssets>all</PrivateAssets>
24+
</PackageReference>
25+
</ItemGroup>
26+
27+
<ItemGroup>
28+
<ProjectReference Include="..\Common\Common.csproj" />
29+
</ItemGroup>
30+
31+
</Project>
+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
{
2+
"AzureAd": {
3+
"Instance": "https://login.microsoftonline.com/",
4+
"Domain": "msidlab4.onmicrosoft.com",
5+
"TenantId": "f645ad92-e38d-4d1a-b510-d1b09a74a8ca",
6+
"ClientId": "9a192b78-6580-4f8a-aace-f36ffea4f7be",
7+
"CallbackPath": "/signin-oidc",
8+
"SignedOutCallbackPath": "/signout-callback-oidc",
9+
"ClientCertificates": [
10+
{
11+
"SourceType": "KeyVault",
12+
"KeyVaultUrl": "https://webappsapistests.vault.azure.net",
13+
"KeyVaultCertificateName": "Self-Signed-5-5-22"
14+
}
15+
]
16+
},
17+
"Logging": {
18+
"LogLevel": {
19+
"Default": "Warning"
20+
}
21+
},
22+
"AllowedHosts": "*",
23+
"DownstreamApi": {
24+
"BaseUrl": "https://graph.microsoft.com/v1.0",
25+
"Scopes": "user.read contacts.read"
26+
},
27+
"SpaRedirectUri": "https://localhost:44321/"
28+
}

UiTests/UiTests.sln

+8-2
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
1212
Directory.Build.props = Directory.Build.props
1313
EndProjectSection
1414
EndProject
15-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "B2CUiTest", "B2CUiTest\B2CUiTest.csproj", "{BF7D9973-9B92-4BED-ADE2-09087DDA9C85}"
15+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "B2CUiTest", "B2CUiTest\B2CUiTest.csproj", "{BF7D9973-9B92-4BED-ADE2-09087DDA9C85}"
1616
EndProject
17-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GraphUserTokenCache", "GraphUserTokenCache\GraphUserTokenCache.csproj", "{B083D288-AB6E-4849-9AC2-E1DA1F727483}"
17+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GraphUserTokenCache", "GraphUserTokenCache\GraphUserTokenCache.csproj", "{B083D288-AB6E-4849-9AC2-E1DA1F727483}"
18+
EndProject
19+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HybridFlowUiTest", "HybridFlowUiTest\HybridFlowUiTest.csproj", "{344CD55E-14C7-4999-A040-6C049F0070CB}"
1820
EndProject
1921
Global
2022
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -38,6 +40,10 @@ Global
3840
{B083D288-AB6E-4849-9AC2-E1DA1F727483}.Debug|Any CPU.Build.0 = Debug|Any CPU
3941
{B083D288-AB6E-4849-9AC2-E1DA1F727483}.Release|Any CPU.ActiveCfg = Release|Any CPU
4042
{B083D288-AB6E-4849-9AC2-E1DA1F727483}.Release|Any CPU.Build.0 = Release|Any CPU
43+
{344CD55E-14C7-4999-A040-6C049F0070CB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
44+
{344CD55E-14C7-4999-A040-6C049F0070CB}.Debug|Any CPU.Build.0 = Debug|Any CPU
45+
{344CD55E-14C7-4999-A040-6C049F0070CB}.Release|Any CPU.ActiveCfg = Release|Any CPU
46+
{344CD55E-14C7-4999-A040-6C049F0070CB}.Release|Any CPU.Build.0 = Release|Any CPU
4147
EndGlobalSection
4248
GlobalSection(SolutionProperties) = preSolution
4349
HideSolutionNode = FALSE

0 commit comments

Comments
 (0)