microsoft / playwright-dotnet

.NET version of the Playwright testing and automation library.
https://playwright.dev/dotnet/
MIT License
2.47k stars 235 forks source link

[BUG] Playwright and Azure Function Deployment Issues #2150

Closed Pieeer1 closed 2 years ago

Pieeer1 commented 2 years ago

There is an issue with .net 6.0 playwright version 1.22.0 that is currently not allowing for deployment to Azure Functions. We have tried multiple solutions including manually setting up the browser EXE's as well as installing them locally. We created a test app shown below that outputs the error below that.

namespace PlaywrightTesterLibrary
{
    using Microsoft.Extensions.Logging;
    using Microsoft.Playwright;
    public class PlaywrightTester : IPlaywrightTester
    {
        private readonly ILogger _logger;

        public PlaywrightTester(ILogger<PlaywrightTester> logger)
        {
            _logger = logger;
        }

        public void Run()
        {
            PlaywrightExecution().Wait();

        }
        private async Task PlaywrightExecution()
        {
            try
            {
                Microsoft.Playwright.Program.Main(new[] { "install", "chromium" });
                _logger.LogDebug("Playwright Installed");

                using var playwright = await Playwright.CreateAsync();
                _logger.LogDebug("Created Playwright Asynchroniously");
                await using var browser = await playwright.Chromium.LaunchAsync(
                    new BrowserTypeLaunchOptions
                    {
                        Headless = false,
                        ExecutablePath = Environment.GetEnvironmentVariable("HOME_EXPANDED"),
                    });
                _logger.LogDebug("Creating Browser");
                var page = await browser.NewPageAsync();
                _logger.LogDebug("Opening Page");
                await page.GotoAsync("https://playwright.dev/dotnet");
                _logger.LogDebug("Going to Playwright Page");
                await page.ScreenshotAsync(new PageScreenshotOptions { Path = "screenshot.png" });
                _logger.LogDebug("Taking Screenshot");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message + ex);
            }
            finally
            {
                _logger.LogDebug("Success");
            }

        }

    }
}

This function runs locally, successfully (without the home expanded environment variable)

Error in Playwright: Failed to launch: Error: spawn D:\DWASFiles\Sites\test-inc-robot\VirtualDirectory0 ENOENT =========================== logs =========================== D:\DWASFiles\Sites\test-inc-robot\VirtualDirectory0 --disable-field-trial-config --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync --allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --no-service-autorun --export-tagged-pdf --no-sandbox --user-data-dir=C:\local\Temp\playwright_chromiumdev_profile-2czlmr --remote-debugging-pipe --no-startup-window [pid=N/A] starting temporary directories cleanup [pid=N/A] finished temporary directories cleanup ============================================================Microsoft.Playwright.PlaywrightException: Failed to launch: Error: spawn D:\DWASFiles\Sites\test-inc-robot\VirtualDirectory0 ENOENT =========================== logs =========================== D:\DWASFiles\Sites\test-inc-robot\VirtualDirectory0 --disable-field-trial-config --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync --allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --no-service-autorun --export-tagged-pdf --no-sandbox --user-data-dir=C:\local\Temp\playwright_chromiumdevprofile-2czlmr --remote-debugging-pipe --no-startup-window [pid=N/A] starting temporary directories cleanup [pid=N/A] finished temporary directories cleanup ============================================================ at Microsoft.Playwright.Transport.Connection.InnerSendMessageToServerAsync[T](String guid, String method, Object args) in //src/Playwright/Transport/Connection.cs:line 164 at Microsoft.Playwright.Transport.Connection.WrapApiCallAsync[T](Func`1 action, Boolean isInternal) in //src/Playwright/Transport/Connection.cs:line 475 at Microsoft.Playwright.Core.BrowserType.LaunchAsync(BrowserTypeLaunchOptions options) in //src/Playwright/Core/BrowserType.cs:line 61 at PlaywrightTesterLibrary.PlaywrightTester.PlaywrightExecution() in /home/vsts/work/1/application/Projects/PlaywrightTester/PlaywrightTester.cs:line 28

Once deployed this error is thrown.

yury-s commented 2 years ago

The ExexutablePath you set is a directory ("D:\DWASFiles\Sites\test-inc-robot\VirtualDirectory0") while it is expected to be a path to the .exe file of the browser. You should be able to install the bundled browser by running

# Install required browsers - replace netX with actual output folder name, f.ex. net6.0.
pwsh bin\Debug\netX\playwright.ps1 install

or programmatically from the you app and omit custom ExecutablePath, see this doc.

