Exemplo n.º 1
0
        public void ShouldNavigateToSearchOnSubmit()
        {
            // Arrange
            var expectedSearch = "EXPECTED SEARCH";

            using var ctx = new TestContext();
            ctx.AddTestAuthorization();
            var mockSignOutManager    = ctx.Services.AddSignOutManager();
            var mockNavigationManager = ctx.Services.AddMockNavigationManager("/");
            var mockHttpClient        = ctx.Services.AddMockHttpClient();

            mockHttpClient.When($"/api/content/count").RespondJson(0);
            mockHttpClient.When($"/api/tags/count").RespondJson(0);
            mockHttpClient.When($"/api/authors/count").RespondJson(0);
            mockHttpClient.When($"/api/brands/count").RespondJson(0);

            // Act
            var cut         = ctx.RenderComponent <Client.Pages.Index>();
            var searchForm  = cut.Find("form");
            var searchInput = cut.Find("input[type=\"search\"]");

            searchInput.Input(expectedSearch);
            searchForm.Submit();

            // Assert
            Assert.Equal(
                $"/search?Search={System.Uri.EscapeDataString(expectedSearch)}",
                mockNavigationManager.NavigateToLocation);
        }
Exemplo n.º 2
0
        public void ShouldDisplayContentReaderWithTitleAndText()
        {
            // Arrange
            var expectedContentId = 0xbeef;
            var expectedPath      = $"/reader/{expectedContentId}";
            var expectedText      = "Expected Text";

            using var ctx = new TestContext();
            ctx.AddTestAuthorization();
            var mockSignOutManager    = ctx.Services.AddSignOutManager();
            var mockNavigationManager = ctx.Services.AddMockNavigationManager(expectedPath);
            var mockHttpClient        = ctx.Services.AddMockHttpClient();

            mockNavigationManager.SetUri($"http://localhost:5000{expectedPath}");
            mockHttpClient.When($"/api/content/text/{expectedContentId}").RespondText(expectedText);
            mockHttpClient.When($"/api/content/{expectedContentId}").RespondJson(
                new Content(0, "BRAND", "TITLE", "DESC", "AUTHOR", new string[0]));

            ctx.JSInterop.SetupVoid("interopFunctions.observeHiddenRefResized", IsElementReference).SetVoidResult();
            ctx.JSInterop.SetupVoid("interopFunctions.observeReaderRefResized", IsElementReference).SetVoidResult();
            ctx.JSInterop.SetupVoid("interopFunctions.unObserveHiddenRefResized", IsElementReference).SetVoidResult();
            ctx.JSInterop.SetupVoid("interopFunctions.unObserveReaderRefResized", IsElementReference).SetVoidResult();
            ctx.JSInterop.SetupVoid("interopFunctions.initializeBody").SetVoidResult();
            ctx.JSInterop.SetupVoid("interopFunctions.disposeBody").SetVoidResult();
            ctx.JSInterop.SetupVoid("interopFunctions.listenToSwipes").SetVoidResult();
            ctx.JSInterop.SetupVoid("interopFunctions.unlistenToSwipes").SetVoidResult();

            // Act
            using var cut = ctx.RenderComponent <Client.Pages.Reader>(parameters => parameters.Add(p => p.ContentId, expectedContentId));
            cut.WaitForState(() => !string.IsNullOrWhiteSpace(cut.Find(".reader").TextContent), timeout: TimeSpan.FromMilliseconds(500));

            // Assert
            Assert.Contains("TITLE", cut.Find(".reader").TextContent);
            Assert.Contains("Expected Text", cut.Find(".reader").TextContent);
        }
Exemplo n.º 3
0
        public void ShouldDisplaySearchResults()
        {
            // Arrange
            var expectedSearch  = "EXPECTED SEARCH";
            var expectedPath    = $"/search?search={Uri.EscapeDataString(expectedSearch)}";
            var expectedResults = new List <Content> {
                new Content(0, "BRAND", "TITLE", "DESC", "AUTHOR", new string[0]),
                new Content(1, "BRAND", "TITLE", "DESC", "AUTHOR", new string[0]),
                new Content(2, "BRAND", "TITLE", "DESC", "AUTHOR", new string[0]),
            };

            using var ctx = new TestContext();
            ctx.AddTestAuthorization();
            var mockSignOutManager    = ctx.Services.AddSignOutManager();
            var mockNavigationManager = ctx.Services.AddMockNavigationManager(expectedPath);
            var mockHttpClient        = ctx.Services.AddMockHttpClient();

            mockNavigationManager.SetUri($"http://localhost:5000{expectedPath}");
            mockHttpClient.When("/api/search*").RespondJson(
                new SearchResponse(expectedResults, 0, 20, 3, 10, 0xbeef, expectedSearch));

            // Act
            var cut = ctx.RenderComponent <Client.Pages.Search>();

            cut.WaitForState(() => cut.FindAll("li").Count == expectedResults.Count, TimeSpan.FromMilliseconds(500));
        }
