Beispiel #1
0
        public void Post_Update()
        {
            // Arrange
            var recordContract = new RecordContract
            {
                ApplicationName = "testAppName",
                DataType        = "dataType",
                Version         = "version1",
                Value           = "value",
                DateCreated     = DateTime.UtcNow,
                DateModified    = DateTime.UtcNow
            };

            var req = new MockHttpRequest
            {
                Body = RecordFunctionTests.GenerateStreamFromString(_record)
            };
            var mapper = Substitute.For <IMapper>();
            var repo   = Substitute.For <IRepository>();

            repo.UpsertRecord(Arg.Any <Model.Record>()).Returns(Task.FromResult <Model.Record>(new Model.Record
            {
                DateModified = DateTime.Now
            }));

            var logger = Substitute.For <ILogger <Records> >();

            var target = new Records(repo, mapper);

            // Act
            var result = target.Post(req, logger).Result;

            // Assert
            Assert.IsType <OkObjectResult>(result);
        }
        public async Task <ITestableHttpResponse> SendAsync(HttpRequestMessage request)
        {
            var testableHttpRequest = new MockHttpRequest(request, request.Content != null ? await request.Content.ReadAsByteArrayAsync() : null, _client.BaseAddress);
            var response            = await _client.SendAsync(request, HttpCompletionOption.ResponseContentRead);

            return(LastResponse = new TestableHttpResponse(response, await response.Content.ReadAsByteArrayAsync(), testableHttpRequest));
        }
    public async Task ReadGet()
    {
        var mockHttpRequest = new MockHttpRequest
        {
            Query = new QueryCollection(
                new Dictionary <string, StringValues>
            {
                {
                    "query",
                    new StringValues("theQuery")
                },
                {
                    "operation",
                    new StringValues("theOperation")
                },
                {
                    "variables",
                    new StringValues(JsonConvert.SerializeObject(
                                         new Inputs(new Dictionary <string, object>
                    {
                        { "key", "value" }
                    })))
                }
            })
        };
        var result = RequestReader.ReadGet(mockHttpRequest);

        await Verify(new
        {
            result.inputs,
            result.operation,
            result.query
        });
    }
        public void Can_mock_uploading_files()
        {
            using (new BasicAppHost
            {
                ConfigureAppHost = host => host.VirtualFiles = new InMemoryVirtualPathProvider(host),
            }.Init())
            {
                var ms = new MemoryStream("mocked".ToUtf8Bytes());
                var httpFile = new HttpFile
                {
                    ContentType = "application/x-msaccess",
                    FileName = "C:\\path\\to\\file.txt",
                    InputStream = ms,
                    ContentLength = ms.ToArray().Length,
                };
                var mockReq = new MockHttpRequest
                {
                    Files = new IHttpFile[] { httpFile },
                };
                //Mock Session
                mockReq.Items[Keywords.Session] = new AuthUserSession { Id = "sess-id" };

                var service = new UploadFileService
                {
                    Request = mockReq
                };

                service.Any(new MockUploadFile());

                var files = HostContext.VirtualFiles.GetAllFiles().ToList();
                Assert.That(files[0].ReadAllText(), Is.EqualTo("mocked"));
            }
        }
Beispiel #5
0
        public void Initialize(string accessToken, Func <string> pathGetter, bool verifyResult = true, bool logoutResult = true)
        {
            RedirectUrl      = string.Empty;
            LogoutToken      = string.Empty;
            VerifyToken      = string.Empty;
            IsNextStepCalled = false;

            var request = new MockHttpRequest(new Dictionary <string, string>()
            {
                { "access_token", accessToken }
            }, pathGetter);
            var response = new MockHttpResponse(url => RedirectUrl = url);

            _mockHttpContext = new MockHttpContext(request, response);

            Func <string, Task <bool> > OnLogout = lt => { LogoutToken = lt; return(Task.FromResult(logoutResult)); };
            Func <string, Task <bool> > OnVerify = vt => { VerifyToken = vt; return(Task.FromResult(verifyResult)); };

            var mockAuthService = new Mock <IAuthenticationService>();

            mockAuthService.Setup(s => s.Logout(It.IsAny <string>())).Returns(OnLogout);
            mockAuthService.Setup(s => s.VerifyToken(It.IsAny <string>())).Returns(OnVerify);
            mockAuthService.Setup(s => s.RedirectToLogin(It.IsAny <string>(), It.IsAny <Action <string> >()))
            .Callback <string, Action <string> >((url, rdr) => rdr(url));

            RequestDelegate reqDlg = context => { IsNextStepCalled = true; return(Task.FromResult(true)); };

            _middleware = new AuthenticationMiddleware(reqDlg, LoggerFactory, AuthenticationOptions, mockAuthService.Object);
        }
Beispiel #6
0
        private async Task ProcessRequest(HttpListenerContext ctx)
        {
            var response = new MockHttpResponse(ctx.Response);

            try
            {
                var content = await ReadContentAsync(ctx);

                var request = new MockHttpRequest(ctx.Request, content, BaseAddress);

                var processor = _processors.FirstOrDefault(p => p.Match(request)) ?? NotImplementedProcessor;
                await processor.ProcessRequestAsync(request, response);

                await response.SendResponseAsync();
            }
            catch (Exception e)
            {
                ctx.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;
                ctx.Response.ContentType = "text";
                var buffer = Encoding.UTF8.GetBytes(e.ToString());
                ctx.Response.ContentEncoding = Encoding.UTF8;
                ctx.Response.ContentLength64 = buffer.Length;
                ctx.Response.OutputStream.Write(buffer, 0, buffer.Length);
            }
            finally
            {
                response.Close();
            }
        }
Beispiel #7
0
        private static void CanOptimizeResult(string contentType, IPlugin pluginFormat)
        {
            using var appHost = new BasicAppHost().Init();
            var dto = new TestDto {
                Name = "test"
            };

            var httpReq = new MockHttpRequest {
                PathInfo = "/"
            };

            httpReq.Headers.Add(HttpHeaders.AcceptEncoding, "gzip,deflate,sdch");
            httpReq.ResponseContentType = contentType;

            if (pluginFormat != null)
            {
                pluginFormat.Register(appHost);
            }

#pragma warning disable CS0618
            object result = httpReq.ToOptimizedResult(dto);
#pragma warning restore CS0618
            Assert.IsNotNull(result);
            Assert.IsTrue(result is CompressedResult);
        }
 /// <summary>Creates a request.</summary>
 ///
 /// <param name="userHostAddress">The user host address.</param>
 ///
 /// <returns>The new request.</returns>
 public IHttpRequest CreateRequest(string userHostAddress)
 {
     var httpReq = new MockHttpRequest("test", HttpMethods.Get, ContentType.Json, "/", null, null, null) {
         UserHostAddress = userHostAddress
     };
     return httpReq;
 }
Beispiel #9
0
        public void ShouldRedirectToFailurePathIfErrorIn()
        {
            // See https://tools.ietf.org/html/rfc6749#section-4.1.2.1
            var subject = new MicrosoftGraphAuthenticationProvider(new TestAzureGraphService())
            {
                FailureRedirectPath = "/auth-failure"
            };
            var auth = new Authenticate
            {
                UserName = "******"
            };

            var request = new MockHttpRequest("auth", "GET", "text", "/auth/foo?error=invalid_request",
                                              new NameValueCollection {
                { "error", "invalid_request" }
            }, Stream.Null, null);
            var mockAuthService = MockAuthService(request);

            var response = subject.Authenticate(mockAuthService.Object, new AuthUserSession(), auth);

            var result = (IHttpResult)response;

            //var redirectRequest = new Uri(result.Headers["Location"]);
            Assert.Equal("http://localhost/auth-failure?f=invalid_request&response_type=code",
                         result.Headers["Location"]);
            var query = PclExportClient.Instance.ParseQueryString(new Uri(result.Headers["Location"]).Query);

            Assert.Equal("code", query["response_type"]);
        }
        public async Task Can_respond_to_non_range_requests_with_200_OK_response()
        {
            var mockRequest  = new MockHttpRequest();
            var mockResponse = new MockHttpResponse(mockRequest);

            string customText = "1234567890";

            byte[] customTextBytes = customText.ToUtf8Bytes();
            var    ms = new MemoryStream();

            ms.Write(customTextBytes, 0, customTextBytes.Length);

            var httpResult = new HttpResult(ms, "audio/mpeg");

            bool responseWasAutoHandled = await mockResponse.WriteToResponse(mockRequest, httpResult);

            Assert.That(responseWasAutoHandled, Is.True);

            string writtenString = mockResponse.ReadAsString();

            Assert.That(writtenString, Is.EqualTo(customText));

            Assert.That(mockResponse.Headers.ContainsKey("Content-Range"), Is.False);
            Assert.That(mockResponse.Headers["Accept-Ranges"], Is.EqualTo("bytes"));
            Assert.That(mockResponse.StatusCode, Is.EqualTo(200));
        }
Beispiel #11
0
        public object GetRequest(
            string httpMethod,
            string pathInfo,
            Dictionary <string, string> queryString,
            Dictionary <string, string> formData,
            string requestBody)
        {
            var httpHandler = GetHandler(httpMethod, pathInfo);

            var contentType = (formData != null && formData.Count > 0)
                ? MimeTypes.FormUrlEncoded
                : requestBody != null ? MimeTypes.Json : null;

            var httpReq = new MockHttpRequest(
                httpHandler.RequestName, httpMethod, contentType,
                pathInfo,
                queryString.ToNameValueCollection(),
                requestBody == null ? null : new MemoryStream(Encoding.UTF8.GetBytes(requestBody)),
                formData.ToNameValueCollection()
                );

            var request = httpHandler.CreateRequest(httpReq, httpHandler.RequestName);

            return(request);
        }
        private static void CanOptimizeResult(string contentType, IPlugin pluginFormat)
        {
            var dto = new TestDto {
                Name = "test"
            };

            var httpReq = new MockHttpRequest();

            httpReq.Headers.Add(HttpHeaders.AcceptEncoding, "gzip,deflate,sdch");
            httpReq.ResponseContentType = contentType;
            var httpRes = new ViewTests.MockHttpResponse();

            var httpRequestContext = new HttpRequestContext(httpReq, httpRes, dto);

            var appHost = new TestAppHost();

            if (pluginFormat != null)
            {
                pluginFormat.Register(appHost);
            }

            EndpointHost.ContentTypeFilter = appHost.ContentTypeFilters;

            object result = httpRequestContext.ToOptimizedResult(dto);

            Assert.IsNotNull(result);
            Assert.IsTrue(result is CompressedResult);
        }
Beispiel #13
0
        public void ShouldSetCallbackUrlWithoutParameters()
        {
            var subject = new MicrosoftGraphAuthenticationProvider(new TestAzureGraphService());
            var auth    = new Authenticate
            {
                UserName = "******"
            };

            var request = new MockHttpRequest("auth", "GET", "text",
                                              "/auth/foo/bar?redirect=" + "http://localhost/secure-resource".UrlEncode(), new NameValueCollection
            {
                { "redirect", "http://localhost/secure-resource" }
            }, Stream.Null, null);
            var mockAuthService = MockAuthService(request);

            var response = subject.Authenticate(mockAuthService.Object, new AuthUserSession(), auth);

            var result      = (IHttpResult)response;
            var codeRequest = new Uri(result.Headers["Location"]);
            var query       = PclExportClient.Instance.ParseQueryString(codeRequest.Query);

            Assert.Equal(query["response_type"], "code");
            Assert.Equal(subject.CallbackUrl, "http://localhost/auth/foo/bar");
            Assert.Equal(query["redirect_uri"].UrlDecode(), subject.CallbackUrl);
        }
        public void ShouldRequestTokenWithCustomDirectoryResolver(string username)
        {
            var appHost   = TestServer.Current;
            var directory = new ApplicationRegistration
            {
                ClientId      = "custom-clientid",
                ClientSecret  = "custom-clientsecret",
                DirectoryName = "custom-foodomain.com"
            };
            var auth = new Authenticate {
                UserName = username
            };

            var subject = new AzureAuthenticationProvider(new TestAzureGraphService())
            {
                ApplicationDirectoryResolver = (serviceBase, registryService, s) => directory,
            };

            var session = new AuthUserSession
            {
                State    = "D79E5777-702E-4260-9A62-37F75FF22CCE",
                UserName = auth.UserName
            };

            subject.CallbackUrl = "http://localhost/myapp/";
            var request = new MockHttpRequest("myapp", "GET", "text", "/myapp", new NameValueCollection
            {
                {
                    "code",
                    "AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrqqf_ZT_p5uEAEJJ_nZ3UmphWygRNy2C3jJ239gV_DBnZ2syeg95Ki-374WHUP-i3yIhv5i-7KU2CEoPXwURQp6IVYMw-DjAOzn7C3JCu5wpngXmbZKtJdWmiBzHpcO2aICJPu1KvJrDLDP20chJBXzVYJtkfjviLNNW7l7Y3ydcHDsBRKZc3GuMQanmcghXPyoDg41g8XbwPudVh7uCmUponBQpIhbuffFP_tbV8SNzsPoFz9CLpBCZagJVXeqWoYMPe2dSsPiLO9Alf_YIe5zpi-zY4C3aLw5g9at35eZTfNd0gBRpR5ojkMIcZZ6IgAA"
                },
                { "session_state", "7B29111D-C220-4263-99AB-6F6E135D75EF" },
                { "state", "D79E5777-702E-4260-9A62-37F75FF22CCE" }
            }, Stream.Null, new NameValueCollection());

            var mockAuthService = MockAuthService(request, appHost);
            var response        = (IHttpResult)subject.Authenticate(mockAuthService.Object, session, auth);

            Assert.True(session.IsAuthenticated);
            var tokens = session.GetAuthTokens("ms-graph");

            Assert.NotNull(tokens);
            Assert.Equal("ms-graph", tokens.Provider);
            Assert.Equal(tokens.AccessTokenSecret, TokenHelper.AccessToken);
            Assert.NotNull(tokens.RefreshTokenExpiry);
            Assert.Equal(tokens.RefreshToken, TokenHelper.RefreshToken);

            // Regardless of what is entered up front, Azure will determine what the identity values are
            Assert.Equal("d542096aa0b94e2195856b57e43257e4", tokens.UserId); // oid
            Assert.Equal("*****@*****.**", tokens.UserName);
            Assert.Equal("Some User", tokens.DisplayName);
            Assert.Equal(session.UserName, tokens.UserName);
            Assert.Equal(session.LastName, tokens.LastName);
            Assert.Equal(session.FirstName, tokens.FirstName);
            Assert.Equal(session.DisplayName, tokens.DisplayName);

            var result = (IHttpResult)response;

            Assert.StartsWith("http://localhost#s=1", result.Headers["Location"]);
        }
        public void ShouldSetReferrerFromRedirectParam()
        {
            var appHost = TestServer.Current;
            var subject = new AzureAuthenticationProvider(new TestAzureGraphService());
            var auth    = new Authenticate
            {
                UserName = "******"
            };

            var session = new AuthUserSession();
            var request = new MockHttpRequest("myapp", "GET", "text", "/myapp", new NameValueCollection
            {
                { "redirect", "http://localhost/myapp/secure-resource" }
            }, Stream.Null, null)
            {
                Items =
                {
                    { Keywords.Session, session }
                }
            };
            //subject.Request = request;
            var mockAuthService = MockAuthService(request, appHost);

            var result = subject.Authenticate(mockAuthService.Object, session, auth); // subject.Post(auth);

            Assert.Equal("http://localhost/myapp/secure-resource", session.ReferrerUrl);
        }
            public void WhenAuthorizeSubscriptionServiceRequestsAndForGetSubscriptionAndAuthenticatedInWrongRole_ThenThrowsForbidden()
            {
                var feature = new WebhookFeature();

                feature.Register(appHost);
                var request = new MockHttpRequest
                {
                    PathInfo = new GetSubscription
                    {
                        Id = "asubscriptionid"
                    }.ToGetUrl(),
                    Dto = new GetSubscription()
                };

                request.Items.Add(Keywords.Session, new AuthUserSession
                {
                    IsAuthenticated = true,
                    Roles           = new List <string> {
                        "anotherrole"
                    }
                });
                var response = new MockHttpResponse(request);

                Assert.That(() => feature.AuthorizeSubscriptionServiceRequests(request, response, new TestDto()), ThrowsHttpError.WithStatusCode(HttpStatusCode.Forbidden));
            }
Beispiel #17
0
        private void VerifyNotAuthenticatedByToken()
        {
            Subject.CallbackUrl = "http://localhost/myapp/";
            using (TestAppHost())
            {
                var request = new MockHttpRequest("myapp", "GET", "text", "/myapp", new NameValueCollection
                {
                    { "code", "code123" },
                    { "state", "D79E5777-702E-4260-9A62-37F75FF22CCE" }
                }, Stream.Null, null);
                var mockAuthService = MockAuthService(request);
                using (new HttpResultsFilter
                {
                    StringResult =
                        @"{
                          ""access_token"": ""token456"",
                          ""id_token"": ""eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83ZmU4MTQ0Ny1kYTU3LTQzODUtYmVjYi02ZGU1N2YyMTQ3N2UvIiwiaWF0IjoxMzg4NDQwODYzLCJuYmYiOjEzODg0NDA4NjMsImV4cCI6MTM4ODQ0NDc2MywidmVyIjoiMS4wIiwidGlkIjoiN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0NzdlIiwib2lkIjoiNjgzODlhZTItNjJmYS00YjE4LTkxZmUtNTNkZDEwOWQ3NGY1IiwidXBuIjoiZnJhbmttQGNvbnRvc28uY29tIiwidW5pcXVlX25hbWUiOiJmcmFua21AY29udG9zby5jb20iLCJzdWIiOiJKV3ZZZENXUGhobHBTMVpzZjd5WVV4U2hVd3RVbTV5elBtd18talgzZkhZIiwiZmFtaWx5X25hbWUiOiJNaWxsZXIiLCJnaXZlbl9uYW1lIjoiRnJhbmsifQ.""
                        }"
                })
                {
                    var session = new AuthUserSession();

                    try{ Subject.Authenticate(mockAuthService.Object, session, new Authenticate()); }
                    catch (UnauthorizedAccessException) {}

                    session.IsAuthenticated.Should().BeFalse();
                }
            }
        }
        public void Can_optimize_result_with_ToOptimizedResult()
        {
            var dto = new TestDto {
                Name = "test"
            };

            var httpReq = new MockHttpRequest();

            httpReq.Headers.Add(HttpHeaders.AcceptEncoding, "gzip,deflate,sdch");
            httpReq.ResponseContentType = "text/html";
            var httpRes = new ViewTests.MockHttpResponse();

            var httpRequestContext = new HttpRequestContext(httpReq, httpRes, dto);

            var appHost = new TestAppHost();

            new HtmlFormat().Register(appHost);

            EndpointHost.ContentTypeFilter = appHost.ContentTypeFilters;

            object result = httpRequestContext.ToOptimizedResult(dto);

            Assert.IsNotNull(result);
            Assert.IsTrue(result is CompressedResult);
        }
Beispiel #19
0
        public void ShouldSaveExtendedInfoFromPayload()
        {
            using (TestAppHost())
            {
                Subject.SaveExtendedUserInfo = true;
                Subject.ClientId             = "2d4d11a2-f814-46a7-890a-274a72a7309e";
                var request = new MockHttpRequest("myapp", "GET", "text", "/myapp", new NameValueCollection {
                    { "code", "c1" },
                    { "state", "s1" }
                }, Stream.Null, null);
                var mockAuthService = MockAuthService(request);
                using (new HttpResultsFilter
                {
                    StringResult = @"{
                          ""access_token"": ""t1"",
                          ""token_type"": ""Bearer"",
                          ""id_token"": ""eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83ZmU4MTQ0Ny1kYTU3LTQzODUtYmVjYi02ZGU1N2YyMTQ3N2UvIiwiaWF0IjoxMzg4NDQwODYzLCJuYmYiOjEzODg0NDA4NjMsImV4cCI6MTM4ODQ0NDc2MywidmVyIjoiMS4wIiwidGlkIjoiN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0NzdlIiwib2lkIjoiNjgzODlhZTItNjJmYS00YjE4LTkxZmUtNTNkZDEwOWQ3NGY1IiwidXBuIjoiZnJhbmttQGNvbnRvc28uY29tIiwidW5pcXVlX25hbWUiOiJmcmFua21AY29udG9zby5jb20iLCJzdWIiOiJKV3ZZZENXUGhobHBTMVpzZjd5WVV4U2hVd3RVbTV5elBtd18talgzZkhZIiwiZmFtaWx5X25hbWUiOiJNaWxsZXIiLCJnaXZlbl9uYW1lIjoiRnJhbmsifQ.""
                        }"
                })
                {
                    var session = new AuthUserSession {
                        State = "s1"
                    };

                    Subject.Authenticate(mockAuthService.Object, session, new Authenticate());

                    var tokens = session.GetOAuthTokens("aad");
                    var items  = tokens.Items;
                    items["token_type"].Should().Be("Bearer");
                    items["iss"].Should().Be("https://sts.windows.net/7fe81447-da57-4385-becb-6de57f21477e/");
                    items["sub"].Should().Be("JWvYdCWPhhlpS1Zsf7yYUxShUwtUm5yzPmw_-jX3fHY");
                }
            }
        }
Beispiel #20
0
        private static MockHttpRequest GetBearerToken(Dictionary <string, string> postData)
        {
            //get an access_token to test with ex:

            //{
            //"access_token":"eyJhbGciOiJSUzI1NiIsImtpZCI6IjcyOThjZjAyMDA2MWU4MDIzYzE1NjM3ZTc3NzNjZGE2IiwidHlwIjoiSldUIn0.eyJuYmYiOjE1MjM5MDMxMjcsImV4cCI6MTUyMzkwNjcyNywiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC9yZXNvdXJjZXMiLCJhcGkxIl0sImNsaWVudF9pZCI6InJvLmNsaWVudCIsInN1YiI6IjEiLCJhdXRoX3RpbWUiOjE1MjM5MDMxMjcsImlkcCI6ImxvY2FsIiwic2NvcGUiOlsiYXBpMSJdLCJhbXIiOlsicHdkIl19.Gv9SI2nBy0_qoZ-VAUVO0Xa0qxhXLTSsb4jTn1AXUvJYb3xBme6OCQgJu3i8yZh4LMsVzTn1HJZUQYdFgw2dXuLrPr_KrOblU7DzOyhXWEGM4UawVng518FwOWd9raN-NbE1GzYUiEzjX6v-ZyVbgpypvTepGpmk8c4gNM-6N9KoeAcnchoxHmvJSMS-MgYPeJ-hJRGUVkIdc1l5eAAhU3vyrBjK9ydk2FRhk_Bg1SlExvIKcKxDcv1I1pc7pc1eyFCb7DBnA7lDbdK4_Sjre94jNDLjaTqtD6KIbHH1eOGCk_DgOMCUsn-nKIZeVtce5OJ0opVKucokGxUX9ft6fA",
            //	"expires_in":3600,
            //	"token_type":"Bearer"
            //}

            var issuer = new Uri(newConfig.issuer);
            //possible discovery config
            var tokenUri = new Uri(issuer, "connect/token");

            HttpClient client = new HttpClient();

            var content = new FormUrlEncodedContent(postData);

            var response = client.PostAsync(tokenUri, content).GetAwaiter().GetResult();

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception($"status: {response.StatusCode} {response.ReasonPhrase}");
            }
            var responseString = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
            var token          = JsonConvert.DeserializeObject <Access_Token>(responseString);

            //'Authorization: Bearer ACCESS_TOKEN'
            var request = new MockHttpRequest(new Dictionary <string, string> {
                { "Authorization", $"{token.token_type} {token.access_token}" }
            });

            return(request);
        }
        public void CreateRequestsReturnsEmpty()
        {
            MockHttpRequest.RegisterMockResponse(new Uri("http://host/"), "text/html", "<html/>");
            var consumer = TestSupport.CreateRelyingParty(null);

            CollectionAssert.IsEmpty(consumer.CreateRequests("http://host/", realm, returnTo));
        }
            public void WhenPreAuthenticateWithOnGetSecretAndRightSignature_ThenPopulatesSession()
            {
                var body      = Encoding.UTF8.GetBytes("abody");
                var signature = Webhooks.Security.HmacUtils.CreateHmacSignature(body, "asecret");

                using (var stream = MemoryStreamFactory.GetStream(body))
                {
                    var request = new MockHttpRequest
                    {
                        InputStream = stream,
                        Headers     = new NameValueCollection
                        {
                            { WebhookEventConstants.SecretSignatureHeaderName, signature },
                            { WebhookEventConstants.RequestIdHeaderName, "arequestid" }
                        },
                        IsSecureConnection = true
                    };

                    provider.Secret      = null;
                    provider.OnGetSecret = (req, name) => provider.Secret = "asecret";

                    provider.PreAuthenticate(request, new MockHttpResponse(request));

                    var session = request.GetSession();
                    Assert.That(session.Id, Is.Not.Null);
                    Assert.That(session.IsAuthenticated, Is.True);
                    Assert.That(session.UserAuthId, Is.EqualTo("arequestid"));
                    Assert.That(session.UserAuthName, Is.EqualTo("localhost"));
                    Assert.That(session.UserName, Is.EqualTo("localhost"));
                }
            }
Beispiel #23
0
        public void ShouldRequestAuthorizationFromUserDomain()
        {
            using (AadAuthProviderTest.TestAppHost())
            {
                var request = new MockHttpRequest("myapp", "GET", "text", "/myapp", new NameValueCollection
                {
                    { "redirect", "http://localhost/myapp/secure-resource" }
                }, Stream.Null, null);
                var mockAuthService = MockAuthService(_directoryRepository, request);
                var session         = new AuthUserSession();

                var username = "******" + OrmLiteDirectoryRepositoryTest.Directory1.DirectoryDomain;
                var response = Subject.Authenticate(mockAuthService.Object, session, new Authenticate()
                {
                    UserName = username,
                    provider = AadMultiTenantAuthProvider.Name
                });
                var result      = (IHttpResult)response;
                var codeRequest = new Uri(result.Headers["Location"]);
                var query       = PclExportClient.Instance.ParseQueryString(codeRequest.Query);
                var d           = OrmLiteDirectoryRepositoryTest.Directory1;

                query["client_id"].Should().Be(d.ClientId);
                query["domain_hint"].Should().Be(d.DomainHint);
                query["login_hint"].Should().Be(username);
                codeRequest.Authority.Should().Be("login.microsoftonline.com");
                codeRequest.LocalPath.Should().Be($"/{d.TenantId}/oauth2/authorize");
                codeRequest.Scheme.Should().Be(Uri.UriSchemeHttps);

                session.ReferrerUrl.Should().Be("http://localhost/myapp/secure-resource");
            }
        }
        public async Task Can_use_fileStream()
        {
            byte[] fileBytes = uploadedTextFile.ReadFully();
            string fileText  = Encoding.ASCII.GetString(fileBytes);

            "File content size {0}".Print(fileBytes.Length);
            "File content is {0}".Print(fileText);

            var mockRequest  = new MockHttpRequest();
            var mockResponse = new MockHttpResponse(mockRequest);

            mockRequest.Headers.Add("Range", "bytes=6-8");

            var httpResult = new HttpResult(uploadedTextFile, "audio/mpeg");

            bool reponseWasAutoHandled = await mockResponse.WriteToResponse(mockRequest, httpResult);

            Assert.That(reponseWasAutoHandled, Is.True);

            string writtenString = mockResponse.ReadAsString();

            Assert.That(writtenString, Is.EqualTo(fileText.Substring(6, 3)));

            Assert.That(mockResponse.Headers["Content-Range"], Is.EqualTo("bytes 6-8/33"));
            Assert.That(mockResponse.Headers["Content-Length"], Is.EqualTo(writtenString.Length.ToString()));
            Assert.That(mockResponse.Headers["Accept-Ranges"], Is.EqualTo("bytes"));
            Assert.That(mockResponse.StatusCode, Is.EqualTo(206));
        }
        public async Task Can_seek_from_beginning_to_further_than_end()
        {
            // Not sure if this would ever occur in real streaming scenarios, but it does occur
            // when some crawlers use range headers to specify a max size to return.
            // e.g. Facebook crawler always sends range header of 'bytes=0-524287'.

            var mockRequest  = new MockHttpRequest();
            var mockResponse = new MockHttpResponse(mockRequest);

            mockRequest.Headers[HttpHeaders.Range] = "bytes=0-524287";

            string customText = "1234567890";

            byte[] customTextBytes = customText.ToUtf8Bytes();
            var    ms = new MemoryStream();

            ms.Write(customTextBytes, 0, customTextBytes.Length);

            var httpResult = new HttpResult(ms, "audio/mpeg");

            bool reponseWasAutoHandled = await mockResponse.WriteToResponse(mockRequest, httpResult);

            Assert.That(reponseWasAutoHandled, Is.True);

            string writtenString = mockResponse.ReadAsString();

            Assert.That(writtenString, Is.EqualTo(customText));

            Assert.That(mockResponse.Headers["Content-Range"], Is.EqualTo("bytes 0-9/10"));
            Assert.That(mockResponse.Headers["Content-Length"], Is.EqualTo(writtenString.Length.ToString()));
            Assert.That(mockResponse.Headers["Accept-Ranges"], Is.EqualTo("bytes"));
            Assert.That(mockResponse.StatusCode, Is.EqualTo(206));
        }
Beispiel #26
0
        public object GetRequest(
            string httpMethod,
            string pathInfo,
            Dictionary <string, string> queryString,
            Dictionary <string, string> formData,
            string requestBody)
        {
            var contentType = (formData != null && formData.Count > 0)
                ? MimeTypes.FormUrlEncoded
                : requestBody != null ? MimeTypes.Json : null;

            var httpReq = new MockHttpRequest(
                nameof(MockHttpRequest),
                httpMethod,
                contentType,
                pathInfo,
                queryString.ToNameValueCollection(),
                requestBody == null ? null : Encoding.UTF8.GetBytes(requestBody).InMemoryStream(),
                formData.ToNameValueCollection()
                );

            var httpHandler = (IRequestHttpHandler)GetHandler(httpReq);

            httpReq.OperationName = httpHandler.RequestName;

            var request = httpHandler.CreateRequestAsync(httpReq, httpHandler.RequestName).Result;

            return(request);
        }
        public void Can_mock_uploading_files()
        {
            using (new BasicAppHost
            {
                ConfigureAppHost = host => host.VirtualFiles = new MemoryVirtualFiles(),
            }.Init())
            {
                var ms       = new MemoryStream("mocked".ToUtf8Bytes());
                var httpFile = new HttpFile
                {
                    ContentType   = "application/x-msaccess",
                    FileName      = "C:\\path\\to\\file.txt",
                    InputStream   = ms,
                    ContentLength = ms.ToArray().Length,
                };
                var mockReq = new MockHttpRequest
                {
                    Files = new IHttpFile[] { httpFile },
                };
                //Mock Session
                mockReq.Items[Keywords.Session] = new AuthUserSession {
                    Id = "sess-id"
                };

                var service = new UploadFileService
                {
                    Request = mockReq
                };

                service.Any(new MockUploadFile());

                var files = HostContext.VirtualFiles.GetAllFiles().ToList();
                Assert.That(files[0].ReadAllText(), Is.EqualTo("mocked"));
            }
        }
Beispiel #28
0
        public void Benchmark_Razor_vs_Markdown()
        {
            var iterations = 10000;
            var razorFormat = RazorFormat.Instance;
            var markdownFmt = MarkdownFormat.Instance;
            var dto = new RockstarsResponse { Results = Rockstar.SeedData.ToList() };

            "Warm up MVC Razor...".Print();
            var mockReq = new MockHttpRequest { OperationName = "RockstarsRazor" };
            var mockRes = new MockHttpResponse(mockReq);
            razorFormat.ProcessRequest(mockReq, mockRes, dto);
            mockRes.ReadAsString().Print();

            "Warm up Markdown Razor...".Print();
            mockReq = new MockHttpRequest { OperationName = "RockstarsMark" };
            mockRes = new MockHttpResponse(mockReq);
            markdownFmt.ProcessRequest(mockReq, mockRes, dto);
            mockRes.ReadAsString().Print();

            "\n\nRunning for {0} times...".Fmt(iterations).Print();
            CompareRuns(iterations,
                "MVC Razor", () => {
                    mockReq = new MockHttpRequest { OperationName = "RockstarsRazor" };
                    mockRes = new MockHttpResponse(mockReq);
                    razorFormat.ProcessRequest(mockReq, mockRes, dto);
                },
                "Markdown Razor", () => {
                    mockReq = new MockHttpRequest { OperationName = "RockstarsMark" };
                    mockRes = new MockHttpResponse(mockReq);
                    markdownFmt.ProcessRequest(mockReq, mockRes, dto);
                });
        }
        public async Task Can_seek_from_middle_to_middle()
        {
            var mockRequest = new MockHttpRequest();

            mockRequest.Headers.Add("Range", "bytes=3-5");
            var mockResponse = new MockHttpResponse(mockRequest);

            string customText = "1234567890";

            byte[] customTextBytes = customText.ToUtf8Bytes();
            var    ms = new MemoryStream();

            ms.Write(customTextBytes, 0, customTextBytes.Length);


            var httpResult = new HttpResult(ms, "audio/mpeg");

            bool reponseWasAutoHandled = await mockResponse.WriteToResponse(mockRequest, httpResult);

            Assert.That(reponseWasAutoHandled, Is.True);

            string writtenString = mockResponse.ReadAsString();

            Assert.That(writtenString, Is.EqualTo("456"));

            Assert.That(mockResponse.Headers["Content-Range"], Is.EqualTo("bytes 3-5/10"));
            Assert.That(mockResponse.Headers["Content-Length"], Is.EqualTo(writtenString.Length.ToString()));
            Assert.That(mockResponse.Headers["Accept-Ranges"], Is.EqualTo("bytes"));
            Assert.That(mockResponse.StatusCode, Is.EqualTo(206));
        }
Beispiel #30
0
        public void TestClientCredentials()
        {
            MockHttpRequest request = GetBearerToken(client_credentials);
            var             result  = _core.Auth.ProcessLogin(request, new MockHttpResponse(), 3600);

            Assert.IsTrue(result.success);
        }
        public void GetRequestCorrelationId_ReturnsRequestFromHeader(string header)
        {
            var request = new MockHttpRequest();
            request.Headers.Add("x-mac-requestid", header);

            var value = request.GetRequestCorrelationId();
            value.Should().Be(header);
        }
Beispiel #32
0
        private static Mock <IServiceBase> MockAuthService(MockHttpRequest request = null)
        {
            request = request ?? new MockHttpRequest();
            var mockAuthService = new Mock <IServiceBase>();

            mockAuthService.SetupGet(s => s.Request).Returns(request);
            return(mockAuthService);
        }
        private void SetCorrelationId()
        {
            var mock = new MockHttpRequest();

            mock.Headers[HeaderName] = correlationId;

            gateway.GetServiceGateway(mock);
        }
        public void GetServiceGateway_CallsUnderlyingGetServiceGateway()
        {
            var mockHttpRequest = new MockHttpRequest();

            gateway.GetServiceGateway(mockHttpRequest);

            A.CallTo(() => decorated.GetServiceGateway(mockHttpRequest)).MustHaveHappened();
        }
Beispiel #35
0
        public void IsMatch_ExactTextRuleInversedWithNonMatchingString_ReturnsTrue()
        {
            var request = new MockHttpRequest
            {
                RawUrl = "/passed/"
            };

            var rule = new UrlRule("not:/failed/");
            Assert.IsTrue(rule.IsMatch(request));
        }
 /// <summary>
 /// Mock a controller context
 /// </summary>
 public MockControllerContext(
         IController ControllerToSet,
         MockPrincipal PrincipalToSet,
         MockIdentity IdentityToSet,
         MockHttpRequest RequestToSet,
         MockHttpResponse ResponseToSet,
         MockHttpSessionState SessionStateToSet)
     : base(new MockHttpContext(PrincipalToSet, RequestToSet, ResponseToSet, SessionStateToSet), new RouteData(), (ControllerBase)ControllerToSet)
 {
 }
        public void GetConfigKeysForRequest_ReturnsCorrectNumberOfKeys()
        {
            MockHttpRequest request = new MockHttpRequest();
            SetupAuthenticatedSession("123", request);

            var keyGenerator = GetGenerator();
            var keys = keyGenerator.GetConfigKeysForRequest(request);

            keys.Count().Should().Be(3);
        }
        public void GetConsumerId_ReturnsUserId_IfAuthenticated(string userAuthId)
        {
            MockHttpRequest request = new MockHttpRequest();
            var authSession = SetupAuthenticatedSession(userAuthId, request);

            var keyGenerator = GetGenerator();
            var consumerId = keyGenerator.GetConsumerId(request);

            consumerId.Should().Be(authSession.UserAuthId.ToLower());
        }
        public void ProcessRequest_CallsGetLimits()
        {
            var mockHttpRequest = new MockHttpRequest();
            A.CallTo(() => limitProvider.GetLimits(mockHttpRequest)).Returns(null);

            var feature = GetSut();
            feature.ProcessRequest(mockHttpRequest, new MockHttpResponse(), null);

            A.CallTo(() => limitProvider.GetLimits(mockHttpRequest)).MustHaveHappened();
        }
Beispiel #40
0
        public void IsMatch_ExactTextRuleInversedWithNonMatchingString_ReturnsTrue()
        {
            var request = new MockHttpRequest
            {
                HttpMethod = "GET"
            };

            var rule = new HttpMethodRule("not:POST");
            Assert.IsTrue(rule.IsMatch(request));
        }
 /// <summary>
 /// Constructor
 /// </summary>       
 /// <param name="PrincipalToSet">Principal</param>
 /// <param name="RequestToSet">Request to mock</param>
 /// <param name="ResponseToSet">Response to mock</param>
 /// <param name="SessionStateToSet">Mocked session state</param>
 public MockHttpContext(MockPrincipal PrincipalToSet,
                        MockHttpRequest RequestToSet,
                        MockHttpResponse ResponseToSet,
                        MockHttpSessionState SessionStateToSet)
 {
     Principal = PrincipalToSet;
     MockedSessionState = SessionStateToSet;
     MockedHttpResponse = ResponseToSet;
     MockedHttpRequest = RequestToSet;
 }
 private static string GetRazorInstanceHtml()
 {
     var razorFormat = RazorFormat.Instance;
     var mockReq = new MockHttpRequest { OperationName = "RazorInstance" };
     var mockRes = new MockHttpResponse();
     var dto = new RockstarsResponse { Results = Rockstar.SeedData.ToList() };
     razorFormat.ProcessRequest(mockReq, mockRes, dto);
     var html = mockRes.ReadAsString();
     return html;
 }
        public HealthCheckServiceTests(AppHostFixture fixture)
        {
            this.fixture = fixture;
            this.fixture.Host.Container.RegisterAutoWired<HealthCheckService>();
            consulFeature = fixture.Host.GetPlugin<ConsulFeature>();

            var mockHttpRequest = new MockHttpRequest("Heartbeat", "GET", "json", "heartbeat", null, null, null);

            service = new HealthCheckService { Request = mockHttpRequest };
        }
        public void GetRequestCorrelationId_UsesHeaderNameFromFeature(string header)
        {
            string defaultHeaderName = RateLimitFeature.CorrelationIdHeader;

            const string headerName = "sunkilmoon";
            RateLimitFeature.CorrelationIdHeader = headerName;

            var request = new MockHttpRequest();
            request.Headers.Add(headerName, header);

            var value = request.GetRequestCorrelationId();
            value.Should().Be(header);

            RateLimitFeature.CorrelationIdHeader = defaultHeaderName;
        }
        public void Can_deserialize_TestRequest_QueryStringSerializer_output()
        {
            // Setup
            new BasicAppHost(new Container(), typeof(TestService).Assembly).Init();
            var restPath = new RestPath(typeof(TestRequest), "/service", "GET");
            var restHandler = new RestHandler { RestPath = restPath };

            var requestString = "ListOfA={ListOfB:[{Property:prop1},{Property:prop2}]}";
            NameValueCollection queryString = HttpUtility.ParseQueryString(requestString);
            var httpReq = new MockHttpRequest("service", "GET", "application/json", "service", queryString, new MemoryStream(), new NameValueCollection());

            var request2 = (TestRequest)restHandler.CreateRequest(httpReq, "service");

            Assert.That(request2.ListOfA.Count, Is.EqualTo(1));
            Assert.That(request2.ListOfA.First().ListOfB.Count, Is.EqualTo(2));
        }
        public void Does_process_Markdown_pages()
        {
            var markdownHandler = new MarkdownHandler("/AppData/NoTemplate/Static")
            {
                MarkdownFormat = markdownFormat,
            };
            var httpReq = new MockHttpRequest { QueryString = PclExportClient.Instance.NewNameValueCollection() };
            var httpRes = new MockHttpResponse();
            markdownHandler.ProcessRequestAsync(httpReq, httpRes, "Static").Wait();

            var expectedHtml = markdownFormat.Transform(
                File.ReadAllText("~/AppData/NoTemplate/Static.md".MapProjectPath()));

            httpRes.Close();
            Assert.That(httpRes.Contents, Is.EqualTo(expectedHtml));
        }
        private static void CanOptimizeResult(string contentType, IPlugin pluginFormat)
        {
            using (var appHost = new BasicAppHost().Init())
            {
                var dto = new TestDto { Name = "test" };

                var httpReq = new MockHttpRequest();
                httpReq.Headers.Add(HttpHeaders.AcceptEncoding, "gzip,deflate,sdch");
                httpReq.ResponseContentType = contentType;

                if (pluginFormat != null) pluginFormat.Register(appHost);

                object result = httpReq.ToOptimizedResult(dto);
                Assert.IsNotNull(result);
                Assert.IsTrue(result is CompressedResult);
            }
        }
Beispiel #48
0
        public string GetHtml(object dto, string format)
        {
            var httpReq = new MockHttpRequest
            {
                Headers = PclExportClient.Instance.NewNameValueCollection(),
                OperationName = "OperationName",
                QueryString = PclExportClient.Instance.NewNameValueCollection(),
            };
            httpReq.QueryString.Add("format", format);
            using (var ms = new MemoryStream())
            {
                var httpRes = new HttpResponseStreamWrapper(ms, httpReq);
                appHost.ViewEngines[0].ProcessRequest(httpReq, httpRes, dto);

                var utf8Bytes = ms.ToArray();
                var html = utf8Bytes.FromUtf8Bytes();
                return html;
            }
        }
Beispiel #49
0
        public void Can_send_ResponseText_test_with_StatusDescription()
        {
            var mockRequest = new MockHttpRequest { ContentType = MimeTypes.Json };
            var mockResponse = mockRequest.Response;

            var customStatus = "Custom Status Description";

            var httpResult = new HttpResult(System.Net.HttpStatusCode.Accepted, customStatus)
            {
                RequestContext = mockRequest
            };

            var reponseWasAutoHandled = mockResponse.WriteToResponse(httpResult, MimeTypes.Html);

            Assert.That(reponseWasAutoHandled.Result, Is.True);

            var statusDesc = mockResponse.StatusDescription;
            Assert.That(mockResponse.StatusCode, Is.EqualTo((int)System.Net.HttpStatusCode.Accepted));
            Assert.That(statusDesc, Is.EqualTo(customStatus));
        }
        private static void CanOptimizeResult(string contentType, IPlugin pluginFormat)
        {
            var dto = new TestDto {Name = "test"};

            var httpReq = new MockHttpRequest();
            httpReq.Headers.Add(HttpHeaders.AcceptEncoding, "gzip,deflate,sdch");
            httpReq.ResponseContentType = contentType;
            var httpRes = new ViewTests.MockHttpResponse();

            var httpRequestContext = new HttpRequestContext(httpReq, httpRes, dto);

            var appHost = new TestAppHost();
            if (pluginFormat != null) pluginFormat.Register(appHost);

            EndpointHost.ContentTypeFilter = appHost.ContentTypeFilters;

            object result = httpRequestContext.ToOptimizedResult(dto);
            Assert.IsNotNull(result);
            Assert.IsTrue(result is CompressedResult);
        }
        public void GetConfigKeysForRequest_ReturnsResultsInOrder(string key, int index)
        {
            const string operationName = "opname";
            const string userAuthId = "userId";

            var request = new MockHttpRequest(operationName, "GET", "text/json", string.Empty, null, null, null);
            SetupAuthenticatedSession(userAuthId, request);

            var keyGenerator = GetGenerator();
            var keys = keyGenerator.GetConfigKeysForRequest(request);

            keys.ToList()[index].Should().Be(key.ToLower());
        }
        public async Task Can_use_fileStream()
        {
            byte[] fileBytes = uploadedTextFile.ReadFully();
            string fileText = Encoding.ASCII.GetString(fileBytes);

            "File content size {0}".Print(fileBytes.Length);
            "File content is {0}".Print(fileText);

            var mockRequest = new MockHttpRequest();
            var mockResponse = new MockHttpResponse(mockRequest);
            mockRequest.Headers.Add("Range", "bytes=6-8");

            var httpResult = new HttpResult(uploadedTextFile, "audio/mpeg");

            bool reponseWasAutoHandled = await mockResponse.WriteToResponse(mockRequest, httpResult);
            Assert.That(reponseWasAutoHandled, Is.True);

            string writtenString = mockResponse.ReadAsString();
            Assert.That(writtenString, Is.EqualTo(fileText.Substring(6, 3)));

            Assert.That(mockResponse.Headers["Content-Range"], Is.EqualTo("bytes 6-8/33"));
            Assert.That(mockResponse.Headers["Content-Length"], Is.EqualTo(writtenString.Length.ToString()));
            Assert.That(mockResponse.Headers["Accept-Ranges"], Is.EqualTo("bytes"));
            Assert.That(mockResponse.StatusCode, Is.EqualTo(206));
        }
        public async Task Can_seek_from_middle_to_middle()
        {
            var mockRequest = new MockHttpRequest();
            mockRequest.Headers.Add("Range", "bytes=3-5");
            var mockResponse = new MockHttpResponse(mockRequest);

            string customText = "1234567890";
            byte[] customTextBytes = customText.ToUtf8Bytes();
            var ms = new MemoryStream();
            ms.Write(customTextBytes, 0, customTextBytes.Length);


            var httpResult = new HttpResult(ms, "audio/mpeg");

            bool reponseWasAutoHandled = await mockResponse.WriteToResponse(mockRequest, httpResult);
            Assert.That(reponseWasAutoHandled, Is.True);

            string writtenString = mockResponse.ReadAsString();
            Assert.That(writtenString, Is.EqualTo("456"));

            Assert.That(mockResponse.Headers["Content-Range"], Is.EqualTo("bytes 3-5/10"));
            Assert.That(mockResponse.Headers["Content-Length"], Is.EqualTo(writtenString.Length.ToString()));
            Assert.That(mockResponse.Headers["Accept-Ranges"], Is.EqualTo("bytes"));
            Assert.That(mockResponse.StatusCode, Is.EqualTo(206));
        }
        public async Task Can_seek_from_beginning_to_further_than_end()
        {
            // Not sure if this would ever occur in real streaming scenarios, but it does occur
            // when some crawlers use range headers to specify a max size to return.
            // e.g. Facebook crawler always sends range header of 'bytes=0-524287'.

            var mockRequest = new MockHttpRequest();
            var mockResponse = new MockHttpResponse(mockRequest);

            mockRequest.Headers[HttpHeaders.Range] = "bytes=0-524287";

            string customText = "1234567890";
            byte[] customTextBytes = customText.ToUtf8Bytes();
            var ms = new MemoryStream();
            ms.Write(customTextBytes, 0, customTextBytes.Length);

            var httpResult = new HttpResult(ms, "audio/mpeg");

            bool reponseWasAutoHandled = await mockResponse.WriteToResponse(mockRequest, httpResult);
            Assert.That(reponseWasAutoHandled, Is.True);

            string writtenString = mockResponse.ReadAsString();
            Assert.That(writtenString, Is.EqualTo(customText));

            Assert.That(mockResponse.Headers["Content-Range"], Is.EqualTo("bytes 0-9/10"));
            Assert.That(mockResponse.Headers["Content-Length"], Is.EqualTo(writtenString.Length.ToString()));
            Assert.That(mockResponse.Headers["Accept-Ranges"], Is.EqualTo("bytes"));
            Assert.That(mockResponse.StatusCode, Is.EqualTo(206));
        }
        public async Task Can_respond_to_non_range_requests_with_200_OK_response()
        {
            var mockRequest = new MockHttpRequest();
            var mockResponse = new MockHttpResponse(mockRequest);

            string customText = "1234567890";
            byte[] customTextBytes = customText.ToUtf8Bytes();
            var ms = new MemoryStream();
            ms.Write(customTextBytes, 0, customTextBytes.Length);

            var httpResult = new HttpResult(ms, "audio/mpeg");            

            bool reponseWasAutoHandled = await mockResponse.WriteToResponse(mockRequest, httpResult);
            Assert.That(reponseWasAutoHandled, Is.True);

            string writtenString = mockResponse.ReadAsString();
            Assert.That(writtenString, Is.EqualTo(customText));

            Assert.That(mockResponse.Headers["Content-Range"], Is.Null);
            Assert.That(mockResponse.Headers["Accept-Ranges"], Is.EqualTo("bytes"));
            Assert.That(mockResponse.StatusCode, Is.EqualTo(200));
        }
        public void GetConfigKeysForUser_ReturnsResultsInOrder_ObeyDelimiterAndPrefix(string key, int index)
        {
            const string userAuthId = "userId";
            MockHttpRequest request = new MockHttpRequest();
            SetupAuthenticatedSession(userAuthId, request);

            LimitKeyGenerator.Delimiter = "|";
            LimitKeyGenerator.Prefix = "test";

            var keyGenerator = GetGenerator();
            var keys = keyGenerator.GetConfigKeysForUser(request);

            keys.ToList()[index].Should().Be(key);

            // Now set the values back as they're static (avoid breaking tests)
            LimitKeyGenerator.Delimiter = "/";
            LimitKeyGenerator.Prefix = "ss";
        }
 private HttpRequestContext CreateContext(string httpMethod)
 {
     var ctx = new MockHttpRequest { HttpMethod = httpMethod };
     return new HttpRequestContext(ctx, new MockHttpResponse(), null, HttpMethods.GetEndpointAttribute(httpMethod));
 }
        public void GetConfigKeysForRequest_ReturnsResultsInOrder_ObeyDelimiterAndPrefix(string key, int index)
        {
            const string operationName = "opname";
            const string userAuthId = "userId";
            LimitKeyGenerator.Delimiter = ":";
            LimitKeyGenerator.Prefix = null;

            var request = new MockHttpRequest(operationName, "GET", "text/json", string.Empty, null, null, null);
            SetupAuthenticatedSession(userAuthId, request);

            var keyGenerator = GetGenerator();
            var keys = keyGenerator.GetConfigKeysForRequest(request);

            keys.ToList()[index].Should().Be(key.ToLower());

            // Now set the values back as they're static (avoid breaking tests)
            LimitKeyGenerator.Delimiter = "/";
            LimitKeyGenerator.Prefix = "ss";
        }
        public void GetConfigKeysForUser_ReturnsResultsInOrder(string key, int index)
        {
            const string userAuthId = "userId";
            MockHttpRequest request = new MockHttpRequest();
            SetupAuthenticatedSession(userAuthId, request);

            var keyGenerator = GetGenerator();
            var keys = keyGenerator.GetConfigKeysForUser(request);

            keys.ToList()[index].Should().Be(key);
        }
 private MockHttpRequest CreateContext(string httpMethod)
 {
     var ctx = new MockHttpRequest { HttpMethod = httpMethod };
     return ctx;
 }