Пример #1
0
 public async Task StartupMissing_Fallback()
 {
     var builder = CreateWebHostBuilder();
     var serverFactory = new TestServerFactory();
     var engine = builder.UseServer(serverFactory).UseStartup("MissingStartupAssembly").Build();
     using (engine.Start())
     {
         await AssertResponseContains(serverFactory.Application, "MissingStartupAssembly");
     }
 }
Пример #2
0
 public async Task StartupCtorThrows_Fallback()
 {
     var builder = CreateWebHostBuilder();
     var serverFactory = new TestServerFactory();
     var engine = builder.UseServer(serverFactory).UseStartup<StartupCtorThrows>().Build();
     using (engine.Start())
     {
         await AssertResponseContains(serverFactory.Application, "Exception from constructor");
     }
 }
Пример #3
0
 public async Task IApplicationLifetimeRegisteredEvenWhenStartupCtorThrows_Fallback()
 {
     var builder = CreateWebHostBuilder();
     var serverFactory = new TestServerFactory();
     var engine = builder.UseServer(serverFactory).UseStartup<StartupCtorThrows>().Build();
     using (engine.Start())
     {
         var service = engine.ApplicationServices.GetService<IApplicationLifetime>();
         Assert.NotNull(service);
         await AssertResponseContains(serverFactory.Application, "Exception from constructor");
     }
 }
Пример #4
0
        public void Open(Action<IAppBuilder> startup, StartOptions options)
        {
            var testAppLoaderProvider = new TestAppLoaderFactory(startup);
            var testServerFactory = new TestServerFactory();

            IServiceProvider services = ServicesFactory.Create(container => container.AddInstance<IAppLoaderFactory>(testAppLoaderProvider));
            var engine = services.GetService<IHostingEngine>();
            var context = new StartContext(options ?? new StartOptions());
            context.ServerFactory = new ServerFactoryAdapter(testServerFactory);
            _started = engine.Start(context);
            _invoke = testServerFactory.Invoke;
        }
Пример #5
0
        public async Task Returns_409_Conflict_For_A_Patch_Request_If_A_Delete_Is_Ongoing()
        {
            var fileId = Guid.NewGuid().ToString();

            using (var server = TestServerFactory.Create(app =>
            {
                var store = Substitute.For <ITusStore, ITusTerminationStore>();
                store.FileExistAsync(fileId, Arg.Any <CancellationToken>()).Returns(true);
                ((ITusTerminationStore)store).DeleteFileAsync(fileId, Arg.Any <CancellationToken>()).Returns(info =>
                {
                    Thread.Sleep(500);
                    return(Task.FromResult(0));
                });

                app.UseTus(request => new DefaultTusConfiguration
                {
                    Store = store,
                    UrlPath = "/files"
                });
            }))
            {
                var deleteRequest = server.CreateRequest($"/files/{fileId}")
                                    .AddTusResumableHeader()
                                    .SendAsync("DELETE");

                var patchRequest = server.CreateRequest($"/files/{fileId}")
                                   .And(message =>
                {
                    message.Content = new StreamContent(new MemoryStream(new byte[3]));
                    message.Content.Headers.ContentType =
                        new MediaTypeHeaderValue("application/offset+octet-stream");
                })
                                   .AddHeader("Upload-Offset", "0")
                                   .AddTusResumableHeader()
                                   .SendAsync("PATCH");

                await Task.WhenAll(deleteRequest, patchRequest);

                deleteRequest.Result.StatusCode.ShouldBe(HttpStatusCode.NoContent);
                patchRequest.Result.StatusCode.ShouldBe(HttpStatusCode.Conflict);
            }
        }
