public async Task Posting_command_JSON_applies_a_command_with_the_specified_name_to_an_aggregate_with_the_specified_id()
        {
            var order = new Order(Guid.NewGuid())
                        .Apply(new ChangeCustomerInfo {
                CustomerName = "Joe"
            })
                        .SavedToEventStore();

            var json = new AddItem
            {
                Quantity    = 5,
                Price       = 19.99m,
                ProductName = "Bag o' Treats"
            }.ToJson();

            var request = new HttpRequestMessage(HttpMethod.Post, $"http://contoso.com/orders/{order.Id}/additem")
            {
                Content = new StringContent(json, Encoding.UTF8, "application/json")
            };

            var testApi = new TestApi <Order>();
            var client  = testApi.GetClient();

            var response = client.SendAsync(request).Result;

            response.StatusCode.Should().Be(HttpStatusCode.OK);

            var updatedOrder = await Configuration.Current.Repository <Order>().GetLatest(order.Id);

            updatedOrder.Items.Single().Quantity.Should().Be(5);
        }
예제 #2
0
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (_displayManager.HideMenuStrip && (keyData & Keys.Alt) == Keys.Alt)
            {
                if (mnuMain.Visible && !mnuMain.ContainsFocus)
                {
                    mnuMain.Visible = false;
                }
                else
                {
                    mnuMain.Visible = true;
                    mnuMain.Focus();
                }
            }

#if !HIDETESTMENU
            if (keyData == Keys.Pause && EmuRunner.IsRunning())
            {
                if (TestApi.RomTestRecording())
                {
                    TestApi.RomTestStop();
                }
                else
                {
                    TestApi.RomTestRecord(ConfigManager.TestFolder + "\\" + EmuApi.GetRomInfo().GetRomName() + ".mtp", true);
                }
            }
#endif

            return(base.ProcessCmdKey(ref msg, keyData));
        }
예제 #3
0
        public void Command_properties_can_be_validated()
        {
            var order = new Order(Guid.NewGuid())
                .Apply(new ChangeCustomerInfo { CustomerName = "Joe" })
                .Apply(new Deliver())
                .SavedToEventStore();

            var httpClient = new TestApi<Order>().GetClient();

            var result = httpClient.PostAsync(
                $"http://contoso.com/orders/{order.Id}/additem/validate",
                new JsonContent(new AddItem
                {
                    Price = 1m,
                    Quantity = 1,
                    ProductName = "Widget"
                })).Result;

            result.ShouldSucceed();

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

            Console.WriteLine(content);

            content.Should().Contain("\"Failures\":[{\"Message\":\"The order has already been fulfilled.\"");
        }
예제 #4
0
        public void GenericApiSourceOfComposableFunctionIsCorrect()
        {
            var api       = new TestApi();
            var arguments = new object[0];

            var source = api.Source <DateTime>(
                "Namespace", "Function", arguments);

            Assert.Equal(typeof(DateTime), source.ElementType);
            Assert.True(source.Expression is MethodCallExpression);
            var methodCall = source.Expression as MethodCallExpression;

            Assert.Null(methodCall.Object);
            Assert.Equal(typeof(ApiData), methodCall.Method.DeclaringType);
            Assert.Equal("Source", methodCall.Method.Name);
            Assert.Equal(typeof(DateTime), methodCall.Method.GetGenericArguments()[0]);
            Assert.Equal(3, methodCall.Arguments.Count);
            Assert.True(methodCall.Arguments[0] is ConstantExpression);
            Assert.Equal("Namespace", (methodCall.Arguments[0] as ConstantExpression).Value);
            Assert.True(methodCall.Arguments[1] is ConstantExpression);
            Assert.Equal("Function", (methodCall.Arguments[1] as ConstantExpression).Value);
            Assert.True(methodCall.Arguments[2] is ConstantExpression);
            Assert.Equal(arguments, (methodCall.Arguments[2] as ConstantExpression).Value);
            Assert.Equal(source.Expression.ToString(), source.ToString());
        }
