Exemple #1
0
        public async Task ShouldFilterOutIgnoredDefaultArguments()
        {
            string[] defaultArgsWithoutUserDataDir = Playwright.GetDefaultArgs(TestConstants.GetDefaultBrowserOptions());

            var withUserDataDirOptions = TestConstants.GetDefaultBrowserOptions();

            withUserDataDirOptions.UserDataDir = "fake-profile";
            string[] defaultArgsWithUserDataDir = Playwright.GetDefaultArgs(withUserDataDirOptions);

            var launchOptions = TestConstants.GetDefaultBrowserOptions();

            launchOptions.UserDataDir        = "fake-profile";
            launchOptions.IgnoreDefaultArgs  = true;
            launchOptions.IgnoredDefaultArgs = defaultArgsWithUserDataDir.Where(x => !defaultArgsWithoutUserDataDir.Contains(x)).ToArray();

            using var browserApp = await Playwright.LaunchBrowserAppAsync(launchOptions);

            Assert.DoesNotContain("fake-profile", browserApp.Process.StartInfo.Arguments);
        }
Exemple #2
0
        public async Task ShouldWorkWithRequestInterception()
        {
            await using var browser = await BrowserType.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            var context = await browser.NewContextAsync(new BrowserContextOptions
            {
                IgnoreHTTPSErrors = true
            });

            var page = await context.NewPageAsync();

            await page.SetRequestInterceptionAsync(true);

            page.Request += async(sender, e) => await e.Request.ContinueAsync();

            var response = await page.GoToAsync(TestConstants.HttpsPrefix + "/empty.html");

            Assert.Equal(HttpStatusCode.OK, response.Status);
        }
Exemple #3
0
        public async Task ShouldPassFirefoxUserPreferences()
        {
            var options = TestConstants.GetDefaultBrowserOptions();

            options.FirefoxUserPrefs = new Dictionary <string, object>
            {
                ["network.proxy.type"]      = 1,
                ["network.proxy.http"]      = "127.0.0.1",
                ["network.proxy.http_port"] = 333,
            };

            await using var browser = await BrowserType.LaunchAsync(options);

            var page = await browser.NewPageAsync();

            var exception = await Assert.ThrowsAnyAsync <PlaywrightSharpException>(() => page.GoToAsync("http://example.com"));

            Assert.Contains("NS_ERROR_PROXY_CONNECTION_REFUSED", exception.Message);
        }
        public void InitializeTests()
        {
            if (_repairService == null)
            {
                var dbContextOptions = new DbContextOptionsBuilder <CarMechanicContext>().UseInMemoryDatabase("testDB")
                                       .Options;
                _carMechanicContext = new CarMechanicContext(dbContextOptions);
                _carMechanicContext.Database.EnsureCreated();

                var mappingConfig = new MapperConfiguration(conf => { conf.AddProfile <CarMechanicMapper>(); });
                _mapper        = mappingConfig.CreateMapper();
                _repairService = new RepairService(_mapper, _carMechanicContext);

                var testCar  = TestConstants.GetTestCar(typeName: "BMW", model: "E46 320i", engineSerial: "N90", licensePlate: "asd123");
                var testUser = TestConstants.GetTestUser(name: "Teszt Felhasznalo", email: "*****@*****.**", phoneNumber: "456789");
                initialTestRepair     = TestConstants.GetTestRepair(price: 1000000, paid: false, status: Status.WaitingForParts, works: "Turbo Charger change");
                testCar.User          = testUser;
                testUser.Car          = testCar;
                testCar.Repair        = initialTestRepair;
                initialTestRepair.Car = testCar;

                _carMechanicContext.Repairs.Add(initialTestRepair);
                _carMechanicContext.StatusEntities.Add(new StatusEntity()
                {
                    Status = Status.Finished
                });
                _carMechanicContext.StatusEntities.Add(new StatusEntity()
                {
                    Status = Status.AddedForService
                });
                _carMechanicContext.StatusEntities.Add(new StatusEntity()
                {
                    Status = Status.WaitingForParts
                });
                _carMechanicContext.StatusEntities.Add(new StatusEntity()
                {
                    Status = Status.WorkingOnCarNow
                });

                _carMechanicContext.SaveChanges();
            }
        }