Pieeer1 commented 2 years ago

So I have tried a variety of those fixes without success. With the programmatic fix, We get Exception:Microsoft.Playwright.PlaywrightException: Executable doesn't exist at D:\DWASFiles\Sites{user}\VirtualDirectory0\PlaywrightBrowserPath\chromium-1000\chrome-win\chrome.exe╔═════════════════════════════════════════════════════════════════════════╗║ Looks like Playwright Test or Playwright was just installed or updated. ║║ Please run the following command to download new browsers: ║║ ║║ pwsh bin\Debug\netX\playwright.ps1 install ║║ ║║ <3 Playwright Team ║╚═════════════════════════════════════════════════════════════════════════╝at

We are unable to run pwsh bin\Debug\net6.0\playwright.ps1 install on the cloud since the environment does not have pwsh as a valid command and we do not have access to add it. When omitting the executable path, we get the same error. The file structure for chrome fully exists at that path and we are able to access the directory and file. Confused as to why we are getting a does not exist error, when it clearly exists.

Pieeer1 commented 2 years ago

To add on, when we try to directly path it inside of the actual application, we get an EONET error:

Failed to launch: Error: spawn C:\home\site\wwwroot\.playwright\package\.local-browsers\chromium-1005\chrome-win ENOENT =========================== logs =========================== <launching> C:\home\site\wwwroot\.playwright\package\.local-browsers\chromium-1005\chrome-win --disable-field-trial-config --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync --allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --no-service-autorun --export-tagged-pdf --headless --hide-scrollbars --mute-audio --blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4 --no-sandbox --user-data-dir=C:\local\Temp\playwright_chromiumdev_profile-oktNuR --remote-debugging-pipe --no-startup-window [pid=N/A] starting temporary directories cleanup [pid=N/A] finished temporary directories cleanup ============================================================Microsoft.Playwright.PlaywrightException: Failed to launch: Error: spawn C:\home\site\wwwroot\.playwright\package\.local-browsers\chromium-1005\chrome-win ENOENT =========================== logs =========================== <launching> C:\home\site\wwwroot\.playwright\package\.local-browsers\chromium-1005\chrome-win --disable-field-trial-config --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync --allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --no-service-autorun --export-tagged-pdf --headless --hide-scrollbars --mute-audio --blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4 --no-sandbox --user-data-dir=C:\local\Temp\playwright_chromiumdev_profile-oktNuR --remote-debugging-pipe --no-startup-window [pid=N/A] starting temporary directories cleanup [pid=N/A] finished temporary directories cleanup ============================================================ at Microsoft.Playwright.Transport.Connection.InnerSendMessageToServerAsync[T](String guid, String method, Object args) in /_/src/Playwright/Transport/Connection.cs:line 164 at Microsoft.Playwright.Transport.Connection.WrapApiCallAsync[T](Func`1 action, Boolean isInternal) in /_/src/Playwright/Transport/Connection.cs:line 475 at Microsoft.Playwright.Core.BrowserType.LaunchAsync(BrowserTypeLaunchOptions options) in /_/src/Playwright/Core/BrowserType.cs:line 61 at PlaywrightTesterLibrary.PlaywrightTester.PlaywrightExecution() in /home/vsts/work/1/application/Projects/PlaywrightTester/PlaywrightTester.cs:line 27

Is it even possible to deploy playwright directly into an azure function?

Pieeer1 commented 2 years ago

Now we are at a point where we have installed the correct path chrome exe, and are now stuck at the error

spawn UNKNOWN =========================== logs =========================== <launching> C:\home\playwright-browsers\chromium-1005\chrome-win\chrome.exe --disable-field-trial-config --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync --allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --no-service-autorun --export-tagged-pdf --headless --hide-scrollbars --mute-audio --blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4 --no-sandbox --user-data-dir=C:\local\Temp\playwright_chromiumdev_profile-ReEYPG --remote-debugging-pipe --no-startup-window

Completely lost at this point as there has not been any other indication that this error should be happening

mxschmitt commented 2 years ago

Playwright requires a lot of dependencies to function properly, this includes the driver (shipped with nuget), the browsers (installed with the pwsh command), OS dependencies (they need to be installed manually or pwsh playwright install --with-deps).

Thats why we usually recommend using our official Docker image, which does all of this out of the box: https://playwright.dev/dotnet/docs/docker

Would that work for you? The newly launched Azure Container Apps might be a good fit for that.

Pieeer1 commented 2 years ago

Ok! Well we decided to pivot to a javascript verison of playwright which is functioning as intended in Azure! Thank you for the help.