예제 #5
0
        public async Task Posting_an_invalid_command_does_not_affect_the_aggregate_state()
        {
            var order = new Order(Guid.NewGuid(),
                                  new Order.CustomerInfoChanged {
                CustomerName = "Joe"
            },
                                  new Order.Fulfilled());
            await order.SaveToEventStore();

            var json = new AddItem
            {
                Quantity    = 5,
                Price       = 19.99m,
                ProductName = "Bag o' Treats"
            }.ToJson();

            var request = new HttpRequestMessage(HttpMethod.Post, string.Format("http://contoso.com/orders/{0}/additem", order.Id))
            {
                Content = new StringContent(json, Encoding.UTF8, "application/json")
            };

            var testApi = new TestApi <Order>();
            var client  = testApi.GetClient();

            var response = client.SendAsync(request).Result;

            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);

            var updatedOrder = await new SqlEventSourcedRepository <Order>().GetLatest(order.Id);

            updatedOrder.Items.Count().Should().Be(0);
        }
예제 #6
0
        public void CanCallGetApiService()
        {
            var api    = new TestApi(serviceProvider);
            var result = api.GetApiService <IQueryExpressionSourcer>();

            result.Should().BeAssignableTo <IQueryExpressionSourcer>();
        }
        public async Task Posting_command_JSON_applies_a_command_with_the_specified_name_to_an_aggregate_with_the_specified_id()
        {
            var order = new Order(Guid.NewGuid(),
                                  new Order.CustomerInfoChanged { CustomerName = "Joe" });
            await order.SaveToEventStore();
            var json = new AddItem
            {
                Quantity = 5,
                Price = 19.99m,
                ProductName = "Bag o' Treats"
            }.ToJson();

            var request = new HttpRequestMessage(HttpMethod.Post, string.Format("http://contoso.com/orders/{0}/additem", order.Id))
            {
                Content = new StringContent(json, Encoding.UTF8, "application/json")
            };

            var testApi = new TestApi<Order>();
            var client = testApi.GetClient();

            var response = client.SendAsync(request).Result;

            response.StatusCode.Should().Be(HttpStatusCode.OK);

            var updatedOrder = await new SqlEventSourcedRepository<Order>().GetLatest(order.Id);

            updatedOrder.Items.Single().Quantity.Should().Be(5);
        }
예제 #8
0
        public static void Prepare()
        {
            var testApi = new TestApi(DefaultConfig);

            testApi.ApiTestCleanupPost();
            testApi.ApiTestPreparePost();
        }
예제 #9
0
 public void DefaultApiBaseCanBeCreatedAndDisposed()
 {
     using (var api = new TestApi())
     {
         api.Dispose();
     }
 }
예제 #10
0
        public void SetUp()
        {
            // disable authorization checks
            Command <Order> .AuthorizeDefault = (o, c) => true;

            var events = new IEvent <Order>[]
            {
                new Order.ItemAdded {
                    Price = 10m, Quantity = 2, ProductName = "Widget"
                },
                new Order.FulfillmentMethodSelected {
                    FulfillmentMethod = FulfillmentMethod.Delivery
                },
                new Order.Placed(),
                new Order.Shipped(),
                new Order.Paid(20),
                new Order.Delivered(),
                new Order.Fulfilled()
            };

            // set up an order to work with
            order = new Order(Guid.NewGuid(), events).SaveToEventStore();

            api = new TestApi <Order>();
        }
예제 #11
0
        public void CannotConstructWithNullRequest()
        {
            var    api = new TestApi(serviceProviderFixture.ServiceProvider.Object);
            Action act = () => new QueryContext(api, default(QueryRequest));

            act.Should().Throw <ArgumentNullException>();
        }
예제 #12
0
        public async Task Command_properties_can_be_validated()
        {
            var order = new Order(
                Guid.NewGuid(),
                new Order.Fulfilled());
            await order.SaveToEventStore();

            Console.WriteLine(order.Id);

            var httpClient = new TestApi<Order>().GetClient();

            var result = httpClient.PostAsync(
                string.Format("http://contoso.com/orders/{0}/additem/validate", order.Id),
                new JsonContent(new AddItem
                {
                    Price = 1m,
                    Quantity = 1,
                    ProductName = "Widget"
                })).Result;

            result.ShouldSucceed();

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

            Console.WriteLine(content);

            content.Should().Contain("\"Failures\":[{\"Message\":\"The order has already been fulfilled.\"");
        }
