public void Validate_DepthChecks(string expand, int maxExpansionDepth)
        {
            // Arrange
            SelectExpandQueryValidator validator = new SelectExpandQueryValidator(_queryContext.DefaultQuerySettings);
            SelectExpandQueryOption    selectExpandQueryOption = new SelectExpandQueryOption(null, expand, _queryContext);

            selectExpandQueryOption.LevelsMaxLiteralExpansionDepth = 1;

            // Act & Assert
            ExceptionAssert.Throws <ODataException>(
                () => validator.Validate(selectExpandQueryOption, new ODataValidationSettings {
                MaxExpansionDepth = maxExpansionDepth
            }),
                String.Format(CultureInfo.CurrentCulture, MaxExpandDepthExceededErrorString, maxExpansionDepth));

            ExceptionAssert.DoesNotThrow(
                () => validator.Validate(selectExpandQueryOption, new ODataValidationSettings {
                MaxExpansionDepth = maxExpansionDepth + 1
            }));
        }
Ejemplo n.º 2
0
        public void ReplaceInstanceToUnload()
        {
            updateResult = string.Empty;
            var c = MakeDriver();

            c.Singleton <TestStaticClass>();
            c.Make <TestStaticClass>();

            c.Instance <TestStaticClass>(null);

            var d = c.Make <IMonoDriver>() as MDriver;

            d.Update();
            Assert.AreEqual(string.Empty, updateResult);

            ExceptionAssert.DoesNotThrow(() =>
            {
                c.Release <TestStaticClass>();
            });
        }
Ejemplo n.º 3
0
        public void NoParamsHasTaskTest()
        {
            var timer = App.Instance.Make <ITimerManager>();
            var statu = 0;

            timer.MakeQueue(() =>
            {
                timer.Make(() =>
                {
                    statu++;
                });
            });

            ExceptionAssert.DoesNotThrow(() =>
            {
                RunTime(App.Instance, 1);
            });

            Assert.AreEqual(0, statu);
        }
Ejemplo n.º 4
0
        public async Task Can_Patch_Entity_In_Inheritance_DerivedEngine()
        {
            // Arrange
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("PATCH"), "http://localhost/PatchMotorcycle_When_Expecting_Motorcycle_DerivedEngine");

            request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
            AddRequestInfo(request);
            request.Content = new StringContent("{ 'CanDoAWheelie' : false, 'MyEngine' : {'@odata.type' : 'Microsoft.AspNet.OData.Test.Builder.TestModels.V4' ,'Hp':4000} }");
            request.Content.Headers.ContentType = MediaTypeWithQualityHeaderValue.Parse("application/json");

            // Act
            HttpResponseMessage response = await _client.SendAsync(request);

            // Assert
            ExceptionAssert.DoesNotThrow(() => response.EnsureSuccessStatusCode());

            dynamic result = JObject.Parse(await response.Content.ReadAsStringAsync());

            Assert.False((bool)result.CanDoAWheelie);
            Assert.Equal(4000, (int)result.MyEngine.Hp);
        }
Ejemplo n.º 5
0
        public async Task ExtensionResolver_ReturnsSameResult_ForCaseSensitiveAndCaseInsensitive(string queryOption, string caseInsensitive)
        {
            // Arrange
            HttpClient caseSensitiveclient   = new HttpClient(new HttpServer(GetQueryOptionConfiguration(caseInsensitive: true)));
            HttpClient caseInsensitiveclient = new HttpClient(new HttpServer(GetQueryOptionConfiguration(caseInsensitive: true)));

            // Act
            HttpResponseMessage response = await caseSensitiveclient.SendAsync(new HttpRequestMessage(
                                                                                   HttpMethod.Get, "http://localhost/query/ParserExtenstionCustomers?" + queryOption));

            ExceptionAssert.DoesNotThrow(() => response.EnsureSuccessStatusCode()); // Guard
            string caseSensitivePayload = await response.Content.ReadAsStringAsync();

            response = await caseInsensitiveclient.SendAsync(new HttpRequestMessage(
                                                                 HttpMethod.Get, "http://localhost/query/ParserExtenstionCustomers?" + caseInsensitive));

            ExceptionAssert.DoesNotThrow(() => response.EnsureSuccessStatusCode()); // Guard
            string caseInsensitivePayload = await response.Content.ReadAsStringAsync();

            // Assert
            Assert.Equal(caseSensitivePayload, caseInsensitivePayload);
        }