Exemple #5
0
        public void PluginsFound()
        {
            bool pluginsLoadedEventFire = false;

            TestConstants.Prepare();

            // Listen to warnings:

            GlobalEvents.Hook <PluginsLoaded>((x) =>
            {
                Assert.AreNotEqual(x.Simulators, null);
                Assert.AreNotEqual(x.Widgets, null);
                Assert.AreNotEqual(x.Extensions, null);

                Assert.AreEqual(x.Simulators.ToList().Count, cfgSimulatorPlugins - cfgSimulatorPluginsInvalid);
                Assert.AreEqual(x.Widgets.ToList().Count, cfgWidgetPlugins - cfgWidgetPluginsInvalid);
                Assert.AreEqual(x.Extensions.ToList().Count, cfgExtensionPlugins - cfgExtensionPluginsInvalid);

                pluginsLoadedEventFire = true;
            }, true);

            // Manually count the no of plugins in the bin directory.
            var files   = Directory.GetFiles(TestConstants.SimulatorsBinFolder);
            var plugins = files.Where(x => Path.GetFileName(x).Contains("SimTelemetry.Plugins.") && x.ToLower().EndsWith(".dll"));

            using (var pluginHost = new Plugins())
            {
                pluginHost.PluginDirectory = TestConstants.SimulatorsBinFolder;

                pluginHost.Load();

                // Resolve the no. of plugins there are available:
                var iPluginsManualCount = plugins.ToList().Count;
                var iPluginsTelemetry   = pluginHost.Simulators.ToList().Count;

                Assert.AreNotEqual(0, iPluginsManualCount);
                Assert.AreEqual(iPluginsTelemetry, iPluginsManualCount);
            }

            Assert.AreEqual(pluginsLoadedEventFire, true);
            Assert.AreEqual(TestConstants.Warnings, cfgWidgetPluginsInvalid + cfgSimulatorPluginsInvalid + cfgExtensionPluginsInvalid);
        }
        public async Task ShouldRejectWaitForSelectorWhenBrowserCloses()
        {
            Server.SetRoute("/empty.html", context => Task.Delay(10000));

            await using var browserServer = await BrowserType.LaunchServerAsync(TestConstants.GetDefaultBrowserOptions());

            var remote = await BrowserType.ConnectAsync(new ConnectOptions { WSEndpoint = browserServer.WSEndpoint });

            var page = await remote.NewPageAsync();

            var watchdog = page.WaitForSelectorAsync("div", new WaitForSelectorOptions {
                State = WaitForState.Attached, Timeout = 60000
            });

            await page.WaitForSelectorAsync("body", new WaitForSelectorOptions { State = WaitForState.Attached });

            await remote.CloseAsync();

            await Assert.ThrowsAsync <TargetClosedException>(() => watchdog);
        }
        public async Task ShouldRejectNavigationWhenBrowserCloses()
        {
            Server.SetRoute("/one-style.css", context => Task.Delay(10000));

            await using var browserServer = await BrowserType.LaunchServerAsync(TestConstants.GetDefaultBrowserOptions());

            var remote = await BrowserType.ConnectAsync(new ConnectOptions { WSEndpoint = browserServer.WSEndpoint });

            var page = await remote.NewPageAsync();

            var navigationTask = page.GoToAsync(TestConstants.ServerUrl + "/one-style.html", new GoToOptions
            {
                Timeout = 60000
            });
            await Server.WaitForRequest("/one-style.css");

            await remote.CloseAsync();

            await Assert.ThrowsAsync <NavigationException>(() => navigationTask);
        }