예제 #13
0
        public async Task Command_properties_can_be_validated()
        {
            var order = new Order(
                Guid.NewGuid(),
                new Order.Fulfilled());
            await order.SaveToEventStore();

            Console.WriteLine(order.Id);

            var httpClient = new TestApi <Order>().GetClient();

            var result = httpClient.PostAsync(
                string.Format("http://contoso.com/orders/{0}/additem/validate", order.Id),
                new JsonContent(new AddItem
            {
                Price       = 1m,
                Quantity    = 1,
                ProductName = "Widget"
            })).Result;

            result.ShouldSucceed();

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

            Console.WriteLine(content);

            content.Should().Contain("\"Failures\":[{\"Message\":\"The order has already been fulfilled.\"");
        }
예제 #14
0
        public void Command_properties_can_be_validated()
        {
            var order = new Order(Guid.NewGuid())
                        .Apply(new ChangeCustomerInfo {
                CustomerName = "Joe"
            })
                        .Apply(new Deliver())
                        .SavedToEventStore();

            var httpClient = new TestApi <Order>().GetClient();

            var result = httpClient.PostAsync(
                $"http://contoso.com/orders/{order.Id}/additem/validate",
                new JsonContent(new AddItem
            {
                Price       = 1m,
                Quantity    = 1,
                ProductName = "Widget"
            })).Result;

            result.ShouldSucceed();

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

            Console.WriteLine(content);

            content.Should().Contain("\"Failures\":[{\"Message\":\"The order has already been fulfilled.\"");
        }
        public void SetUp()
        {
            ConfigurationManager.AppSettings["ServiceControl/ForwardAuditMessages"] = bool.FalseString;
            ConfigurationManager.AppSettings["ServiceControl/ForwardErrorMessages"] = bool.FalseString;
            ConfigurationManager.AppSettings["ServiceControl/AuditRetentionPeriod"] = TimeSpan.FromHours(10).ToString();
            ConfigurationManager.AppSettings["ServiceControl/ErrorRetentionPeriod"] = TimeSpan.FromDays(10).ToString();

            testApi = new TestApi()
            {
                Settings = new Settings("TestService")
                {
                    Port            = 3333,
                    RemoteInstances = new[]
                    {
                        new RemoteInstanceSetting
                        {
                            ApiUri       = "http://localhost:33334/api",
                            QueueAddress = "remote1"
                        }
                    }
                }
            };

            localInstanceId   = InstanceIdGenerator.FromApiUrl(testApi.Settings.ApiUrl);
            remote1InstanceId = InstanceIdGenerator.FromApiUrl(testApi.Settings.RemoteInstances[0].ApiUri);
        }
예제 #16
0
        public async Task Posting_an_invalid_command_does_not_affect_the_aggregate_state()
        {
            var order = new Order(Guid.NewGuid())
                .Apply(new ChangeCustomerInfo { CustomerName = "Joe" })
                .Apply(new Deliver())
                .SavedToEventStore();

            var json = new AddItem
            {
                Quantity = 5,
                Price = 19.99m,
                ProductName = "Bag o' Treats"
            }.ToJson();

            var request = new HttpRequestMessage(HttpMethod.Post, $"http://contoso.com/orders/{order.Id}/additem")
            {
                Content = new StringContent(json, Encoding.UTF8, "application/json")
            };

            var testApi = new TestApi<Order>();
            var client = testApi.GetClient();

            var response = client.SendAsync(request).Result;

            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);

            var updatedOrder = await Configuration.Current.Repository<Order>().GetLatest(order.Id);

            updatedOrder.Items.Count.Should().Be(0);
        }
예제 #17
0
        public void NewApiContextIsConfiguredCorrectly()
        {
            var api     = new TestApi();
            var context = api.Context;

            Assert.NotNull(context.Configuration);
        }
예제 #18
0
 public void DefaultApiBaseCanBeCreatedAndDisposed()
 {
     using (var api = new TestApi())
     {
         api.Dispose();
     }
 }
예제 #19
0
        public override void ResetFixture()
        {
            IdentityProvider.ResetFixture();
            TestApi.ResetFixture();

            MessageCancellation = Mock.Of <IMessageCancellation>(
                ctx => ctx.GetCancellationToken() == CancellationToken.None);
        }
