Exemplo n.º 1
0
        public async Task ControllerAction_CanSpecifyReturnResource_UsingAttribute()
        {
            // Arrange:
            var hostPlugin = new MockAppHostPlugin();

            hostPlugin.AddPluginType <ConventionBasedResourceMap>();

            var mockResource = new LinkedResource2
            {
                Id     = 10,
                Value1 = 100,
                Value2 = "value-2",
                Value3 = 300,
                Value4 = 400
            };

            var serviceMock = new MockUnitTestService
            {
                ServerResources = new[] { mockResource }
            };

            // Act:
            var client = RequestSettings.Create()
                         .CreateTestClient(hostPlugin, serviceMock);

            var request  = ApiRequest.Create("api/convention/links/resource2", HttpMethod.Get);
            var resource = (await client.Send <LinkedResourceModel>(request)).Content;

            // Assert:
            resource.Links.Should().HaveCount(1);
            resource.AssertLink("self", HttpMethod.Get, "/api/convention/links/self/return/attribute/10");
        }
Exemplo n.º 2
0
        public static HttpClient Create(
            MockAppHostPlugin hostPlugin,
            IMessagingService messagingService)
        {
            var builder = new WebHostBuilder()
                          .ConfigureServices(services =>
            {
                hostPlugin.UseMessagingPlugin();

                // Creates the typical StartUp class used by ASP.NET Core.
                var startup = new TestStartup(hostPlugin);
                services.AddSingleton <IStartup>(startup);

                // Adds mock messaging service so know results can be returned
                // for sent commands.
                services.AddSingleton(messagingService);
            }).UseSetting(WebHostDefaults.ApplicationKey, typeof(TestHttpClient).Assembly.FullName);


            // Create an instance of the server and create an HTTP Client
            // to communicate with in-memory web-host.
            var server     = new TestServer(builder);
            var httpClient = server.CreateClient();

            return(httpClient);
        }
Exemplo n.º 3
0
        public async Task Response_DescriptiveProperties_SetCorrectly()
        {
            // Arrange:
            var hostPlugin = new MockAppHostPlugin();

            hostPlugin.AddPluginType <LinkedResourceMap>();

            var mockResource = new LinkedResource
            {
                Id     = 10,
                Value1 = 100,
                Value2 = "value-2",
                Value3 = 300,
                Value4 = 400
            };

            var serviceMock = new MockUnitTestService
            {
                ServerResources = new[] { mockResource }
            };

            // Act:
            var client = RequestSettings.Create()
                         .CreateTestClient(hostPlugin, serviceMock);

            var request = ApiRequest.Create("api/linked/resource", HttpMethod.Get);

            var resource = await client.Send <LinkedResourceModel>(request);

            resource.MediaType.Should().Be("application/hal+json");
            resource.CharSet.Should().Be("utf-8");
            resource.ContentLength.Should().Be(1108);
        }