Exemple #8
0
        public async Task UserDataDirArgument()
        {
            var launcher    = new Launcher(TestConstants.LoggerFactory);
            var userDataDir = Launcher.GetTemporaryDirectory();
            var options     = TestConstants.DefaultBrowserOptions();

            options.Args = options.Args.Concat(new[] { $"--user-data-dir=\"{userDataDir}\"" }).ToArray();

            using (var browser = await launcher.LaunchAsync(options))
            {
                // Open a page to make sure its functional.
                await browser.NewPageAsync();

                Assert.True(Directory.GetFiles(userDataDir).Length > 0);
                await browser.CloseAsync();

                Assert.True(Directory.GetFiles(userDataDir).Length > 0);
                await launcher.TryDeleteUserDataDir();
            }
        }
        public async Task ShouldThrowWhenUsedAfterIsConnectedReturnsFalse()
        {
            await using var browserServer = await BrowserType.LaunchServerAsync(TestConstants.GetDefaultBrowserOptions());

            var remote = await BrowserType.ConnectAsync(new ConnectOptions { WSEndpoint = browserServer.WSEndpoint });

            var page = await remote.NewPageAsync();

            var disconnectedTask = new TaskCompletionSource <bool>();

            remote.Disconnected += (sender, e) => disconnectedTask.TrySetResult(true);

            await Task.WhenAll(browserServer.CloseAsync(), disconnectedTask.Task);

            Assert.False(remote.IsConnected);

            var exception = await Assert.ThrowsAnyAsync <PlaywrightSharpException>(() => page.EvaluateAsync("1 + 1"));

            Assert.Contains("has been closed", exception.Message);
        }
Exemple #10
0
        public async Task ShouldFailGracefullyWhenTryingToWorkWithFilechoosersWithinMultipleConnections()
        {
            // 1. Launch a browser and connect to all pages.
            var originalBrowser = await Puppeteer.LaunchAsync(TestConstants.DefaultBrowserOptions());

            await originalBrowser.PagesAsync();

            // 2. Connect a remote browser and connect to first page.
            var remoteBrowser = await Puppeteer.ConnectAsync(new ConnectOptions
            {
                BrowserWSEndpoint = originalBrowser.WebSocketEndpoint
            });

            var page = (await remoteBrowser.PagesAsync())[0];
            // 3. Make sure |page.waitForFileChooser()| does not work with multiclient.
            var ex = await Assert.ThrowsAsync <PuppeteerException>(() => page.WaitForFileChooserAsync());

            Assert.Equal("File chooser handling does not work with multiple connections to the same page", ex.Message);
            await originalBrowser.CloseAsync();
        }