예제 #20
0
        public void InvocationContextGetsApiServicesCorrectly()
        {
            var api        = new TestApi();
            var apiContext = api.Context;
            var context    = new InvocationContext(apiContext);

            Assert.Same(api.ApiService, context.GetApiService <IServiceA>());
        }
예제 #21
0
        public void SetUp()
        {
            var api = new TestApi();

            var request = new Request("GET", new Url($"http://doesnt/really/matter?{QueryString}"));

            Results = api.AggregateResults(request, GetData().ToArray());
        }
예제 #22
0
        public void GenericSourceOfComposableFunctionThrowsIfWrongType()
        {
            var api       = new TestApi();
            var context   = api.Context;
            var arguments = new object[0];

            Assert.Throws <ArgumentException>(() => context.GetQueryableSource <object>("Namespace", "Function", arguments));
        }
예제 #23
0
        public void CanCallGetModel()
        {
            var api = new TestApi(serviceProvider);
            var cancellationToken = CancellationToken.None;
            var result            = api.GetModel();

            result.Should().NotBeNull();
        }
예제 #24
0
        public void SetUp()
        {
            var api = new TestApi(null, null, null);

            var request = new HttpRequestMessage(new HttpMethod("GET"), $"http://doesnt/really/matter?{QueryString}");

            Results = api.AggregateResults(request, GetData());
        }
예제 #25
0
        public async Task Posting_an_invalid_create_command_returns_400_Bad_request()
        {
            var testApi  = new TestApi <Order>();
            var response = await testApi.GetClient()
                           .PostAsJsonAsync(string.Format("http://contoso.com/orders/createorder/{0}", Any.Guid()), new object());

            response.ShouldFailWith(HttpStatusCode.BadRequest);
        }
예제 #26
0
        public void GenericSourceOfEntityContainerElementThrowsIfWrongType()
        {
            var api       = new TestApi();
            var context   = api.Context;
            var arguments = new object[0];

            Assert.Throws <ArgumentException>(() => context.GetQueryableSource <object>("Test", arguments));
        }
예제 #27
0
        public void NewInvocationContextIsConfiguredCorrectly()
        {
            var api        = new TestApi();
            var apiContext = api.Context;
            var context    = new InvocationContext(apiContext);

            Assert.Same(apiContext, context.ApiContext);
        }
예제 #28
0
        public async Task ApiSubmitAsyncCorrectlyForwardsCall()
        {
            var api = new TestApi();

            var submitResult = await api.SubmitAsync();

            Assert.NotNull(submitResult.CompletedChangeSet);
        }
예제 #29
0
 public ApiControllerBehavior(ITestOutputHelper output)
 {
     _api = new TestApi <Startup, IConfigService>
     {
         Output          = output,
         HttpClientTuner = client => client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "blablabla")
     };
 }
예제 #30
0
        public void RequestIsInitializedCorrectly()
        {
            var api             = new TestApi(serviceProviderFixture.ServiceProvider.Object);
            var queryableSource = new QueryableSource <Test>(Expression.Constant(new Mock <IQueryable>().Object));
            var request         = new QueryRequest(queryableSource);
            var instance        = new QueryContext(api, request);

            instance.Request.Should().Be(request);
        }
예제 #31
0
 public HttpApi(string url)
 {
     _config.BasePath = url;
     Default          = new DefaultApi(_config);
     Test             = new TestApi(_config);
     Auth             = new AuthApi(_config);
     DBDatas          = new DbDatasApi(_config);
     DBUsers          = new DbUsersApi(_config);
 }
예제 #32
0
        public void CachedConfigurationIsCachedCorrectly()
        {
            ApiBase api = new TestApi();
            var configuration = api.Context.Configuration;

            ApiBase anotherApi = new TestApi();
            var cached = anotherApi.Context.Configuration;
            Assert.Same(configuration, cached);
        }
예제 #33
0
        public async Task ApiQueryAsyncWithSingletonQueryReturnsResult()
        {
            var api = new TestApi();

            var result = await api.QueryAsync(
                api.Source <string>("Test"), q => q.Single());

            Assert.Equal("Test", result);
        }
