Exemplo n.º 1
0
        public void When_Array_Like_Then_Exception()
        {
            // Arrange
            var handler = new TestApiOperationHandler <InvalidArrayCookieOperation>(null);

            // Act
            Action executor = () => TestApiOperationExecutor.CreateHttp(o => o.WithHandler(handler));

            // Assert
            executor.Should().ThrowExactly <InvalidOperationException>()
            .WithMessage("Cannot create decoder for property InvalidArrayCookieOperation.Lengths as it is array-like and FromCookie does not support multiple values.");
        }
Exemplo n.º 2
0
        public async Task When_HttpMessagePopulation_Child_Operation_Then_Properties_Are_Not_Populated()
        {
            // Arrange
            var executor = TestApiOperationExecutor.CreateHttp(o => o
                                                               .WithOperation <CreationOperation>()
                                                               .WithOperation <SelfQuery>()
                                                               .AddResourceEvents <NullResourceEventRepository>());

            // Act
            var result = await executor.ExecuteAsync(new CreationOperation { IdToCreate = "1234" });

            // Assert
            result.ShouldBeContent <CreatedResourceEvent>().Data.Id.Should().Be("1234");
        }
Exemplo n.º 3
0
        public async Task When_Operation_with_inline_handler_then_populates_variables()
        {
            // Arrange
            var executor = TestApiOperationExecutor
                           .CreateHttp(o => o.WithOperation <HttpOperation>());

            var context = executor.HttpContextFor <HttpOperation>();

            // Act
            var result = await executor.ExecuteAsync(context);

            // Assert
            result.ShouldBeOperationResultType <NoResultOperationResult>();
        }
Exemplo n.º 4
0
        private static async Task AssertPopulatedFromQueryString <TOperation>(TOperation expected, string queryString = null)
        {
            // Arrange
            var handler  = new TestApiOperationHandler <TOperation>(null);
            var executor = TestApiOperationExecutor.CreateHttp(o => o.WithHandler(handler));

            var context = GetContext <TOperation>(executor, queryString);

            // Act
            await executor.ExecuteAsync(context);

            // Assert
            handler.OperationPassed.Should().BeEquivalentTo(expected);
        }
Exemplo n.º 5
0
        private static async Task AssertPopulatedFromRoute <TOperation, TPropertyType>(TOperation expected, string routeDataKeyOverride = null) where TOperation : RouteableOperation <TPropertyType>
        {
            // Arrange
            var handler  = new TestApiOperationHandler <TOperation>(null);
            var executor = TestApiOperationExecutor.CreateHttp(o => o.WithHandler(handler));

            // These tests are checking whether a conversion happens, so we will always put the route data as the ToString() value of the object
            var context = GetContext <TOperation>(executor, routeDataKeyOverride ?? nameof(expected.RouteProperty), expected.RouteProperty.ToString());

            // Act
            await executor.ExecuteAsync(context);

            // Assert
            handler.OperationPassed.Should().BeEquivalentTo(expected);
        }
        private static async Task AssertHeaders <TOperation>(
            TOperation expected,
            Dictionary <string, string> headers = null)
        {
            // Arrange
            var handler  = new TestApiOperationHandler <TOperation>(null);
            var executor = TestApiOperationExecutor.CreateHttp(o => o.WithHandler(handler));

            var context = GetContext <TOperation>(executor, headers);

            // Act
            await executor.ExecuteAsync(context);

            // Assert
            handler.OperationPassed.Should().BeEquivalentTo(expected);
        }
Exemplo n.º 7
0
        public async Task When_LinkGeneration_Middleware_Added_First_Then_Links_Populated()
        {
            // Arrange
            var executor = TestApiOperationExecutor.CreateHttp(o => o
                                                               .WithOperation <CreationOperation>()
                                                               .WithOperation <SelfQuery>()
                                                               .AddHateoasLinks()
                                                               .AddResourceEvents <NullResourceEventRepository>());

            // Act
            var result1 = await executor.ExecuteAsync(new CreationOperation { IdToCreate = "1234" });

            // Assert
            var evt = result1.ShouldBeContent <CreatedResourceEvent>();

            evt.Data.Links["self"].Href.Should().EndWith("/resources/1234");
        }