Exemple #11
0
        public async Task NetworkRedirectsShouldReportSecurityDetails()
        {
            var options = TestConstants.DefaultBrowserOptions();

            options.IgnoreHTTPSErrors = true;

            using (var browser = await Puppeteer.LaunchAsync(options, TestConstants.ChromiumRevision, TestConstants.LoggerFactory))
                using (var page = await browser.NewPageAsync())
                {
                    var responses = new List <Response>();
                    page.Response += (sender, e) => responses.Add(e.Response);

                    await page.GoToAsync(TestConstants.HttpsPrefix + "/plzredirect");

                    Assert.Equal(2, responses.Count);
                    Assert.Equal(HttpStatusCode.Redirect, responses[0].Status);
                    var securityDetails = responses[0].SecurityDetails;
                    Assert.Equal("TLS 1.2", securityDetails.Protocol);
                }
        }
        public async Task ShouldRejectNavigationWhenBrowserCloses()
        {
            Server.SetRoute("/one-style.css", context => Task.Delay(10000));

            using var browserApp = await Playwright.LaunchBrowserAppAsync(TestConstants.GetDefaultBrowserOptions());

            var remote = await Playwright.ConnectAsync(browserApp.ConnectOptions);

            var page = await remote.DefaultContext.NewPageAsync();

            var navigationTask = page.GoToAsync(TestConstants.ServerUrl + "/one-style.html", new GoToOptions
            {
                Timeout = 60000
            });
            await Server.WaitForRequest("/one-style.css");

            await remote.DisconnectAsync();

            await Assert.ThrowsAsync <NavigationException>(() => navigationTask);
        }
        public async Task ShouldRejectWaitForSelectorWhenBrowserCloses()
        {
            Server.SetRoute("/empty.html", context => Task.Delay(10000));

            using var browserApp = await Playwright.LaunchBrowserAppAsync(TestConstants.GetDefaultBrowserOptions());

            var remote = await Playwright.ConnectAsync(browserApp.ConnectOptions);

            var page = await remote.DefaultContext.NewPageAsync();

            var watchdog = page.WaitForSelectorAsync("div", new WaitForSelectorOptions {
                Timeout = 60000
            });

            await page.WaitForSelectorAsync("body");

            await remote.DisconnectAsync();

            await Assert.ThrowsAsync <TargetClosedException>(() => watchdog);
        }
        public async Task ShouldFireClosedEventDuringKill()
        {
            var order = new List <string>();

            await using var browserServer = await BrowserType.LaunchServerAsync(TestConstants.GetDefaultBrowserOptions());

            var closedTcs = new TaskCompletionSource <bool>();

            browserServer.Closed += (server, e) =>
            {
                order.Add("closed");
                closedTcs.TrySetResult(true);
            };

            await Task.WhenAll(
                browserServer.KillAsync().ContinueWith(t => order.Add("killed")),
                closedTcs.Task);

            Assert.Equal(new[] { "closed", "killed" }, order.ToArray());
        }
        /// <inheritsdoc/>
        public async Task InitializeAsync()
        {
            Server.SetRoute("/download", context =>
            {
                context.Response.Headers["Content-Type"]        = "application/octet-stream";
                context.Response.Headers["Content-Disposition"] = "attachment; filename=file.txt";
                return(context.Response.WriteAsync("Hello world"));
            });

            _downloadsPath = new TempDirectory();
            _userDataDir   = new TempDirectory();

            var options = TestConstants.GetDefaultBrowserOptions().ToPersistentOptions();

            options.DownloadsPath   = _downloadsPath.Path;
            options.AcceptDownloads = true;
            _context = await Playwright[TestConstants.Product].LaunchPersistentContextAsync(_userDataDir.Path, options);
            _page    = _context.Pages[0];
            await _page.SetContentAsync($"<a href=\"{TestConstants.ServerUrl}/download\">download</a>");
        }
    private static int Main()
    {
#if !MULTIMODULE_BUILD
        TestLdstr.Run();
        TestException.Run();
        TestThreadStaticNotInitialized.Run();
        TestUntouchedThreadStaticInitialized.Run();
        TestPointers.Run();
        TestConstants.Run();
        TestArray.Run();
        TestArrayOutOfRange.Run();
        TestMdArray.Run();
        TestSimpleObject.Run();
        TestFinalizableObject.Run();
        TestStoreIntoOtherStatic.Run();
        TestCctorCycle.Run();
        TestReferenceTypeAllocation.Run();
        TestReferenceTypeWithGCPointerAllocation.Run();
        TestReferenceTypeWithReadonlyNullGCPointerAllocation.Run();
        TestRelationalOperators.Run();
        TestTryFinally.Run();
        TestTryCatch.Run();
        TestBadClass.Run();
        TestRefs.Run();
        TestDelegate.Run();
        TestInitFromOtherClass.Run();
        TestInitFromOtherClassDouble.Run();
        TestDelegateToOtherClass.Run();
        TestLotsOfBackwardsBranches.Run();
        TestDrawCircle.Run();
        TestValueTypeDup.Run();
        TestFunctionPointers.Run();
        TestGCInteraction.Run();
        TestDuplicatedFields.Run();
        TestInstanceDelegate.Run();
#else
        Console.WriteLine("Preinitialization is disabled in multimodule builds for now. Skipping test.");
#endif

        return(100);
    }