예제 #34
0
        public async Task ApiQueryAsyncWithQueryReturnsResults()
        {
            var api = new TestApi();

            var results = await api.QueryAsync(
                api.Source <string>("Test"));

            Assert.True(results.SequenceEqual(new string[] { "Test" }));
        }
예제 #35
0
 public TestApiBehavior(ITestOutputHelper output)
 {
     _api = new TestApi <Startup, ITestApi>
     {
         Output = output,
         //HttpClientTuner = client => {},
         //ServiceOverrider = services => {}
     };
 }
예제 #36
0
        public void KhronosApi_CheckExtensionCommands()
        {
            Assert.Throws <ArgumentNullException>(() => TestApi.CheckExtensionCommands(null, null, false));
            Assert.Throws <ArgumentNullException>(() => TestApi.CheckExtensionCommands(Gl.Version_100, null, false));

            TestExtensions testExtensions = new TestExtensions();

            Assert.DoesNotThrow(() => TestApi.CheckExtensionCommands(Gl.Version_100, testExtensions, false));
        }
예제 #37
0
        public void ApiAndApiContextCanBeInjectedByDI()
        {
            using (var api = new TestApi())
            {
                var context = api.Context;
                var svc = context.GetApiService<IService>();

                Assert.Same(svc.Api, api);
                Assert.Same(svc.Context, context);

                api.Dispose();
                Assert.Throws<ObjectDisposedException>(() => api.Context);
            }
        }
        public async Task ApplyBatch_can_accept_an_array_of_commands()
        {
            var order = new Order().SavedToEventStore();

            var json = new[]
            {
                new
                {
                    AddItem = new
                    {
                        Quantity = 1,
                        Price = 1,
                        ProductName = "Sprocket"
                    }
                },
                new
                {
                    AddItem = new
                    {
                        Quantity = 1,
                        Price = 2,
                        ProductName = "Cog"
                    }
                }
            }.ToJson();

            var testApi = new TestApi<Order>();
            var client = testApi.GetClient();

            var request = new HttpRequestMessage(HttpMethod.Post, $"http://contoso.com/orders/{order.Id}")
            {
                Content = new StringContent(json, Encoding.UTF8, "application/json")
            };

            var response = await client.SendAsync(request);
            response.ShouldSucceed();

            order = await Configuration.Current.Repository<Order>().GetLatest(order.Id);

            order.Items.Count.Should().Be(2);
            order.Balance.Should().Be(3);
        }
예제 #39
0
        public void Client_validation_hints_can_be_requested_from_the_API_in_order_for_validations_to_be_performed_by_the_client()
        {
            // TODO: (Client_validation_hints_can_be_requested_from_the_API_in_order_for_validations_to_be_performed_by_the_client) 
            var httpClient = new TestApi<Order>().GetClient();

            var result = httpClient.GetAsync(
                "http://contoso.com/orders/commands/additem/rules").Result;

            result.ShouldSucceed();

            var json = result.Content.ReadAsStringAsync().Result;

            Console.WriteLine(json);

            dynamic jobject = JObject.Parse(json);

            // example:
            //"[{"validator":"required","message":"An offer title is required","params":{},"valid":false}]"

            Assert.Fail("Test not written yet.");
        }
예제 #40
0
        public void SetUp()
        {
            // disable authorization checks
            Command<Order>.AuthorizeDefault = (o, c) => true;

            var events = new IEvent<Order>[]
            {
                new Order.ItemAdded { Price = 10m, Quantity = 2, ProductName = "Widget" },
                new Order.FulfillmentMethodSelected { FulfillmentMethod = FulfillmentMethod.Delivery },
                new Order.Placed(),
                new Order.Shipped(), 
                new Order.Paid(20),
                new Order.Delivered(),
                new Order.Fulfilled()
            };

            // set up an order to work with
            order = new Order(Guid.NewGuid(), events).SaveToEventStore();

            api = new TestApi<Order>();
        }
