示例#1
0
        public void ShouldRenderWeatherForecast()
        {
            host.AddMockHttp();
            var component = host.AddComponent <FetchData>();

            Assert.Equal("Weather forecast", component.Find("h1").InnerText);
        }
            public void UserComponent_CheckInitialState()
            {
                var requestMoq = host.AddMockHttp().Capture("/api/users/");
                var component  = host.AddComponent <Users>();

                // Initial component loading state
                component.Find("#userCount").InnerText.Should().Be("0");
                component.GetMarkup().Should().Contain("Loading...");
            }
示例#3
0
        public void ShouldRenderLoading()
        {
            var req = host.AddMockHttp().Capture("");

            var component = host.AddComponent <FetchData>();

            // Assert p
            Assert.Equal("Loading...", component.Find("p em").InnerText);
        }
示例#4
0
        public static void CreateTestHost(string userName, IEnumerable <Claim> claims, string url, TestServer sut, ITestOutputHelper testOutputHelper, out TestHost host, out MockHttpMessageHandler mockHttp)
        {
            var navigationInterceptionMock = new Mock <INavigationInterception>();
            var jsRuntimeMock = new Mock <IJSRuntime>();

            host = new TestHost();
            var httpMock = host.AddMockHttp();

            mockHttp = httpMock;
            var localizerMock = new Mock <ISharedStringLocalizerAsync>();

            localizerMock.Setup(m => m[It.IsAny <string>()]).Returns((string key) => new LocalizedString(key, key));
            localizerMock.Setup(m => m[It.IsAny <string>(), It.IsAny <object[]>()]).Returns((string key, object[] p) => new LocalizedString(key, string.Format(key, p)));

            host.ConfigureServices(services =>
            {
                var httpClient       = sut.CreateClient();
                var appConfiguration = CreateApplicationConfiguration(httpClient);

                WebAssemblyHostBuilderExtensions.ConfigureServices(services, appConfiguration, appConfiguration.Get <Settings>(), httpClient.BaseAddress.ToString());

                sut.Services.GetRequiredService <TestUserService>()
                .SetTestUser(true, claims.Select(c => new Claim(c.Type, c.Value)));

                services
                .AddLogging(configure =>
                {
                    configure.AddProvider(new TestLoggerProvider(testOutputHelper));
                })
                .AddTransient(p => sut.CreateHandler())
                .AddIdentityServer4AdminHttpStores(p =>
                {
                    var client = new HttpClient(new BaseAddressAuthorizationMessageHandler(p.GetRequiredService <IAccessTokenProvider>(),
                                                                                           p.GetRequiredService <NavigationManager>())
                    {
                        InnerHandler = sut.CreateHandler()
                    })
                    {
                        BaseAddress = new Uri(httpClient.BaseAddress, "api")
                    };
                    return(Task.FromResult(client));
                })
                .AddSingleton(p => new TestNavigationManager(uri: url))
                .AddSingleton <NavigationManager>(p => p.GetRequiredService <TestNavigationManager>())
                .AddSingleton(p => navigationInterceptionMock.Object)
                .AddSingleton(p => jsRuntimeMock.Object)
                .AddSingleton <Settings>()
                .AddSingleton(localizerMock.Object)
                .AddSingleton <SignOutSessionStateManager, FakeSignOutSessionStateManager>()
                .AddSingleton <IAccessTokenProviderAccessor, AccessTokenProviderAccessor>()
                .AddSingleton <IAccessTokenProvider>(p => p.GetRequiredService <FakeAuthenticationStateProvider>())
                .AddSingleton <AuthenticationStateProvider>(p => p.GetRequiredService <FakeAuthenticationStateProvider>())
                .AddSingleton(p => new FakeAuthenticationStateProvider(p.GetRequiredService <NavigationManager>(),
                                                                       userName,
                                                                       claims));
            });
        }
示例#5
0
        public void FetchDataWorks()
        {
            // Initially shows loading state
            var req       = host.AddMockHttp().Capture("/sample-data/weather.json");
            var component = host.AddComponent <FetchData>();

            Assert.Contains("Loading...", component.GetMarkup());

            // When the server responds, we display the data
            host.WaitForNextRender(() => req.SetResult(new[]
            {
                new FetchData.WeatherForecast {
                    Summary = "First"
                },
                new FetchData.WeatherForecast {
                    Summary = "Second"
                },
            }));
            Assert.DoesNotContain("Loading...", component.GetMarkup());
            Assert.Collection(component.FindAll("tbody tr"),
                              row => Assert.Contains("First", row.OuterHtml),
                              row => Assert.Contains("Second", row.OuterHtml));
        }
示例#6
0
        public static void CreateTestHost(string userName, IEnumerable <Claim> claims, string url, TestServer sut, ITestOutputHelper testOutputHelper, out TestHost host, out MockHttpMessageHandler mockHttp)
        {
            var navigationInterceptionMock = new Mock <INavigationInterception>();
            var jsRuntimeMock = new Mock <IJSRuntime>();

            host = new TestHost();
            var httpMock = host.AddMockHttp();

            mockHttp = httpMock;
            host.ConfigureServices(services =>
            {
                blazorApp.Program.ConfigureServices(services);
                var httpClient = sut.CreateClient();

                sut.Services.GetRequiredService <TestUserService>()
                .SetTestUser(true, claims.Select(c => new Claim(c.Type, c.Value)));

                services
                .AddLogging(configure =>
                {
                    configure.AddProvider(new TestLoggerProvider(testOutputHelper));
                })
                .AddIdentityServer4AdminHttpStores(p =>
                {
                    var client         = new HttpClient(new blazorApp.OidcDelegationHandler(p.GetRequiredService <IAccessTokenProvider>(), sut.CreateHandler()));
                    client.BaseAddress = new Uri(httpClient.BaseAddress, "api");
                    return(Task.FromResult(client));
                })
                .AddSingleton(p => new TestNavigationManager(uri: url))
                .AddSingleton <NavigationManager>(p => p.GetRequiredService <TestNavigationManager>())
                .AddSingleton(p => navigationInterceptionMock.Object)
                .AddSingleton(p => jsRuntimeMock.Object)
                .AddSingleton <Settings>()
                .AddSingleton <SignOutSessionStateManager, FakeSignOutSessionStateManager>()
                .AddSingleton <AuthenticationStateProvider>(p => new FakeAuthenticationStateProvider(userName, claims));
            });
        }