Exemple #17
0
        public async Task HeadlessShouldBeAbleToReadCookiesWrittenByHeadful()
        {
            // "Too" complex for our skip attribute
            if ((TestConstants.IsWindows && TestConstants.IsChromium) || TestConstants.IsFirefox)
            {
                return;
            }
            using var userDataDir = new TempDirectory();

            // Write a cookie in headful chrome
            var headfulOptions = TestConstants.GetHeadfulOptions();

            headfulOptions.UserDataDir = userDataDir.Path;

            var headfulBrowser = await Playwright.LaunchAsync(headfulOptions);

            var headfulPage = await headfulBrowser.DefaultContext.NewPageAsync();

            await headfulPage.GoToAsync(TestConstants.EmptyPage);

            await headfulPage.EvaluateAsync("() => document.cookie = 'foo=true; expires=Fri, 31 Dec 9999 23:59:59 GMT'");

            await headfulBrowser.CloseAsync();

            // Read the cookie from headless chrome
            var headlessOptions = TestConstants.GetDefaultBrowserOptions();

            headlessOptions.UserDataDir = userDataDir.Path;

            var headlessBrowser = await Playwright.LaunchAsync(headlessOptions);

            var headlessPage = await headlessBrowser.DefaultContext.NewPageAsync();

            await headlessPage.GoToAsync(TestConstants.EmptyPage);

            string cookie = await headlessPage.EvaluateAsync <string>("() => document.cookie");

            await headlessBrowser.CloseAsync();

            Assert.Equal("foo=true", cookie);
        }
        public async Task ShouldEmittedWhenBrowserGetsClosedDisconnectedOrUnderlyingWebsocketGetsClosed()
        {
            var originalBrowser = await Puppeteer.LaunchAsync(TestConstants.DefaultBrowserOptions(), TestConstants.LoggerFactory);

            var connectOptions = new ConnectOptions {
                BrowserWSEndpoint = originalBrowser.WebSocketEndpoint
            };
            var remoteBrowser1 = await Puppeteer.ConnectAsync(connectOptions, TestConstants.LoggerFactory);

            var remoteBrowser2 = await Puppeteer.ConnectAsync(connectOptions, TestConstants.LoggerFactory);

            var disconnectedOriginal = 0;
            var disconnectedRemote1  = 0;
            var disconnectedRemote2  = 0;

            originalBrowser.Disconnected += (sender, e) => ++ disconnectedOriginal;
            remoteBrowser1.Disconnected  += (sender, e) => ++ disconnectedRemote1;
            remoteBrowser2.Disconnected  += (sender, e) => ++ disconnectedRemote2;

            var remoteBrowser2Disconnected = WaitForBrowserDisconnect(remoteBrowser2);

            remoteBrowser2.Disconnect();
            await remoteBrowser2Disconnected;

            Assert.Equal(0, disconnectedOriginal);
            Assert.Equal(0, disconnectedRemote1);
            Assert.Equal(1, disconnectedRemote2);

            var remoteBrowser1Disconnected  = WaitForBrowserDisconnect(remoteBrowser1);
            var originalBrowserDisconnected = WaitForBrowserDisconnect(originalBrowser);

            await Task.WhenAll(
                originalBrowser.CloseAsync(),
                remoteBrowser1Disconnected,
                originalBrowserDisconnected
                );

            Assert.Equal(1, disconnectedOriginal);
            Assert.Equal(1, disconnectedRemote1);
            Assert.Equal(1, disconnectedRemote2);
        }
Exemple #19
0
        public void CanGenerateSas_GetQueueClient()
        {
            // Arrange
            var    constants               = TestConstants.Create(this);
            var    blobEndpoint            = new Uri("https://127.0.0.1/" + constants.Sas.Account);
            var    blobSecondaryEndpoint   = new Uri("https://127.0.0.1/" + constants.Sas.Account + "-secondary");
            var    storageConnectionString = new StorageConnectionString(constants.Sas.SharedKeyCredential, queueStorageUri: (blobEndpoint, blobSecondaryEndpoint));
            string connectionString        = storageConnectionString.ToString(true);

            // Act - QueueServiceClient(string connectionString)
            QueueServiceClient serviceClient = InstrumentClient(new QueueServiceClient(
                                                                    connectionString));
            QueueClient queueClient = serviceClient.GetQueueClient(GetNewQueueName());

            Assert.IsTrue(queueClient.CanGenerateSasUri);

            // Act - QueueServiceClient(string connectionString, string blobContainerName, BlobClientOptions options)
            QueueServiceClient serviceClient2 = InstrumentClient(new QueueServiceClient(
                                                                     connectionString,
                                                                     GetOptions()));
            QueueClient queueClient2 = serviceClient2.GetQueueClient(GetNewQueueName());

            Assert.IsTrue(queueClient2.CanGenerateSasUri);

            // Act - QueueServiceClient(Uri blobContainerUri, BlobClientOptions options = default)
            QueueServiceClient serviceClient3 = InstrumentClient(new QueueServiceClient(
                                                                     blobEndpoint,
                                                                     GetOptions()));
            QueueClient queueClient3 = serviceClient3.GetQueueClient(GetNewQueueName());

            Assert.IsFalse(queueClient3.CanGenerateSasUri);

            // Act - QueueServiceClient(Uri blobContainerUri, StorageSharedKeyCredential credential, BlobClientOptions options = default)
            QueueServiceClient serviceClient4 = InstrumentClient(new QueueServiceClient(
                                                                     blobEndpoint,
                                                                     constants.Sas.SharedKeyCredential,
                                                                     GetOptions()));
            QueueClient queueClient4 = serviceClient4.GetQueueClient(GetNewQueueName());

            Assert.IsTrue(queueClient4.CanGenerateSasUri);
        }