예제 #41
0
        public void Posting_command_JSON_to_a_nonexistent_aggregate_returns_404_Not_found()
        {
            var request = new HttpRequestMessage(HttpMethod.Post, $"http://contoso.com/orders/{Guid.NewGuid()}/cancel")
            {
                Content = new StringContent(new Cancel().ToJson(), Encoding.UTF8, "application/json")
            };

            var client = new TestApi<Order>().GetClient();

            var response = client.SendAsync(request).Result;

            response.StatusCode.Should().Be(HttpStatusCode.NotFound);
        }
예제 #42
0
        public async Task ApiQueryAsyncWithQueryReturnsResults()
        {
            var api = new TestApi();

            var results = await api.QueryAsync(
                api.Source<string>("Test"));
            Assert.True(results.SequenceEqual(new string[] { "Test" }));
        }
예제 #43
0
        public async Task ApiQueryAsyncCorrectlyForwardsCall()
        {
            var api = new TestApi();

            var queryRequest = new QueryRequest(
                api.Source<string>("Test"));
            var queryResult = await api.QueryAsync(queryRequest);
            Assert.True(queryResult.Results.Cast<string>()
                .SequenceEqual(new string[] { "Test" }));
        }
예제 #44
0
        public void GenericApiSourceOfComposableFunctionIsCorrect()
        {
            var api = new TestApi();
            var arguments = new object[0];

            var source = api.Source<DateTime>(
                "Namespace", "Function", arguments);
            Assert.Equal(typeof(DateTime), source.ElementType);
            Assert.True(source.Expression is MethodCallExpression);
            var methodCall = source.Expression as MethodCallExpression;
            Assert.Null(methodCall.Object);
            Assert.Equal(typeof(DataSourceStubs), methodCall.Method.DeclaringType);
            Assert.Equal("Source", methodCall.Method.Name);
            Assert.Equal(typeof(DateTime), methodCall.Method.GetGenericArguments()[0]);
            Assert.Equal(3, methodCall.Arguments.Count);
            Assert.True(methodCall.Arguments[0] is ConstantExpression);
            Assert.Equal("Namespace", (methodCall.Arguments[0] as ConstantExpression).Value);
            Assert.True(methodCall.Arguments[1] is ConstantExpression);
            Assert.Equal("Function", (methodCall.Arguments[1] as ConstantExpression).Value);
            Assert.True(methodCall.Arguments[2] is ConstantExpression);
            Assert.Equal(arguments, (methodCall.Arguments[2] as ConstantExpression).Value);
            Assert.Equal(source.Expression.ToString(), source.ToString());
        }
예제 #45
0
        public async Task ApiSubmitAsyncCorrectlyForwardsCall()
        {
            var api = new TestApi();

            var submitResult = await api.SubmitAsync();
            Assert.NotNull(submitResult.CompletedChangeSet);
        }
예제 #46
0
        public async Task Posting_a_command_that_causes_a_concurrency_error_returns_409_Conflict()
        {
            var order = new Order(Guid.NewGuid())
                .Apply(new ChangeCustomerInfo { CustomerName = "Joe" })
                .SavedToEventStore();

            var testApi = new TestApi<Order>();
            var repository = new Mock<IEventSourcedRepository<Order>>();
            repository.Setup(r => r.GetLatest(It.IsAny<Guid>()))
                      .Returns(Task.FromResult(order));
            repository.Setup(r => r.Save(It.IsAny<Order>()))
                      .Throws(new ConcurrencyException("oops!", new IEvent[0], new Exception("inner oops")));
            Configuration.Current.UseDependency(c => repository.Object);

            var client = testApi.GetClient();

            var response = await client.PostAsJsonAsync($"http://contoso.com/orders/{order.Id}/additem", new { Price = 3m, ProductName = Any.Word() });

            response.ShouldFailWith(HttpStatusCode.Conflict);
        }
예제 #47
0
        public async Task Posting_a_constructor_command_creates_a_new_aggregate_instance()
        {
            var testApi = new TestApi<Order>();

            var orderId = Any.Guid();

            var response = await testApi.GetClient()
                                        .PostAsJsonAsync($"http://contoso.com/orders/createorder/{orderId}", new CreateOrder(Any.FullName()));

            response.ShouldSucceed(HttpStatusCode.Created);
        }