Exemplo n.º 4
0
        public void FetchData_Page_With_Authenticated_User_and_no_data_Should_Render_HtmlCorrectly_Test()
        {
            // Arrange

            const string expectedHtml = @"<h1>Weather forecast</h1>
				<p>This component demonstrates fetching data from the server.</p>
				<p>
				  <em>Loading...</em>
				</p>"                ;

            using var ctx = new TestContext();

            var mock = ctx.Services.AddMockHttpClient();

            var authContext = ctx.AddTestAuthorization();

            authContext.SetAuthorized("TEST USER");

            mock.When("/WeatherForecast").RespondJson((WeatherForecast[])null);

            // Act

            var cut = ctx.RenderComponent <FetchData>();

            // Assert

            cut.MarkupMatches(expectedHtml);
        }
Exemplo n.º 5
0
        public static TestContext AddBlazingPizzaSupport(this TestContext context)
        {
            var fakeAuth = context.AddTestAuthorization();

            context.Services.AddSingleton <TestAuthorizationContext>(fakeAuth);
            context.Services.AddSingleton <SignOutSessionStateManager>();
            context.JSInterop.SetupVoid(
                "sessionStorage.setItem",
                inv => string.Equals(inv.Arguments.FirstOrDefault(), "Microsoft.AspNetCore.Components.WebAssembly.Authentication.SignOutState")
                ).SetVoidResult();
            context.Services.AddSingleton(typeof(IRemoteAuthenticationService <>), typeof(DummyRemoteAuthenticationService <>));

            context.Services.AddSingleton <IAuthenticationViewComponentTypeProvider>(
                new AuthenticationViewComponentTypeProvider(typeof(TestAuthenticationViewComponent)));

            context.Services.AddSingleton <FakePizzaApi>(new FakePizzaApi(fakeAuth));
            context.Services.AddSingleton <IPizzaApi>(s => s.GetRequiredService <FakePizzaApi>());
            context.Services.AddSingleton <FakeNavigationManager>();
            context.Services.AddSingleton <NavigationManager>(s => s.GetRequiredService <FakeNavigationManager>());
            context.Services.AddSingleton <OrderState>();

            context.Services.AddSingleton <INavigationInterception, DummyNavigationInterception>();

            return(context);
        }
    public AuthorizateViewTestHost()
    {
        Instance = new TestContext();
        Instance.JSInterop.Mode = JSRuntimeMode.Loose;
        AuthorizationContext    = Instance.AddTestAuthorization();

        // Mock 脚本
        Instance.JSInterop.Mode = JSRuntimeMode.Loose;

        Instance.Services.AddBootstrapBlazor();
        Instance.Services.AddConfiguration();

        // 渲染 BootstrapBlazorRoot 组件 激活 ICacheManager 接口
        Instance.Services.GetRequiredService <ICacheManager>();
    }
Exemplo n.º 7
0
        public void LoaderShouldRender_WhenNotLoading()
        {
            // Arrange
            using var ctx = new TestContext();
            ctx.AddTestAuthorization();

            // Act
            var cut = ctx.RenderComponent <Loader>(parameters =>
                                                   parameters.Add(p => p.Loading, false)
                                                   );

            // Assert
            cut.Find(".loader-container").MarkupMatches(
                "<aside class=\"loader-container fade hidden\">" +
                "<div class=\"loader flex-fill flex-center\">" +
                "<i class=\"loader-icon las la-book\"></i>" +
                "<div class=\"loader-border\"></div>" +
                "</div>" +
                "</div>");
        }
 public AuthorizationTestHost()
 {
     Instance = new TestContext();
     Instance.JSInterop.Mode = JSRuntimeMode.Loose;
     AuthorizationContext    = Instance.AddTestAuthorization();
 }