Exemple #20
0
        public void GenerateAccountSas_WrongService_Service()
        {
            TestConstants           constants     = TestConstants.Create(this);
            Uri                     serviceUri    = new Uri($"https://{constants.Sas.Account}.queue.core.windows.net");
            AccountSasPermissions   permissions   = AccountSasPermissions.Read | AccountSasPermissions.Write;
            DateTimeOffset          expiresOn     = Recording.UtcNow.AddHours(+1);
            AccountSasServices      services      = AccountSasServices.Blobs; // Wrong Service
            AccountSasResourceTypes resourceTypes = AccountSasResourceTypes.All;
            QueueServiceClient      serviceClient = InstrumentClient(
                new QueueServiceClient(
                    serviceUri,
                    constants.Sas.SharedKeyCredential,
                    GetOptions()));

            AccountSasBuilder sasBuilder = new AccountSasBuilder(permissions, expiresOn, services, resourceTypes);

            // Act
            TestHelper.AssertExpectedException(
                () => serviceClient.GenerateAccountSasUri(sasBuilder),
                new InvalidOperationException("SAS Uri cannot be generated. builder.Services does specify Queues. builder.Services must either specify Queues or specify all Services are accessible in the value."));
        }
        public async Task ShouldReturnBackgroundPages()
        {
            using var userDataDir = new TempDirectory();
            string extensionPath = TestUtils.GetWebServerFile("simple-extension");
            var    options       = TestConstants.GetDefaultBrowserOptions();

            options.Headless = false;
            options.Args     = new[] {
                $"--disable-extensions-except={extensionPath}",
                $"--load-extension={extensionPath}",
            };

            await using var context = await BrowserType.LaunchPersistentContextAsync(userDataDir.Path, options);

            var backgroundPage = ((IChromiumBrowserContext)context).BackgroundPages.Any()
                ? ((IChromiumBrowserContext)context).BackgroundPages.First()
                : (await context.WaitForEventAsync(ContextEvent.BackgroundPage)).Page;

            Assert.NotNull(backgroundPage);
            Assert.Contains(backgroundPage, ((IChromiumBrowserContext)context).BackgroundPages);
            Assert.DoesNotContain(backgroundPage, context.Pages);
        }
        public async Task ShouldRejectWaitForSelectorWhenBrowserCloses()
        {
            Server.SetRoute("/empty.html", _ => Task.Delay(10000));

            await using (var browser = await Puppeteer.LaunchAsync(TestConstants.DefaultBrowserOptions()))
            {
                var remote = await Puppeteer.ConnectAsync(new ConnectOptions
                {
                    BrowserWSEndpoint = browser.WebSocketEndpoint
                });

                var page = await remote.NewPageAsync();

                var watchdog = page.WaitForSelectorAsync("div", new WaitForSelectorOptions {
                    Timeout = 60000
                });
                remote.Disconnect();
                var exception = await Assert.ThrowsAsync <TargetClosedException>(() => watchdog);

                Assert.Equal("Connection disposed", exception.CloseReason);
            }
        }
        public void ToSasQueryParameters_IdentifierTest()
        {
            // Arrange
            TestConstants  constants     = TestConstants.Create(this);
            string         containerName = GetNewContainerName();
            string         resource      = "c";
            BlobSasBuilder sasBuilder    = new BlobSasBuilder()
            {
                Identifier        = constants.Sas.Identifier,
                BlobContainerName = containerName,
                Protocol          = SasProtocol.Https,
                Resource          = resource,
            };

            // Act
            BlobSasQueryParameters sasQueryParameters = sasBuilder.ToSasQueryParameters(constants.Sas.SharedKeyCredential);

            // Assert
            Assert.AreEqual(constants.Sas.Identifier, sasQueryParameters.Identifier);
            Assert.AreEqual(SasProtocol.Https, sasQueryParameters.Protocol);
            Assert.AreEqual(resource, sasQueryParameters.Resource);
        }