예제 #48
0
        public async Task Posting_a_second_constructor_command_with_the_same_aggregate_id_results_in_a_409_Conflict()
        {
            // arrange
            var testApi = new TestApi<Order>();

            var orderId = Any.Guid();
            await testApi.GetClient()
                         .PostAsJsonAsync($"http://contoso.com/orders/createorder/{orderId}", new CreateOrder(Any.FullName()));

            // act
            var response = await testApi.GetClient()
                                        .PostAsJsonAsync($"http://contoso.com/orders/createorder/{orderId}", new CreateOrder(Any.FullName()));

            // assert
            response.ShouldFailWith(HttpStatusCode.Conflict);
        }
예제 #49
0
        public async Task An_ETag_header_is_applied_to_the_command()
        {
            var order = new Order(Guid.NewGuid())
                .Apply(new ChangeCustomerInfo { CustomerName = "Joe" })
                .SavedToEventStore();

            var json = new AddItem
            {
                Quantity = 5,
                Price = 19.99m,
                ProductName = "Bag o' Treats"
            }.ToJson();
            
            var etag = new EntityTagHeaderValue("\"" + Any.Guid() + "\"");

            Func<HttpRequestMessage> createRequest = () =>
            {
                var request = new HttpRequestMessage(HttpMethod.Post, $"http://contoso.com/orders/{order.Id}/additem")
                {
                    Content = new StringContent(json, Encoding.UTF8, "application/json")
                };
                request.Headers.IfNoneMatch.Add(etag);
                return request;
            };

            var testApi = new TestApi<Order>();
            var client = testApi.GetClient();

            // act: send the request twice
            var response1 = await client.SendAsync(createRequest());
            var response2 = await client.SendAsync(createRequest());

            // assert
            response1.ShouldSucceed(HttpStatusCode.OK);
            response2.ShouldFailWith(HttpStatusCode.NotModified);

            var updatedOrder = await Configuration.Current.Repository<Order>().GetLatest(order.Id);
            updatedOrder.Items.Single().Quantity.Should().Be(5);
        }
예제 #50
0
        public async Task Posting_an_invalid_create_command_returns_400_Bad_request()
        {
            var testApi = new TestApi<Order>();
            var response = await testApi.GetClient()
                                        .PostAsJsonAsync(string.Format("http://contoso.com/orders/createorder/{0}", Any.Guid()), new object());

            response.ShouldFailWith(HttpStatusCode.BadRequest);
        }
예제 #51
0
        public async Task Posting_unauthorized_command_JSON_returns_403_Forbidden()
        {
            var order = new Order(Guid.NewGuid())
                .Apply(new ChangeCustomerInfo { CustomerName = "Joe" })
                .Apply(new Deliver())
                .SavedToEventStore();

            Command<Order>.AuthorizeDefault = (o, command) => false;
            var request = new HttpRequestMessage(HttpMethod.Post, $"http://contoso.com/orders/{order.Id}/cancel")
            {
                Content = new StringContent(new Cancel().ToJson(), Encoding.UTF8, "application/json")
            };

            var client = new TestApi<Order>().GetClient();

            var response = await client.SendAsync(request);

            response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
        }
예제 #52
0
        public void GenericApiSourceOfEntityContainerElementIsCorrect()
        {
            var api = new TestApi();
            var arguments = new object[0];

            var source = api.Source<string>("Test", arguments);
            Assert.Equal(typeof(string), source.ElementType);
            Assert.True(source.Expression is MethodCallExpression);
            var methodCall = source.Expression as MethodCallExpression;
            Assert.Null(methodCall.Object);
            Assert.Equal(typeof(DataSourceStubs), methodCall.Method.DeclaringType);
            Assert.Equal("Source", methodCall.Method.Name);
            Assert.Equal(typeof(string), methodCall.Method.GetGenericArguments()[0]);
            Assert.Equal(2, methodCall.Arguments.Count);
            Assert.True(methodCall.Arguments[0] is ConstantExpression);
            Assert.Equal("Test", (methodCall.Arguments[0] as ConstantExpression).Value);
            Assert.True(methodCall.Arguments[1] is ConstantExpression);
            Assert.Equal(arguments, (methodCall.Arguments[1] as ConstantExpression).Value);
            Assert.Equal(source.Expression.ToString(), source.ToString());
        }