playwright-dotnet icon indicating copy to clipboard operation
playwright-dotnet copied to clipboard

[Feature] Set ContextOptions via runsettings file

Open hughesjs opened this issue 2 years ago • 8 comments

One of the big benefits of using the nunit package is not having to worry about lots of setup boilerplate.

However, I can't seem to set the BaseUrl with an env var, which seems pretty crucial to me...

Can we get this added please?

hughesjs avatar Apr 18 '23 11:04 hughesjs

You can do the following, would that work for you?

using Microsoft.Playwright.NUnit;
using Microsoft.Playwright;

namespace PlaywrightTestsN;

[Parallelizable(ParallelScope.Self)]
[TestFixture]
public class MyTest : PageTest
{
    [Test]
    public async Task TestWithCustomContextOptions()
    {
        // The following Page (and BrowserContext) instance has the custom baseURL set:
        await Page.GotoAsync("/login");
    }

    public override BrowserNewContextOptions ContextOptions()
    {
        var baseURL = Environment.GetEnvironmentVariable("BASE_URL");
        if (string.IsNullOrEmpty(baseURL))
        {
            throw new Exception("BASE_URL environment variable is not set.");
        }
        return new BrowserNewContextOptions()
        {
            BaseURL = baseURL,
        };
    }
}

mxschmitt avatar Apr 18 '23 14:04 mxschmitt

Sure, I can, I've already done this:

public class CustomContextTest: ContextTest
{
    public override BrowserNewContextOptions ContextOptions() =>
        new()
            {
                BaseURL = ContextHelper.TestSettings.Host
            };
}

And have two other classes inheriting from it for my equivalent of a PageTest and a MultiPageTest class I've made.

That being said, I don't think it should be necessary. I think setting a BaseURL for automation testing in a .runsettings file or an env var is just as important as indicating whether it's meant to be run headlessly.

Playwright already supports this, I think it's just a case of adding it to the NUnit setup in the same way as we look for HEADED and DEBUG. If this is something you'd consider, I don't mind raising a PR for it.

hughesjs avatar Apr 19 '23 14:04 hughesjs

Arguably, anything in BrowserNewContextOptions should be settable

hughesjs avatar Apr 20 '23 10:04 hughesjs

sounds reasonable! I changed the PR title to reflect this feature request.

mxschmitt avatar Apr 20 '23 12:04 mxschmitt

Hey @mxschmitt, any update on that, it is on the table :)

NikkTod avatar Jun 21 '23 22:06 NikkTod

We use MSTest, and I wrote a TestContext extension method to set BaseUrl and such from the runsettings:

BaseURL = TestContext.GetParameter("BaseUrl")

Exoow avatar Oct 27 '23 07:10 Exoow

@Exoow can you share your TestContext extension in an example? So it's easy to maybe implement the same workaround like you did.

paule96 avatar Mar 05 '24 10:03 paule96

See attachment, just rename the file to .cs :)

TestContextExtensions.txt

Exoow avatar Mar 05 '24 10:03 Exoow