Exemple #24
0
        public async Task CustomInstanceDiscoveryMetadataUri_Async()
        {
            using (var harness = CreateTestHarness())
            {
                var customMetadataUri = new Uri("https://custom.instance.discovery.uri");
                var customAuthrority  = "https://my.custom.authority/common/";

                harness.HttpManager.AddInstanceDiscoveryMockHandler(
                    customAuthrority,
                    customMetadataUri,
                    TestConstants.DiscoveryJsonResponse.Replace("login.microsoftonline.com", "my.custom.authority"));

                PublicClientApplication app = PublicClientApplicationBuilder
                                              .Create(TestConstants.ClientId)
                                              .WithAuthority(customAuthrority, false)
                                              .WithInstanceDiscoveryMetadata(customMetadataUri)
                                              .WithHttpManager(harness.HttpManager)
                                              .BuildConcrete();

                MsalMockHelpers.ConfigureMockWebUI(
                    app.ServiceBundle.PlatformProxy,
                    AuthorizationResult.FromUri(app.AppConfig.RedirectUri + "?code=some-code"));

                // the rest of the communication with AAD happens on the preferred_network alias, not on login.windows.net
                harness.HttpManager.AddMockHandlerForTenantEndpointDiscovery(customAuthrority);
                harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(customAuthrority);

                AuthenticationResult result = await app
                                              .AcquireTokenInteractive(TestConstants.s_scope)
                                              .ExecuteAsync(CancellationToken.None)
                                              .ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.IsNotNull(result.Account);
                Assert.AreEqual(TestConstants.UniqueId, result.UniqueId);
                Assert.AreEqual(TestConstants.CreateUserIdentifier(), result.Account.HomeAccountId.Identifier);
                Assert.AreEqual(TestConstants.DisplayableId, result.Account.Username);
            }
        }
        public async Task ShouldWork()
        {
            var browser = await Playwright.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            var events = new List <string>();

            browser.TargetCreated   += (sender, e) => events.Add("CREATED: " + e.Target.Url);
            browser.TargetChanged   += (sender, e) => events.Add("CHANGED: " + e.Target.Url);
            browser.TargetDestroyed += (sender, e) => events.Add("DESTROYED: " + e.Target.Url);
            var page = await browser.DefaultContext.NewPageAsync();

            await page.GoToAsync(TestConstants.EmptyPage);

            await page.CloseAsync();

            Assert.Equal(new[] {
                $"CREATED: {TestConstants.AboutBlank}",
                $"CHANGED: {TestConstants.EmptyPage}",
                $"DESTROYED: {TestConstants.EmptyPage}"
            }, events);
            await browser.CloseAsync();
        }
Exemple #26
0
        public void SimulatorBasicTests()
        {
            TestConstants.Prepare();

            var trackScanCount = 0;
            var modScanCount   = 0;

            // Events fired from test object:
            GlobalEvents.Hook <PluginTestSimulatorModScanner>((x) => { modScanCount++; }, true);
            GlobalEvents.Hook <PluginTestSimulatorTrackScanner>((x) => { trackScanCount++; }, true);

            using (var pluginHost = new Plugins())
            {
                pluginHost.PluginDirectory = TestConstants.SimulatorsBinFolder;

                pluginHost.Load();

                Assert.Greater(pluginHost.Simulators.Count, 0);

                var testSim = pluginHost.Simulators[0];

                var testSimulator = testSim.GetSimulator();
                Assert.AreEqual(0, trackScanCount);
                Assert.AreEqual(0, modScanCount);

                Assert.AreEqual("rFactor", testSimulator.Name);
                Assert.AreEqual("rfactor", testSimulator.ProcessName);
                Assert.AreEqual("1.255", testSimulator.Version);

                var tracks = testSimulator.Tracks;
                var mods   = testSimulator.Mods;

                Assert.AreEqual(1, modScanCount);
                Assert.AreEqual(1, trackScanCount);

                Assert.AreEqual(1, tracks.Count(x => x.ID != string.Empty));
                Assert.AreEqual(1, mods.Count(x => x.Name != ""));
            }
        }