Exemplo n.º 8
0
        public async Task When_specific_StatusCodeResult_then_renders_correctly()
        {
            // Arrange
            var executor = TestApiOperationExecutor.CreateHttp(o => o
                                                               .WithOperation <CreatedStatusCodeQuery>()
                                                               .AddOpenApi());

            // Act
            var result = await executor.ExecuteAsync <OpenApiQuery>();

            // Assert
            var plaintextResult = result.ShouldBeOperationResultType <PlainTextResult>();
            var openApiDocument = await OpenApiDocument.FromJsonAsync(plaintextResult.Content);

            openApiDocument.Paths.Should().NotBeEmpty();
            await Verifier.Verify(plaintextResult);
        }
        public async Task When_GET_operation_then_renders_correctly()
        {
            // Arrange
            var executor = TestApiOperationExecutor.CreateHttp(o => o
                                                               .WithOperation <OpenApiGetQuery>()
                                                               .AddOpenApi());

            // Act
            var context = executor.HttpContextFor <OpenApiQuery>();
            var result  = await executor.ExecuteAsync(context);

            // Assert
            var plaintextResult = result.ShouldBeOperationResultType <PlainTextResult>();
            var openApiDocument = await OpenApiDocument.FromJsonAsync(plaintextResult.Content);

            openApiDocument.Paths.Should().NotBeEmpty();
            plaintextResult.Content.ShouldMatchSnapshot();
        }
Exemplo n.º 10
0
        public async Task When_ResourceCreated_And_Self_Query_Exists_Populates_Data()
        {
            // Arrange
            var executor = TestApiOperationExecutor.CreateHttp(o => o
                                                               .WithOperation <CreationOperation>()
                                                               .WithOperation <SelfQuery>()
                                                               .AddResourceEvents <NullResourceEventRepository>());

            // Act
            // Note, do 2 executions to ensure correct parameters and being passed around
            var result1 = await executor.ExecuteAsync(new CreationOperation { IdToCreate = "1234" });

            var result2 = await executor.ExecuteAsync(new CreationOperation { IdToCreate = "9876" });

            // Assert
            result1.ShouldBeContent <CreatedResourceEvent>().Data.Id.Should().Be("1234");
            result2.ShouldBeContent <CreatedResourceEvent>().Data.Id.Should().Be("9876");
        }
Exemplo n.º 11
0
        public async Task When_Child_Operation_Has_Authorisation_Then_Skips_And_Allows()
        {
            // Arrange
            var executor = TestApiOperationExecutor.CreateHttp(
                o => o
                .WithOperation <CreationOperation>()
                .WithOperation <SelfQuery>()
                .AddAuthentication(a => a.UseContextLoader <AnonymousUserAuthorisationContextFactory>())
                .AddAuthorisation()
                .AddResourceEvents <NullResourceEventRepository>(),
                s => s.AddSingleton <IClaimsIdentityProvider, NullClaimsIdentityProvider>());

            // Act
            var result = await executor.ExecuteAsync(new CreationOperation { IdToCreate = "1234" });

            // Assert
            result.ShouldBeContent <CreatedResourceEvent>().Data.Id.Should().Be("1234");
        }
Exemplo n.º 12
0
        public async Task When_no_operations_then_renders_correctly()
        {
            // Arrange
            var executor = TestApiOperationExecutor.CreateHttp(o => o
                                                               .AddOpenApi());

            // Act
            var result = await executor.ExecuteAsync <OpenApiQuery>();

            // Assert
            var plaintextResult = result.ShouldBeOperationResultType <PlainTextResult>();
            var openApiDocument = await OpenApiDocument.FromJsonAsync(plaintextResult.Content);

            openApiDocument.Info.Should().NotBeNull();
            openApiDocument.Components.Schemas.Should().BeEmpty();
            openApiDocument.Paths.Should().BeEmpty();

            await Verifier.Verify(plaintextResult);
        }
Exemplo n.º 13
0
        public async Task When_operation_link_exists_with_query_only_properties_renders_correctly()
        {
            // Arrange
            var executor = TestApiOperationExecutor.CreateHttp(o => o
                                                               .WithOperation <OpenApiGetQuery>()
                                                               .WithOperation <LinkedQueryWithQueryOnlyProperties>()
                                                               .WithOperation <LinkedCommandWithNoBody>()
                                                               .AddOpenApi());

            // Act
            var result = await executor.ExecuteAsync <OpenApiQuery>();

            // Assert
            var plaintextResult = result.ShouldBeOperationResultType <PlainTextResult>();
            var openApiDocument = await OpenApiDocument.FromJsonAsync(plaintextResult.Content);

            openApiDocument.Paths.Should().NotBeEmpty();
            await Verifier.Verify(plaintextResult);
        }