Ejemplo n.º 6
0
        public async Task Can_Post_DerivedType_To_Action_Expecting_BaseType_ForJsonLight()
        {
            // Arrange
            Stream body = await GetResponseStream("http://localhost/GetMotorcycleAsVehicle", "application/json;odata.metadata=minimal");

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/PostMotorcycle_When_Expecting_Vehicle");

            request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;odata.metadata=minimal"));
            AddRequestInfo(request);
            request.Content = new StreamContent(body);
            request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata.metadata=minimal");

            // Act
            HttpResponseMessage response = await _client.SendAsync(request);

            // Assert
            ExceptionAssert.DoesNotThrow(() => response.EnsureSuccessStatusCode());

            dynamic result = JObject.Parse(await response.Content.ReadAsStringAsync());

            ValidateMotorcycle(result);
        }
Ejemplo n.º 7
0
        public void TestSetSkip()
        {
            logLevel = string.Empty;
            var app    = DebuggerHelper.GetApplication(false);
            var logger = app.Make <ILogger>();

            ExceptionAssert.DoesNotThrow(() =>
            {
                (logger as Logger).SetSkip(0);
            });

            ExceptionAssert.DoesNotThrow(() =>
            {
                (logger as Logger).SetSkip(10, () =>
                {
                    var flag  = BindingFlags.Instance | BindingFlags.NonPublic;
                    var type  = logger.GetType();
                    var field = type.GetField("skipFrames", flag);
                    Assert.AreEqual(10, (int)field.GetValue(logger));
                });
            });
        }