Exemple #27
0
        public async Task WindowOpenShouldUseParentTabContext()
        {
            await using var browser = await Playwright.LaunchAsync(TestConstants.GetDefaultBrowserOptions());

            var context = await browser.NewContextAsync();

            var page = await context.NewPageAsync();

            await page.GoToAsync(TestConstants.EmptyPage);

            var popupTargetCompletion = new TaskCompletionSource <IPage>();

            page.Popup += (sender, e) => popupTargetCompletion.SetResult(e.Page);

            var(popupTarget, _) = await TaskUtils.WhenAll(
                popupTargetCompletion.Task,
                page.EvaluateAsync("url => window.open(url)", TestConstants.EmptyPage)
                );

            Assert.Same(context, popupTarget.BrowserContext);
            await context.CloseAsync();
        }
Exemple #28
0
        public async Task AcquireTokenInterative_WithValidCustomInstanceMetadata_Async()
        {
            string instanceMetadataJson = File.ReadAllText(
                ResourceHelper.GetTestResourceRelativePath("CustomInstanceMetadata.json"));

            using (var harness = CreateTestHarness())
            {
                // No instance discovery is made - it is important to not have this mock handler added
                // harness.HttpManager.AddInstanceDiscoveryMockHandler();

                PublicClientApplication app = PublicClientApplicationBuilder
                                              .Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri("https://login.windows.net/common/"), false)
                                              .WithInstanceDiscoveryMetadata(instanceMetadataJson)
                                              .WithHttpManager(harness.HttpManager)
                                              .WithTelemetry(new TraceTelemetryConfig())
                                              .BuildConcrete();

                MsalMockHelpers.ConfigureMockWebUI(
                    app.ServiceBundle.PlatformProxy,
                    AuthorizationResult.FromUri(app.AppConfig.RedirectUri + "?code=some-code"));

                // the rest of the communication with AAD happens on the preferred_network alias, not on login.windows.net
                harness.HttpManager.AddMockHandlerForTenantEndpointDiscovery(TestConstants.AuthorityCommonTenant);
                harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(TestConstants.AuthorityCommonTenant);

                AuthenticationResult result = await app
                                              .AcquireTokenInteractive(TestConstants.s_scope)
                                              .ExecuteAsync(CancellationToken.None)
                                              .ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.IsNotNull(result.Account);
                Assert.AreEqual(TestConstants.UniqueId, result.UniqueId);
                Assert.AreEqual(TestConstants.CreateUserIdentifier(), result.Account.HomeAccountId.Identifier);
                Assert.AreEqual(TestConstants.DisplayableId, result.Account.Username);
            }
        }
        public async Task ShouldAllowSyncPageMethod()
        {
            var options = TestConstants.DefaultBrowserOptions();

            if (!options.EnqueueAsyncMessages)
            {
                return;
            }

            await using (var browser = await Puppeteer.LaunchAsync(options))
            {
                // Async low-level use
                await using var page = await browser.NewPageAsync().ConfigureAwait(false);

                await page.GoToAsync("http://ipecho.net/plain", WaitUntilNavigation.DOMContentLoaded).ConfigureAwait(false);

                await page.SetContentAsync("<html><body>REPLACED</body></html>").ConfigureAwait(false);

                // Deep inside an existing mostly sync app...
                var content = page.GetContentAsync().ConfigureAwait(false).GetAwaiter().GetResult();
                Assert.Contains("REPLACE", content);
            }
        }
        public void TestCreateCar()
        {
            //Arrange
            var testCar    = TestConstants.GetTestCar();
            var testUser   = TestConstants.GetTestUser();
            var testRepair = TestConstants.GetTestRepair();

            testCar.User   = testUser;
            testUser.Car   = testCar;
            testCar.Repair = testRepair;
            testRepair.Car = testCar;
            var carDto = _mapper.Map <CarDto>(testCar);
            //Act
            var carDtoResult   = _carService.Save(carDto);
            var carDtoDbResult =
                _carMechanicContext.Cars.SingleOrDefault(x => x.LicensePlate == carDtoResult.LicensePlate);

            //Assert
            Assert.IsNotNull(carDtoResult);
            Assert.IsNotNull(carDtoDbResult);
            Assert.AreEqual(carDtoDbResult.LicensePlate, carDtoResult.LicensePlate);
            Assert.AreEqual(carDtoDbResult.Vintage, carDtoResult.Vintage);
        }