Exemplo n.º 4
0
        public async Task ResourceMap_Convention_ResourceLinks()
        {
            // Arrange:
            var hostPlugin = new MockAppHostPlugin();

            hostPlugin.AddPluginType <ConventionBasedResourceMap>();

            var mockResource = new LinkedResource
            {
                Id     = 10,
                Value1 = 100,
                Value2 = "value-2",
                Value3 = 300,
                Value4 = 400
            };

            var serviceMock = new MockUnitTestService
            {
                ServerResources = new[] { mockResource }
            };

            // Act:
            var client = RequestSettings.Create()
                         .CreateTestClient(hostPlugin, serviceMock);

            var request  = ApiRequest.Create("api/convention/links/resource", HttpMethod.Get);
            var resource = (await client.Send <LinkedResourceModel>(request)).Content;

            // Assert:
            resource.AssertLink("self", HttpMethod.Get, "/api/convention/links/self/10");
            resource.AssertLink("resource:create", HttpMethod.Post, "/api/convention/links/create");
            resource.AssertLink("resource:update", HttpMethod.Put, "/api/convention/links/update/10");
            resource.AssertLink("resource:delete", HttpMethod.Delete, "/api/convention/links/delete/10");
        }
        public async Task CanGenerateUrl_FromStringInterpolatedResourceUrl()
        {
            // Arrange:
            var hostPlugin = new MockAppHostPlugin();

            hostPlugin.AddPluginType <LinkedResourceMap>();

            var mockResource = new LinkedResource
            {
                Id     = 10,
                Value1 = 100,
                Value2 = "value-2",
                Value3 = 300,
                Value4 = 400
            };

            var serviceMock = new MockUnitTestService
            {
                ServerResources = new[] { mockResource }
            };

            // Act:
            var client = RequestSettings.Create()
                         .CreateTestClient(hostPlugin, serviceMock);

            var request  = ApiRequest.Create("api/linked/resource", HttpMethod.Get);
            var resource = (await client.Send <LinkedResourceModel>(request)).Content;

            // Assert:
            resource.AssertLink("scenario-25", HttpMethod.Options, "http://external/api/call/10/info/value-2");
        }
Exemplo n.º 6
0
        public async Task QueryStringParams_CanBeSpecified()
        {
            var settings = RequestSettings.Create(config =>
            {
                config.UseHalDefaults();

                config.QueryString
                .AddParam("a", "v1")
                .AddParam("b", "v2");
            });

            IMockedService mockedSrv = new MockUnitTestService
            {
                Customers = new[] { new CustomerResource {
                                        CustomerId = "ID_1", Age = 47
                                    } }
            };

            var hostPlugin = new MockAppHostPlugin();

            hostPlugin.AddPluginType <CustomerResourceMap>();

            var client = settings.CreateTestClient(hostPlugin, mockedSrv);

            var request  = ApiRequest.Create("api/customers/24234234234", HttpMethod.Get);
            var response = await client.Send <CustomerModel>(request);

            response.Request.RequestUri.PathAndQuery
            .Should().Be("/api/customers/24234234234?a=v1&b=v2");
        }
        public async Task ResourceMap_CanSpecify_AdditionalOptionalLinkProperties()
        {
            // Arrange:
            var hostPlugin = new MockAppHostPlugin();

            hostPlugin.AddPluginType <LinkedResourceMap>();

            var mockResource = new LinkedResource
            {
                Id     = 10,
                Value2 = "value-2"
            };

            var serviceMock = new MockUnitTestService
            {
                ServerResources = new[] { mockResource }
            };

            // Act:
            var client = RequestSettings.Create()
                         .CreateTestClient(hostPlugin, serviceMock);

            var request  = ApiRequest.Create("api/linked/resource", HttpMethod.Get);
            var resource = (await client.Send <LinkedResourceModel>(request)).Content;

            // Assert:
            resource.AssertLink("scenario-30", HttpMethod.Options, "http://external/api/call/10/info/value-2");

            var link = resource.Links["scenario-30"];

            Assert.Equal(link.Name, "test-name");
            Assert.Equal(link.Title, "test-title");
            Assert.Equal(link.Type, "test-type");
            Assert.Equal(link.HrefLang, "test-href-lang");
        }
Exemplo n.º 8
0
        public async Task ResourceLinks_NotSerializedWithRequest()
        {
            var mockedSrv  = new MockUnitTestService();
            var hostPlugin = new MockAppHostPlugin();

            hostPlugin.AddPluginType <CustomerResourceMap>();

            var client = RequestSettings.Create()
                         .CreateTestClient(hostPlugin, mockedSrv);

            // Create a test resource as it would have been returned from the server.
            var resource = new CustomerModel {
                CustomerId = Guid.NewGuid().ToString(),
                FirstName  = "Doug",
                LastName   = "Bowan",
                Age        = 77,
                Links      = new Dictionary <string, Link> {
                    { "test:lj4000", new Link {
                          Href = "pull/rip/cord"
                      } }
                }
            };

            var request = ApiRequest.Post("api/customers/pass-through").WithContent(resource);

            await client.Send <CustomerModel>(request);

            var serverReceivedResource = mockedSrv.ServerReceivedResource as CustomerResource;

            serverReceivedResource.Should().NotBeNull("Client Resource Deserialized in Server Resource Representation.");
            serverReceivedResource.CustomerId.Should().Be(resource.CustomerId, "Server Side Serialized Resource Matches Client Resource.");
            serverReceivedResource.Links.Should().BeNull("Links Should only be returned from Server.");
        }
