public async Task Post_OpenEntityTypeWithNullComplexTypeProperty() { // Arrange const string Payload = "{" + "\"@odata.context\":\"http://localhost/odata/$metadata#OpenCustomers/$entity\"," + "\"CustomerId\":99,\"Name\":\"FirstName 99\"," + // special CustomerId to test the Address == null in the controller. "\"Address\": null," + "\"Website\": \"WebSite #6\"," + "\"[email protected]\":\"#String\",\"Place\":\"My Dynamic Place\"," + // odata.type is necessary, otherwise it will get an ODataUntypedValue "\"[email protected]\":\"#Guid\",\"Token\":\"2c1f450a-a2a7-4fe1-a25d-4d9332fc0694\"," + "\"[email protected]\":\"#Collection(Double)\"," + "\"DoubleList\":[5.5, 4.4, 3.3]" + "}"; const string RequestUri = "http://localhost/odata/SimpleOpenCustomers"; var controllers = new[] { typeof(SimpleOpenCustomersController) }; var server = TestServerFactory.Create(controllers, (config) => { config.MapODataServiceRoute("odata", "odata", GetEdmModel()); }); var client = TestServerFactory.CreateClient(server); // Act HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, RequestUri); request.Content = new StringContent(Payload); request.Content.Headers.ContentType = MediaTypeWithQualityHeaderValue.Parse("application/json"); HttpResponseMessage response = await client.SendAsync(request); // Assert Assert.True(response.IsSuccessStatusCode); }
public async Task Returns_400_Bad_Request_If_Upload_Length_Is_Invalid(string uploadLength, string expectedServerErrorMessage) { using var server = TestServerFactory.Create(Substitute.For <ITusStore, ITusCreationStore>()); var response = await server.CreateRequest("/files").AddTusResumableHeader().AddHeader("Upload-Length", uploadLength).PostAsync(); await response.ShouldBeErrorResponse(HttpStatusCode.BadRequest, expectedServerErrorMessage); }
public async Task No_UploadMetadata_Is_Saved_If_None_Is_Provided() { var tusStore = Substitute.For <ITusCreationStore, ITusStore>(); tusStore.CreateFileAsync(1, null, CancellationToken.None).ReturnsForAnyArgs("fileId"); var events = new Events { OnBeforeCreateAsync = ctx => { ctx.Metadata.ShouldNotBeNull(); ctx.Metadata.Keys.Count.ShouldBe(0); return(Task.FromResult(0)); } }; using var server = TestServerFactory.Create((ITusStore)tusStore, events); var response = await server .CreateRequest("/files") .AddTusResumableHeader() .AddHeader("Upload-Length", "1") .PostAsync(); response.StatusCode.ShouldBe(HttpStatusCode.Created); var createFileAsyncCall = tusStore .ReceivedCalls() .FirstOrDefault(f => f.GetMethodInfo().Name == nameof(tusStore.CreateFileAsync)); createFileAsyncCall.ShouldNotBeNull("No call to CreateFileAsync occurred."); // ReSharper disable once PossibleNullReferenceException createFileAsyncCall.GetArguments()[1].ShouldBe(null); }
public HighLevelTests(ITestOutputHelper outputHelper) { _outputHelper = outputHelper; var server = TestServerFactory.Create(outputHelper, LogLevel.Error); _client = server.CreateClient(); }
protected override IHttpClientFactory CreateRemoteSchemas( Dictionary <string, HttpClient> connections) { TestServer server = TestServerFactory.Create( SchemaBuilder.New() .AddDocumentFromString( "type Query { foo(a: String): String }") .AddResolver("Query", "foo", c => c.Argument <string>("a")) .Create(), new QueryMiddlewareOptions()); connections["someSchema"] = server.CreateClient(); var httpClientFactory = new Mock <IHttpClientFactory>(); httpClientFactory.Setup(t => t.CreateClient(It.IsAny <string>())) .Returns(new Func <string, HttpClient>(n => { if (connections.ContainsKey(n)) { return(connections[n]); } throw new Exception(); })); return(httpClientFactory.Object); }
public async Task Returns_460_Checksum_Mismatch_If_The_Checksum_Does_Not_Match(string methodToUse) { var store = Substitute.For <ITusStore, ITusChecksumStore>(); store = store.WithExistingFile("checksum", 10, 5); store.AppendDataAsync("checksum", Arg.Any <Stream>(), Arg.Any <CancellationToken>()).Returns(5); var checksumStore = (ITusChecksumStore)store; checksumStore.GetSupportedAlgorithmsAsync(CancellationToken.None).ReturnsForAnyArgs(new[] { "sha1" }); checksumStore.VerifyChecksumAsync(null, null, null, CancellationToken.None).ReturnsForAnyArgs(false); using (var server = TestServerFactory.Create(store)) { var response = await server .CreateTusResumableRequest("/files/checksum") .AddHeader("Upload-Offset", "5") .AddHeader("Upload-Checksum", "sha1 Kq5sNclPz7QV2+lfQIuc6R7oRu0=") .AddBody() .OverrideHttpMethodIfNeeded("PATCH", methodToUse) .SendAsync(methodToUse); await response.ShouldBeErrorResponse((HttpStatusCode)460, "Header Upload-Checksum does not match the checksum of the file"); response.ShouldContainTusResumableHeader(); } }
public async Task Requests_Return_404_NotFound_If_Upload_Expires_Header_Has_Expired(string methodToUse) { var store = Substitute.For <ITusStore, ITusExpirationStore>(); var expirationStore = (ITusExpirationStore)store; store.FileExistAsync(null, CancellationToken.None).ReturnsForAnyArgs(true); expirationStore.GetExpirationAsync(null, CancellationToken.None) .ReturnsForAnyArgs(DateTimeOffset.UtcNow.AddSeconds(-1)); using (var server = TestServerFactory.Create(app => { app.UseTus(c => new DefaultTusConfiguration { UrlPath = "/files", Store = store, Expiration = new AbsoluteExpiration(TimeSpan.FromSeconds(5)) }); })) { foreach (var method in new[] { "PUT", "DELETE", "HEAD" }) { var response = await server .CreateRequest("/files/expirationtestfile") .And(m => m.AddBody()) .AddTusResumableHeader() .OverrideHttpMethodIfNeeded(method, methodToUse) .SendAsync(methodToUse); response.StatusCode.ShouldBe(HttpStatusCode.NotFound); } } }
public async Task EnableQuery_Works_WithAutoExpanded(string queryString) { // Arrange string url = "http://localhost/odata/AutoExpandedCustomers"; Type[] controllers = new Type[] { typeof(AutoExpandedCustomersController) }; ODataModelBuilder builder = ODataConventionModelBuilderFactory.Create(); builder.EntitySet <AutoExpandedCustomer>("AutoExpandedCustomers"); IEdmModel model = builder.GetEdmModel(); var server = TestServerFactory.Create(controllers, (config) => { config.MapODataServiceRoute("odata", "odata", model); config.Count().OrderBy().Filter().Expand().MaxTop(null).Select(); }); HttpClient client = TestServerFactory.CreateClient(server); // Act HttpResponseMessage response = await client.GetAsync(url + queryString); string responseString = await response.Content.ReadAsStringAsync(); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Contains("1234", responseString); Assert.Contains("5678", responseString); }
[InlineData("GET", "http://localhost/Mary/NS.SpecialCustomer/NS.IsSpecialUpgraded()", "IsSpecialUpgraded")] // function bound to derived entity type public async Task AttriubteRoutingOnSingleton_SelectsExpectedControllerAndAction(string method, string requestUri, string expectedResult) { // Arrange CustomersModelWithInheritance model = new CustomersModelWithInheritance(); var controllers = new[] { typeof(MaryController), typeof(MaryOrdersController) }; var server = TestServerFactory.Create(controllers, (config) => { config.MapODataServiceRoute("odata", "", model.Model); }); HttpClient client = TestServerFactory.CreateClient(server); HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(method), requestUri); // Act var response = await client.SendAsync(request); // Assert if (!response.IsSuccessStatusCode) { Assert.False(true, await response.Content.ReadAsStringAsync()); } var result = await response.Content.ReadAsObject <AttributeRoutingTestODataResponse>(); Assert.Equal(expectedResult, result.Value); }
public async Task Request_Is_Cancelled_If_OnAuthorized_Fails_The_Request() { using (var server = TestServerFactory.Create(_mockTusConfiguration.Store, new Events { OnAuthorizeAsync = ctx => { ctx.FailRequest(HttpStatusCode.Unauthorized); return(Task.FromResult(0)); } })) { var response = await server .CreateRequest("/files/testfile") .AddTusResumableHeader() .SendAsync("HEAD"); response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); response.ShouldNotContainHeaders( "Tus-Resumable", "Tus-Version", "Tus-Extension", "Tus-Checksum-Algorithm", "Content-Type"); } }
public async Task Ignores_Request_If_Url_Does_Not_Match() { using (var server = TestServerFactory.Create(app => { app.UseTus(_ => _mockTusConfiguration); app.Use((_, __) => { _callForwarded = true; return(Task.FromResult(true)); }); })) { await server.CreateRequest("/files").AddTusResumableHeader().SendAsync("OPTIONS"); AssertForwardCall(false); await server.CreateRequest("/otherfiles").AddTusResumableHeader().SendAsync("OPTIONS"); AssertForwardCall(true); await server.CreateRequest("/files/testfile").AddTusResumableHeader().SendAsync("OPTIONS"); AssertForwardCall(true); } }
public async Task CanDispatch_ActionPayloadWithEntity_ToBoundAction_UnTyped() { // Arrange HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/UntypedCustomers/NS.MyAction"); request.Headers.Add("accept", "application/json"); var controllers = new[] { typeof(UntypedCustomersController) }; var server = TestServerFactory.Create(controllers, (config) => { config.MapODataServiceRoute("IgnoredRouteName", null, GetUntypeModel()); }); HttpClient client = TestServerFactory.CreateClient(server); request.Content = new StringContent(EntityPayload); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Act HttpResponseMessage response = await client.SendAsync(request); string responseString = await response.Content.ReadAsStringAsync(); // Assert Assert.True(response.IsSuccessStatusCode); Assert.Contains("\"@odata.context\":\"http://localhost/$metadata#Edm.Boolean\",\"value\":true", responseString); }
public async Task Get_OpenEntityTypeWithOrderbyAndFilter(string uri, int[] customerIds) { // Arrange var controllers = new[] { typeof(SimpleOpenCustomersController) }; var server = TestServerFactory.Create(controllers, (config) => { config.MapODataServiceRoute("odata", "odata", GetEdmModel()); }); var client = TestServerFactory.CreateClient(server); // Act HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;odata.metadata=full")); HttpResponseMessage response = await client.SendAsync(request); // Assert Assert.True(response.IsSuccessStatusCode); JObject result = JObject.Parse(await response.Content.ReadAsStringAsync()); var resultArray = result["value"] as JArray; Assert.Equal(2, resultArray.Count); for (var i = 0; i < customerIds.Length; i++) { Assert.Equal(customerIds[i], resultArray[i]["CustomerId"]); } }
public async Task Put_OpenEntityType() { // Arrange const string Payload = "{" + "\"CustomerId\":99,\"Name\":\"ChangedName\"," + "\"[email protected]\":\"#DateTimeOffset\",\"Token\":\"2014-01-01T00:00:00Z\"" + "}"; const string RequestUri = "http://localhost/odata/SimpleOpenCustomers(2)"; var controllers = new[] { typeof(SimpleOpenCustomersController) }; var server = TestServerFactory.Create(controllers, (config) => { config.MapODataServiceRoute("odata", "odata", GetEdmModel()); }); var client = TestServerFactory.CreateClient(server); // Act HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("Put"), RequestUri); request.Content = new StringContent(Payload); request.Content.Headers.ContentType = MediaTypeWithQualityHeaderValue.Parse("application/json"); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;odata.metadata=full")); HttpResponseMessage response = await client.SendAsync(request); // Assert Assert.True(response.IsSuccessStatusCode); Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); }
public async Task Returns_204_No_Content_If_Store_Supports_Checksum_But_No_Checksum_Is_Provided(string methodToUse) { var store = Substitute.For <ITusStore, ITusCreationStore, ITusChecksumStore>(); store.FileExistAsync("checksum", CancellationToken.None).ReturnsForAnyArgs(true); store.GetUploadOffsetAsync("checksum", Arg.Any <CancellationToken>()).Returns(5); store.GetUploadLengthAsync("checksum", Arg.Any <CancellationToken>()).Returns(10); store.AppendDataAsync("checksum", Arg.Any <Stream>(), Arg.Any <CancellationToken>()).Returns(5); // ReSharper disable once SuspiciousTypeConversion.Global var cstore = (ITusChecksumStore)store; cstore.GetSupportedAlgorithmsAsync(CancellationToken.None).ReturnsForAnyArgs(new[] { "sha1" }); cstore.VerifyChecksumAsync(null, null, null, CancellationToken.None).ReturnsForAnyArgs(true); using (var server = TestServerFactory.Create(store)) { var response = await server .CreateRequest("/files/checksum") .And(m => m.AddBody()) .AddTusResumableHeader() .AddHeader("Upload-Offset", "5") .OverrideHttpMethodIfNeeded("PATCH", methodToUse) .SendAsync(methodToUse); response.StatusCode.ShouldBe(HttpStatusCode.NoContent); response.ShouldContainTusResumableHeader(); } }
public async Task Response_Contains_The_Correct_Headers_On_Success(string methodToUse) { using (var server = TestServerFactory.Create(app => { var tusStore = Substitute.For <ITusCreationStore, ITusStore>(); tusStore.CreateFileAsync(1, null, CancellationToken.None).ReturnsForAnyArgs("fileId"); app.UseTus(request => new DefaultTusConfiguration { Store = (ITusStore)tusStore, UrlPath = "/files" }); })) { var response = await server .CreateRequest("/files") .AddTusResumableHeader() .AddHeader("Upload-Length", "1") .OverrideHttpMethodIfNeeded("POST", methodToUse) .SendAsync(methodToUse); response.ShouldContainTusResumableHeader(); response.Headers.Location.ToString().ShouldBe("/files/fileId"); response.Headers.Contains("Upload-Expires").ShouldBeFalse(); } }
public async Task Returns_400_Bad_Request_If_Checksum_Algorithm_Is_Not_Supported(string methodToUse) { var store = Substitute.For <ITusStore, ITusCreationStore, ITusChecksumStore>(); store = store.WithExistingFile("checksum", 10, 5); store.AppendDataAsync("checksum", Arg.Any <Stream>(), Arg.Any <CancellationToken>()).Returns(5); var checksumStore = (ITusChecksumStore)store; checksumStore.GetSupportedAlgorithmsAsync(CancellationToken.None).ReturnsForAnyArgs(new[] { "md5" }); using (var server = TestServerFactory.Create(store)) { var response = await server .CreateTusResumableRequest("/files/checksum") .AddHeader("Upload-Offset", "5") .AddHeader("Upload-Checksum", "sha1 Kq5sNclPz7QV2+lfQIuc6R7oRu0=") .AddBody() .OverrideHttpMethodIfNeeded("PATCH", methodToUse) .SendAsync(methodToUse); await response.ShouldBeErrorResponse(HttpStatusCode.BadRequest, "Unsupported checksum algorithm. Supported algorithms are: md5"); response.ShouldContainTusResumableHeader(); await store.DidNotReceive().FileExistAsync(null, CancellationToken.None); await store.DidNotReceive().GetUploadOffsetAsync("checksum", Arg.Any <CancellationToken>()); await store.DidNotReceive().AppendDataAsync("checksum", Arg.Any <Stream>(), Arg.Any <CancellationToken>()); } }
public async Task Returns_400_Bad_Request_If_UploadMetadata_Is_Empty() { // The Upload-Metadata request and response header MUST consist of one or more comma-separated key-value pairs. using (var server = TestServerFactory.Create(app => { var tusStore = Substitute.For <ITusCreationStore, ITusStore>(); tusStore.CreateFileAsync(1, null, CancellationToken.None).ReturnsForAnyArgs("fileId"); app.UseTus(request => new DefaultTusConfiguration { Store = (ITusStore)tusStore, UrlPath = "/files" }); })) { // Check empty header var response = await server .CreateRequest("/files") .AddTusResumableHeader() .AddHeader("Upload-Length", "1") .AddHeader("Upload-Metadata", "") .PostAsync(); response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); response.Content .ReadAsStringAsync() .Result .ShouldBe("Header Upload-Metadata must consist of one or more comma-separated key-value pairs"); } }
public async Task Patch_Requests_Contain_Upload_Expires_Header_For_Normal_Uploads_If_Expiration_Is_Configured(string methodToUse) { var store = Substitute.For <ITusStore, ITusExpirationStore>(); var expirationStore = (ITusExpirationStore)store; store.FileExistAsync(null, CancellationToken.None).ReturnsForAnyArgs(true); store.GetUploadLengthAsync(null, CancellationToken.None).ReturnsForAnyArgs(10); store.GetUploadOffsetAsync(null, CancellationToken.None).ReturnsForAnyArgs(3); expirationStore.GetExpirationAsync(null, CancellationToken.None).ReturnsForAnyArgs(DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(8))); using (var server = TestServerFactory.Create(app => { app.UseTus(request => new DefaultTusConfiguration { Store = store, UrlPath = "/files", Expiration = new AbsoluteExpiration(TimeSpan.FromMinutes(8)) }); })) { var response = await server .CreateRequest("/files/expirationtestfile") .And(m => m.AddBody()) .AddTusResumableHeader() .AddHeader("Upload-Offset", "3") .OverrideHttpMethodIfNeeded("PATCH", methodToUse) .SendAsync(methodToUse); response.StatusCode.ShouldBe(HttpStatusCode.NoContent); response.ShouldContainHeader("Upload-Expires", DateTime.UtcNow.Add(TimeSpan.FromMinutes(8)).ToString("r")); } }
public async Task Returns_400_Bad_Request_If_UploadMetadata_Contains_Values_That_Are_Not_Base64_Encoded() { // The key SHOULD be ASCII encoded and the value MUST be Base64 encoded using (var server = TestServerFactory.Create(app => { var tusStore = Substitute.For <ITusCreationStore, ITusStore>(); tusStore.CreateFileAsync(1, null, CancellationToken.None).ReturnsForAnyArgs("fileId"); app.UseTus(request => new DefaultTusConfiguration { Store = (ITusStore)tusStore, UrlPath = "/files" }); })) { // Check empty header var response = await server .CreateRequest("/files") .AddTusResumableHeader() .AddHeader("Upload-Length", "1") // Invalid base64, missing "==" at the end. .AddHeader("Upload-Metadata", "filename d29ybGRfZG9taW5hdGlvbl9wbGFuLnBkZg") .PostAsync(); response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); } }
public async Task Post_Requests_Contain_Upload_Expires_Header_For_Normal_Uploads_If_Expiration_Is_Configured(string methodToUse) { var store = Substitute.For <ITusStore, ITusCreationStore, ITusExpirationStore>(); var creationStore = (ITusCreationStore)store; store.FileExistAsync(null, CancellationToken.None).ReturnsForAnyArgs(false); creationStore.CreateFileAsync(-1, null, CancellationToken.None) .ReturnsForAnyArgs(Guid.NewGuid().ToString()); using (var server = TestServerFactory.Create(app => { app.UseTus(request => new DefaultTusConfiguration { Store = store, UrlPath = "/files", Expiration = new AbsoluteExpiration(TimeSpan.FromMinutes(10)) }); })) { var response = await server .CreateRequest("/files") .AddTusResumableHeader() .AddHeader("Upload-Length", "1") .OverrideHttpMethodIfNeeded("POST", methodToUse) .SendAsync(methodToUse); response.StatusCode.ShouldBe(HttpStatusCode.Created); response.ShouldContainHeader("Upload-Expires", DateTime.UtcNow.Add(TimeSpan.FromMinutes(10)).ToString("r")); } }
public async Task Returns_400_Bad_Request_Is_All_UploadMetadata_Keys_Are_Not_Unique() { // All keys MUST be unique. using (var server = TestServerFactory.Create(app => { var tusStore = Substitute.For <ITusCreationStore, ITusStore>(); tusStore.CreateFileAsync(1, null, CancellationToken.None).ReturnsForAnyArgs("fileId"); app.UseTus(request => new DefaultTusConfiguration { Store = (ITusStore)tusStore, UrlPath = "/files" }); })) { var response = await server .CreateRequest("/files") .AddTusResumableHeader() .AddHeader("Upload-Length", "1") .AddHeader("Upload-Metadata", "filename d29ybGRfZG9taW5hdGlvbl9wbGFuLnBkZg==,filename dHVzZG90bmV0X2RvbWluYXRpb25fcGxhbi5wZGY=") .PostAsync(); response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var message = await response.Content.ReadAsStringAsync(); message.ShouldBe("Header Upload-Metadata: Duplicate keys are not allowed"); } }
public async Task Ignores_Requests_Where_Method_Is_Not_Supported() { var callForwarded = false; using (var server = TestServerFactory.Create(app => { app.UseTus(request => { var tusConfiguration = Substitute.For <DefaultTusConfiguration>(); tusConfiguration.Store.Returns(Substitute.For <ITusStore>()); tusConfiguration.UrlPath.Returns("/files"); return(tusConfiguration); }); app.Use((ctx, next) => { callForwarded = true; return(Task.FromResult(true)); }); })) { await server .CreateRequest("/files") .AddTusResumableHeader() .GetAsync(); callForwarded.ShouldBeTrue(); callForwarded = false; await server .CreateRequest("/files/testfile") .AddTusResumableHeader() .GetAsync(); } }
public async Task Returns_400_Bad_Request_If_OnBeforeCreateAsync_Fails_The_Request(string method) { var store = Substitute.For <ITusCreationStore, ITusStore>(); var fileId = Guid.NewGuid().ToString(); store.CreateFileAsync(Arg.Any <long>(), Arg.Any <string>(), Arg.Any <CancellationToken>()).Returns(fileId); var events = new Events { OnBeforeCreateAsync = ctx => { ctx.FailRequest("The request failed with custom error message"); return(Task.FromResult(0)); } }; using (var server = TestServerFactory.Create((ITusStore)store, events)) { var response = await server.CreateRequest("/files") .AddTusResumableHeader() .AddHeader("Upload-Length", "1") .OverrideHttpMethodIfNeeded("POST", method) .SendAsync(method); await response.ShouldBeErrorResponse(HttpStatusCode.BadRequest, "The request failed with custom error message"); } }
public async Task Returns_400_Bad_Request_If_Upload_Length_Is_Not_Specified() { using var server = TestServerFactory.Create(Substitute.For <ITusStore, ITusCreationStore>()); var response = await server.CreateRequest("/files").AddTusResumableHeader().PostAsync(); await response.ShouldBeErrorResponse(HttpStatusCode.BadRequest, "Missing Upload-Length header"); }
public async Task OnAuthorized_Is_Called() { var onAuthorizeWasCalled = false; IntentType?intentProvidedToOnAuthorize = null; var store = Substitute.For <ITusCreationStore, ITusStore>(); store.CreateFileAsync(1, null, CancellationToken.None).ReturnsForAnyArgs("fileId"); using (var server = TestServerFactory.Create((ITusStore)store, new Events { OnAuthorizeAsync = ctx => { onAuthorizeWasCalled = true; intentProvidedToOnAuthorize = ctx.Intent; return(Task.FromResult(0)); } })) { var response = await server.CreateRequest("/files").AddTusResumableHeader().AddHeader("Upload-Length", "1").SendAsync("POST"); onAuthorizeWasCalled.ShouldBeTrue(); intentProvidedToOnAuthorize.ShouldBe(IntentType.CreateFile); } }
public async Task UploadMetadata_Is_Saved_If_Provided() { const string metadata = "filename d29ybGRfZG9taW5hdGlvbl9wbGFuLnBkZg==,othermeta c29tZSBvdGhlciBkYXRh"; var tusStore = Substitute.For <ITusCreationStore, ITusStore>(); tusStore.CreateFileAsync(1, null, CancellationToken.None).ReturnsForAnyArgs("fileId"); using var server = TestServerFactory.Create((ITusStore)tusStore); var response = await server .CreateRequest("/files") .AddTusResumableHeader() .AddHeader("Upload-Length", "1") .AddHeader("Upload-Metadata", metadata) .PostAsync(); response.StatusCode.ShouldBe(HttpStatusCode.Created); var createFileAsyncCall = tusStore .ReceivedCalls() .FirstOrDefault(f => f.GetMethodInfo().Name == nameof(tusStore.CreateFileAsync)); createFileAsyncCall.ShouldNotBeNull("No call to CreateFileAsync occurred."); // ReSharper disable once PossibleNullReferenceException createFileAsyncCall.GetArguments()[1].ShouldBe(metadata); }
public async Task Forwards_Calls_If_The_Store_Does_Not_Support_Creation() { using (var server = TestServerFactory.Create(app => { app.UseTus(request => new DefaultTusConfiguration { Store = Substitute.For <ITusStore>(), UrlPath = "/files", Events = new Events { OnAuthorizeAsync = ctx => { _onAuthorizeWasCalled = true; return(Task.FromResult(0)); } } }); app.Use((context, func) => { _callForwarded = true; return(Task.FromResult(true)); }); })) { await server.CreateRequest("/files").PostAsync(); AssertForwardCall(true); } }
public async Task Returns_400_Bad_Request_If_UploadMetadata_Is_In_An_Incorrect_Format_Using_AllowEmptyValues_Metadata_Parsing_Strategy(string uploadHeader, string expectedErrorMessage = "Header Upload-Metadata: The Upload-Metadata request and response header MUST consist of one or more comma - separated key - value pairs. The key and value MUST be separated by a space.The key MUST NOT contain spaces and commas and MUST NOT be empty. The key SHOULD be ASCII encoded and the value MUST be Base64 encoded. All keys MUST be unique. The value MAY be empty. In these cases, the space, which would normally separate the key and the value, MAY be left out.") { // The key and value MUST be separated by a space. // The key MUST NOT contain spaces and commas and MUST NOT be empty. // The value MAY be empty. // In these cases, the space, which would normally separate the key and the value, MAY be left out. var tusStore = Substitute.For <ITusCreationStore, ITusStore>(); tusStore.CreateFileAsync(1, null, CancellationToken.None).ReturnsForAnyArgs("fileId"); using var server = TestServerFactory.Create((ITusStore)tusStore, metadataParsingStrategy: MetadataParsingStrategy.AllowEmptyValues); // Check header with only a key and no value var response = await server .CreateRequest("/files") .AddTusResumableHeader() .AddHeader("Upload-Length", "1") .AddHeader("Upload-Metadata", uploadHeader) .PostAsync(); response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var message = await response.Content.ReadAsStringAsync(); message.ShouldBe(expectedErrorMessage); }
public async Task Get_OpenEntityTypeWithSelect() { // Arrange const string RequestUri = "http://localhost/odata/SimpleOpenCustomers?$select=Token"; var controllers = new[] { typeof(SimpleOpenCustomersController) }; var server = TestServerFactory.Create(controllers, (config) => { config.MapODataServiceRoute("odata", "odata", GetEdmModel()); }); var client = TestServerFactory.CreateClient(server); // Act HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, RequestUri); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;odata.metadata=full")); HttpResponseMessage response = await client.SendAsync(request); // Assert Assert.True(response.IsSuccessStatusCode); JObject result = JObject.Parse(await response.Content.ReadAsStringAsync()); var resultArray = result["value"] as JArray; Assert.Equal(6, resultArray.Count); Assert.NotNull(resultArray[2]["Token"]); //customer 2 has a token Assert.NotNull(resultArray[4]["Token"]); //customer 4 has a token }