Ejemplo n.º 8
0
        public void Conversions()
        {
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToBoolean(null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToByte(null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToChar(null));
            ExceptionAssert.DoesNotThrow(() => ((IConvertible)UnixTimestamp.MaxValue).ToDateTime(null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToDecimal(null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToDouble(null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToInt16(null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToInt32(null));
            ExceptionAssert.DoesNotThrow(() => ((IConvertible)UnixTimestamp.MaxValue).ToInt64(null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToSByte(null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToSingle(null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToString(null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToUInt16(null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToUInt32(null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToUInt64(null));

            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToType(typeof(bool), null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToType(typeof(byte), null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToType(typeof(char), null));
            ExceptionAssert.DoesNotThrow(() => ((IConvertible)UnixTimestamp.MaxValue).ToType(typeof(DateTime), null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToType(typeof(decimal), null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToType(typeof(double), null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToType(typeof(short), null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToType(typeof(int), null));
            ExceptionAssert.DoesNotThrow(() => ((IConvertible)UnixTimestamp.MaxValue).ToType(typeof(long), null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToType(typeof(sbyte), null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToType(typeof(Single), null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToType(typeof(string), null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToType(typeof(ushort), null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToType(typeof(uint), null));
            ExceptionAssert.Throws <InvalidCastException>(() => ((IConvertible)UnixTimestamp.MaxValue).ToType(typeof(ulong), null));

            Assert.AreEqual(((IConvertible)UnixTimestamp.MaxValue).GetTypeCode(), TypeCode.Object);

            Assert.IsInstanceOfType((UnixTimestamp)rawTimestamp, typeof(UnixTimestamp));
            Assert.IsInstanceOfType((long)UnixTimestamp.MaxValue, typeof(long));
        }
Ejemplo n.º 9
0
        public void TestAddRang()
        {
            var dict = new Dictionary <string, int>
            {
                { "1", 1 },
                { "2", 2 },
                { "3", 3 }
            };

            Dict.AddRange(dict, new Dictionary <string, int>
            {
                { "9", 9 },
                { "10", 10 }
            });

            ExceptionAssert.Throws(() =>
            {
                Dict.AddRange(dict, new Dictionary <string, int>
                {
                    { "9", 9 },
                    { "10", 10 }
                }, false);
            });

            Dict.AddRange(dict, new Dictionary <string, int>
            {
                { "10", 12 }
            });

            ExceptionAssert.DoesNotThrow(() =>
            {
                Dict.AddRange(dict, null);
            });

            Assert.AreEqual(true, dict.ContainsKey("9"));
            Assert.AreEqual(true, dict.ContainsKey("10"));
            Assert.AreEqual(12, dict["10"]);
        }
Ejemplo n.º 10
0
        public async Task ODataModelBinderProvider_Works_OtherParameters(string action, string parameterName, string parameterValue)
        {
            // Arrange
            HttpConfiguration configuration = new HttpConfiguration();

            configuration.Services.Replace(typeof(ModelBinderProvider), new ODataModelBinderProvider());
            configuration.MapODataServiceRoute("odata", "", GetEdmModel());

            var controllers = new[] { typeof(ODataModelBinderProviderTestODataController) };
            TestAssemblyResolver resolver = new TestAssemblyResolver(new MockAssembly(controllers));

            configuration.Services.Replace(typeof(IAssembliesResolver), resolver);

            HttpServer server = new HttpServer(configuration);
            HttpClient client = new HttpClient(server);

            // Act
            string url = String.Format("http://localhost/{0}({1}=@p)?@p={2}", action, parameterName, parameterValue);
            HttpResponseMessage response = await client.GetAsync(url);

            // Assert
            ExceptionAssert.DoesNotThrow(() => response.EnsureSuccessStatusCode());
        }
Ejemplo n.º 11
0
        public async Task NullCollectionProperties_SerializeAsEmpty_FromEntity(string propertyName)
        {
            // Arrange
            NullCollectionsTestsModel testObject = new NullCollectionsTestsModel();

            testObject.GetType().GetProperty(propertyName).SetValue(testObject, null);
            NullCollectionsTestsController.TestObject = testObject;

            // Act
            HttpRequestMessage  request  = new HttpRequestMessage(HttpMethod.Get, "http://localhost/NullCollectionsTests/");
            HttpResponseMessage response = await _client.SendAsync(request);

            // Assert
            ExceptionAssert.DoesNotThrow(() => response.EnsureSuccessStatusCode());
            string responseJson = await response.Content.ReadAsStringAsync();

            dynamic result = JToken.Parse(responseJson);

            Assert.NotNull(result[propertyName]);
            IEnumerable <JObject> collection = result[propertyName].Values <JObject>();

            Assert.Empty(collection);
        }
Ejemplo n.º 12
0
        public void ValidateSelectExpandQueryValidator_DoesNotThrow_DefaultLevelsMaxLiteralExpansionDepth(int maxExpansionDepth)
        {
            // Arrange
            string expand = "Parent($levels=1)";
            SelectExpandQueryValidator  validator = new SelectExpandQueryValidator();
            ODataConventionModelBuilder builder   = new ODataConventionModelBuilder();

            builder.EntitySet <ODataLevelsTest.LevelsEntity>("Entities");
            IEdmModel model   = builder.GetEdmModel();
            var       context = new ODataQueryContext(model, typeof(ODataLevelsTest.LevelsEntity));

            context.DefaultQuerySettings.EnableExpand = true;
            context.RequestContainer = new MockServiceProvider();
            var selectExpandQueryOption = new SelectExpandQueryOption(null, expand, context);

            // Act & Assert
            ExceptionAssert.DoesNotThrow(
                () => validator.Validate(
                    selectExpandQueryOption,
                    new ODataValidationSettings {
                MaxExpansionDepth = maxExpansionDepth
            }));
        }
Ejemplo n.º 13
0
        public async Task DollarFormat_Applies_IfPresent(string path, string mediaTypeFormat)
        {
            // Arrange
            MediaTypeHeaderValue expected = MediaTypeHeaderValue.Parse(mediaTypeFormat);
            string    url           = string.Format("http://localhost/{0}?$format={1}", path, mediaTypeFormat);
            IEdmModel model         = GetEdmModel();
            var       configuration = RoutingConfigurationFactory.CreateWithTypes(
                new[] { typeof(FormatCustomersController), typeof(ThisController) });
            HttpServer server = new HttpServer(configuration);
            HttpClient client = new HttpClient(server);

            configuration.MapODataServiceRoute("odata", routePrefix: null, model: model);

            // Act
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);

            request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
            HttpResponseMessage response = await client.SendAsync(request);

            // Assert
            ExceptionAssert.DoesNotThrow(() => response.EnsureSuccessStatusCode());
            Assert.Equal(expected, response.Content.Headers.ContentType);
        }
Ejemplo n.º 14
0
        public async Task QueryValidationErrors_Are_SentToTheClient()
        {
            HttpServer server = new HttpServer(InitializeConfiguration("QueryCompositionCustomerValidation", useCustomEdmModel: false));
            HttpClient client = new HttpClient(server);

            // skip = 1 is ok
            HttpResponseMessage response = await GetResponse(client, server.Configuration,
                                                             "http://localhost:8080/QueryCompositionCustomerValidation/?$skip=1");

            ExceptionAssert.DoesNotThrow(() => response.EnsureSuccessStatusCode());

            List <QueryCompositionCustomer> customers = await response.Content.ReadAsObject <List <QueryCompositionCustomer> >();

            Assert.Equal(new[] { 11, 22, 33 }, customers.Select(customer => customer.Id));

            // skip = 2 exceeds the limit
            response = await GetResponse(client, server.Configuration,
                                         "http://localhost:8080/QueryCompositionCustomerValidation/?$skip=2");

            // Assert
            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
            Assert.Contains("The limit of '1' for Skip query has been exceeded. The value from the incoming request is '2'.", await response.Content.ReadAsStringAsync());
        }
Ejemplo n.º 15
0
        public void TestWriteEntityReferenceLink_InJsonLight_WithEntityAndNavigationProperty_DoesNotThrow()
        {
            // Arrange
            IODataResponseMessage      response = CreateResponse();
            ODataMessageWriterSettings settings = CreateJsonLightSettings();
            IEdmModel model = CreateModel();
            ODataEntityReferenceLink link = new ODataEntityReferenceLink
            {
                Url = CreateFakeUri()
            };
            IEdmEntitySet entitySet = model.EntityContainer.EntitySets().First();

            Assert.NotNull(entitySet);
            IEdmNavigationProperty navigationProperty =
                model.EntityContainer.EntitySets().First().NavigationPropertyBindings.First().NavigationProperty;

            Assert.NotNull(navigationProperty);

            using (ODataMessageWriter writer = new ODataMessageWriter(response, settings, model))
            {
                // Act & Assert
                ExceptionAssert.DoesNotThrow(() => writer.WriteEntityReferenceLink(link));
            }
        }
Ejemplo n.º 16
0
        public void Validate_NoException_ForParameterAlias()
        {
            // Arrange
            IEdmModel         model     = GetEdmModel();
            IEdmEntityType    edmType   = model.SchemaElements.OfType <IEdmEntityType>().Single(t => t.Name == "LimitedEntity");
            IEdmEntitySet     entitySet = model.FindDeclaredEntitySet("Microsoft.AspNet.OData.Query.Validators.LimitedEntities");
            ODataQueryContext context   = new ODataQueryContext(model, edmType);

            OrderByQueryOption option = new OrderByQueryOption(
                "@p,@q desc",
                context,
                new ODataQueryOptionParser(
                    model,
                    edmType,
                    entitySet,
                    new Dictionary <string, string> {
                { "$orderby", "@p,@q desc" }, { "@p", "Id" }, { "@q", "RelatedEntity/Id" }
            }));

            ODataValidationSettings settings = new ODataValidationSettings();

            // Act & Assert
            ExceptionAssert.DoesNotThrow(() => _validator.Validate(option, settings));
        }
Ejemplo n.º 17
0
        public void Validate_DepthChecks_DollarLevels(string expand, int maxExpansionDepth)
        {
            // Arrange
            var validator = new SelectExpandQueryValidator(new DefaultQuerySettings {
                EnableExpand = true
            });
            var builder = ODataConventionModelBuilderFactory.Create();

            builder.EntitySet <ODataLevelsTest.LevelsEntity>("Entities");
            IEdmModel model   = builder.GetEdmModel();
            var       context = new ODataQueryContext(model, typeof(ODataLevelsTest.LevelsEntity));

            context.RequestContainer = new MockContainer();
            var selectExpandQueryOption = new SelectExpandQueryOption(null, expand, context);

            selectExpandQueryOption.LevelsMaxLiteralExpansionDepth = 1;

            // Act & Assert
            ExceptionAssert.Throws <ODataException>(
                () => validator.Validate(
                    selectExpandQueryOption,
                    new ODataValidationSettings {
                MaxExpansionDepth = maxExpansionDepth
            }),
                String.Format(
                    CultureInfo.CurrentCulture,
                    MaxExpandDepthExceededErrorString,
                    maxExpansionDepth));

            ExceptionAssert.DoesNotThrow(
                () => validator.Validate(
                    selectExpandQueryOption,
                    new ODataValidationSettings {
                MaxExpansionDepth = maxExpansionDepth + 1
            }));
        }
Ejemplo n.º 18
0
        public void ValidateDoesNotThrow_IfExpansionDepthIsZero_DollarLevels()
        {
            // Arrange
            string expand    = "Parent($expand=Parent($expand=Parent($levels=10)))";
            var    validator = new SelectExpandQueryValidator(new DefaultQuerySettings {
                EnableExpand = true
            });
            var builder = ODataConventionModelBuilderFactory.Create();

            builder.EntitySet <ODataLevelsTest.LevelsEntity>("Entities");
            IEdmModel model   = builder.GetEdmModel();
            var       context = new ODataQueryContext(model, typeof(ODataLevelsTest.LevelsEntity));

            context.RequestContainer = new MockContainer();
            var selectExpandQueryOption = new SelectExpandQueryOption(null, expand, context);

            // Act & Assert
            ExceptionAssert.DoesNotThrow(
                () => validator.Validate(
                    selectExpandQueryOption,
                    new ODataValidationSettings {
                MaxExpansionDepth = 0
            }));
        }
Ejemplo n.º 19
0
 public void Empty_Ctor_DoesnotThrow()
 {
     ExceptionAssert.DoesNotThrow(() => new ForeignKeyAttributeConvention());
 }
Ejemplo n.º 20
0
 public void EmptyPageResult_CanBeCreated()
 {
     ExceptionAssert.DoesNotThrow(() => new PageResult <string>(new string[] {}, null, 0));
 }
        public async Task SendAsync_CorrectlyCopiesHeadersToIndividualRequests(
            IEnumerable <string> batchPreferHeaderValues,
            string getRequest,
            string deleteRequest,
            string postRequest)
        {
            var batchRef               = $"batch_{Guid.NewGuid()}";
            var changesetRef           = $"changeset_{Guid.NewGuid()}";
            var endpoint               = "http://localhost/odata";
            var acceptJsonFullMetadata = "application/json;odata.metadata=minimal";
            var postPayload            = "Bar";

            Type[] controllers = new[] { typeof(BatchTestHeadersCustomersController) };
            var    builder     = new WebHostBuilder()
                                 .ConfigureServices(services =>
            {
                var builder = new ODataConventionModelBuilder();
                builder.EntitySet <BatchTestHeadersCustomer>("BatchTestHeadersCustomers");
                IEdmModel model = builder.GetEdmModel();
                services.AddOData(opt => opt.AddModel("odata", model, new DefaultODataBatchHandler()).Expand());
            })
                                 .Configure(app =>
            {
                ApplicationPartManager applicationPartManager = app.ApplicationServices.GetRequiredService <ApplicationPartManager>();
                applicationPartManager.ApplicationParts.Clear();

                if (controllers != null)
                {
                    AssemblyPart part = new AssemblyPart(new MockAssembly(controllers));
                    applicationPartManager.ApplicationParts.Add(part);
                }

                app.UseODataBatching();
                app.UseRouting();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            });

            var server = new TestServer(builder);
            var client = server.CreateClient();

            var batchRequest = new HttpRequestMessage(HttpMethod.Post, $"{endpoint}/$batch");

            batchRequest.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("multipart/mixed"));
            batchRequest.Headers.Add("Prefer", batchPreferHeaderValues);

            var batchContent = $@"
--{batchRef}
Content-Type: application/http
Content-Transfer-Encoding: binary

GET {endpoint}/BatchTestHeadersCustomers HTTP/1.1
OData-Version: 4.0
OData-MaxVersion: 4.0
Accept: application/json;odata.metadata=minimal
Accept-Charset: UTF-8


--{batchRef}
Content-Type: application/http
Content-Transfer-Encoding: binary

DELETE {endpoint}/BatchTestHeadersCustomers(1) HTTP/1.1
OData-Version: 4.0
OData-MaxVersion: 4.0
Accept: application/json;odata.metadata=minimal
Accept-Charset: UTF-8
Prefer: wait=100,handling=lenient


--{batchRef}
Content-Type: application/http
Content-Transfer-Encoding: binary

POST {endpoint}/BatchTestHeadersCustomers HTTP/1.1
OData-Version: 4.0;NetFx
OData-MaxVersion: 4.0;NetFx
Content-Type: text/plain; charset=utf-8
Content-Length: {postPayload.Length}
Accept: {acceptJsonFullMetadata}
Accept-Charset: UTF-8

{postPayload}
--{batchRef}--
";

            var httpContent = new StringContent(batchContent);

            httpContent.Headers.ContentType   = MediaTypeHeaderValue.Parse($"multipart/mixed; boundary={batchRef}");
            httpContent.Headers.ContentLength = batchContent.Length;
            batchRequest.Content = httpContent;
            var response = await client.SendAsync(batchRequest);

            ExceptionAssert.DoesNotThrow(() => response.EnsureSuccessStatusCode());
            var responseContent = await response.Content.ReadAsStringAsync();

            Assert.Contains(getRequest, responseContent);
            Assert.Contains(deleteRequest, responseContent);
            Assert.Contains(postRequest, responseContent);
        }
        public async Task SendAsync_Works_ForBatchRequestWithInsertedEntityReferencedInAnotherRequest()
        {
            // Arrange
            var builder = new WebHostBuilder()
                          .ConfigureServices(services =>
            {
                services.ConfigureControllers(typeof(BatchTestCustomersController), typeof(BatchTestOrdersController));
                var builder = new ODataConventionModelBuilder();
                builder.EntitySet <BatchTestCustomer>("BatchTestCustomers");
                builder.EntitySet <BatchTestOrder>("BatchTestOrders");
                IEdmModel model = builder.GetEdmModel();
                services.AddOData(opt => opt.AddModel("odata", model, new DefaultODataBatchHandler()).Expand());
            })
                          .Configure(app =>
            {
                app.UseODataBatching();
                app.UseRouting();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            });

            var server = new TestServer(builder);

            const string acceptJsonFullMetadata = "application/json;odata.metadata=minimal";
            const string acceptJson             = "application/json";

            var client = server.CreateClient();

            var endpoint = "http://localhost/odata";

            var batchRef     = $"batch_{Guid.NewGuid()}";
            var changesetRef = $"changeset_{Guid.NewGuid()}";

            var orderId            = 2;
            var createOrderPayload = $@"{{""@odata.type"":""Microsoft.AspNetCore.OData.Test.Batch.BatchTestOrder"",""Id"":{orderId},""Amount"":50}}";
            var createRefPayload   = @"{""@odata.id"":""$3""}";

            var batchRequest = new HttpRequestMessage(HttpMethod.Post, $"{endpoint}/$batch");

            batchRequest.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("multipart/mixed"));
            StringContent httpContent = new StringContent($@"
--{batchRef}
Content-Type: multipart/mixed; boundary={changesetRef}

--{changesetRef}
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 3

POST {endpoint}/BatchTestOrders HTTP/1.1
OData-Version: 4.0;NetFx
OData-MaxVersion: 4.0;NetFx
Content-Type: {acceptJsonFullMetadata}
Accept: {acceptJsonFullMetadata}
Accept-Charset: UTF-8

{createOrderPayload}
--{changesetRef}
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 4

POST {endpoint}/BatchTestCustomers(2)/Orders/$ref HTTP/1.1
OData-Version: 4.0;NetFx
OData-MaxVersion: 4.0;NetFx
Content-Type: {acceptJsonFullMetadata}
Accept: {acceptJsonFullMetadata}
Accept-Charset: UTF-8

{createRefPayload}
--{changesetRef}--
--{batchRef}--
");

            httpContent.Headers.ContentType = MediaTypeHeaderValue.Parse($"multipart/mixed; boundary={batchRef}");
            batchRequest.Content            = httpContent;

            // Act
            var response = await client.SendAsync(batchRequest);

            // Assert
            ExceptionAssert.DoesNotThrow(() => response.EnsureSuccessStatusCode());

            HttpRequestMessage customerRequest = new HttpRequestMessage(HttpMethod.Get, $"{endpoint}/BatchTestCustomers(2)?$expand=Orders");

            customerRequest.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(acceptJson));

            var customerResponse = client.SendAsync(customerRequest).Result;
            var objAsJsonString  = await customerResponse.Content.ReadAsStringAsync();

            var customer = JsonConvert.DeserializeObject <BatchTestCustomer>(objAsJsonString);

            Assert.NotNull(customer.Orders?.SingleOrDefault(d => d.Id.Equals(orderId)));
        }
 public void DefaultCtor()
 {
     ExceptionAssert.DoesNotThrow(() => new DataContractAttributeEdmTypeConvention());
 }
Ejemplo n.º 24
0
        public async Task SendAsync_CorrectlyCopiesHeadersToIndividualRequests(
            IEnumerable <string> batchPreferHeaderValues,
            string getRequest,
            string deleteRequest,
            string postRequest)
        {
            var batchRef               = $"batch_{Guid.NewGuid()}";
            var changesetRef           = $"changeset_{Guid.NewGuid()}";
            var endpoint               = "http://localhost";
            var acceptJsonFullMetadata = "application/json;odata.metadata=minimal";
            var postPayload            = "Bar";

            Type[] controllers = new[] { typeof(BatchTestHeadersCustomersController) };
            var    server      = TestServerFactory.Create(controllers, (config) =>
            {
                var builder = ODataConventionModelBuilderFactory.Create(config);
                builder.EntitySet <BatchTestHeadersCustomer>("BatchTestHeadersCustomers");

                config.MapODataServiceRoute("odata", null, builder.GetEdmModel(), new DefaultODataBatchHandler());
                config.Expand();
                config.EnableDependencyInjection();
            });

            var client = TestServerFactory.CreateClient(server);

            var batchRequest = new HttpRequestMessage(HttpMethod.Post, $"{endpoint}/$batch");

            batchRequest.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("multipart/mixed"));
            batchRequest.Headers.Add("Prefer", batchPreferHeaderValues);

            var batchContent = $@"
--{batchRef}
Content-Type: application/http
Content-Transfer-Encoding: binary

GET {endpoint}/BatchTestHeadersCustomers HTTP/1.1
OData-Version: 4.0
OData-MaxVersion: 4.0
Accept: application/json;odata.metadata=minimal
Accept-Charset: UTF-8


--{batchRef}
Content-Type: application/http
Content-Transfer-Encoding: binary

DELETE {endpoint}/BatchTestHeadersCustomers(1) HTTP/1.1
OData-Version: 4.0
OData-MaxVersion: 4.0
Accept: application/json;odata.metadata=minimal
Accept-Charset: UTF-8
Prefer: wait=100,handling=lenient


--{batchRef}
Content-Type: application/http
Content-Transfer-Encoding: binary

POST {endpoint}/BatchTestHeadersCustomers HTTP/1.1
OData-Version: 4.0;NetFx
OData-MaxVersion: 4.0;NetFx
Content-Type: text/plain; charset=utf-8
Content-Length: {postPayload.Length}
Accept: {acceptJsonFullMetadata}
Accept-Charset: UTF-8

{postPayload}
--{batchRef}--
";

            var httpContent = new StringContent(batchContent);

            httpContent.Headers.ContentType   = MediaTypeHeaderValue.Parse($"multipart/mixed; boundary={batchRef}");
            httpContent.Headers.ContentLength = batchContent.Length;
            batchRequest.Content = httpContent;
            var response = await client.SendAsync(batchRequest);

            ExceptionAssert.DoesNotThrow(() => response.EnsureSuccessStatusCode());
            var responseContent = await response.Content.ReadAsStringAsync();

            Assert.Contains(getRequest, responseContent);
            Assert.Contains(deleteRequest, responseContent);
            Assert.Contains(postRequest, responseContent);
        }
 public void EmptyCtor_DoesnotThrow()
 {
     ExceptionAssert.DoesNotThrow(() => new ODataSerializerContext());
 }
 public void Empty_Ctor_DoesnotThrow()
 {
     ExceptionAssert.DoesNotThrow(() => new IgnoreDataMemberAttributeEdmPropertyConvention());
 }
Ejemplo n.º 27
0
 public void AllowedFunctions_SetToAllFunctions_DoesNotThrow()
 {
     ExceptionAssert.DoesNotThrow(() => new ODataValidationSettings().AllowedFunctions = AllowedFunctions.AllFunctions);
 }
Ejemplo n.º 28
0
 public void Ctor_DoesnotThrows_IfPropertyIsDateTime(Type type)
 {
     ExceptionAssert.DoesNotThrow(() => new ComplexTypeConfiguration(Mock.Of <ODataModelBuilder>(), type));
 }
Ejemplo n.º 29
0
        public async Task SendAsync_CorrectlyHandlesCookieHeader()
        {
            var batchRef     = $"batch_{Guid.NewGuid()}";
            var changesetRef = $"changeset_{Guid.NewGuid()}";
            var endpoint     = "http://localhost";

            Type[] controllers = new[] { typeof(BatchTestCustomersController), typeof(BatchTestOrdersController) };

            var builder = new WebHostBuilder()
                          .ConfigureServices(services =>
            {
                var builder = new ODataConventionModelBuilder();
                builder.EntitySet <BatchTestOrder>("BatchTestOrders");
                IEdmModel model = builder.GetEdmModel();
                services.AddOData(opt => opt.AddModel(model, new DefaultODataBatchHandler()).Expand());
            })
                          .Configure(app =>
            {
                ApplicationPartManager applicationPartManager = app.ApplicationServices.GetRequiredService <ApplicationPartManager>();
                applicationPartManager.ApplicationParts.Clear();

                if (controllers != null)
                {
                    AssemblyPart part = new AssemblyPart(new MockAssembly(controllers));
                    applicationPartManager.ApplicationParts.Add(part);
                }

                app.UseODataBatching();
                app.UseRouting();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            });

            var server = new TestServer(builder);
            var client = server.CreateClient();

            var orderId            = 2;
            var createOrderPayload = $@"{{""@odata.type"":""Microsoft.AspNetCore.OData.Test.Batch.BatchTestOrder"",""Id"":{orderId},""Amount"":50}}";

            var batchRequest = new HttpRequestMessage(HttpMethod.Post, $"{endpoint}/$batch");

            batchRequest.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("text/plain"));

            // Add cookie (for example IdentityServer adds antiforgery after login)
            batchRequest.Headers.TryAddWithoutValidation("Cookie", ".AspNetCore.Antiforgery.9TtSrW0hzOs=" + Guid.NewGuid());

            var batchContent = $@"
--{batchRef}
Content-Type: multipart/mixed;boundary={changesetRef}

--{changesetRef}
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 1

POST {endpoint}/BatchTestOrders HTTP/1.1
Content-Type: application/json;type=entry
Prefer: return=representation

{createOrderPayload}
--{changesetRef}--
--{batchRef}
Content-Type: application/http
Content-Transfer-Encoding: binary

GET {endpoint}/BatchTestOrders({orderId}) HTTP/1.1
Content-Type: application/json;type=entry
Prefer: return=representation

--{batchRef}--
";

            var httpContent = new StringContent(batchContent);

            httpContent.Headers.ContentType   = MediaTypeHeaderValue.Parse($"multipart/mixed;boundary={batchRef}");
            httpContent.Headers.ContentLength = batchContent.Length;
            batchRequest.Content = httpContent;
            var response = await client.SendAsync(batchRequest);

            ExceptionAssert.DoesNotThrow(() => response.EnsureSuccessStatusCode());

            // TODO: assert somehow?
        }
Ejemplo n.º 30
0
        public async Task SendAsync_CorrectlyHandlesCookieHeader()
        {
            var batchRef     = $"batch_{Guid.NewGuid()}";
            var changesetRef = $"changeset_{Guid.NewGuid()}";
            var endpoint     = "http://localhost";

            Type[] controllers = new[] { typeof(BatchTestCustomersController), typeof(BatchTestOrdersController), };
            var    server      = TestServerFactory.Create(controllers, (config) =>
            {
                var builder = ODataConventionModelBuilderFactory.Create(config);
                builder.EntitySet <BatchTestOrder>("BatchTestOrders");

                config.MapODataServiceRoute("odata", null, builder.GetEdmModel(), new DefaultODataBatchHandler());
                config.Expand();
                config.EnableDependencyInjection();
            });

            var client = TestServerFactory.CreateClient(server);

            var orderId            = 2;
            var createOrderPayload = $@"{{""@odata.type"":""Microsoft.AspNet.OData.Test.Batch.BatchTestOrder"",""Id"":{orderId},""Amount"":50}}";

            var batchRequest = new HttpRequestMessage(HttpMethod.Post, $"{endpoint}/$batch");

            batchRequest.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("text/plain"));

            // Add cookie (for example IdentityServer adds antiforgery after login)
            batchRequest.Headers.TryAddWithoutValidation("Cookie", ".AspNetCore.Antiforgery.9TtSrW0hzOs=" + Guid.NewGuid());

            var batchContent = $@"
--{batchRef}
Content-Type: multipart/mixed;boundary={changesetRef}

--{changesetRef}
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 1

POST {endpoint}/BatchTestOrders HTTP/1.1
Content-Type: application/json;type=entry
Prefer: return=representation

{createOrderPayload}
--{changesetRef}--
--{batchRef}
Content-Type: application/http
Content-Transfer-Encoding: binary

GET {endpoint}/BatchTestOrders({orderId}) HTTP/1.1
Content-Type: application/json;type=entry
Prefer: return=representation

--{batchRef}--
";

            var httpContent = new StringContent(batchContent);

            httpContent.Headers.ContentType   = MediaTypeHeaderValue.Parse($"multipart/mixed;boundary={batchRef}");
            httpContent.Headers.ContentLength = batchContent.Length;
            batchRequest.Content = httpContent;
            var response = await client.SendAsync(batchRequest);

            ExceptionAssert.DoesNotThrow(() => response.EnsureSuccessStatusCode());

            // TODO: assert somehow?
        }