Exemplo n.º 9
0
        public static IAppContainer Create(MockAppHostPlugin hostPlugin, IServiceCollection services)
        {
            var resolver = new TestTypeResolver();

            resolver.AddPlugin(hostPlugin);
            var container = ContainerSetup.Bootstrap(resolver);

            container.WithConfig((EnvironmentConfig envConfig) =>
            {
                var configBuilder = new ConfigurationBuilder();
                configBuilder.AddDefaultAppSettings();

                envConfig.UseConfiguration(configBuilder.Build());
            })

            .WithConfig((AutofacRegistrationConfig config) =>
            {
                config.Build = builder =>
                {
                    builder.Populate(services);
                };
            })

            .WithConfig((WebMvcConfig config) =>
            {
                config.EnableRouteMetadata = true;
                config.UseServices(services);
            });

            return(container);
        }
Exemplo n.º 10
0
        public async Task ResourcesToAuthenticateAccess_Received()
        {
            // Arrange:
            var mockMessaging = MockMessagingService.Setup(results => {
                var expectedResult = AuthResult.Authenticated().SetSignedToken("MOCK_TOKEN");
                results.RegisterResponse <AuthenticateCaller, AuthResult>(expectedResult);
            });

            var expectedService = "resource-owner";
            var scope1          = "repository:test/my-app:pull,push";
            var scope2          = "repository:test/my-app2:pull";

            var url = $@"api/boondocks/authentication?service={expectedService}&scope={scope1}&scope={scope2}";

            var plugin     = new MockAppHostPlugin();
            var httpClient = TestHttpClient.Create(plugin, mockMessaging);

            // Act:
            var credentials = new AuthCredentialModel {
            };
            var result      = await httpClient.AuthenticateAsync(url, credentials);

            // Assert:
            Assert.True(mockMessaging.ReceivedMessages.Count() == 1);

            var receivedCommand = (AuthenticateCaller)mockMessaging.ReceivedMessages.First();

            Assert.NotNull(receivedCommand.Context);

            // Assert Owning Service Submitted:
            Assert.Equal(receivedCommand.Context.ResourceOwner, expectedService);

            // Assert Resources to Authenticate Access:
            Assert.NotNull(receivedCommand.Context.Resources);
            Assert.True(receivedCommand.Context.Resources.Length == 2);

            // Assert First Resource Scope:
            var firstScope = receivedCommand.Context.Resources[0];

            Assert.Equal("repository", firstScope.Type);
            Assert.Equal("test/my-app", firstScope.Name);
            Assert.True(firstScope.Actions.Length == 2);
            Assert.Equal("pull", firstScope.Actions[0]);
            Assert.Equal("push", firstScope.Actions[1]);


            // Assert Second Resource Scope:
            var secondScope = receivedCommand.Context.Resources[1];

            Assert.Equal("repository", secondScope.Type);
            Assert.Equal("test/my-app2", secondScope.Name);
            Assert.True(secondScope.Actions.Length == 1);
            Assert.Equal("pull", firstScope.Actions[0]);
        }