Пример #6
0
        public async Task OnCreateCompleteAsync_Receives_FileConcatFinal_For_Final_Files(string methodToUse)
        {
            var store       = Substitute.For <ITusStore, ITusCreationStore, ITusConcatenationStore>();
            var concatStore = (ITusConcatenationStore)store;

            store.FileExistAsync("partial1", Arg.Any <CancellationToken>()).Returns(true);
            store.FileExistAsync("partial2", Arg.Any <CancellationToken>()).Returns(true);
            store.GetUploadLengthAsync("partial1", Arg.Any <CancellationToken>()).Returns(10);
            store.GetUploadLengthAsync("partial2", Arg.Any <CancellationToken>()).Returns(20);
            store.GetUploadOffsetAsync("partial1", Arg.Any <CancellationToken>()).Returns(10);
            store.GetUploadOffsetAsync("partial2", Arg.Any <CancellationToken>()).Returns(20);
            concatStore.GetUploadConcatAsync("partial1", Arg.Any <CancellationToken>()).Returns(new FileConcatPartial());
            concatStore.GetUploadConcatAsync("partial2", Arg.Any <CancellationToken>()).Returns(new FileConcatPartial());
            concatStore.CreateFinalFileAsync(null, null, Arg.Any <CancellationToken>())
            .ReturnsForAnyArgs("finalId");

            FileConcat fileConcat = null;
            var        events     = new Events
            {
                OnCreateCompleteAsync = ctx =>
                {
                    fileConcat = ctx.FileConcatenation;
                    return(Task.FromResult(0));
                }
            };

            using (var server = TestServerFactory.Create(store, events))
            {
                var response = await server
                               .CreateRequest("/files")
                               .AddTusResumableHeader()
                               .AddHeader("Upload-Concat", "final;/files/partial1 /files/partial2")
                               .OverrideHttpMethodIfNeeded("POST", methodToUse)
                               .SendAsync(methodToUse);

                response.StatusCode.ShouldBe(HttpStatusCode.Created);
                fileConcat.ShouldBeOfType <FileConcatFinal>();
                var fileConcatFinal = (FileConcatFinal)fileConcat;
                fileConcatFinal.Files.Length.ShouldBe(2);
                fileConcatFinal.Files.All(f => f == "partial1" || f == "partial2").ShouldBeTrue();
            }
        }