Exemplo n.º 14
0
        public async Task When_PlaintextResponse_result_operation_then_renders_correctly()
        {
            // Arrange
            // Add 'BasicOpenApiGetQuery' so that we output x-links to a PlaintextResult operation
            var executor = TestApiOperationExecutor.CreateHttp(o => o
                                                               .WithOperation <BasicOpenApiGetQuery>()
                                                               .WithOperation <OpenApiPlaintextResponseCommand>()
                                                               .AddOpenApi());

            // Act
            var result = await executor.ExecuteAsync <OpenApiQuery>();

            // Assert
            var plaintextResult = result.ShouldBeOperationResultType <PlainTextResult>();
            var openApiDocument = await OpenApiDocument.FromJsonAsync(plaintextResult.Content);

            openApiDocument.Paths.Should().NotBeEmpty();
            await Verifier.Verify(plaintextResult);
        }
Exemplo n.º 15
0
        public async Task When_called_multiple_times_servers_updated_correctly()
        {
            // Bug report of servers[0].url being wrong on subsequent calls due to how setting BasePath works in NSwag.

            // Arrange
            var executor = TestApiOperationExecutor.CreateHttp(o => o
                                                               .AddOpenApi());

            // Act
            var result1 = await executor.ExecuteAsync <OpenApiQuery>();

            var result2 = await executor.ExecuteAsync <OpenApiQuery>();

            // Assert
            var plaintextResult1 = result1.ShouldBeOperationResultType <PlainTextResult>();
            var plaintextResult2 = result2.ShouldBeOperationResultType <PlainTextResult>();

            plaintextResult1.Content.Should().Be(plaintextResult2.Content);
        }
Exemplo n.º 16
0
        public async Task When_Route_Property_In_Json_Body_But_Not_RouteData_With_Multiple_Routes_Then_Sets(Labelled <Action <BlueprintHttpBuilder> > configureHttp)
        {
            // Arrange
            var expected = new MultipleRouteOperation {
                RouteProperty = "expectedValue"
            };

            var handler  = new TestApiOperationHandler <MultipleRouteOperation>(null);
            var executor = TestApiOperationExecutor.CreateHttp(o => o.WithHandler(handler), configureHttp: configureHttp);
            var context  = GetContext(executor, expected);

            // Act
            var source = executor.WhatCodeDidIGenerate();

            await executor.ExecuteAsync(context);

            // Assert
            handler.OperationPassed.Should().BeEquivalentTo(expected);
            handler.OperationPassed.RouteProperty.Should().Be(expected.RouteProperty);
        }
Exemplo n.º 17
0
        public async Task When_Malformed_JSON_Then_Throws_ApiException(Labelled <Action <BlueprintHttpBuilder> > configureHttp)
        {
            // Arrange
            var handler  = new TestApiOperationHandler <JsonOperation>(null);
            var executor = TestApiOperationExecutor.CreateHttp(o => o.WithHandler(handler), configureHttp: configureHttp);

            var context = executor.HttpContextFor <JsonOperation>();

            context.GetHttpContext().Request.Body = "{..}".AsUtf8Stream();
            context.GetHttpContext().Request.Headers["Content-Type"] = "application/json";

            // Act
            Func <Task> tryExecute = () => executor.ExecuteAsync(context);

            // Assert
            await tryExecute.Should()
            .ThrowApiExceptionAsync()
            .WithType("invalid_json")
            .WithTitle("The JSON payload is invalid");
        }