Exemplo n.º 11
0
        public async Task ClientCan_ReceiveEmbeddedResourceCollection()
        {
            // Arrange the test resources that will be returned from the server
            // to test the client consumer code.
            var serverResource = new CustomerResource
            {
                CustomerId = Guid.NewGuid().ToString()
            };

            var embeddedServerResource = new AddressResource
            {
                AddressId  = Guid.NewGuid().ToString(),
                CustomerId = serverResource.CustomerId
            };

            var embeddedServerResource2 = new AddressResource
            {
                AddressId  = Guid.NewGuid().ToString(),
                CustomerId = serverResource.CustomerId
            };

            serverResource.Embed(new[] { embeddedServerResource, embeddedServerResource2 }, "addresses");

            var mockSrv = new MockUnitTestService
            {
                Customers = new CustomerResource[] { serverResource }
            };

            // Create the test client and call route returning an embedded resource collection.
            var hostPlugin = new MockAppHostPlugin();

            hostPlugin.AddPluginType <CustomerResourceMap>();

            var client = RequestSettings.Create()
                         .CreateTestClient(hostPlugin, mockSrv);

            var request  = ApiRequest.Create("api/customers/embedded/resource", HttpMethod.Get);
            var response = await client.Send <CustomerModel>(request);

            // Validate that an embedded resource collection was returned.
            response.Content.Should().NotBeNull();
            response.Content.Embedded.Should().NotBeNull();
            response.Content.Embedded.Keys.Should().HaveCount(1);
            response.Content.Embedded.ContainsKey("addresses").Should().BeTrue();

            // At this point, the embedded resource is the generic JSON.NET representation.
            // The next line of code will deserialize this generic representation in the C# client side class
            //      matching the server-sided resource collection.

            var embeddedClientResource = response.Content.GetEmbeddedCollection <AddressModel>("addresses");

            embeddedClientResource.Should().NotBeNull();
            embeddedClientResource.Should().HaveCount(2);
        }
Exemplo n.º 12
0
        public async Task ClientSpecified_EnbeddedTypes_SentAsQueryString()
        {
            // Arrange the test resources that will be returned from the server
            // to test the client consumer code.
            var serverResource = new CustomerResource
            {
                CustomerId = Guid.NewGuid().ToString()
            };

            var embeddedServerResource = new AddressResource
            {
                AddressId  = Guid.NewGuid().ToString(),
                CustomerId = serverResource.CustomerId
            };

            var embeddedServerResource2 = new AddressResource
            {
                AddressId  = Guid.NewGuid().ToString(),
                CustomerId = serverResource.CustomerId
            };

            var embeddedServerResource3 = new AddressResource
            {
                AddressId  = Guid.NewGuid().ToString(),
                CustomerId = serverResource.CustomerId
            };

            serverResource.Embed(new[] { embeddedServerResource, embeddedServerResource2 }, "addresses");
            serverResource.Embed(embeddedServerResource3, "vacation-address");

            var mockSrv = new MockUnitTestService
            {
                Customers = new CustomerResource[] { serverResource }
            };

            // Create the test client and call route returning an embedded resource collection.
            var hostPlugin = new MockAppHostPlugin();

            hostPlugin.AddPluginType <CustomerResourceMap>();

            var client = RequestSettings.Create()
                         .CreateTestClient(hostPlugin, mockSrv);

            var request  = ApiRequest.Create("api/customers/embedded/resource", HttpMethod.Get).Embed("vacation-address");
            var response = await client.Send <CustomerModel>(request);

            response.Request.RequestUri.Query.Should().Equals("?embed=vacation-address");

            // If supported by the service then only one embedded resource should have been returned.
            response.Content.Embedded.Should().HaveCount(1);
            response.Content.Embedded.ContainsKey("vacation-address").Should().BeTrue();
        }
Exemplo n.º 13
0
 public void PluginAssemblyName_MustBeSpecified()
 {
     ContainerSetup
     .Arrange((TestTypeResolver config) =>
     {
         var appHostPlugin = new MockAppHostPlugin {
             AssemblyName = ""
         };
         config.AddPlugin(appHostPlugin);
     })
     .Test(
         c => c.Build(), (c, e) =>
     {
         e.Should().NotBeNull();
         e.Should().BeOfType <ContainerException>();
     });
 }
