I recently migrated from Selenium/Java to Playwright with NUnit on .NET for work, and I'm trying to monitor all HTTP requests & responses for each of my E2E tests, and if any requests time out with a 408 code I need the page to refresh. I have this Setup method, which seems to correctly log my requests/responses if I'm just running each individual test, but when I run the entire test class (sequentially), the tests run but it only logs my requests/responses for the very first test. I'm not sure if this approach is viable or if I'm doing something completely wrong here, but I was under the impression a new page & context would be created for each test, I'm disposing my contexts after each test in my Teardown method
private IBrowser browser;
private IBrowserContext context;
private IPage page;
//private ThreadLocal<IPage> threadPage = new ThreadLocal<IPage>();
[SetUp]
public async Task Setup()
{
//Page.SetDefaultTimeout(15000);
TestContext.Out.WriteLine("Starting test: " + TestContext.CurrentContext.Test.MethodName);
//create browser instance, add launch options here
browser = await Playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
{
Headless = false,
SlowMo = 250
});
//context instance, add video and network options here
context = await browser.NewContextAsync(new()
{
RecordVideoDir = "videos/"
});
//new page instance
page = await context.NewPageAsync();
//monitor requests & responses during test
page.Request += (_, request) => TestContext.Out.WriteLine(">> " + request.Method + " " + request.Url);
page.Response += (_, response) =>
{
TestContext.Out.WriteLine("<< " + response.Status + " " + response.Url);
if (response.Status == 200)
{
TestContext.Out.WriteLine("Successful request.");
}else if(response.Status == 408)
{
page.ReloadAsync();
TestContext.Out.WriteLine("Connection timed out, refreshing page");
}
};
//login with valid admin credentials
await LoginAdmin();
}
[TearDown]
public async Task Teardown()
{
if (TestContext.CurrentContext.Result.Outcome.Status != TestStatus.Passed && TestContext.CurrentContext.Result.Outcome.Status != TestStatus.Skipped)
{
Assert.Fail("Test failed due to exception: " + TestContext.CurrentContext.Result.Message);
}
await context.CloseAsync();
await browser.CloseAsync();
}`
Initially I was using PageTest to write each test, then tried to add the request & response monitoring and that's when I ran into the same problem as when I was creating each page and browser context manually as up above. Also tried to use ThreadLocal to see if that'd fix the pages seemingly not getting a new context but I don't know if that's the case or if that'd be the right approach here anyways since my test methods are running sequentially and classes in parallel but even the monitoring on one test class file is only working for the first test in the class. Any ideas how I can try fixing this behavior?