Exemplo n.º 18
0
        public async Task When_Json_Body_And_FromBody_Attribute_Then_Populates(Labelled <Action <BlueprintHttpBuilder> > configureHttp)
        {
            // Arrange
            var expectedBody = new JsonOperation
            {
                IntegerProperty  = 761,
                EnumProperty     = OperationEnum.EnumOne,
                GuidProperty     = Guid.NewGuid(),
                StringArray      = new[] { "arr1", "arr2" },
                StringEnumerable = new[] { "arr3", "arr4" },
                StringList       = new List <string> {
                    "arr5", "arr6"
                },
                StringProperty          = "a string",
                NullableIntegerProperty = null,
                StringIntegerDictionary = new Dictionary <string, int> {
                    { "one", 1 }, { "twice", 12 }
                }
            };

            var handler  = new TestApiOperationHandler <JsonOperationUsingFromBody>(null);
            var executor = TestApiOperationExecutor.CreateHttp(
                o => o.WithHandler(handler),
                configureHttp: configureHttp);

            var jsonBody = JsonConvert.SerializeObject(expectedBody);

            var context = executor.HttpContextFor <JsonOperationUsingFromBody>();

            context.GetHttpContext().Request.Body = jsonBody.AsUtf8Stream();
            context.GetHttpContext().Request.Headers["Content-Type"] = "application/json";

            // Act
            await executor.ExecuteAsync(context);

            // Assert
            handler.OperationPassed.Should().BeEquivalentTo(new JsonOperationUsingFromBody
            {
                JsonOperation = expectedBody,
            });
        }
        public async Task When_browser_request_returns_Refit_html()
        {
            // Arrange
            var executor = TestApiOperationExecutor
                           .CreateHttp(o => o
                                       .AddOpenApi());

            // Act
            var context = executor.HttpContextFor <OpenApiQuery>(c =>
            {
                c.Request.Headers["Accept"] = "text/html";
            });

            var result = await executor.ExecuteAsync(context);

            // Assert
            var plaintextResult = result.ShouldBeOperationResultType <PlainTextResult>();

            plaintextResult.ContentType.Should().Be("text/html");
            plaintextResult.Content.Should().Contain("redoc");
        }
        public async Task When_browser_request_with_json_query_key_returns_json()
        {
            // Arrange
            var executor = TestApiOperationExecutor
                           .CreateHttp(o => o
                                       .AddOpenApi());

            // Act
            var context = executor.HttpContextFor <OpenApiQuery>(c =>
            {
                c.Request.Headers["Accept"] = "text/html";
                c.Request.QueryString       = new QueryString("?json");
            });

            var result = await executor.ExecuteAsync(context);

            // Assert
            var plaintextResult = result.ShouldBeOperationResultType <PlainTextResult>();

            plaintextResult.ContentType.Should().Be("application/json");
        }
        public async Task When_HttpMessagePopulation_Operation_Then_Properties_Are_Populated()
        {
            // Arrange
            var executor = TestApiOperationExecutor.CreateHttp(o => o
                                                               .WithOperation <CreationOperation>()
                                                               .WithOperation <SelfQuery>()
                                                               .AddResourceEvents <NullResourceEventRepository>());

            // Act
            var context = executor.HttpContextFor(new CreationOperation
            {
                IdToCreate    = "1234",
                EmailToCreate = "*****@*****.**",
            });

            var result = await executor.ExecuteAsync(context);

            // Assert
            result.ShouldBeContent <CreatedResourceEvent>().Data.Id.Should().Be("1234");
            result.ShouldBeContent <CreatedResourceEvent>().Data.Email.Should().Be("*****@*****.**");
        }
Exemplo n.º 22
0
        public async Task When_Route_Property_In_Json_Body_Then_Route_Value_Wins(Labelled <Action <BlueprintHttpBuilder> > configureHttp)
        {
            // Arrange
            var expected = new JsonWithRouteOperation
            {
                RouteProperty    = "unexpectedRouteValue",
                IntegerProperty  = 761,
                EnumProperty     = OperationEnum.EnumOne,
                GuidProperty     = Guid.NewGuid(),
                StringArray      = new[] { "arr1", "arr2" },
                StringEnumerable = new[] { "arr3", "arr4" },
                StringList       = new List <string> {
                    "arr5", "arr6"
                },
                StringProperty          = "a string",
                NullableIntegerProperty = null,
                StringIntegerDictionary = new Dictionary <string, int> {
                    { "one", 1 }, { "twice", 12 }
                }
            };

            var expectedRouteValue = "theRouteValue";

            var handler  = new TestApiOperationHandler <JsonWithRouteOperation>(null);
            var executor = TestApiOperationExecutor.CreateHttp(o => o.WithHandler(handler), configureHttp: configureHttp);
            var context  = GetContext(executor, expected);

            context.GetRouteData().Values[nameof(JsonWithRouteOperation.RouteProperty)] = expectedRouteValue;

            // Act
            await executor.ExecuteAsync(context);

            // Assert
            handler.OperationPassed.Should().BeEquivalentTo(
                expected,
                o => o.Excluding(x => x.RouteProperty));

            handler.OperationPassed.RouteProperty.Should().Be(expectedRouteValue);
        }
Exemplo n.º 23
0
        public async Task When_ConfigureOperation_provided_then_can_modify_all_operations()
        {
            // Arrange
            var executor = TestApiOperationExecutor.CreateHttp(o => o
                                                               .WithOperation <OpenApiGetQuery>()
                                                               .WithOperation <OpenApiPutCommand>()
                                                               .AddOpenApi(d =>
            {
                d.ConfigureOperation = (o, a) =>
                {
                    o.Tags.Add(a.OperationType.FullName);
                };
            }));

            // Act
            var result = await executor.ExecuteAsync <OpenApiQuery>();

            // Assert
            var plaintextResult = result.ShouldBeOperationResultType <PlainTextResult>();
            var openApiDocument = await OpenApiDocument.FromJsonAsync(plaintextResult.Content);

            openApiDocument.Paths.Should().NotBeEmpty();
            await Verifier.Verify(plaintextResult);
        }