Exemplo n.º 14
0
 public void AllPluginManifests_MustHaveIdentityValue()
 {
     ContainerSetup
     .Arrange((TestTypeResolver config) =>
     {
         var appHostPlugin = new MockAppHostPlugin {
             PluginId = null
         };
         config.AddPlugin(appHostPlugin);
     })
     .Test(c => c.Build(),
           (c, e) =>
     {
         e.Should().NotBeNull();
         e.Should().BeOfType <ContainerException>();
     });
 }
Exemplo n.º 15
0
        public async Task EmbeddedResources_NotSerializedWithRequest()
        {
            var settings = RequestSettings.Create(config => config.UseHalDefaults());

            var hostPlugin = new MockAppHostPlugin();

            hostPlugin.AddPluginType <CustomerResourceMap>();

            var mockedSrv = new MockUnitTestService();
            var client    = settings.CreateTestClient(hostPlugin, mockedSrv);

            // Create a test resource as it would have been returned from the server.
            var resource = new CustomerModel
            {
                CustomerId = Guid.NewGuid().ToString(),
                FirstName  = "Doug",
                LastName   = "Bowan",
                Age        = 77,
            };

            // Create an embedded resource.  This would be the same state as if
            // the embedded resource, returned from the server, was deserialized into
            // the client-side resource representation.
            var embeddedResource = new AddressModel {
                AddressId  = Guid.NewGuid().ToString(),
                CustomerId = resource.CustomerId,
                City       = "Buckhannon",
                Street     = "59 College Avenue",
                ZipCode    = "26201"
            };

            resource.Embedded = new Dictionary <string, object>();
            resource.Embedded.Add("address", embeddedResource);

            var request = ApiRequest.Post("api/customers/pass-through", config => config.WithContent(resource));

            await client.Send <CustomerModel>(request);

            var serverReceivedResource = mockedSrv.ServerReceivedResource as CustomerResource;

            serverReceivedResource.Should().NotBeNull("Client Resource Deserialized in Server Resource Representation.");
            serverReceivedResource.CustomerId.Should().Be(resource.CustomerId, "Server Side Serialized Resource Matches Client Resource.");
            serverReceivedResource.Embedded.Should().BeNull("Embedded Resources Should only be returned from Server.");
        }
Exemplo n.º 16
0
        public async Task InvalidSpecifiedCredentials_UnAuthorized()
        {
            // Arrange:
            var mockMessaging = MockMessagingService.Setup(results => {
                var expectedResult = AuthResult.SetAuthenticated(false);
                results.RegisterResponse <AuthenticateCaller, AuthResult>(expectedResult);
            });

            var plugin     = new MockAppHostPlugin();
            var httpClient = TestHttpClient.Create(plugin, mockMessaging);

            // Act:
            var credentials = new AuthCredentialModel {
            };
            var result      = await httpClient.AuthenticateAsync(credentials);

            // Assert:
            Assert.Equal(HttpStatusCode.Unauthorized, result.StatusCode);
        }
Exemplo n.º 17
0
        public async Task ClientMustPopulate_AllRequiredTemplateTokens()
        {
            var hostPlugin = new MockAppHostPlugin();

            hostPlugin.AddPluginType <CustomerResourceMap>();

            var client = RequestSettings.Create()
                         .CreateTestClient(hostPlugin);

            var routeValues = new Dictionary <string, object>
            {
                { "state", "wv" },
            };

            var request = ApiRequest.Get("api/test/url/{state}/{city}/{?region}", config => config.WithRouteValues(routeValues));

            await Assert.ThrowsAsync <InvalidOperationException>(
                () => client.Send <CustomerModel>(request));
        }