Пример #7
0
        public async Task Get_OpenEntityType(bool enableNullDynamicProperty)
        {
            // Arrange
            const string RequestUri = "http://localhost/odata/SimpleOpenCustomers(9)";

            var controllers = new[] { typeof(SimpleOpenCustomersController) };

            var server = TestServerFactory.Create(controllers, (config) =>
            {
                config.SetSerializeNullDynamicProperty(enableNullDynamicProperty);
                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());

            Assert.Equal("http://localhost/odata/$metadata#SimpleOpenCustomers/Microsoft.AspNet.OData.Test.Common.SimpleVipCustomer/$entity", result["@odata.context"]);
            Assert.Equal("#Microsoft.AspNet.OData.Test.Common.SimpleVipCustomer", result["@odata.type"]);
            Assert.Equal(9, result["CustomerId"]);
            Assert.Equal("VipCustomer", result["Name"]);
            Assert.Equal("#Collection(Int32)", result["*****@*****.**"]);
            Assert.Equal(new JArray(new[] { 200, 100, 300, 0, 400 }), result["ListProp"]);
            Assert.Equal("0001-01-01", result["DateList"][0]);
            Assert.Equal("9999-12-31", result["DateList"][1]);
            if (enableNullDynamicProperty)
            {
                Assert.NotNull(result["Receipt"]);
                Assert.Equal(JValue.CreateNull(), result["Receipt"]);
            }
            else
            {
                Assert.Null(result["Receipt"]);
            }
        }
Пример #8
0
        public ODataAuthorizationTest()
        {
            var model = TestModel.GetModelWithPermissions();

            var controllers = new[]
            {
                typeof(ProductsController),
                typeof(MyProductController),
                typeof(RoutingCustomersController),
                typeof(VipCustomerController),
                typeof(SalesPeopleController),
                typeof(TodoItemController),
                typeof(IncidentsController),
                typeof(IncidentGroupsController)
            };

            var server = TestServerFactory.CreateWithEndpointRouting(controllers, endpoints =>
            {
                endpoints.MapODataRoute("odata", "odata", model);
            }, services =>
            {
                services.AddODataAuthorization((options) =>
                {
                    options.ScopesFinder = (context) =>
                    {
                        var permissions = context.User?.FindAll("Permission").Select(p => p.Value);
                        return(Task.FromResult(permissions ?? Enumerable.Empty <string>()));
                    };

                    options.ConfigureAuthentication("AuthScheme")
                    .AddScheme <CustomAuthOptions, CustomAuthHandler>("AuthScheme", options => { });
                });

                services.AddRouting();
            }, app =>
            {
                app.UseAuthentication();
                app.UseODataAuthorization();
            });

            _client = TestServerFactory.CreateClient(server);
        }
Пример #9
0
        public async Task GetMetadata_WithStreamProperty()
        {
            // Arrange
            const string RequestUri = "http://localhost/odata/$metadata";

            var controllers = new[] { typeof(MetadataController) };
            var server      = TestServerFactory.Create(controllers, (config) =>
            {
                config.MapODataServiceRoute("odata", "odata", GetEdmModel());
            });
            var client = TestServerFactory.CreateClient(server);

            // Act
            HttpResponseMessage response = await client.GetAsync(RequestUri);

            // Assert
            var payload = await response.Content.ReadAsStringAsync();

            Assert.Contains("<Property Name=\"Photo\" Type=\"Edm.Stream\" />", payload);
        }
Пример #10
0
        public async Task Returns_400_Bad_Request_For_Missing_Upload_Offset_Header()
        {
            using (var server = TestServerFactory.Create(app =>
            {
                app.UseTus(request => new DefaultTusConfiguration
                {
                    Store = Substitute.For <ITusStore>(),
                    UrlPath = "/files"
                });
            }))
            {
                var response = await server
                               .CreateRequest("/files/testfile")
                               .And(m => m.AddBody())
                               .AddTusResumableHeader()
                               .SendAsync("patch");

                await response.ShouldBeErrorResponse(HttpStatusCode.BadRequest, "Missing Upload-Offset header");
            }
        }
Пример #11
0
        public async Task Response_Contains_The_Correct_Headers_On_Success(string methodToUse)
        {
            var store = Substitute.For <ITusStore>().WithExistingFile("testfile", uploadLength: 10, uploadOffset: 5);

            store.AppendDataAsync("testfile", Arg.Any <Stream>(), Arg.Any <CancellationToken>()).Returns(5);

            using (var server = TestServerFactory.Create(store))
            {
                var response = await server
                               .CreateTusResumableRequest("/files/testfile")
                               .AddHeader("Upload-Offset", "5")
                               .AddBody()
                               .OverrideHttpMethodIfNeeded("PATCH", methodToUse)
                               .SendAsync(methodToUse);

                response.ShouldContainTusResumableHeader();
                response.ShouldContainHeader("Upload-Offset", "10");
                response.ShouldNotContainHeaders("Upload-Expires");
            }
        }
Пример #12
0
        public async Task Returns_400_Bad_Request_For_Invalid_Upload_Offset_Header(string uploadOffset,
                                                                                   string expectedServerErrorMessage)
        {
            var store = Substitute.For <ITusStore>().WithExistingFile("testfile");

            using (var server = TestServerFactory.Create(store))
            {
                var response = await server
                               .CreateTusResumableRequest("/files/testfile")
                               .AddBody()
                               .AddHeader("Upload-Offset", uploadOffset)
                               .SendAsync("patch");

                await
                response.ShouldBeErrorResponse(HttpStatusCode.BadRequest,
                                               string.IsNullOrEmpty(expectedServerErrorMessage)
                                               ? "Could not parse Upload-Offset header"
                                               : expectedServerErrorMessage);
            }
        }
Пример #13
0
        public async Task Returns_404_Not_Found_If_File_Was_Not_Found()
        {
            using (var server = TestServerFactory.Create(app =>
            {
                app.UseTus(request => new DefaultTusConfiguration
                {
                    Store = Substitute.For <ITusStore>(),
                    UrlPath = "/files"
                });
            }))
            {
                var response = await server
                               .CreateRequest("/files/testfile")
                               .AddTusResumableHeader()
                               .SendAsync("HEAD");

                response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
                response.ShouldContainTusResumableHeader();
            }
        }
Пример #14
0
        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

            var tusStore = Substitute.For <ITusCreationStore, ITusStore>();

            tusStore.CreateFileAsync(1, null, CancellationToken.None).ReturnsForAnyArgs("fileId");

            using var server = TestServerFactory.Create((ITusStore)tusStore);
            // 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 UploadLength_Must_Not_Be_Changed_Once_Set(string methodToUse)
        {
            var store = Substitute.For <ITusStore, ITusCreationStore, ITusCreationDeferLengthStore>();

            store.FileExistAsync(null, CancellationToken.None).ReturnsForAnyArgs(true);
            store.GetUploadLengthAsync(null, CancellationToken.None).ReturnsForAnyArgs(100);

            using (var server = TestServerFactory.Create(store))
            {
                var response = await server.CreateRequest($"/files/{Guid.NewGuid()}")
                               .AddTusResumableHeader()
                               .AddHeader("Upload-Length", "10")
                               .OverrideHttpMethodIfNeeded("PATCH", methodToUse)
                               .And(m => m.AddBody())
                               .SendAsync(methodToUse);

                await response.ShouldBeErrorResponse(HttpStatusCode.BadRequest,
                                                     "Upload-Length cannot be updated once set");
            }
        }
        public async Task Head_Returns_UploadDeferLength_If_No_UploadLength_Has_Been_Set(string methodToUse)
        {
            var store = Substitute.For <ITusStore, ITusCreationStore, ITusCreationDeferLengthStore>();

            store.FileExistAsync(null, CancellationToken.None).ReturnsForAnyArgs(true);
            store.GetUploadLengthAsync(null, CancellationToken.None).ReturnsForAnyArgs((long?)null);

            using (var server = TestServerFactory.Create(store))
            {
                var response = await server
                               .CreateRequest($"/files/{Guid.NewGuid()}")
                               .AddTusResumableHeader()
                               .OverrideHttpMethodIfNeeded("HEAD", methodToUse)
                               .SendAsync(methodToUse);

                response.StatusCode.ShouldBe(HttpStatusCode.OK);
                response.ShouldContainHeader("Upload-Defer-Length", "1");
                response.Headers.Contains("Upload-Length").ShouldBeFalse();
            }
        }
Пример #17
0
        public async Task Returns_Store_Exceptions_As_400_Bad_Request()
        {
            // This test does not work properly using the OWIN TestServer.
            // It will always throw an exception instead of returning the proper error message to the client.

            var store = Substitute.For <ITusStore>().WithExistingFile("testfile", uploadLength: 10, uploadOffset: 5);

            store.AppendDataAsync("testfile", Arg.Any <Stream>(), Arg.Any <CancellationToken>())
            .Throws(new TusStoreException("Test exception"));

            using var server = TestServerFactory.Create(store);
            var response = await server
                           .CreateTusResumableRequest("/files/testfile")
                           .AddHeader("Upload-Offset", "5")
                           .AddBody()
                           .SendAsync("PATCH");

            response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
            response.Content.ReadAsStringAsync().Result.ShouldBe("Test exception");
        }
Пример #18
0
        public async Task Response_Contains_The_Correct_Headers_On_Success(string methodToUse)
        {
            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")
                               .OverrideHttpMethodIfNeeded("POST", methodToUse)
                               .SendAsync(methodToUse);

                response.ShouldContainTusResumableHeader();
                response.Headers.Location.ToString().ShouldBe("/files/fileId");
                response.Headers.Contains("Upload-Expires").ShouldBeFalse();
            }
        }
