|
| 1 | +using Microsoft.Playwright; |
| 2 | +using System.Diagnostics; |
| 3 | +using System.Xml.Linq; |
| 4 | + |
| 5 | +namespace PlaywrightTestRunner |
| 6 | +{ |
| 7 | + [Parallelizable(ParallelScope.Self)] |
| 8 | + [TestFixture] |
| 9 | + public class TestRunner : PageTest |
| 10 | + { |
| 11 | + // test port |
| 12 | + string dotnetVersion = ""; |
| 13 | + static ushort _port = 32301; |
| 14 | + StaticFileServer? staticFileServer; |
| 15 | + protected string BaseUrl = Environment.GetEnvironmentVariable("BASE_URL") ?? $"https://localhost:{_port}/"; |
| 16 | + /// <summary> |
| 17 | + /// This environment value should be set by the batch file that calls this script |
| 18 | + /// </summary> |
| 19 | + protected string TestProjectDirName = Environment.GetEnvironmentVariable("TestProjectDirName") ?? ""; |
| 20 | + /// <summary> |
| 21 | + /// Unit test page |
| 22 | + /// </summary> |
| 23 | + protected string UnitTestPage = Environment.GetEnvironmentVariable("UnitTestPage") ?? ""; |
| 24 | + /// <inheritdoc/> |
| 25 | + public override BrowserNewContextOptions ContextOptions() |
| 26 | + { |
| 27 | + return new BrowserNewContextOptions |
| 28 | + { |
| 29 | + // required to use the included self signed certificate |
| 30 | + IgnoreHTTPSErrors = true, |
| 31 | + }; |
| 32 | + } |
| 33 | + /// <summary> |
| 34 | + /// Starts serving the Blazor WebAssembly app using dotnet and waits for it to be ready for a max amount of time |
| 35 | + /// </summary> |
| 36 | + [OneTimeSetUp] |
| 37 | + public async Task StartApp() |
| 38 | + { |
| 39 | + // get the directory that contains the project being tested |
| 40 | + var projectDirectory = Path.GetFullPath($@"../../../../{TestProjectDirName}"); |
| 41 | + if (!Directory.Exists(projectDirectory)) |
| 42 | + { |
| 43 | + throw new DirectoryNotFoundException(projectDirectory); |
| 44 | + } |
| 45 | + |
| 46 | + // find the first *.csproj in the project's directory |
| 47 | + var projectPath = Directory.GetFiles(projectDirectory, "*.csproj").FirstOrDefault(); |
| 48 | + if (projectPath == null) |
| 49 | + { |
| 50 | + throw new FileNotFoundException($".csproj not found in: {projectDirectory}"); |
| 51 | + } |
| 52 | + |
| 53 | + // get the Blazor WASM project's dotnet version from its csproj file |
| 54 | + dotnetVersion = GetDotnetVersion(projectPath); |
| 55 | + |
| 56 | + // get wwwroot path |
| 57 | + var publishPath = Path.GetFullPath(Path.Combine(projectDirectory, $"bin/Release/{dotnetVersion}/publish/wwwroot")); |
| 58 | + |
| 59 | + // create https server for testing using StaticFileServer |
| 60 | + // uses the included self signed certificate for unit testing: assets/testcert.pfx |
| 61 | + staticFileServer = new StaticFileServer(publishPath, BaseUrl); |
| 62 | + |
| 63 | + // start https server |
| 64 | + staticFileServer.Start(); |
| 65 | + |
| 66 | + // wait for the server to start |
| 67 | + // use HttpClient to test for the server readiness |
| 68 | + using var httpClient = new HttpClient() { BaseAddress = new Uri(BaseUrl) }; |
| 69 | + var sw = Stopwatch.StartNew(); |
| 70 | + while (sw.Elapsed < TimeSpan.FromSeconds(30)) |
| 71 | + { |
| 72 | + try |
| 73 | + { |
| 74 | + using var response = await httpClient.GetAsync(BaseUrl).WaitAsync(TimeSpan.FromSeconds(2)); |
| 75 | + if (response?.IsSuccessStatusCode == true) |
| 76 | + { |
| 77 | + break; |
| 78 | + } |
| 79 | + } |
| 80 | + catch { } |
| 81 | + await Task.Delay(1000); |
| 82 | + } |
| 83 | + } |
| 84 | + /// <summary> |
| 85 | + /// Shutdown Blazor WASM host process |
| 86 | + /// </summary> |
| 87 | + [OneTimeTearDown] |
| 88 | + public async Task StopApp() |
| 89 | + { |
| 90 | + // shutdown the Blazor WASM host |
| 91 | + if (staticFileServer != null) |
| 92 | + { |
| 93 | + await staticFileServer.Stop(); |
| 94 | + } |
| 95 | + } |
| 96 | + /// <summary> |
| 97 | + /// Runs all tests in Home.razor > UnitTestsView component one at a time |
| 98 | + /// </summary> |
| 99 | + /// <returns></returns> |
| 100 | + /// <exception cref="Exception"></exception> |
| 101 | + [Test] |
| 102 | + public async Task RunAllTestsInTable_ShouldSucceed() |
| 103 | + { |
| 104 | + var testPage = new Uri(new Uri(BaseUrl), UnitTestPage).ToString(); |
| 105 | + await Page.GotoAsync(testPage); |
| 106 | + |
| 107 | + // get the table |
| 108 | + var table = Page.Locator("table.unit-test-view"); |
| 109 | + |
| 110 | + // wait for the table to finish rendering |
| 111 | + await Expect(table).ToHaveClassAsync(new Regex("unit-test-ready"), new() { Timeout = 10000 }); |
| 112 | + |
| 113 | + // get table body |
| 114 | + var tbody = table.Locator("tbody"); |
| 115 | + |
| 116 | + // get all rows in the target table body |
| 117 | + var rows = tbody.Locator("tr"); |
| 118 | + |
| 119 | + // iterate the rows |
| 120 | + int rowCount = await rows.CountAsync(); |
| 121 | + for (int i = 0; i < rowCount; i++) |
| 122 | + { |
| 123 | + // get the specific row by index |
| 124 | + var currentRow = rows.Nth(i); |
| 125 | + |
| 126 | + // find the button within THIS specific row |
| 127 | + var runButton = currentRow.GetByRole(AriaRole.Button, new() { Name = "Run" }); |
| 128 | + |
| 129 | + // click the button to start the process for this row |
| 130 | + await runButton.ClickAsync(); |
| 131 | + |
| 132 | + // assert that the row eventually gets the class 'test-state-done' |
| 133 | + await Expect(currentRow).ToHaveClassAsync(new Regex("test-state-done"), new() { Timeout = 15000 }); |
| 134 | + |
| 135 | + // get test type name |
| 136 | + var typeName = await currentRow.Locator(".test-type-name").TextContentAsync(); |
| 137 | + |
| 138 | + // get test method name |
| 139 | + var methodName = await currentRow.Locator(".test-method-name").TextContentAsync(); |
| 140 | + |
| 141 | + // current state text |
| 142 | + var stateMessage = await currentRow.Locator(".test-state").TextContentAsync(); |
| 143 | + |
| 144 | + // check for error class |
| 145 | + var wasError = await currentRow.EvaluateAsync<bool>("el => el.classList.contains('test-error')"); |
| 146 | + if (wasError) |
| 147 | + { |
| 148 | + throw new Exception($"Failed - {typeName}.{methodName}\nTest-error: {stateMessage}"); |
| 149 | + } |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + /// <summary> |
| 154 | + /// Gets the dotnet version from the csproj file |
| 155 | + /// </summary> |
| 156 | + /// <param name="projectPath">Path to the csproj file</param> |
| 157 | + /// <returns>The dotnet version</returns> |
| 158 | + private string GetDotnetVersion(string projectPath) |
| 159 | + { |
| 160 | + var xml = XDocument.Load(projectPath); |
| 161 | + var targetFramework = xml.Descendants("TargetFramework").FirstOrDefault(); |
| 162 | + if (targetFramework == null) |
| 163 | + { |
| 164 | + throw new Exception("Could not find TargetFramework in csproj file"); |
| 165 | + } |
| 166 | + return targetFramework.Value; |
| 167 | + } |
| 168 | + } |
| 169 | +} |
0 commit comments