Exemplo n.º 18
0
 public void AfterContainerBuild_ConfigurationCannotBeAdded()
 {
     ContainerSetup
     .Arrange((TestTypeResolver config) =>
     {
         var appHostPlugin = new MockAppHostPlugin {
         };
         config.AddPlugin(appHostPlugin);
     })
     .Test(c =>
     {
         c.Build();
         c.WithConfig <MockPluginConfig>();
     },
           (c, e) =>
     {
         e.Should().NotBeNull();
         e.Should().BeOfType <ContainerException>();
     });
 }
Exemplo n.º 19
0
 public void NonStartedContainer_CannotBeStopped()
 {
     ContainerSetup
     .Arrange((TestTypeResolver config) =>
     {
         var appHostPlugin = new MockAppHostPlugin {
         };
         config.AddPlugin(appHostPlugin);
     })
     .Test(c =>
     {
         c.Build();
         c.Stop();
     },
           (c, e) =>
     {
         e.Should().NotBeNull();
         e.Should().BeOfType <ContainerException>();
     });
 }
Exemplo n.º 20
0
 public void PluginContainingType_CanBeQueried()
 {
     ContainerSetup
     .Arrange((TestTypeResolver config) =>
     {
         var appHostPlugin = new MockAppHostPlugin {
             PluginId = "__101"
         };
         appHostPlugin.AddPluginType <MockTypeOneBasedOnKnownType>();
         config.AddPlugin(appHostPlugin);
     })
     .Test(
         c => c.Build(),
         c =>
     {
         var plugIn = c.GetPluginForType(typeof(MockTypeOneBasedOnKnownType));
         plugIn.Manifest.PluginId.Should().Be("__101");
     }
         );
 }
Exemplo n.º 21
0
 public void Container_CanOnlyBeStartedOnce()
 {
     ContainerSetup
     .Arrange((TestTypeResolver config) =>
     {
         var appHostPlugin = new MockAppHostPlugin {
         };
         config.AddPlugin(appHostPlugin);
     })
     .Test(c =>
     {
         var builtContainer = c.Build();
         builtContainer.Start();
         builtContainer.Start();
     },
           (c, e) =>
     {
         e.Should().NotBeNull();
         e.Should().BeOfType <ContainerException>();
     });
 }
Exemplo n.º 22
0
        public async Task IfErrorStatusCode_SuccessStaus_SetCorrectly()
        {
            // Arrange:
            var hostPlugin = new MockAppHostPlugin();

            var serviceMock = new MockUnitTestService
            {
                ReturnsStatusCode = StatusCodes.Status404NotFound
            };

            // Act:
            var client = RequestSettings.Create()
                         .CreateTestClient(hostPlugin, serviceMock);

            var request = ApiRequest.Create("api/error/server/http/error-code", HttpMethod.Get);

            var response = await client.Send(request);

            response.StatusCode.Should().Be(HttpStatusCode.NotFound);
            response.ReasonPhase.Should().Be("Not Found");
        }
Exemplo n.º 23
0
        public void PluginIdsValues_MustBeUnique()
        {
            ContainerSetup
            .Arrange((TestTypeResolver config) =>
            {
                var appHostPlugin = new MockAppHostPlugin {
                    PluginId = "1"
                };
                var corePlugin = new MockCorePlugin {
                    PluginId = "1"
                };

                config.AddPlugin(appHostPlugin, corePlugin);
            })
            .Test(
                c => c.Build(),
                (c, e) =>
            {
                e.Should().NotBeNull();
                e.Should().BeOfType <ContainerException>();
            });
        }
Exemplo n.º 24
0
        public async Task IfServerException_ExceptionRaised()
        {
            // Arrange:
            var hostPlugin = new MockAppHostPlugin();

            var serviceMock = new MockUnitTestService
            {
                TriggerServerSideException = true
            };

            // Act:
            var client = RequestSettings.Create()
                         .CreateTestClient(hostPlugin, serviceMock);

            var request = ApiRequest.Create("api/error/server/side", HttpMethod.Get);

            var exception = await Record.ExceptionAsync(() => client.Send(request));

            exception.Should().NotBeNull();
            exception.Should().BeOfType <InvalidOperationException>();
            exception.Message.Should().Be("Test-Exception");
        }