Пример #19
0
        public async Task Partial_File_Can_Be_Created(string methodToUse)
        {
            var store       = CreateStoreForPartialFileConcatenation(returnThisPartialFileIdOnCreate: "partial1");
            var concatStore = (ITusConcatenationStore)store;

            using (var server = TestServerFactory.Create(store))
            {
                var response = await server
                               .CreateRequest("/files")
                               .AddTusResumableHeader()
                               .AddHeader("Upload-Length", "1")
                               .AddHeader("Upload-Concat", "partial")
                               .OverrideHttpMethodIfNeeded("POST", methodToUse)
                               .SendAsync(methodToUse);

                response.StatusCode.ShouldBe(HttpStatusCode.Created);
                response.ShouldContainHeader("location", "/files/partial1");
                await concatStore.Received().CreatePartialFileAsync(1, null, Arg.Any <CancellationToken>());
            }
        }
Пример #20
0
        private static HttpClient GetClient(TimeZoneInfo timeZoneInfo)
        {
            var controllers = new[] { typeof(MetadataController), typeof(DateTimeModelsController) };

            var server = TestServerFactory.Create(controllers, (config) =>
            {
                config.Count().OrderBy().Filter().Expand().MaxTop(null).Select();
                if (timeZoneInfo != null)
                {
                    config.SetTimeZoneInfo(timeZoneInfo);
                }
                else
                {
                    config.SetTimeZoneInfo(TimeZoneInfo.Local);
                }
                config.MapODataServiceRoute("odata", "odata", GetEdmModel());
            });

            return(TestServerFactory.CreateClient(server));
        }
Пример #21
0
        public async Task No_Data_Is_Written_And_201_Created_Is_Returned_With_Upload_Offset_Zero_If_OnAuthorizeAsync_Fails_For_Write_File_Intent(string uploadConcatHeader)
        {
            var fileId   = Guid.NewGuid().ToString("n");
            var tusStore = MockStoreHelper.CreateWithExtensions <ITusCreationStore, ITusConcatenationStore>();

            var tusCreationStore = (ITusCreationStore)tusStore;

            tusCreationStore.CreateFileAsync(1, null, CancellationToken.None).ReturnsForAnyArgs(fileId);

            var tusConcatenationStore = (ITusConcatenationStore)tusStore;

            tusConcatenationStore.CreatePartialFileAsync(1, null, CancellationToken.None).ReturnsForAnyArgs(fileId);

            var events = new Events
            {
                OnAuthorizeAsync = authorizeContext =>
                {
                    if (authorizeContext.Intent == IntentType.WriteFile)
                    {
                        authorizeContext.FailRequest(HttpStatusCode.Forbidden);
                    }

                    return(Task.FromResult(0));
                }
            };

            using (var server = TestServerFactory.Create(tusStore, events))
            {
                var response = await server
                               .CreateTusResumableRequest("/files")
                               .AddHeader("Upload-Length", "100")
                               .AddHeaderIfNotEmpty("Upload-Concat", uploadConcatHeader)
                               .AddBody()
                               .PostAsync();

                response.StatusCode.ShouldBe(HttpStatusCode.Created);
                response.ShouldContainHeader("Upload-Offset", "0");

                await tusStore.DidNotReceiveWithAnyArgs().AppendDataAsync(fileId, Arg.Any <Stream>(), Arg.Any <CancellationToken>());
            }
        }
Пример #22
0
        public ODataRoutingTest()
        {
            var model = ODataRoutingModel.GetModel();

            var controllers = new[]
            {
                typeof(DateTimeOffsetKeyCustomersController),
                typeof(MetadataController),
                typeof(RoutingCustomersController),
                typeof(ProductsController),
                typeof(EnumCustomersController),
                typeof(DestinationsController),
                typeof(IncidentsController),
                typeof(NotFoundWithIdCustomersController),
                typeof(NotFoundCustomersController),
                typeof(AttributeCustomersController)
            };

            // Separate clients and servers so routes are not ambiguous.
            var nullPrefixServer = TestServerFactory.Create(controllers, (config) =>
            {
                config.MapODataServiceRoute("NullPrefixRoute", null, model);
            });

            _nullPrefixClient = TestServerFactory.CreateClient(nullPrefixServer);

            // FixedPrefixRoute has both a non-empty virtual path root and a fixed route prefix.
            var fixedPrefixServer = TestServerFactory.Create(controllers, (config) =>
            {
                config.MapODataServiceRoute("FixedPrefixRoute", "MyRoot/odata", model);
            });

            _fixedPrefixClient = TestServerFactory.CreateClient(fixedPrefixServer);

            var parameterizedPrefixServer = TestServerFactory.Create(controllers, (config) =>
            {
                config.MapODataServiceRoute("ParameterizedPrefixRoute", "{a}", model);
            });

            _parameterizedPrefixClient = TestServerFactory.CreateClient(parameterizedPrefixServer);
        }
Пример #23
0
        public async Task Response_Contains_The_Correct_Headers_On_Success(string methodToUse)
        {
            using (var server = TestServerFactory.Create(app => app.UseTus(request => _mockTusConfiguration)))
            {
                var response = await server
                               .CreateRequest("/files")
                               .OverrideHttpMethodIfNeeded("OPTIONS", methodToUse)
                               .SendAsync(methodToUse);

                response.ShouldContainHeader("Tus-Resumable", "1.0.0");
                response.ShouldContainHeader("Tus-Version", "1.0.0");
                response.ShouldContainHeader("Tus-Extension", "creation,termination,checksum,concatenation,expiration,creation-defer-length");
                response.ShouldContainHeader("Tus-Checksum-Algorithm", "sha1");
            }

            // Test again but with a store that does not implement ITusCreationStore.
            using (var server = TestServerFactory.Create(app =>
            {
                app.UseTus(request => new DefaultTusConfiguration
                {
                    Store = Substitute.For <ITusStore>(),
                    UrlPath = "/files"
                });
            }))
            {
                var response = await server.CreateRequest("/files").SendAsync("OPTIONS");

                response.Headers.Contains("Tus-Resumable").ShouldBeTrue();
                var tusResumable = response.Headers.GetValues("Tus-Resumable").ToList();
                tusResumable.Count.ShouldBe(1);
                tusResumable[0].ShouldBe("1.0.0");

                response.Headers.Contains("Tus-Version").ShouldBeTrue();
                var tusVersion = response.Headers.GetValues("Tus-Version").ToList();
                tusVersion.Count.ShouldBe(1);
                tusVersion[0].ShouldBe("1.0.0");

                // Store does not implement any extensions.
                response.Headers.Contains("Tus-Extension").ShouldBeFalse();
            }
        }
        public async Task UploadLength_Must_Be_Included_In_Patch_Request_If_UploadDeferLength_Has_Been_Set(
            string methodToUse)
        {
            var store = Substitute.For <ITusStore, ITusCreationStore, ITusCreationDeferLengthStore>();

            store.FileExistAsync(null, CancellationToken.None).ReturnsForAnyArgs(true);
            store.GetUploadLengthAsync(null, CancellationToken.None).ReturnsForAnyArgs((long?)null);

            using (var server = TestServerFactory.Create(store))
            {
                var response = await server.CreateRequest($"/files{Guid.NewGuid()}")
                               .AddTusResumableHeader()
                               .AddHeader("Upload-Offset", "0")
                               .OverrideHttpMethodIfNeeded("PATCH", methodToUse)
                               .And(m => m.AddBody())
                               .SendAsync(methodToUse);

                await response.ShouldBeErrorResponse(HttpStatusCode.BadRequest,
                                                     "Header Upload-Length must be specified as this file was created using Upload-Defer-Length");
            }
        }
Пример #25
0
        public async Task Returns_415_Unsupported_Media_Type_If_An_Incorrect_Content_Type_Is_Provided(string contentType)
        {
            var store = Substitute.For <ITusStore>().WithExistingFile("testfile");

            using var server = TestServerFactory.Create(store);
            var requestBuilder = server
                                 .CreateTusResumableRequest("/files/testfile")
                                 .AddHeader("Upload-Offset", "0");

            if (contentType != null)
            {
                requestBuilder = requestBuilder.AddBody(contentType);
            }

            var response = await requestBuilder.SendAsync("PATCH");

            await response.ShouldBeErrorResponse(HttpStatusCode.UnsupportedMediaType,
                                                 $"Content-Type {contentType} is invalid. Must be application/offset+octet-stream");

            response.ShouldContainTusResumableHeader();
        }
Пример #26
0
        public async Task Returns_400_Bad_Request_If_Any_Partial_File_Is_Not_Complete(string methodToUse)
        {
            var store = MockStoreHelper.CreateWithExtensions <ITusCreationStore, ITusConcatenationStore>();

            store
            .WithExistingPartialFile("partial1", 10, 10)
            .WithExistingPartialFile("partial2", 20, 15);

            using (var server = TestServerFactory.Create(store))
            {
                var response = await server
                               .CreateRequest("/files")
                               .AddTusResumableHeader()
                               .AddHeader("Upload-Concat", "final;/files/partial1 /files/partial2")
                               .OverrideHttpMethodIfNeeded("POST", methodToUse)
                               .SendAsync(methodToUse);

                await response.ShouldBeErrorResponse(HttpStatusCode.BadRequest,
                                                     "Some of the files supplied for concatenation are not finished and can not be concatenated: partial2");
            }
        }
        public async Task No_Data_Is_Written_And_201_Created_Is_Returned_If_Request_Body_Is_Empty()
        {
            var fileId           = Guid.NewGuid().ToString("n");
            var tusStore         = Substitute.For <ITusStore, ITusCreationStore>();
            var tusCreationStore = (ITusCreationStore)tusStore;

            tusCreationStore.CreateFileAsync(1, null, CancellationToken.None).ReturnsForAnyArgs(fileId);

            using (var server = TestServerFactory.Create(tusStore))
            {
                var response = await server
                               .CreateTusResumableRequest("/files")
                               .AddHeader("Upload-Length", "100")
                               .SendAsync("POST");

                response.StatusCode.ShouldBe(HttpStatusCode.Created);
                response.ShouldNotContainHeaders("Upload-Offset");

                await tusStore.DidNotReceiveWithAnyArgs().AppendDataAsync(fileId, Arg.Any <Stream>(), Arg.Any <CancellationToken>());
            }
        }
        public async Task Returns_400_BadRequest_If_UploadDeferLength_Is_Not_One(string methodToUse)
        {
            var invalidDeferLengthValues = new[] { "2", Guid.NewGuid().ToString(), "hello world" };

            var store = Substitute.For <ITusStore, ITusCreationStore, ITusCreationDeferLengthStore>();

            using (var server = TestServerFactory.Create(store))
            {
                foreach (var deferLength in invalidDeferLengthValues)
                {
                    var response = await server.CreateRequest("/files")
                                   .AddTusResumableHeader()
                                   .OverrideHttpMethodIfNeeded("POST", methodToUse)
                                   .AddHeader("Upload-Defer-Length", deferLength)
                                   .SendAsync(methodToUse);

                    await response.ShouldBeErrorResponse(HttpStatusCode.BadRequest,
                                                         "Header Upload-Defer-Length must have the value '1' or be omitted");
                }
            }
        }
Пример #29
0
        public async Task Configuration_Is_Validated_On_Each_Request()
        {
            var tusConfiguration = Substitute.For <ITusConfiguration>();

            // Empty configuration
            using (var server = TestServerFactory.Create(app =>
            {
                // ReSharper disable once AccessToModifiedClosure
                app.UseTus(request => tusConfiguration);
            }))
            {
                // ReSharper disable once AccessToDisposedClosure
                await AssertRequests(server);
            }

            // Configuration with only Store specified
            tusConfiguration = Substitute.For <ITusConfiguration>();
            tusConfiguration.Store.Returns(Substitute.For <ITusStore>());
            using (var server = TestServerFactory.Create(app =>
            {
                // ReSharper disable once AccessToModifiedClosure
                app.UseTus(request => tusConfiguration);
            }))
            {
                // ReSharper disable once AccessToDisposedClosure
                await AssertRequests(server);
            }

            tusConfiguration = Substitute.For <ITusConfiguration>();
            tusConfiguration.UrlPath.Returns("/files");
            tusConfiguration.Store.Returns((ITusStore)null);
            using (var server = TestServerFactory.Create(app =>
            {
                app.UseTus(request => tusConfiguration);
            }))
            {
                // ReSharper disable once AccessToDisposedClosure
                await AssertRequests(server);
            }
        }
Пример #30
0
        public EnableNestedPathsTest()
        {
            _deserializerProvider    = ODataDeserializerProviderFactory.Create();
            _resourceSetDeserializer = new ODataResourceSetDeserializer(_deserializerProvider);
            _resourceDeserializer    = new ODataResourceDeserializer(_deserializerProvider);
            _primitiveDeserializer   = new ODataPrimitiveDeserializer();

            ODataModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            builder.EntitySet <EnableNestedPathsCustomer>("EnableNestedPathsCustomers");
            builder.EntitySet <EnableNestedPathsProduct>("EnableNestedPathsProducts");
            builder.Singleton <EnableNestedPathsCustomer>("EnableNestedPathsTopCustomer");
            builder.EntityType <EnableNestedPathsVipCustomer>();

            builder.EntityType <EnableNestedPathsVipCustomer>()
            .Function("GetMostPurchasedProduct")
            .ReturnsFromEntitySet <EnableNestedPathsProduct>("EnableNestedPathsProduct");

            builder.EntityType <EnableNestedPathsProduct>()
            .Collection
            .Action("SetDiscountRate");

            _model = builder.GetEdmModel();

            Type[] controllers = new Type[] {
                typeof(EnableNestedPathsCustomersController),
                typeof(EnableNestedPathsProductsController),
                typeof(EnableNestedPathsTopCustomerController)
            };

            _server = TestServerFactory.Create(controllers, (config) =>
            {
                config.MapODataServiceRoute("odata", "odata", _model);
                config.Count().OrderBy().Filter().Expand().MaxTop(null).Select();
            });

            _client = TestServerFactory.CreateClient(_server);

            _db = new EnableNestedPathsDatabase();
        }
