Created
April 30, 2024 16:03
-
-
Save sadukie/bed69e775aa5fa78f6edfe70683ab8dd to your computer and use it in GitHub Desktop.
Using Shared State in Playwright for .NET
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
using Microsoft.Playwright; | |
using NimblePros.SuperSecretProject.FrontEndTests.PageObjects; | |
namespace NimblePros.SuperSecretProject.FrontEndTests; | |
internal class AuthenticatedPlaywrightDriver : IDisposable | |
{ | |
private IPlaywright? _playwright; | |
private IBrowser? _browser; | |
private IBrowserContext? _context; | |
public AuthenticatedPlaywrightDriver() | |
{ | |
} | |
internal async Task<IPage> CreateAuthenticatedPage() | |
{ | |
_playwright = await Playwright.CreateAsync(); | |
_browser = await _playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false }); | |
_context = await CreateAuthenticatedContext(); | |
return await _context.NewPageAsync(); | |
} | |
private async Task<IBrowserContext> CreateAuthenticatedContext() | |
{ | |
// Load storage state from file | |
var storageState = await LoadStorageStateFromFile("state.json"); | |
// Create a new browser context with the loaded storage state | |
var contextOptions = new BrowserNewContextOptions | |
{ | |
StorageState = storageState.ToString() | |
}; | |
_context = await _browser!.NewContextAsync(contextOptions); | |
if (string.IsNullOrEmpty(storageState)) | |
{ | |
// If the state file didn't exist, a new file is created | |
// That would get you here to this point | |
// Since the login page object handles logging into the portal, | |
// We will add that dependency here. | |
var loginPage = new LoginPage(await _context.NewPageAsync()); | |
await loginPage.LoginAsync(); | |
} | |
return _context; | |
} | |
private async Task<string> LoadStorageStateFromFile(string filePath) | |
{ | |
if (!File.Exists(filePath)) | |
{ | |
// Create the file and release the lock | |
File.Create(filePath).Dispose(); | |
} | |
// Read the storage state file | |
return await File.ReadAllTextAsync(filePath); | |
} | |
public void Dispose() | |
{ | |
_browser!.DisposeAsync(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment