Xunit.Assert.True(System.Nullable, string)

Here are the examples of the csharp api Xunit.Assert.True(System.Nullable, string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1803 Examples 7

19 View Source File : SendFileResponseExtensionsTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public void SendFileSupport()
        {
            IOwinResponse response = new OwinResponse();
            replacedert.False(response.SupportsSendFile());
            // response.Set("sendfile.SendAsync", new Object());
            // replacedert.False(response.SupportsSendFile()); // Get<type> throw for type mismatch.
            response.Set("sendfile.SendAsync", new Func<string, long, long?, CancellationToken, Task>((_, __, ___, ____) => Task.FromResult(0)));
            replacedert.True(response.SupportsSendFile());
        }

19 View Source File : ResponseHeadersTests.cs
License : Apache License 2.0
Project Creator : aspnet

public void SetCustomResponseHeader(IAppBuilder app)
        {
            app.Run(context =>
            {
                replacedert.False(context.Response.Headers.ContainsKey("custom"));
                context.Response.Headers["custom"] = "custom value";
                replacedert.True(context.Response.Headers.ContainsKey("custom"));
                context.Response.StatusCode = ExpectedStatusCode;
                return Task.FromResult(0);
            });
        }

19 View Source File : IfRangeTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory, Trait("FunctionalTests", "General")]
        [InlineData(HostType.HttpListener)]
        public void Static_ValidIfRange(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var applicationUrl = deployer.Deploy(hostType, ValidIfRangeConfiguration);
                var httpClient = new HttpClient() { BaseAddress = new Uri(applicationUrl) };

                var fileContent = File.ReadAllBytes(@"RequirementFiles/Dir1/RangeRequest.txt");

                var response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);

                //Range with 500 bytes starting at 0 with a conditional Etag. 
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(0, 499);
                httpClient.DefaultRequestHeaders.IfRange = new RangeConditionHeaderValue(response.Headers.ETag.Tag);
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.PartialContent, response.StatusCode);
                replacedert.True(response.Content.Headers.ContentRange.HasRange &&
                    response.Content.Headers.ContentRange.Unit == "bytes" && response.Content.Headers.ContentRange.Length == fileContent.Length &&
                    response.Content.Headers.ContentRange.From == 0 && response.Content.Headers.ContentRange.To == 499);
                replacedert.Equal<long?>(500, response.Content.Headers.ContentLength);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 0, 499);

                //Range with 500 bytes starting at 0 with an invalid Etag - Range header is ignored if If-Range evalutates to false.
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(0, 499);
                httpClient.DefaultRequestHeaders.IfRange = new RangeConditionHeaderValue("\"invalidEtag\"");
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
                replacedert.Equal<long?>(fileContent.Length, response.Content.Headers.ContentLength);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 0, fileContent.Length - 1);

                //Range with 500 bytes starting at 0 with a If-Range date = lastmodified
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(0, 499);
                httpClient.DefaultRequestHeaders.IfRange = new RangeConditionHeaderValue(response.Content.Headers.LastModified.Value);
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.PartialContent, response.StatusCode);
                replacedert.True(response.Content.Headers.ContentRange.HasRange &&
                    response.Content.Headers.ContentRange.Unit == "bytes" && response.Content.Headers.ContentRange.Length == fileContent.Length &&
                    response.Content.Headers.ContentRange.From == 0 && response.Content.Headers.ContentRange.To == 499);
                replacedert.Equal<long?>(500, response.Content.Headers.ContentLength);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 0, 499);

                //Range with 500 bytes starting at 0 with a If-Range date > Lastmodified
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(0, 499);
                httpClient.DefaultRequestHeaders.IfRange = new RangeConditionHeaderValue(response.Content.Headers.LastModified.Value.Add(new TimeSpan(10 * 1000)));
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.PartialContent, response.StatusCode);
                replacedert.True(response.Content.Headers.ContentRange.HasRange &&
                    response.Content.Headers.ContentRange.Unit == "bytes" && response.Content.Headers.ContentRange.Length == fileContent.Length &&
                    response.Content.Headers.ContentRange.From == 0 && response.Content.Headers.ContentRange.To == 499);
                replacedert.Equal<long?>(500, response.Content.Headers.ContentLength);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 0, 499);

                //Range with 500 bytes starting at 0 with a If-Range date < lastmodified
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(0, 499);
                httpClient.DefaultRequestHeaders.IfRange = new RangeConditionHeaderValue(response.Content.Headers.LastModified.Value.Subtract(new TimeSpan(10 * 1000)));
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
                replacedert.Equal<long?>(fileContent.Length, response.Content.Headers.ContentLength);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 0, fileContent.Length - 1);

                //Range with 500 bytes starting at 0 with a If-Range date which is invalid
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(0, 499);
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("If-Range", "InvalidDate");
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
                replacedert.Equal<long?>(fileContent.Length, response.Content.Headers.ContentLength);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 0, fileContent.Length - 1);

                //-0. Range is not satisfiable, but the If-Range evaluated to partial content, then we expect full content. 
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(null, 0);
                httpClient.DefaultRequestHeaders.IfRange = new RangeConditionHeaderValue(response.Content.Headers.LastModified.Value.Add(new TimeSpan(10 * 1000)));
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.RequestedRangeNotSatisfiable, response.StatusCode);
                replacedert.Equal<long?>(0, response.Content.Headers.ContentLength);
                replacedert.Equal<string>("bytes */2543", response.Content.Headers.ContentRange.ToString());
            }
        }

19 View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public async Task OwinHttpListenerResponse_NoWrite_OnSendingHeaders()
        {
            OwinHttpListener listener = CreateServer(
                env =>
                {
                    env["owin.ResponseStatusCode"] = 200;
                    env["owin.ResponseReasonPhrase"] = "Custom";
                    var responseStream = env.Get<Stream>("owin.ResponseBody");

                    var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");

                    env.Get<Action<Action<object>, object>>("server.OnSendingHeaders")(state =>
                    {
                        env["owin.ResponseStatusCode"] = 201;
                        env["owin.ResponseReasonPhrase"] = "Custom1";
                        responseHeaders["custom-header"] = new string[] { "customvalue" };
                    }, null);

                    responseHeaders["content-length"] = new string[] { "0" };
                    return Task.FromResult(0);
                },
                HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(HttpClientAddress);
                replacedert.Equal(HttpStatusCode.Created, response.StatusCode);
                replacedert.Equal("Custom1", response.ReasonPhrase);
                replacedert.Equal(3, response.Headers.Count()); // Date, Server
                replacedert.True(response.Headers.Date.HasValue);
                replacedert.Equal(1, response.Headers.Server.Count);
                replacedert.Equal("customvalue", response.Headers.GetValues("custom-header").First());
                replacedert.Equal(0, (await response.Content.ReadAsByteArrayAsync()).Length);
            }
        }

19 View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public async Task OwinHttpListenerResponse_HeadRequestWithContentLength_Success()
        {
            OwinHttpListener listener = CreateServer(env =>
            {
                var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
                responseHeaders["Content-Length"] = new string[] { "10" };
                return Task.FromResult(0);
            }, HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, HttpClientAddress);
                HttpResponseMessage response = await client.SendAsync(request);
                replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
                replacedert.Equal("OK", response.ReasonPhrase);
                replacedert.Equal(2, response.Headers.Count());
                replacedert.False(response.Headers.TransferEncodingChunked.HasValue);
                replacedert.True(response.Headers.Date.HasValue);
                replacedert.Equal(1, response.Headers.Server.Count);
                replacedert.Equal(1, response.Content.Headers.Count()); // Content-Length
                replacedert.Equal(10, response.Content.Headers.ContentLength);
                replacedert.Equal(string.Empty, await response.Content.ReadreplacedtringAsync());
            }
        }

19 View Source File : DirectoryBrowser.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory, Trait("FunctionalTests", "General")]
        [InlineData(HostType.HttpListener)]
        public void Static_DirectoryCustomRequestPathToPhysicalPathMapping(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string applicationUrl = deployer.Deploy(hostType, DirectoryCustomRequestPathToPhysicalPathMappingConfiguration);

                HttpResponseMessage response = null;

                //Directory with a default file - case request path ending with a '/'. A local directory referred by relative path
                var responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl + "customrequestPath/", out response);
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
                replacedert.True(!string.IsNullOrWhiteSpace(responseText), "Received empty response");
                replacedert.True((response.Content).Headers.ContentType.ToString() == "text/html; charset=utf-8");
                replacedert.True(responseText.Contains("Unknown.Unknown"));
                replacedert.True(responseText.Contains("Default.html"));

                //Directory with a default file - case request path ending with a '/' + Head request. A local directory referred by relative path
                responseText = HttpClientUtility.HeadResponseTextFromUrl(applicationUrl + "customrequestPath/", out response);
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
                replacedert.Equal<string>(string.Empty, responseText);

                //Directory with a default file - case request path ending with a '/'. A local directory referred by absolute path
                responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl + "customrequestFullPath/", out response);
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
                replacedert.True(responseText.Contains("TextFile2.txt"));
                replacedert.True(responseText.Contains("Unknown.Unknown"));

                //Directory with a default file - case request path ending with a '/' + Head request. A local directory referred by absolute path
                responseText = HttpClientUtility.HeadResponseTextFromUrl(applicationUrl + "customrequestFullPath/", out response);
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
                replacedert.Equal<string>(string.Empty, responseText);

                //Directory with a default file - case request path ending with a '/'. Mapped to a UNC path.
                responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl + "customrequestUNCPath/", out response);
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
                replacedert.True(responseText.Contains("Dir31"));
                replacedert.True(responseText.Contains("Dir32"));
                replacedert.True(responseText.Contains("TextFile3.txt"));
                replacedert.True(responseText.Contains("TextFile4.txt"));

                //Directory with a default file - case request path ending with a '/' + Head request. Mapped to a UNC path.
                responseText = HttpClientUtility.HeadResponseTextFromUrl(applicationUrl + "customrequestUNCPath/", out response);
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
                replacedert.Equal<string>(string.Empty, responseText);
            }
        }

19 View Source File : HostPropertyTests.cs
License : Apache License 2.0
Project Creator : aspnet

public void StartupPropertiesInspection(IAppBuilder app)
        {
            IDictionary<string, object> properties = app.Properties;
            replacedert.NotNull(properties);

            var ct = properties.Get<CancellationToken>("host.OnAppDisposing");
            replacedert.True(ct.CanBeCanceled);
            replacedert.False(ct.IsCancellationRequested);

            var appName = properties.Get<string>("host.AppName");
            replacedert.NotNull(appName);

            var trace = properties.Get<TextWriter>("host.TraceOutput");
            replacedert.NotNull(trace);

            app.Run(context => { return Task.FromResult(0); });
        }

19 View Source File : IntegratedPipelineWithMap.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact, Trait("FunctionalTests", "General")]
        public void IntegratedPipelineWithMapMiddleware()
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string applicationUrl = deployer.Deploy(HostType.IIS, WithMapMiddleware);
                WebDeployer webDeployer = (WebDeployer)deployer.Application;

                Directory.CreateDirectory(Path.Combine(webDeployer.Application.VirtualDirectories[0].PhysicalPath, "Branch1"));
                Directory.CreateDirectory(Path.Combine(webDeployer.Application.VirtualDirectories[0].PhysicalPath, "Branch2"));

                webDeployer.Application.Deploy("Branch1\\IntegratedPipelineTest.aspx", File.ReadAllText("RequirementFiles\\IntegratedPipelineTest.aspx"));
                webDeployer.Application.Deploy("Branch2\\IntegratedPipelineTest.aspx", File.ReadAllText("RequirementFiles\\IntegratedPipelineTest.aspx"));

                replacedert.True(HttpClientUtility.GetResponseTextFromUrl(applicationUrl + "/Branch1/IntegratedPipelineTest.aspx").Contains("1;11"), "Pipeline order incorrect");
                replacedert.True(HttpClientUtility.GetResponseTextFromUrl(applicationUrl + "/Branch2/IntegratedPipelineTest.aspx").Contains("1;21"), "Pipeline order incorrect");
            }
        }

19 View Source File : AzureWebHookDequeueManagerTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory]
        [InlineData(0)]
        [InlineData(100)]
        [InlineData(250)]
        public async Task Dispose_CancelsStartTask(int millisecondDelay)
        {
            // Arrange
            _dequeueManager = new AzureWebHookDequeueManagerMock(this);

            // Act
            var actual = _dequeueManager.Start(_tokenSource.Token);
            await Task.Delay(millisecondDelay);
            _dequeueManager.Dispose();
            await actual;

            // replacedert
            replacedert.True(actual.IsCompleted);
        }

19 View Source File : WsFederationTest.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory, Trait("FunctionalTests", "Security")]
        [InlineData(HostType.IIS)]
        [InlineData(HostType.HttpListener)]
        public void Security_WsFederationAuthentication(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var applicationUrl = deployer.Deploy(hostType, WsFederationAuthenticationConfiguration);

                var handler = new HttpClientHandler() { AllowAutoRedirect = false };
                var httpClient = new HttpClient(handler);

                //Set the right metadata doreplacedent in the server cache
                var kvps = new List<KeyValuePair<string, string>>();
                kvps.Add(new KeyValuePair<string, string>("metadata", File.ReadAllText(@"Facts\Security\Federation\federationmetadata.xml")));
                httpClient.PostAsync(applicationUrl + "metadata", new FormUrlEncodedContent(kvps));

                //Verify if the request is redirected to STS with right parameters
                var response = httpClient.GetAsync(applicationUrl).Result;
                replacedert.Equal<string>("https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/wsfed", response.Headers.Location.AbsoluteUri.Replace(response.Headers.Location.Query, string.Empty));
                var queryItems = response.Headers.Location.ParseQueryString();
                replacedert.Equal<string>("http://Automation1", queryItems["wtrealm"]);
                replacedert.True(queryItems["wctx"].StartsWith("WsFedOwinState="), "wctx does not start with a WsFedOwinState=");
                replacedert.True(queryItems["mystate"].EndsWith("customValue"), "wctx does not end with a &mystate=customValue");
                replacedert.Equal<string>(applicationUrl + "signin-wsfed", queryItems["wreply"]);
                replacedert.Equal<string>("wsignin1.0", queryItems["wa"]);

                //Send an invalid token and verify that the token is not honored
                httpClient = new HttpClient();
                kvps = new List<KeyValuePair<string, string>>();
                kvps.Add(new KeyValuePair<string, string>("wa", "wsignin1.0"));
                kvps.Add(new KeyValuePair<string, string>("wresult", File.ReadAllText(@"Facts\Security\Federation\InvalidToken.xml")));
                kvps.Add(new KeyValuePair<string, string>("wctx", queryItems["wctx"]));
                response = httpClient.PostAsync(queryItems["wreply"], new FormUrlEncodedContent(kvps)).Result;

                //Did the request end in the actual resource requested for
                replacedert.Equal<string>("AuthenticationFailed", response.Content.ReadreplacedtringAsync().Result);
            }
        }

19 View Source File : SystemWebIntegrationTests.cs
License : Apache License 2.0
Project Creator : aspnet

public void ExpectedKeys(IAppBuilder app)
        {
            app.UseErrorPage();
            app.Use((context, next) =>
            {
                var env = context.Environment;
                object ignored;
                replacedert.True(env.TryGetValue("owin.RequestMethod", out ignored));
                replacedert.Equal("GET", env["owin.RequestMethod"]);

                replacedert.True(env.TryGetValue("owin.RequestPath", out ignored));
                replacedert.Equal("/", env["owin.RequestPath"]);

                replacedert.True(env.TryGetValue("owin.RequestPathBase", out ignored));
                replacedert.Equal(string.Empty, env["owin.RequestPathBase"]);

                replacedert.True(env.TryGetValue("owin.RequestProtocol", out ignored));
                replacedert.Equal("HTTP/1.1", env["owin.RequestProtocol"]);

                replacedert.True(env.TryGetValue("owin.RequestQueryString", out ignored));
                replacedert.Equal(string.Empty, env["owin.RequestQueryString"]);

                replacedert.True(env.TryGetValue("owin.RequestScheme", out ignored));
                replacedert.Equal("http", env["owin.RequestScheme"]);

                replacedert.True(env.TryGetValue("owin.Version", out ignored));
                replacedert.Equal("1.0", env["owin.Version"]);

                replacedert.True(env.TryGetValue("owin.RequestId", out ignored));
                replacedert.False(string.IsNullOrWhiteSpace((string)env["owin.RequestId"]));

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

19 View Source File : ExceptionsTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory]
        [InlineData("Microsoft.Owin.Host.SystemWeb")]
        [InlineData("Microsoft.Owin.Host.HttpListener")]
        public async Task AsyncExceptionAfterHeaders(string serverName)
        {
            int port = RunWebServer(
                serverName,
                AsyncExceptionAfterHeadersApp);

            var client = new HttpClient();
            var response = await client.GetAsync("http://localhost:" + port, HttpCompletionOption.ResponseHeadersRead);
            replacedert.True(response.IsSuccessStatusCode);
            Stream body = response.Content.ReadreplacedtreamAsync().Result;
            int read = body.Read(new byte[11], 0, 11);
            replacedert.Equal(11, read);
            replacedert.Throws<IOException>(() =>
            {
                read = body.Read(new byte[10], 0, 10);
                replacedert.Equal(-1, read);
            });
        }

19 View Source File : DirectoryBrowser.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory, Trait("FunctionalTests", "General")]
        [InlineData(HostType.HttpListener)]
        public void Static_DirectoryBrowserDefaults(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string applicationUrl = deployer.Deploy(hostType, DirectoryBrowserDefaultsConfiguration);

                HttpResponseMessage response = null;

                //1. Check directory browsing enabled at application level
                var responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl, out response);
                replacedert.True(!string.IsNullOrWhiteSpace(responseText), "Received empty response");
                replacedert.True((response.Content).Headers.ContentType.ToString() == "text/html; charset=utf-8");
                replacedert.True(responseText.Contains("RequirementFiles/"));

                //2. Check directory browsing @RequirementFiles with a ending '/'
                responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl + "RequirementFiles/", out response);
                replacedert.True(!string.IsNullOrWhiteSpace(responseText), "Received empty response");
                replacedert.True((response.Content).Headers.ContentType.ToString() == "text/html; charset=utf-8");
                replacedert.True(responseText.Contains("Dir1/") && responseText.Contains("Dir2/") && responseText.Contains("Dir3/"), "Directories Dir1, Dir2, Dir3 not found");

                //2. Check directory browsing @RequirementFiles with request path not ending '/'
                responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl + "RequirementFiles", out response);
                replacedert.True(!string.IsNullOrWhiteSpace(responseText), "Received empty response");
                replacedert.True((response.Content).Headers.ContentType.ToString() == "text/html; charset=utf-8");
                replacedert.True(responseText.Contains("Dir1/") && responseText.Contains("Dir2/") && responseText.Contains("Dir3/"), "Directories Dir1, Dir2, Dir3 not found");
            }
        }

19 View Source File : SystemWebChunkingCookieManagerTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory]
        [InlineData("name", "value", "name=value; path=/")]
        [InlineData("name123", "value456", "name123=value456; path=/")]
        [InlineData("[email protected]#$%^&*()_", "[email protected]#$%^&*()_", "name%2B%21%40%23%24%25%5E%26%2A%28%29_=chunks:2; path=/; name%2B%21%40%23%24%25%5E%26%2A%28%29_C1=value%2B%21%40%23%24%25%5E%26%; path=/; name%2B%21%40%23%24%25%5E%26%2A%28%29_C2=2A%28%29_; path=/")]
        public async Task AppendCookie(string cookieName, string value, string expected)
        {
            int port = RunWebServer("Microsoft.Owin.Host.SystemWeb", ChunkingCookieManagerAppendCookieApp);

            var client = new HttpClient(new HttpClientHandler() { UseCookies = false });
            var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost:" + port + "/AppendCookie");
            message.Headers.TryAddWithoutValidation("CookieName", cookieName);
            message.Headers.TryAddWithoutValidation("CookieValue", value);
            var response = await client.SendAsync(message);
            replacedert.Equal("AppendCookieApp", await response.Content.ReadreplacedtringAsync());
            IEnumerable<string> values;
            replacedert.True(response.Headers.TryGetValues("Set-Cookie", out values));
            replacedert.Equal(expected, string.Join("; ", values));
        }

19 View Source File : AzureAdB2COpenIDConnectEventHandlersTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public async Task OnRemoteError_HandlesResponseWhenErrorIsUnknown()
        {
            // Arrange

            var handlers = new AzureADB2COpenIDConnectEventHandlers(
                AzureADB2CDefaults.AuthenticationScheme,
                new AzureADB2COptions() { SignUpSignInPolicyId = "B2C_1_SiUpIn" });

            var remoteFailureContext = new RemoteFailureContext(
                new DefaultHttpContext(),
                new AuthenticationScheme(
                    AzureADB2CDefaults.AuthenticationScheme,
                    displayName: null,
                    handlerType: typeof(OpenIdConnectHandler)),
                new OpenIdConnectOptions(),
                new OpenIdConnectProtocolException("some_other_error"));

            // Act
            await handlers.OnRemoteFailure(remoteFailureContext);

            // replacedert
            replacedert.Equal(StatusCodes.Status302Found, remoteFailureContext.Response.StatusCode);
            replacedert.Equal("/AzureADB2C/Account/Error", remoteFailureContext.Response.Headers[HeaderNames.Location]);
            replacedert.True(remoteFailureContext.Result.Handled);
        }

19 View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public async Task OwinHttpListenerResponse_101ResponseWithBody_BodyIgnoredByClient()
        {
            OwinHttpListener listener = CreateServer(
                env =>
                {
                    env["owin.ResponseStatusCode"] = 101;
                    var responseStream = env.Get<Stream>("owin.ResponseBody");

                    var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
                    responseHeaders["content-length"] = new string[] { "10" };

                    responseStream.Write(new byte[10], 0, 10);
                    return Task.FromResult(0);
                },
                HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(HttpClientAddress);
                replacedert.Equal(HttpStatusCode.SwitchingProtocols, response.StatusCode);
                replacedert.Equal("Switching Protocols", response.ReasonPhrase);
                replacedert.Equal(2, response.Headers.Count()); // Date, Server
                replacedert.True(response.Headers.Date.HasValue);
                replacedert.Equal(1, response.Headers.Server.Count);
                replacedert.Equal(0, (await response.Content.ReadAsByteArrayAsync()).Length);
            }
        }

19 View Source File : EmbeddedDirectoryBrowser.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory, Trait("FunctionalTests", "General")]
        [InlineData(HostType.HttpListener)]
        public void Static_EmbeddedDirectoryBrowserFileSystem(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var applicationUrl = deployer.Deploy(hostType, EmbeddedDirectoryBrowserFileSystemConfiguration);

                HttpResponseMessage response = null;

                var responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl, out response);
                replacedert.True(!string.IsNullOrWhiteSpace(responseText), "Received empty response");
                replacedert.True((response.Content).Headers.ContentType.ToString() == "text/html; charset=utf-8");
                replacedert.True(responseText.Contains("RequirementFiles.EmbeddedResources.SampleAVI.avi"));
            }
        }

19 View Source File : RequestBodyTests.cs
License : Apache License 2.0
Project Creator : aspnet

public void DisableRequestBufferingApp(IAppBuilder app)
        {
            app.Run(context =>
            {
                replacedert.True(context.Request.Body.CanSeek);
                var disableBuffering = context.Get<Action>("server.DisableRequestBuffering");
                replacedert.NotNull(disableBuffering);
                disableBuffering();
                replacedert.False(context.Request.Body.CanSeek);
                var reader = new StreamReader(context.Request.Body);
                string text = reader.ReadToEnd();
                replacedert.False(context.Request.Body.CanSeek);
                return context.Response.WriteAsync(text);
            });
        }

19 View Source File : AzureAdB2COpenIDConnectEventHandlersTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public async Task OnRedirectToIdenreplacedyProviderHandler_DoesNothingForTheDefaultPolicy()
        {
            // Arrange
            var handlers = new AzureADB2COpenIDConnectEventHandlers(
                AzureADB2CDefaults.AuthenticationScheme,
                new AzureADB2COptions() { SignUpSignInPolicyId = "B2C_1_SiUpIn" });

            var authenticationProperties = new AuthenticationProperties(new Dictionary<string, string>
            {
                [AzureADB2CDefaults.PolicyKey] = "B2C_1_SiUpIn"
            });
            var redirectContext = new RedirectContext(
                new DefaultHttpContext(),
                new AuthenticationScheme(AzureADB2CDefaults.AuthenticationScheme, "", typeof(OpenIdConnectHandler)),
                new OpenIdConnectOptions(),
                authenticationProperties)
            {
                ProtocolMessage = new OpenIdConnectMessage
                {
                    Scope = OpenIdConnectScope.OpenId,
                    ResponseType = OpenIdConnectResponseType.Code,
                    IssuerAddress = "https://login.microsoftonline.com/tfp/domain.onmicrosoft.com/B2C_1_SiUpIn/v2.0"
                }
            };

            // Act
            await handlers.OnRedirectToIdenreplacedyProvider(redirectContext);

            // replacedert
            replacedert.Equal(OpenIdConnectScope.OpenId, redirectContext.ProtocolMessage.Scope);
            replacedert.Equal(OpenIdConnectResponseType.Code, redirectContext.ProtocolMessage.ResponseType);
            replacedert.Equal(
                "https://login.microsoftonline.com/tfp/domain.onmicrosoft.com/B2C_1_SiUpIn/v2.0",
                redirectContext.ProtocolMessage.IssuerAddress);
            replacedert.True(authenticationProperties.Items.ContainsKey(AzureADB2CDefaults.PolicyKey));
        }

19 View Source File : ContainerServiceProviderTest.cs
License : MIT License
Project Creator : aspnet

[Fact]
        public void GetService_Should_Cache_Type_That_Cannot_Be_Resolved_By_UnityContainer()
        {
            var containerSP = new ContainerServiceProvider(null);
            var resolvedObj = containerSP.GetService(typeof(TypeToResolveBase));

            replacedert.NotNull(resolvedObj);
            replacedert.IsType<TypeToResolveBase>(resolvedObj);
            replacedert.True(containerSP.TypeCannotResolveDictionary.ContainsKey(typeof(TypeToResolveBase)));
        }

19 View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public async Task OwinHttpListenerResponse_Empty200Response_Success()
        {
            OwinHttpListener listener = CreateServer(call => Task.FromResult(0), HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(HttpClientAddress);
                replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
                replacedert.Equal("OK", response.ReasonPhrase);
                replacedert.Equal(2, response.Headers.Count());
                replacedert.False(response.Headers.TransferEncodingChunked.HasValue);
                replacedert.True(response.Headers.Date.HasValue);
                replacedert.Equal(1, response.Headers.Server.Count);
                replacedert.Equal(1, response.Content.Headers.Count()); // Content-Length
                replacedert.Equal(0, response.Content.Headers.ContentLength);
                replacedert.Equal(string.Empty, await response.Content.ReadreplacedtringAsync());
            }
        }

19 View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public async Task OwinHttpListenerResponse_Empty404Response_Success()
        {
            OwinHttpListener listener = CreateServer(env =>
            {
                env["owin.ResponseStatusCode"] = 404;
                return Task.FromResult(0);
            }, HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(HttpClientAddress);
                replacedert.Equal(HttpStatusCode.NotFound, response.StatusCode);
                replacedert.Equal("Not Found", response.ReasonPhrase);
                replacedert.Equal(2, response.Headers.Count());
                replacedert.False(response.Headers.TransferEncodingChunked.HasValue);
                replacedert.True(response.Headers.Date.HasValue);
                replacedert.Equal(1, response.Headers.Server.Count);
                replacedert.Equal(1, response.Content.Headers.Count()); // Content-Length
                replacedert.Equal(0, response.Content.Headers.ContentLength);
                replacedert.Equal(string.Empty, await response.Content.ReadreplacedtringAsync());
            }
        }

19 View Source File : AzureADAuthenticationBuilderExtensionsTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public void AddAzureAD_ConfiguresAllOptions()
        {
            // Arrange
            var services = new ServiceCollection();
            services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());

            // Act
            services.AddAuthentication()
                .AddAzureAD(o =>
                {
                    o.Instance = "https://login.microsoftonline.com";
                    o.ClientId = "ClientId";
                    o.ClientSecret = "ClientSecret";
                    o.CallbackPath = "/signin-oidc";
                    o.Domain = "domain.onmicrosoft.com";
                    o.TenantId = "Common";
                });
            var provider = services.BuildServiceProvider();

            // replacedert
            var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
            replacedert.NotNull(azureADOptionsMonitor);
            var azureADOptions = azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme);
            replacedert.Equal(AzureADDefaults.OpenIdScheme, azureADOptions.OpenIdConnectSchemeName);
            replacedert.Equal(AzureADDefaults.CookieScheme, azureADOptions.CookieSchemeName);
            replacedert.Equal("https://login.microsoftonline.com", azureADOptions.Instance);
            replacedert.Equal("ClientId", azureADOptions.ClientId);
            replacedert.Equal("ClientSecret", azureADOptions.ClientSecret);
            replacedert.Equal("/signin-oidc", azureADOptions.CallbackPath);
            replacedert.Equal("domain.onmicrosoft.com", azureADOptions.Domain);

            var openIdOptionsMonitor = provider.GetService<IOptionsMonitor<OpenIdConnectOptions>>();
            replacedert.NotNull(openIdOptionsMonitor);
            var openIdOptions = openIdOptionsMonitor.Get(AzureADDefaults.OpenIdScheme);
            replacedert.Equal("ClientId", openIdOptions.ClientId);
            replacedert.Equal($"https://login.microsoftonline.com/Common", openIdOptions.Authority);
            replacedert.True(openIdOptions.UseTokenLifetime);
            replacedert.Equal("/signin-oidc", openIdOptions.CallbackPath);
            replacedert.Equal(AzureADDefaults.CookieScheme, openIdOptions.SignInScheme);
        }

19 View Source File : ExceptionsTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory]
        [InlineData("Microsoft.Owin.Host.SystemWeb")]
        [InlineData("Microsoft.Owin.Host.HttpListener")]
        public async Task SyncExceptionAfterHeaders(string serverName)
        {
            int port = RunWebServer(
                serverName,
                SyncExceptionAfterHeadersApp);

            var client = new HttpClient();
            var response = await client.GetAsync("http://localhost:" + port, HttpCompletionOption.ResponseHeadersRead);
            replacedert.True(response.IsSuccessStatusCode);
            Stream body = response.Content.ReadreplacedtreamAsync().Result;
            int read = body.Read(new byte[11], 0, 11);
            replacedert.Equal(11, read);
            replacedert.Throws<IOException>(() => body.Read(new byte[10], 0, 10));
        }

19 View Source File : WsFederationTest.cs
License : Apache License 2.0
Project Creator : aspnet

public void WsFederationAuthenticationConfiguration(IAppBuilder app)
        {
            app.UseStaticFiles();

            app.UseAuthSignInCookie();

            app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions()
                {
                    Wtrealm = "http://Automation1",
                    MetadataAddress = "https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/federationmetadata/2007-06/federationmetadata.xml",
                    BackchannelHttpHandler = new WaadMetadataDoreplacedentHandler(),
                    StateDataFormat = new CustomStateDataFormat(),
                    Notifications = new WsFederationAuthenticationNotifications()
                    {
                        MessageReceived = notification =>
                            {
                                replacedert.True(notification.ProtocolMessage.Wctx.EndsWith("&mystate=customValue"), "wctx is not ending with &mystate=customValue");
                                notification.ProtocolMessage.Wctx = notification.ProtocolMessage.Wctx.Replace("&mystate=customValue", string.Empty);
                                notification.OwinContext.Set<bool>("MessageReceived", true);
                                return Task.FromResult(0);
                            },
                        RedirectToIdenreplacedyProvider = notification =>
                            {
                                if (notification.ProtocolMessage.IsSignInMessage)
                                {
                                    //Sign in message
                                    notification.ProtocolMessage.Wreply = notification.Request.Uri.AbsoluteUri + "signin-wsfed";
                                    notification.ProtocolMessage.Wctx += "&mystate=customValue";
                                }

                                return Task.FromResult(0);
                            },
                        SecurityTokenReceived = notification =>
                            {
                                notification.OwinContext.Set<bool>("SecurityTokenReceived", true);
                                return Task.FromResult(0);
                            },
                        SecurityTokenValidated = notification =>
                            {
                                var context = notification.AuthenticationTicket;

                                replacedert.True(notification.OwinContext.Get<bool>("MessageReceived"), "MessageReceived notification not invoked");
                                replacedert.True(notification.OwinContext.Get<bool>("SecurityTokenReceived"), "SecurityTokenReceived notification not invoked");

                                if (context.Idenreplacedy != null)
                                {
                                    context.Idenreplacedy.AddClaim(new Claim("ReturnEndpoint", "true"));
                                    context.Idenreplacedy.AddClaim(new Claim("Authenticated", "true"));
                                    context.Idenreplacedy.AddClaim(new Claim(context.Idenreplacedy.RoleClaimType, "Guest", ClaimValueTypes.String));
                                }

                                return Task.FromResult(0);
                            },
                        AuthenticationFailed = notification =>
                            {
                                //Change the request url to something different and skip Wsfed. This new url will handle the request and let us know if this notification was invoked.
                                notification.OwinContext.Request.Path = new PathString("/AuthenticationFailed");
                                notification.SkipToNextMiddleware();
                                return Task.FromResult(0);
                            }
                    }
                });

            app.Map("/Logout", subApp =>
                {
                    subApp.Run(async context =>
                        {
                            if (context.Authentication.User.Idenreplacedy.IsAuthenticated)
                            {
                                var authProperties = new AuthenticationProperties() { RedirectUri = context.Request.Uri.AbsoluteUri };
                                context.Authentication.SignOut(authProperties, WsFederationAuthenticationDefaults.AuthenticationType);
                                await context.Response.WriteAsync("Signing out...");
                            }
                            else
                            {
                                await context.Response.WriteAsync("SignedOut");
                            }
                        });
                });

            app.Map("/AuthenticationFailed", subApp =>
            {
                subApp.Run(async context =>
                {
                    await context.Response.WriteAsync("AuthenticationFailed");
                });
            });

            app.Map("/signout-wsfed", subApp =>
            {
                subApp.Run(async context =>
                {
                    await context.Response.WriteAsync("signout-wsfed");
                });
            });

            #region Utilities to set the metadata xml.
            app.Map("/metadata", subApp =>
            {
                subApp.Run(async context =>
                {
                    if (context.Request.Method == "POST")
                    {
                        var formParameters = await context.Request.ReadFormAsync();
                        metadataXml = formParameters.GetValues("metadata")[0];
                        await context.Response.WriteAsync("Received metadata");
                    }
                    else
                    {
                        context.Response.ContentType = "text/xml";
                        await context.Response.WriteAsync(metadataXml);
                    }
                });
            });
            #endregion

            app.UseExternalApplication(WsFederationAuthenticationDefaults.AuthenticationType);
        }

19 View Source File : SystemWebCookieManagerTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory]
        [InlineData("name", "name=; expires=Thu, 01-Jan-1970 00:00:00 GMT; path=/")]
        [InlineData("name123", "name123=; expires=Thu, 01-Jan-1970 00:00:00 GMT; path=/")]
        [InlineData("[email protected]#$%^&*()_", "name%2B%21%40%23%24%25%5E%26%2A%28%29_=; expires=Thu, 01-Jan-1970 00:00:00 GMT; path=/")]
        public async Task DeleteCookie(string cookieName, string expected)
        {
            int port = RunWebServer("Microsoft.Owin.Host.SystemWeb", CookieManagerDeleteCookieApp);

            var client = new HttpClient(new HttpClientHandler() { UseCookies = false });
            var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost:" + port + "/DeleteCookie");
            message.Headers.TryAddWithoutValidation("CookieName", cookieName);
            var response = await client.SendAsync(message);
            replacedert.Equal("DeleteCookieApp", await response.Content.ReadreplacedtringAsync());
            IEnumerable<string> values;
            replacedert.True(response.Headers.TryGetValues("Set-Cookie", out values));
            replacedert.Equal(1, values.Count());
            replacedert.Equal(expected, values.First());
        }

19 View Source File : ExceptionsTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory]
        [InlineData("Microsoft.Owin.Host.SystemWeb")]
        [InlineData("Microsoft.Owin.Host.HttpListener")]
        public async Task ExceptionAfterHeadersWithContentLength(string serverName)
        {
            int port = RunWebServer(
                serverName,
                ExceptionAfterHeadersWithContentLengthApp);

            var client = new HttpClient();
            var response = await client.GetAsync("http://localhost:" + port, HttpCompletionOption.ResponseHeadersRead);
            replacedert.True(response.IsSuccessStatusCode);
            replacedert.Equal(20, response.Content.Headers.ContentLength.Value);
            Stream body = response.Content.ReadreplacedtreamAsync().Result;
            int read = body.Read(new byte[11], 0, 11);
            replacedert.Equal(11, read);
            replacedert.Throws<IOException>(() => body.Read(new byte[10], 0, 10));
        }

19 View Source File : MapOwinRouteTest.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact, Trait("FunctionalTests", "General")]
        public void MapOwinRoute()
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string url = deployer.Deploy(HostType.IIS, MapOwinRouteConfiguration);
                ((WebDeployer)deployer.Application).Application.Deploy("Default.aspx", File.ReadAllText("RequirementFiles\\Default.aspx"));

                replacedert.True(HttpClientUtility.GetResponseTextFromUrl(url + "/Default.aspx").Contains("Asp.net Test page"), "Default.aspx page not returned successfully in SxS mode");
                replacedert.Equal(HttpClientUtility.GetResponseTextFromUrl(url + "/Route"), "Route");
                replacedert.Equal(HttpClientUtility.GetResponseTextFromUrl(url + "/Route/Test"), "Route");
                replacedert.Equal(HttpClientUtility.GetResponseTextFromUrl(url + "/RouteOne"), "RouteOne");
                replacedert.Equal(HttpClientUtility.GetResponseTextFromUrl(url + "/RouteOne/Test"), "RouteOne");
                replacedert.Equal(HttpClientUtility.GetResponseTextFromUrl(url + "/RouteTwo"), "RouteTwo");
                replacedert.Equal(HttpClientUtility.GetResponseTextFromUrl(url + "/RouteTwo/Test"), "RouteTwo");
                replacedert.Equal(HttpClientUtility.GetResponseTextFromUrl(url + "/RouteRouteTest"), "RouteRouteTest");
                replacedert.Equal(HttpClientUtility.GetResponseTextFromUrl(url + "/RouteRouteTest/Test"), "RouteRouteTest");
            }
        }

19 View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public async Task Headers_OtherReservedHeaders_PreplacededThrough()
        {
            OwinHttpListener listener = CreateServer(
                env =>
                {
                    var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
                    responseHeaders.Add("Transfer-Encoding", new string[] { "ChUnKed" });
                    responseHeaders.Add("CONNECTION", new string[] { "ClOsE" });
                    return Task.FromResult(0);
                },
                HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(HttpClientAddress);
                replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
                replacedert.Equal(4, response.Headers.Count()); // Date, Server
                replacedert.Equal("chunked", response.Headers.TransferEncoding.ToString()); // Normalized by server
                replacedert.True(response.Headers.TransferEncodingChunked.Value);
                replacedert.Equal("close", response.Headers.Connection.First()); // Normalized by server
                replacedert.True(response.Headers.ConnectionClose.Value);
            }
        }

19 View Source File : AzureAdB2COpenIDConnectEventHandlersTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public async Task OnRemoteError_HandlesResponseWhenUserCancelsFlowFromTheAzureADB2CUserInterface()
        {
            // Arrange

            var handlers = new AzureADB2COpenIDConnectEventHandlers(
                AzureADB2CDefaults.AuthenticationScheme,
                new AzureADB2COptions() { SignUpSignInPolicyId = "B2C_1_SiUpIn" });

            var remoteFailureContext = new RemoteFailureContext(
                new DefaultHttpContext(),
                new AuthenticationScheme(
                    AzureADB2CDefaults.AuthenticationScheme,
                    displayName: null,
                    handlerType: typeof(OpenIdConnectHandler)),
                new OpenIdConnectOptions(),
                new OpenIdConnectProtocolException("access_denied"));

            // Act
            await handlers.OnRemoteFailure(remoteFailureContext);

            // replacedert
            replacedert.Equal(StatusCodes.Status302Found, remoteFailureContext.Response.StatusCode);
            replacedert.Equal("/", remoteFailureContext.Response.Headers[HeaderNames.Location]);
            replacedert.True(remoteFailureContext.Result.Handled);
        }

19 View Source File : HostPropertyTests.cs
License : Apache License 2.0
Project Creator : aspnet

public void RuntimePropertiesInspection(IAppBuilder app)
        {
            app.Run(context =>
            {
                replacedert.NotNull(context);

                var ct = context.Get<CancellationToken>("host.OnAppDisposing");
                replacedert.True(ct.CanBeCanceled);
                replacedert.False(ct.IsCancellationRequested);

                var appName = context.Get<string>("host.AppName");
                replacedert.NotNull(appName);

                var trace = context.Get<TextWriter>("host.TraceOutput");
                replacedert.NotNull(trace);

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

19 View Source File : DirectoryBrowser.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory, Trait("FunctionalTests", "General")]
        [InlineData(HostType.HttpListener)]
        public void Static_DirectoryMiddlewareMappedToDifferentDirectory(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string applicationUrl = deployer.Deploy(hostType, DirectoryMiddlewareMappedToDifferentDirectoryConfiguration);

                HttpResponseMessage response = null;

                //1. Check directory browsing enabled at application level
                var responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl, out response);
                replacedert.True(!string.IsNullOrWhiteSpace(responseText), "Received empty response");
                replacedert.True((response.Content).Headers.ContentType.ToString() == "text/html; charset=utf-8");
                replacedert.True(responseText.Contains("Default.html"));
                replacedert.True(responseText.Contains("EmptyFile.txt"));
            }
        }

19 View Source File : SystemWebChunkingCookieManagerTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory]
        [InlineData("name", "name=value", "name=; expires=Thu, 01-Jan-1970 00:00:00 GMT; path=/")]
        [InlineData("name123", "name123=value123", "name123=; expires=Thu, 01-Jan-1970 00:00:00 GMT; path=/")]
        [InlineData("[email protected]#$%^&*()_", "name%2B%21%40%23%24%25%5E%26%2A%28%29_=chunks:2;",
            "name%2B%21%40%23%24%25%5E%26%2A%28%29_=; expires=Thu, 01-Jan-1970 00:00:00 GMT; path=/; name%2B%21%40%23%24%25%5E%26%2A%28%29_C1=; expires=Thu, 01-Jan-1970 00:00:00 GMT; path=/; name%2B%21%40%23%24%25%5E%26%2A%28%29_C2=; expires=Thu, 01-Jan-1970 00:00:00 GMT; path=/")]
        public async Task DeleteCookie(string cookieName, string requestCookie, string expected)
        {
            int port = RunWebServer("Microsoft.Owin.Host.SystemWeb", ChunkingCookieManagerDeleteCookieApp);

            var client = new HttpClient(new HttpClientHandler() { UseCookies = false });
            var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost:" + port + "/DeleteCookie");
            message.Headers.TryAddWithoutValidation("CookieName", cookieName);
            message.Headers.TryAddWithoutValidation("Cookie", requestCookie);
            var response = await client.SendAsync(message);
            replacedert.Equal("DeleteCookieApp", await response.Content.ReadreplacedtringAsync());
            IEnumerable<string> values;
            replacedert.True(response.Headers.TryGetValues("Set-Cookie", out values));
            replacedert.Equal(expected, string.Join("; ", values));
        }

19 View Source File : AzureAdB2CAuthenticationBuilderExtensionsTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public void AddAzureADB2C_ConfiguresAllOptions()
        {
            // Arrange
            var services = new ServiceCollection();
            services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());

            // Act
            services.AddAuthentication()
                .AddAzureADB2C(o =>
                {
                    o.Instance = "https://login.microsoftonline.com/tfp";
                    o.ClientId = "ClientId";
                    o.ClientSecret = "ClientSecret";
                    o.CallbackPath = "/signin-oidc";
                    o.Domain = "domain.onmicrosoft.com";
                    o.SignUpSignInPolicyId = "B2C_1_SiUpIn";
                    o.ResetPreplacedwordPolicyId = "B2C_1_SSPR";
                    o.EditProfilePolicyId = "B2C_1_SiPe";
                });
            var provider = services.BuildServiceProvider();

            // replacedert
            var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();
            replacedert.NotNull(azureADB2COptionsMonitor);
            var azureADB2COptions = azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme);
            replacedert.Equal(AzureADB2CDefaults.OpenIdScheme, azureADB2COptions.OpenIdConnectSchemeName);
            replacedert.Equal(AzureADB2CDefaults.CookieScheme, azureADB2COptions.CookieSchemeName);
            replacedert.Equal("https://login.microsoftonline.com/tfp", azureADB2COptions.Instance);
            replacedert.Equal("ClientId", azureADB2COptions.ClientId);
            replacedert.Equal("ClientSecret", azureADB2COptions.ClientSecret);
            replacedert.Equal("/signin-oidc", azureADB2COptions.CallbackPath);
            replacedert.Equal("domain.onmicrosoft.com", azureADB2COptions.Domain);
            replacedert.Equal("B2C_1_SiUpIn", azureADB2COptions.SignUpSignInPolicyId);
            replacedert.Equal("B2C_1_SSPR", azureADB2COptions.ResetPreplacedwordPolicyId);
            replacedert.Equal("B2C_1_SiPe", azureADB2COptions.EditProfilePolicyId);

            var openIdOptionsMonitor = provider.GetService<IOptionsMonitor<OpenIdConnectOptions>>();
            replacedert.NotNull(openIdOptionsMonitor);
            var openIdOptions = openIdOptionsMonitor.Get(AzureADB2CDefaults.OpenIdScheme);
            replacedert.Equal("ClientId", openIdOptions.ClientId);
            replacedert.Equal($"https://login.microsoftonline.com/tfp/domain.onmicrosoft.com/B2C_1_SiUpIn/v2.0", openIdOptions.Authority);
            replacedert.True(openIdOptions.UseTokenLifetime);
            replacedert.Equal("/signin-oidc", openIdOptions.CallbackPath);
            replacedert.Equal(AzureADB2CDefaults.CookieScheme, openIdOptions.SignInScheme);
            replacedert.NotNull(openIdOptions.TokenValidationParameters);
            replacedert.Equal("name", openIdOptions.TokenValidationParameters.NameClaimType);
            replacedert.NotNull(openIdOptions.Events);
            var redirectHandler = openIdOptions.Events.OnRedirectToIdenreplacedyProvider;
            replacedert.NotNull(redirectHandler);
            replacedert.IsType<AzureADB2COpenIDConnectEventHandlers>(redirectHandler.Target);
            var remoteFailureHanlder = openIdOptions.Events.OnRemoteFailure;
            replacedert.NotNull(remoteFailureHanlder);
            replacedert.IsType<AzureADB2COpenIDConnectEventHandlers>(redirectHandler.Target);
        }

19 View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public async Task OwinHttpListenerResponse_Empty101Response_Success()
        {
            OwinHttpListener listener = CreateServer(
                env =>
                {
                    env["owin.ResponseStatusCode"] = 101;
                    return Task.FromResult(0);
                },
                HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(HttpClientAddress);
                replacedert.Equal(HttpStatusCode.SwitchingProtocols, response.StatusCode);
                replacedert.Equal("Switching Protocols", response.ReasonPhrase);
                replacedert.Equal(2, response.Headers.Count()); // Date, Server
                replacedert.True(response.Headers.Date.HasValue);
                replacedert.Equal(1, response.Headers.Server.Count);
                replacedert.Equal(string.Empty, await response.Content.ReadreplacedtringAsync());
            }
        }

19 View Source File : EmbeddedDefaultFiles.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory, Trait("FunctionalTests", "General")]
        [InlineData(HostType.HttpListener)]
        public void Static_EmbeddedFileSystemDefaultFiles(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var applicationUrl = deployer.Deploy(hostType, EmbeddedFileSystemDefaultFilesConfiguration);

                HttpResponseMessage response = null;

                var responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl, out response);
                replacedert.True(!string.IsNullOrWhiteSpace(responseText), "Received empty response");
                replacedert.True((response.Content).Headers.ContentType.ToString() == "text/html");
                replacedert.True(responseText.Contains("SampleHTM"));
            }
        }

19 View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public async Task OwinHttpListenerResponse_OnFirstWrite_OnSendingHeaders()
        {
            OwinHttpListener listener = CreateServer(
                env =>
                {
                    env["owin.ResponseStatusCode"] = 200;
                    env["owin.ResponseReasonPhrase"] = "Custom";
                    var responseStream = env.Get<Stream>("owin.ResponseBody");

                    var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");

                    env.Get<Action<Action<object>, object>>("server.OnSendingHeaders")(state => responseHeaders["custom-header"] = new string[] { "customvalue" }, null);

                    responseHeaders["content-length"] = new string[] { "10" };

                    responseStream.Write(new byte[10], 0, 10);

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

            using (listener)
            {
                var client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(HttpClientAddress);
                replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
                replacedert.Equal("Custom", response.ReasonPhrase);
                replacedert.Equal(3, response.Headers.Count()); // Date, Server
                replacedert.True(response.Headers.Date.HasValue);
                replacedert.Equal(1, response.Headers.Server.Count);
                replacedert.Equal("customvalue", response.Headers.GetValues("custom-header").First());
                replacedert.Equal(10, (await response.Content.ReadAsByteArrayAsync()).Length);
            }
        }

19 View Source File : WelcomePageFacts.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory, Trait("FunctionalTests", "General")]
        [InlineData(HostType.IIS)]
        [InlineData(HostType.HttpListener)]
        public void WelcomePage(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string applicationUrl = deployer.Deploy(hostType, WelcomePageConfiguration);

                HttpResponseMessage response;
                replacedert.True(HttpClientUtility.GetResponseTextFromUrl(applicationUrl, out response).ToLower().Contains("your owin application has been successfully started"));
                replacedert.Equal("text/html", response.Content.Headers.ContentType.MediaType.ToLower());
            }
        }

19 View Source File : RequestBodyTests.cs
License : Apache License 2.0
Project Creator : aspnet

public void ReadBodyTwiceViaPositionApp(IAppBuilder app)
        {
            app.Run(context =>
            {
                var reader = new StreamReader(context.Request.Body);
                string text = reader.ReadToEnd();
                context.Response.WriteAsync(text).Wait();
                replacedert.True(context.Request.Body.CanSeek);
                context.Request.Body.Position = 0;
                reader = new StreamReader(context.Request.Body);
                text = reader.ReadToEnd();
                return context.Response.WriteAsync(text);
            });
        }

19 View Source File : CacheTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory, Trait("FunctionalTests", "General")]
        [InlineData(HostType.HttpListener)]
        public void Static_CacheHeadersDefault(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var applicationUrl = deployer.Deploy(hostType, CacheHeadersDefaultConfiguration);
                var httpClient = new HttpClient() { BaseAddress = new Uri(applicationUrl) };

                var response = httpClient.GetAsync("RequirementFiles/Dir1/Default.html").Result;
                replacedert.True(!string.IsNullOrWhiteSpace(response.Headers.ETag.Tag), "E-Tag header missing");
                replacedert.True(response.Headers.ETag.Tag.StartsWith("\""), "E-Tag header does not start with a quote");
                replacedert.True(response.Headers.ETag.Tag.EndsWith("\""), "E-Tag header does not end with a quote");
                replacedert.True(response.Content.Headers.LastModified.HasValue, "Date-Modified header missing");
            }
        }

19 View Source File : ResponseBodyTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory]
        [InlineData("Microsoft.Owin.Host.SystemWeb")]
        public async Task ResponseFlushedFromOtherFramwork_OnSendingHeadersStillFires(string serverName)
        {
            int port = RunWebServer(
                serverName,
                MockMvcFlushApp);

            var client = new HttpClient();
            var result = await client.GetAsync("http://localhost:" + port);

            IEnumerable<string> values;
            var found = result.Headers.TryGetValues("OSH", out values);

            // New in .NET 4.6, used for version detection
            MethodInfo PushPromiseMethod = typeof(HttpResponseBase).GetMethods().FirstOrDefault(info => info.Name.Equals("PushPromise"));
            if (PushPromiseMethod == null)
            {
                replacedert.False(found);
            }
            else
            {
                replacedert.True(found);
                replacedert.Equal("Fired", values.First());
            }
        }

19 View Source File : GridifyMapperShould.cs
License : MIT License
Project Creator : alirezanet

[Fact]
      public void GenerateMappings()
      {
         _sut.GenerateMappings();
         
         var props = typeof(TestClreplaced).GetProperties()
            .Where(q => !q.PropertyType.IsClreplaced || q.PropertyType == typeof(string)); 

         replacedert.Equal(props.Count(), _sut.GetCurrentMaps().Count());
         replacedert.True(_sut.HasMap("Id"));
      }

19 View Source File : SystemWebCookieManagerTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory]
        [InlineData("name", "value", "name=value; path=/")]
        [InlineData("name123", "value456", "name123=value456; path=/")]
        [InlineData("[email protected]#$%^&*()_", "[email protected]#$%^&*()_", "name%2B%21%40%23%24%25%5E%26%2A%28%29_=value%2B%21%40%23%24%25%5E%26%2A%28%29_; path=/")]
        public async Task AppendCookie(string cookieName, string value, string expected)
        {
            int port = RunWebServer("Microsoft.Owin.Host.SystemWeb", CookieManagerAppendCookieApp);

            var client = new HttpClient(new HttpClientHandler() { UseCookies = false });
            var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost:" + port + "/AppendCookie");
            message.Headers.TryAddWithoutValidation("CookieName", cookieName);
            message.Headers.TryAddWithoutValidation("CookieValue", value);
            var response = await client.SendAsync(message);
            replacedert.Equal("AppendCookieApp", await response.Content.ReadreplacedtringAsync());
            IEnumerable<string> values;
            replacedert.True(response.Headers.TryGetValues("Set-Cookie", out values));
            replacedert.Equal(1, values.Count());
            replacedert.Equal(expected, values.First());
        }

19 View Source File : RangeTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory, Trait("FunctionalTests", "General")]
        [InlineData(HostType.HttpListener)]
        public void Static_ValidRange(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var applicationUrl = deployer.Deploy(hostType, ValidRangeConfiguration);
                var httpClient = new HttpClient() { BaseAddress = new Uri(applicationUrl) };
                var fileContent = File.ReadAllBytes(@"RequirementFiles/Dir1/RangeRequest.txt");

                //Range with 1 bytes starting at 0
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(0, 0);
                var response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.PartialContent, response.StatusCode);
                replacedert.True(response.Content.Headers.ContentRange.HasRange &&
                    response.Content.Headers.ContentRange.Unit == "bytes" && response.Content.Headers.ContentRange.Length == fileContent.Length &&
                    response.Content.Headers.ContentRange.From == 0 && response.Content.Headers.ContentRange.To == 0);
                replacedert.Equal<long?>(1, response.Content.Headers.ContentLength);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 0, 0);

                //Range with 1 bytes starting at 9
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(9, 9);
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.PartialContent, response.StatusCode);
                replacedert.True(response.Content.Headers.ContentRange.HasRange &&
                    response.Content.Headers.ContentRange.Unit == "bytes" && response.Content.Headers.ContentRange.Length == fileContent.Length &&
                    response.Content.Headers.ContentRange.From == 9 && response.Content.Headers.ContentRange.To == 9);
                replacedert.Equal<long?>(1, response.Content.Headers.ContentLength);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 9, 9);

                //Range with 2 bytes starting at 5
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(5, 6);
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.PartialContent, response.StatusCode);
                replacedert.True(response.Content.Headers.ContentRange.HasRange &&
                    response.Content.Headers.ContentRange.Unit == "bytes" && response.Content.Headers.ContentRange.Length == fileContent.Length &&
                    response.Content.Headers.ContentRange.From == 5 && response.Content.Headers.ContentRange.To == 6);
                replacedert.Equal<long?>(2, response.Content.Headers.ContentLength);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 5, 6);

                //Range with 500 bytes starting at 0
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(0, 499);
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.PartialContent, response.StatusCode);
                replacedert.True(response.Content.Headers.ContentRange.HasRange &&
                    response.Content.Headers.ContentRange.Unit == "bytes" && response.Content.Headers.ContentRange.Length == fileContent.Length &&
                    response.Content.Headers.ContentRange.From == 0 && response.Content.Headers.ContentRange.To == 499);
                replacedert.Equal<long?>(500, response.Content.Headers.ContentLength);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 0, 499);

                //Range with second 500 bytes starting at 500
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(500, 999);
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.PartialContent, response.StatusCode);
                replacedert.True(response.Content.Headers.ContentRange.HasRange &&
                    response.Content.Headers.ContentRange.Unit == "bytes" && response.Content.Headers.ContentRange.Length == fileContent.Length &&
                    response.Content.Headers.ContentRange.From == 500 && response.Content.Headers.ContentRange.To == 999);
                replacedert.Equal<long?>(500, response.Content.Headers.ContentLength);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 500, 999);

                //-500
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(null, 500);
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.PartialContent, response.StatusCode);
                replacedert.True(response.Content.Headers.ContentRange.HasRange &&
                    response.Content.Headers.ContentRange.Unit == "bytes" && response.Content.Headers.ContentRange.Length == fileContent.Length &&
                    response.Content.Headers.ContentRange.From == fileContent.Length - 500 && response.Content.Headers.ContentRange.To == fileContent.Length - 1);
                replacedert.Equal<long?>(500, response.Content.Headers.ContentLength);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, fileContent.Length - 500, fileContent.Length - 1);

                //0-
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(0, null);
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.PartialContent, response.StatusCode);
                replacedert.True(response.Content.Headers.ContentRange.HasRange &&
                    response.Content.Headers.ContentRange.Unit == "bytes" && response.Content.Headers.ContentRange.Length == fileContent.Length &&
                    response.Content.Headers.ContentRange.From == 0 && response.Content.Headers.ContentRange.To == fileContent.Length - 1);
                replacedert.Equal<long?>(fileContent.Length, response.Content.Headers.ContentLength);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 0, fileContent.Length - 1);

                //10-
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(10, null);
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.PartialContent, response.StatusCode);
                replacedert.True(response.Content.Headers.ContentRange.HasRange &&
                    response.Content.Headers.ContentRange.Unit == "bytes" && response.Content.Headers.ContentRange.Length == fileContent.Length &&
                    response.Content.Headers.ContentRange.From == 10 && response.Content.Headers.ContentRange.To == fileContent.Length - 1);
                replacedert.Equal<long?>(fileContent.Length - 10, response.Content.Headers.ContentLength);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 10, fileContent.Length - 1);

                //0-10*10000
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(0, 10 * 10000);
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.PartialContent, response.StatusCode);
                replacedert.True(response.Content.Headers.ContentRange.HasRange &&
                    response.Content.Headers.ContentRange.Unit == "bytes" && response.Content.Headers.ContentRange.Length == fileContent.Length &&
                    response.Content.Headers.ContentRange.From == 0 && response.Content.Headers.ContentRange.To == fileContent.Length - 1);
                replacedert.Equal<long?>(fileContent.Length, response.Content.Headers.ContentLength);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 0, fileContent.Length - 1);

                //9500-
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(9500, null);
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.RequestedRangeNotSatisfiable, response.StatusCode);
                replacedert.Equal<long?>(0, response.Content.Headers.ContentLength);

                //-0
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(null, 0);
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.RequestedRangeNotSatisfiable, response.StatusCode);
                replacedert.Equal<long?>(0, response.Content.Headers.ContentLength);

                //Invalid ranges last-post > first-pos
                httpClient.DefaultRequestHeaders.Range = null;
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Range", "bytes=100-50");
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
                replacedert.Null(response.Content.Headers.ContentRange);
                replacedert.Equal<long>(fileContent.Length, response.Content.Headers.ContentLength.Value);

                //Invalid Customized ranges 'pages' instead of 'bytes'. We don't understand what this is. So we should return the full page. 
                httpClient.DefaultRequestHeaders.Remove("Range");
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Range", "pages=1-b");
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
                replacedert.Null(response.Content.Headers.ContentRange);
                replacedert.Equal<long>(fileContent.Length, response.Content.Headers.ContentLength.Value);

                //Multi range requests - not understand we serve the entire file
                httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue();
                httpClient.DefaultRequestHeaders.Range.Ranges.Add(new RangeItemHeaderValue(1, 2));
                httpClient.DefaultRequestHeaders.Range.Ranges.Add(new RangeItemHeaderValue(5, 12));
                httpClient.DefaultRequestHeaders.Range.Ranges.Add(new RangeItemHeaderValue(22, 32));
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                replacedert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
                replacedert.Null(response.Content.Headers.ContentRange);
                replacedert.Equal<long?>(fileContent.Length, response.Content.Headers.ContentLength);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 0, fileContent.Length - 1);
            }
        }

19 View Source File : PersistentCookie.cs
License : Apache License 2.0
Project Creator : aspnet

[Theory, Trait("FunctionalTests", "Security")]
        [InlineData(HostType.IIS)]
        [InlineData(HostType.HttpListener)]
        public void Security_PersistentCookie(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string applicationUrl = deployer.Deploy(hostType, PersistentCookieConfiguration);
                string homePath = applicationUrl + "Auth/Home";
                string logoutPath = applicationUrl + string.Format("Auth/Logout?ReturnUrl={0}", new Uri(homePath).AbsolutePath);

                var handler = new HttpClientHandler();
                var httpClient = new HttpClient(handler);

                // Unauthenticated request
                var response = httpClient.GetAsync(applicationUrl).Result;
                CookiesCommon.IsRedirectedToCookiesLogin(response.RequestMessage.RequestUri, applicationUrl, "Unauthenticated requests not automatically redirected to login page");

                // Valid credentials
                var validPersistingCredentials = new FormUrlEncodedContent(new kvp[] { new kvp("username", "test"), new kvp("preplacedword", "test"), new kvp("rememberme", "on") });
                response = httpClient.PostAsync(response.RequestMessage.RequestUri, validPersistingCredentials).Result;
                response.EnsureSuccessStatusCode();
                replacedert.Equal<string>(applicationUrl, response.RequestMessage.RequestUri.AbsoluteUri);

                //Verify cookie sent
                replacedert.True(handler.CookieContainer.Count == 1, "Did not receive one cookie as expected");
                var cookie = handler.CookieContainer.GetCookies(new Uri(applicationUrl))[0];
                replacedert.True(cookie != null && cookie.Name == "KATANACOOKIE", "Cookie with name 'KATANACOOKIE' not found");
                replacedert.True((cookie.Expires - DateTime.Now).Days > 10, "Did not receive a persistent cookie");

                //Logout the client
                response = httpClient.GetAsync(logoutPath).Result;
                replacedert.True(handler.CookieContainer.Count == 0, "Cookie is not cleared on logout");
                replacedert.Equal<string>(homePath, response.RequestMessage.RequestUri.AbsoluteUri);

                //Try accessing protected resource again. It should get redirected to login page
                response = httpClient.GetAsync(applicationUrl).Result;
                CookiesCommon.IsRedirectedToCookiesLogin(response.RequestMessage.RequestUri, applicationUrl, "Request not automatically redirected to login page after cookie expiry");
            }
        }

19 View Source File : Tests.cs
License : MIT License
Project Creator : adamped

[Fact]
		public void Test()
		{
			Mock<IService> serviceMock = new Mock<IService>();
			serviceMock.Setup(x => x.Login("username", "preplacedword"))
					   .Returns(true);

			var model = new AuthenticationModel(serviceMock.Object);

			replacedert.True(model.IsAuthenticated(), "User was not authenticated");
		}

19 View Source File : GridifyMapperShould.cs
License : MIT License
Project Creator : alirezanet

[Fact]
      public void CaseSensitivity()
      {
         var sut = new GridifyMapper<TestClreplaced>(q => q.CaseSensitive = true);
         sut.AddMap("id", q => q.Id);

         replacedert.True(sut.HasMap("id"));
         replacedert.False(sut.HasMap("ID"));
      }

19 View Source File : AzureAdB2COpenIDConnectEventHandlersTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public async Task OnRemoteError_HandlesResponseWhenTryingToResetPreplacedwordFromTheLoginPage()
        {
            // Arrange

            var handlers = new AzureADB2COpenIDConnectEventHandlers(
                AzureADB2CDefaults.AuthenticationScheme,
                new AzureADB2COptions() { SignUpSignInPolicyId = "B2C_1_SiUpIn" });

            var remoteFailureContext = new RemoteFailureContext(
                new DefaultHttpContext(),
                new AuthenticationScheme(
                    AzureADB2CDefaults.AuthenticationScheme,
                    displayName: null,
                    handlerType: typeof(OpenIdConnectHandler)),
                new OpenIdConnectOptions(),
                new OpenIdConnectProtocolException("AADB2C90118"));

            // Act
            await handlers.OnRemoteFailure(remoteFailureContext);

            // replacedert
            replacedert.Equal(StatusCodes.Status302Found, remoteFailureContext.Response.StatusCode);
            replacedert.Equal("/AzureADB2C/Account/ResetPreplacedword/AzureADB2C", remoteFailureContext.Response.Headers[HeaderNames.Location]);
            replacedert.True(remoteFailureContext.Result.Handled);
        }

19 View Source File : MapOwinPathTest.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact, Trait("FunctionalTests", "General")]
        public void MapOwinPath()
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                string url = deployer.Deploy(HostType.IIS, MapOwinPathConfiguration);
                ((WebDeployer)deployer.Application).Application.Deploy("Default.aspx", File.ReadAllText("RequirementFiles\\Default.aspx"));

                replacedert.True(HttpClientUtility.GetResponseTextFromUrl(url + "/Default.aspx").Contains("Asp.net Test page"), "Default.aspx page not returned successfully in SxS mode");
                replacedert.Equal(HttpClientUtility.GetResponseTextFromUrl(url + "/prefix1"), "prefix1");
                replacedert.Equal(HttpClientUtility.GetResponseTextFromUrl(url + "/prefix1Append"), "prefix1Append");
                replacedert.Equal(HttpClientUtility.GetResponseTextFromUrl(url + "/prefix2"), "prefix2");
            }
        }

19 View Source File : RequestBodyTests.cs
License : Apache License 2.0
Project Creator : aspnet

public void ReadBodyTwiceViaSeekApp(IAppBuilder app)
        {
            app.Run(context =>
            {
                var reader = new StreamReader(context.Request.Body);
                string text = reader.ReadToEnd();
                context.Response.WriteAsync(text).Wait();
                replacedert.True(context.Request.Body.CanSeek);
                context.Request.Body.Seek(0, SeekOrigin.Begin);
                reader = new StreamReader(context.Request.Body);
                text = reader.ReadToEnd();
                return context.Response.WriteAsync(text);
            });
        }

See More Examples