Exemplo n.º 25
0
        public async Task ClientCredentialsReceived_WhenSent()
        {
            // Arrange:
            var mockMessaging = MockMessagingService.Setup(results => {
                var expectedResult = AuthResult.Authenticated().SetSignedToken("MOCK_TOKEN");
                results.RegisterResponse <AuthenticateCaller, AuthResult>(expectedResult);
            });

            var plugin     = new MockAppHostPlugin();
            var httpClient = TestHttpClient.Create(plugin, mockMessaging);

            // Act:
            var credentialModle = new AuthCredentialModel
            {
                Credentials = new Dictionary <string, string>
                {
                    { "CertKey1", "CertValue1" },
                    { "CertKey2", "CertValue2" }
                }
            };

            var result = await httpClient.AuthenticateAsync(credentialModle);

            // Assert:
            Assert.True(mockMessaging.ReceivedMessages.Count() == 1);

            var receivedCommand = (AuthenticateCaller)mockMessaging.ReceivedMessages.First();

            Assert.NotNull(receivedCommand.Context);

            var receivedCredentials = receivedCommand.Context.Credentials;

            Assert.NotNull(receivedCredentials);

            Assert.True(receivedCredentials.ContainsKey("CertKey1"));
            Assert.True(receivedCredentials.ContainsKey("CertKey2"));
            Assert.Equal("CertValue1", receivedCredentials["CertKey1"]);
            Assert.Equal("CertValue2", receivedCredentials["CertKey2"]);
        }
Exemplo n.º 26
0
        public async Task ValidCredentials_ResourceAccess_Returned()
        {
            // Arrange:
            var allowedResourceAccess = new ResourcePermission[] {
                new ResourcePermission(type: "ResourceType", name: "ResourceName", actions: new string[] { "action1", "action2" })
            };

            var mockMessaging = MockMessagingService.Setup(results => {
                var expectedResult = AuthResult.Authenticated(allowedResourceAccess)
                                     .SetSignedToken("MOCK_TOKEN");
                results.RegisterResponse <AuthenticateCaller, AuthResult>(expectedResult);
            });

            var plugin     = new MockAppHostPlugin();
            var httpClient = TestHttpClient.Create(plugin, mockMessaging);

            // Act:
            var credentials = new AuthCredentialModel {
            };
            var result      = await httpClient.AuthenticateAsync(credentials);

            // Assert:
            var responseValue = await result.Content.ReadAsStringAsync();

            var resource = JsonConvert.DeserializeObject <AuthResultResource>(responseValue);
            var resourcesGrantedAccess = resource.GetEmbeddedCollection <AuthAccessResource>("resource-access");

            Assert.NotNull(resourcesGrantedAccess);
            Assert.True(resourcesGrantedAccess.Count() == 1);

            var access = resourcesGrantedAccess.First();

            Assert.Equal("ResourceType", access.Type);
            Assert.Equal("ResourceName", access.Name);
            Assert.True(access.Actions.Length == 2);
            Assert.Equal("action1", access.Actions[0]);
            Assert.Equal("action2", access.Actions[1]);
        }
Exemplo n.º 27
0
        public async Task ValidCredentials_OkStatus_WithTokenHeader()
        {
            // Arrange:
            var mockMessaging = MockMessagingService.Setup(results => {
                var expectedResult = AuthResult.Authenticated()
                                     .SetSignedToken("MOCK_TOKEN");
                results.RegisterResponse <AuthenticateCaller, AuthResult>(expectedResult);
            });

            var plugin     = new MockAppHostPlugin();
            var httpClient = TestHttpClient.Create(plugin, mockMessaging);

            // Act:
            var credentials = new AuthCredentialModel {
            };
            var result      = await httpClient.AuthenticateAsync(credentials);

            // Assert:
            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            result.Headers.TryGetValues("X-Custom-Token", out IEnumerable <string> values);
            Assert.True(values.Count() == 1);
            Assert.Equal("MOCK_TOKEN", values.First());
        }