示例#7
0
        private static void NavigateToLoginPage(TestLoggerProvider testLoggerProvider, TestServer server, IServiceScope scope, ConcurrentDictionary <object, object> sessionStore, out HttpClient httpClient, out string redirectUri)
        {
            SeedData.SeedUsers(scope);
            SeedData.SeedConfiguration(scope);

            using var host = new TestHost();
            var jsRuntimeMock = new Mock <IJSRuntime>();
            var navigationInterceptionMock = new Mock <INavigationInterception>();
            var navigationManager          = new TestNavigationManager(uri: "http://exemple.com");

            var client = server.CreateClient();

            httpClient = client;

            host.ConfigureServices(services =>
            {
                blazorApp.Program.ConfigureServices(services);
                services
                .AddLogging(configure =>
                {
                    configure.AddProvider(testLoggerProvider);
                })
                .AddIdentityServer4AdminHttpStores(p => Task.FromResult(client))
                .AddSingleton(p => navigationManager)
                .AddSingleton <NavigationManager>(p => p.GetRequiredService <TestNavigationManager>())
                .AddSingleton(p => jsRuntimeMock.Object)
                .AddSingleton(p => navigationInterceptionMock.Object);
            });

            var httpMock = host.AddMockHttp();

            httpMock.Fallback.Respond(httpClient);
            jsRuntimeMock.Setup(m => m.InvokeAsync <object>("sessionStorage.setItem", It.IsAny <object[]>()))
            .Callback <string, object[]>((_, array) => sessionStore.AddOrUpdate(array[0], array[1], (k, v) => array[1]))
            .ReturnsAsync(null);

            string navigatedUri = null;
            var    waitHandle   = new ManualResetEvent(false);

            navigationManager.OnNavigateToCore = (uri, f) =>
            {
                navigatedUri = uri;
                waitHandle.Set();
            };

            var settingsRequest = httpMock.Capture("/settings.json");
            var component       = host.AddComponent <blazorApp.App>();

            var markup = component.GetMarkup();

            Assert.Contains("Authentication in progress", markup);

            host.WaitForNextRender(() =>
            {
                settingsRequest.SetResult(new
                {
                    ClientId = "theidserveradmin",
                    Scope    = "openid profile theidserveradminapi"
                });
            });

            host.WaitForContains(component, "You are redirecting to the login page. please wait");

            WaitForHttpResponse(waitHandle);

            redirectUri = navigatedUri;
        }
示例#8
0
        private static void OpenLogggedPage(TestLoggerProvider testLoggerProvider, HttpClient httpClient, ConcurrentDictionary <object, object> sessionStore, string location)
        {
            using var host = new TestHost();
            var jsRuntimeMock = new Mock <IJSRuntime>();
            var navigationInterceptionMock = new Mock <INavigationInterception>();
            var navigationManager          = new TestNavigationManager(uri: location);

            host.ConfigureServices(services =>
            {
                blazorApp.Program.ConfigureServices(services);
                services
                .AddLogging(configure =>
                {
                    configure.AddProvider(testLoggerProvider);
                })
                .AddIdentityServer4AdminHttpStores(p => Task.FromResult(httpClient))
                .AddSingleton(p => navigationManager)
                .AddSingleton <NavigationManager>(p => p.GetRequiredService <TestNavigationManager>())
                .AddSingleton(p => jsRuntimeMock.Object)
                .AddSingleton(p => navigationInterceptionMock.Object);
            });

            var httpMock = host.AddMockHttp();

            httpMock.Fallback.Respond(httpClient);

            foreach (var key in sessionStore.Keys)
            {
                jsRuntimeMock.Setup(m => m.InvokeAsync <string>("sessionStorage.getItem", It.Is <object[]>(p => p[0].ToString() == key.ToString())))
                .ReturnsAsync <string, object[], IJSRuntime, string>((_, array) =>
                {
                    if (sessionStore.TryGetValue(array[0], out object value))
                    {
                        return((string)value);
                    }
                    throw new InvalidOperationException($"sessionStore doesn't contain key {key}");
                });
            }

            string navigatedUri = null;
            var    waitHandle   = new ManualResetEvent(false);

            navigationManager.OnNavigateToCore = (uri, f) =>
            {
                navigatedUri = uri;
                waitHandle.Set();
            };

            var settingsRequest = httpMock.Capture("/settings.json");
            var component       = host.AddComponent <blazorApp.App>();

            var markup = component.GetMarkup();

            Assert.Contains("Authentication in progress", markup);

            host.WaitForNextRender(() =>
            {
                settingsRequest.SetResult(new
                {
                    ClientId = "theidserveradmin",
                    Scope    = "openid profile theidserveradminapi"
                });
            });


            WaitForHttpResponse(waitHandle);

            Assert.Equal("http://exemple.com", navigatedUri);
        }