Exemplo n.º 9
0
        public void ConfigureTestContext(string userName,
                                         IEnumerable <Claim> claims,
                                         TestContext testContext)
        {
            testContext.JSInterop.Mode = JSRuntimeMode.Loose;
            testContext.Services.AddScoped <JSRuntimeImpl>();

            var authContext = testContext.AddTestAuthorization();

            authContext.SetAuthorized(userName);
            authContext.SetClaims(claims.ToArray());
            authContext.SetPolicies(claims.Where(c => c.Type == "role").Select(c => c.Value).ToArray());

            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)));

            var services         = testContext.Services;
            var httpClient       = CreateClient();
            var appConfiguration = TestUtils.CreateApplicationConfiguration(httpClient);

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

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

            services.AddTransient(p => Server.CreateHandler())
            .AddAdminHttpStores(p =>
            {
                var client = new HttpClient(new BaseAddressAuthorizationMessageHandler(p.GetRequiredService <IAccessTokenProvider>(),
                                                                                       p.GetRequiredService <NavigationManager>())
                {
                    InnerHandler = Server.CreateHandler()
                })
                {
                    BaseAddress = new Uri(httpClient.BaseAddress ?? new Uri(string.Empty), "api")
                };
                return(Task.FromResult(client));
            })
            .AddScoped(p => new Settings
            {
                ApiBaseUrl       = appConfiguration["ApiBaseUrl"],
                WelcomeContenUrl = $"{httpClient.BaseAddress}api/welcomefragment"
            })
            .AddScoped(p => localizerMock.Object)
            .AddScoped(p => localizerMock)
            .AddTransient(p => new HttpClient(Server.CreateHandler()))
            .AddTransient <BaseAddressAuthorizationMessageHandler>()
            .AddScoped <SignOutSessionStateManager, TestUtils.FakeSignOutSessionStateManager>()
            .AddSingleton <IAccessTokenProviderAccessor, TestUtils.AccessTokenProviderAccessor>()
            .AddScoped <IAccessTokenProvider>(p => p.GetRequiredService <TestUtils.FakeAuthenticationStateProvider>())
            .AddScoped <AuthenticationStateProvider>(p => p.GetRequiredService <TestUtils.FakeAuthenticationStateProvider>())
            .AddScoped(p => new TestUtils.FakeAuthenticationStateProvider(
                           userName,
                           claims))
            .AddScoped <LazyAssemblyLoader>()
            .AddHttpClient("oidc")
            .ConfigureHttpClient(httpClient =>
            {
                var apiUri             = new Uri(httpClient.BaseAddress ?? new Uri(string.Empty), "api");
                httpClient.BaseAddress = apiUri;
            })
            .AddHttpMessageHandler(() => new TestUtils.FakeDelegatingHandler(Server.CreateHandler()));

            services.AddHttpClient(nameof(ConfigurationService))
            .AddHttpMessageHandler(() => new TestUtils.FakeDelegatingHandler(Server.CreateHandler()));
        }
        public void FetchData_Page_With_Data_And_Authorized_User_Should_Render_HtmlCorrectly_Test()
        {
            // Arrange

            const string expectedHtml = @"<h1>Weather forecast</h1>
																		<p>This component demonstrates fetching data from the server.</p>
																		<table class=""table"">
																			<thead>
																			<tr>
																			<th>Date</th>
																			<th>Temp. (C)</th>
																			<th>Temp. (F)</th>
																			<th>Summary</th>
																			</tr>
																			</thead>
																			<tbody>
																			<tr>
																			<td>05/06/2018</td>
																			<td>1</td>
																			<td>33</td>
																			<td>Freezing</td>
																			</tr>
																			<tr>
																			<td>05/07/2018</td>
																			<td>14</td>
																			<td>57</td>
																			<td>Bracing</td>
																			</tr>
																			<tr>
																			<td>05/08/2018</td>
																			<td>-13</td>
																			<td>9</td>
																			<td>Freezing</td>
																			</tr>
																			<tr>
																			<td>05/09/2018</td>
																			<td>-16</td>
																			<td>4</td>
																			<td>Balmy</td>
																			</tr>
																			<tr>
																			<td>05/10/2018</td>
																			<td>-2</td>
																			<td>29</td>
																			<td>Chilly</td>
																			</tr>
																			</tbody>
																		</table>"                                                                        ;

            var weather = MockHelpers.GetListOfSampleWeatherForecastData().ToArray();

            using var ctx = new TestContext();

            var mock = ctx.Services.AddMockHttpClient();

            var authContext = ctx.AddTestAuthorization();

            authContext.SetAuthorized("TEST USER");

            mock.When("/WeatherForecast").RespondJson(weather);

            // Act

            var cut = ctx.RenderComponent <FetchData>();

            // Wait for state before continuing test
            cut.WaitForState(() => cut.FindAll("tbody tr").Count > 0);
            //cut.WaitForState(() => cut.Find("p").TextContent != "Loading...");

            // Assert

            cut.MarkupMatches(expectedHtml);
        }