Exemplo n.º 28
0
        public async Task RequestSpecificSettings_MergedWithBaseAddressDefaultSettings()
        {
            var defaultSettings = RequestSettings.Create(config => {
                config.Headers
                .Add("h1", "dv1", "dv2")
                .Add("h2", "dv3");

                config.QueryString
                .AddParam("p1", "pv1")
                .AddParam("p2", "pv2");
            });

            var reqestSpecificSettings = RequestSettings.Create(config => {
                config.Headers
                .Add("h1", "rs100")
                .Add("h3", "rs200");

                config.QueryString
                .AddParam("p2", "pv300")
                .AddParam("p3", "pv400");
            });

            var hostPlugin = new MockAppHostPlugin();

            hostPlugin.AddPluginType <CustomerResourceMap>();

            var client = defaultSettings.CreateTestClient(hostPlugin);

            var request  = ApiRequest.Get("api/customers/pass-through").UsingSettings(reqestSpecificSettings);
            var response = await client.Send <CustomerModel>(request);

            response.Request.RequestUri.PathAndQuery
            .Should().Be("/api/customers/pass-through?p1=pv1&p2=pv300&p3=pv400");

            response.Request.Headers.ToString()
            .Should().Equals("Accept: application/hal+json, application/json\\r\\nh1: rs100\\r\\nh2: dv3\\r\\nh3: rs200\\r\\nHost: localhost\\r\\n");
        }
Exemplo n.º 29
0
        public async Task IncorrectedOrMissingCredentials_BadRequest()
        {
            // Arrange:
            var mockMessaging = MockMessagingService.Setup(results => {
                var expectedResult = AuthResult.Failed("INVALID_CONTEXT");
                results.RegisterResponse <AuthenticateCaller, AuthResult>(expectedResult);
            });

            var plugin     = new MockAppHostPlugin();
            var httpClient = TestHttpClient.Create(plugin, mockMessaging);

            // Act:
            var credentials = new AuthCredentialModel {
            };
            var result      = await httpClient.AuthenticateAsync(credentials);

            // Assert:
            Assert.Equal(HttpStatusCode.BadRequest, result.StatusCode);
            Assert.NotNull(result.Content);

            var content = await result.Content.ReadAsStringAsync();

            Assert.Equal("INVALID_CONTEXT", content);
        }
Exemplo n.º 30
0
        public static IRequestClient CreateTestClient(this IRequestSettings requestSettings,
                                                      MockAppHostPlugin hostPlugin,
                                                      IMockedService mockService = null)
        {
            requestSettings.UseHalDefaults();

            var serializers = new Dictionary <string, IMediaTypeSerializer>
            {
                { InternetMediaTypes.Json, new JsonMediaTypeSerializer() },
                { InternetMediaTypes.HalJson, new JsonMediaTypeSerializer() }
            };

            var builder = new WebHostBuilder()
                          .ConfigureServices(services =>
            {
                // Add the needed ResourcePlugin modules since this is
                // what the unit tests will be testing.
                hostPlugin.UseResourcePlugin();

                // Creates the typical StartUp class used by ASP.NET Core.
                var startup = new TestStartup(hostPlugin);
                services.AddSingleton <IStartup>(startup);

                // This service will be injected by the WebApi controller and
                // can be used to very the system under test.
                services.AddSingleton <IMockedService>(mockService ?? new NullUnitTestService());
            });

            // Create an instance of the server and create an HTTP Client
            // to communicate with in-memory web-host.
            var server     = new TestServer(builder);
            var httpClient = server.CreateClient();

            // Return an instance of the ResourceClient to be tested.
            return(new RequestClient(httpClient, serializers, requestSettings));
        }