Пример #31
0
        public async Task Ignores_Requests_Without_The_Tus_Resumable_Header()
        {
            var callForwarded = false;

            using (var server = TestServerFactory.Create(app =>
            {
                app.UseTus(request =>
                {
                    var tusConfiguration = Substitute.For <ITusConfiguration>();
                    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").SendAsync("POST");

                callForwarded.ShouldBeTrue();
                callForwarded = false;
                await server.CreateRequest("/files/testfile").SendAsync("HEAD");

                callForwarded.ShouldBeTrue();
                callForwarded = false;
                await server.CreateRequest("/files").SendAsync("POST");

                callForwarded.ShouldBeTrue();
                callForwarded = false;

                // OPTIONS requests ignore the Tus-Resumable header according to spec.
                await server.CreateRequest("/files").SendAsync("OPTIONS");

                callForwarded.ShouldBeFalse();
            }
        }
Пример #32
0
        public TestEnvironmentBase(TestEnvironmentArgs args = null)
        {
            if (args == null)
            {
                args = new TestEnvironmentArgs();
            }

            if (args.FullUri == null && args.HostName == null)
            {
                args.HostName = "127.0.0.1";
            }

            string uri = args.FullUri != null ? args.FullUri : new Uri($"{(args.UseHttps ? "https" : "http")}://{args.HostName}:{args.Port}/").ToString();

            if (args.UseProxyBasedDependencyManager == true)
            {
                DefaultDependencyManager.Current = new AutofacTestDependencyManager();

                TestDependencyManager.CurrentTestDependencyManager.AutoProxyCreationIncludeRules.AddRange(args.AutoProxyCreationIncludeRules.Union(new Func <TypeInfo, bool>[]
                {
                    serviceType => GetType().GetTypeInfo().Assembly == serviceType.Assembly
                }));

                TestDependencyManager.CurrentTestDependencyManager.AutoProxyCreationIgnoreRules.AddRange(args.AutoProxyCreationIgnoreRules);
            }

            DefaultDependenciesManagerProvider.Current = args.CustomDependenciesManagerProvider ?? DependenciesManagerProviderBuilder(args);
            DefaultAppEnvironmentProvider.Current      = args.CustomAppEnvironmentProvider ?? AppEnvironmentProviderBuilder(args);

            if (args.UseRealServer == true)
            {
                Server = TestServerFactory.GetSelfHostTestServer();
            }
            else
            {
                Server = TestServerFactory.GetEmbeddedTestServer();
            }

            Server.Initialize(uri);
        }
Пример #33
0
        public async Task Post_Requests_Contain_Upload_Expires_Header_For_Partial_Uploads_If_Expiration_Is_Configured(
            string methodToUse)
        {
            var store = (ITusStore)Substitute.For(new[]
            {
                typeof(ITusStore),
                typeof(ITusCreationStore),
                typeof(ITusConcatenationStore),
                typeof(ITusExpirationStore)
            },
                                                  new object[0]
                                                  );
            var concatenationStore = (ITusConcatenationStore)store;

            //store.FileExistAsync(null, CancellationToken.None).ReturnsForAnyArgs(false);
            concatenationStore.CreatePartialFileAsync(-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")
                               .AddHeader("Upload-Concat", "partial")
                               .OverrideHttpMethodIfNeeded("POST", methodToUse)
                               .SendAsync(methodToUse);

                response.StatusCode.ShouldBe(HttpStatusCode.Created);
                response.ShouldContainHeader("Upload-Expires", DateTime.UtcNow.Add(TimeSpan.FromMinutes(10)).ToString("r"));
            }
        }
Пример #34
0
        public ODataFunctionTests()
        {
            DefaultODataPathHandler pathHandler = new DefaultODataPathHandler();
            var controllers = new[] { typeof(MetadataController), typeof(FCustomersController) };
            var model       = GetUnTypedEdmModel();
            var server      = TestServerFactory.Create(controllers, (configuration) =>
            {
                // without attribute routing
                configuration.MapODataServiceRoute("odata1", "odata", model, pathHandler, ODataRoutingConventions.CreateDefault());

                // only with attribute routing
                IList <IODataRoutingConvention> routingConventions = new List <IODataRoutingConvention>
                {
#if NETCORE
                    new AttributeRoutingConvention("odata2", configuration.ServiceProvider, pathHandler)
#else
                    new AttributeRoutingConvention("odata2", configuration)
#endif
                };

                configuration.MapODataServiceRoute("odata2", "attribute", model, pathHandler, routingConventions);
            });