public void ServiceFunctions_AddService_ReturnsOkAndServiceId()
        {
            // Arrange
            #region BodyString
            var bodyString = @"# BodyString
Method: GET
Path: /api/things/53";
            #endregion

            var request = new TestHttpRequest()
            {
                Method     = "POST",
                Path       = "/__vs/services",
                BodyString = bodyString
            };
            var response = new TestHttpResponse();
            var context = new TestHttpContext(request, response);
            Task next() => Task.CompletedTask;

            // Act
            ServiceFunctions.AddService(context, next).Wait();

            // Assert
            Assert.AreEqual(200, response.StatusCode);
            Assert.AreEqual("text/plain", response.ContentType);
            Assert.IsTrue(Guid.TryParse(response.ReadBody(), out Guid serviceId));
            Assert.AreNotEqual(Guid.Empty, serviceId);
        }
        public void ServiceFunctions_DeleteService_InvokesNextFunctionWhenPathNotCorrect()
        {
            // Arrange
            var request = new TestHttpRequest()
            {
                Method = "GET",
                // This path causes the request not to match the required pattern.
                Path       = "/__vs/badResource/ab61870e-8427-ae57effd5c6a",
                BodyString = string.Empty
            };
            var response = new TestHttpResponse();
            var context  = new TestHttpContext(request, response);

            var numCallsToNext = 0;

            Task next()
            {
                numCallsToNext++;
                return(Task.CompletedTask);
            }

            // Act
            ServiceFunctions.DeleteService(context, next).Wait();

            // Assert
            Assert.AreEqual(1, numCallsToNext);
        }
Exemple #3
0
        public async Task RetrieveUniqueId_InvalidRequest_SiteId_Returns404()
        {
            ISettingsProvider settingsProvider = new pm.DefaultSettingProvider(Directory.GetCurrentDirectory());

            TestHttpRequest httpRequest = new TestHttpRequest();

            httpRequest.Path = "/smokeTest/SiteId";
            TestHttpResponse httpResponse = new TestHttpResponse();

            IPluginHelperService pluginHelperServices = _testPluginSmokeTest.GetRequiredService <IPluginHelperService>();
            IPluginTypesService  pluginTypesService   = _testPluginSmokeTest.GetRequiredService <IPluginTypesService>();

            TestHttpContext httpContext = new TestHttpContext(httpRequest, httpResponse);
            ILogger         logger      = new Logger();


            using (WebSmokeTestMiddleware sut = new WebSmokeTestMiddleware(null, pluginHelperServices,
                                                                           pluginTypesService, settingsProvider, logger))
            {
                List <WebSmokeTestItem> smokeTests = sut.SmokeTests;

                Assert.IsTrue(smokeTests.Count > 1);

                await sut.Invoke(httpContext);

                Assert.AreEqual(404, httpResponse.StatusCode);
            }
        }
        private static HttpContext CreateContextWithUserId()
        {
            var context = new TestHttpContext();

            context.Session.SetInt32("userId", userId);
            return(context);
        }
Exemple #5
0
        public async Task ReturnsFalse_IfApplicationfound_ButNoModel()
        {
            var context = new TestHttpContext($"/{clients[0].ClientId}");
            var result  = await target.TryHandle(context);

            Assert.False(result);
        }
Exemple #6
0
        public async Task ReturnsTrue_IfApplicationfound_ButNoModel()
        {
            var context = new TestHttpContext($"/{clients[0].ClientId}/{nameof(SimpleConfig)}");
            var result  = await target.TryHandle(context);

            Assert.True(result);
        }
        public async Task LoginFromCookieValueCookieValidLoginUserFound()
        {
            ISettingsProvider           settingsProvider        = new pm.DefaultSettingProvider(Directory.GetCurrentDirectory());
            LoginControllerSettings     loginControllerSettings = settingsProvider.GetSettings <LoginControllerSettings>(nameof(LoginPlugin));
            TestRequestCookieCollection cookies = new TestRequestCookieCollection();

            cookies.AddCookie("RememberMe", Shared.Utilities.Encrypt("123", loginControllerSettings.EncryptionKey));

            TestHttpRequest  httpRequest  = new TestHttpRequest(cookies);
            TestHttpResponse httpResponse = new TestHttpResponse();

            IPluginClassesService pluginServices = new pm.PluginServices(_testPluginLogin) as IPluginClassesService;
            TestHttpContext       httpContext    = new TestHttpContext(httpRequest, httpResponse);

            httpRequest.SetContext(httpContext);
            MockLoginProvider loginProvider = new MockLoginProvider();

            MockClaimsProvider        claimsProvider        = new MockClaimsProvider(pluginServices);
            TestAuthenticationService authenticationService = new TestAuthenticationService();
            RequestDelegate           requestDelegate       = async(context) => { await Task.Delay(0); };

            LoginMiddleware login = new LoginMiddleware(requestDelegate, loginProvider, settingsProvider,
                                                        claimsProvider);

            await login.Invoke(httpContext, authenticationService);

            TestResponseCookies responseCookies = httpResponse.Cookies as TestResponseCookies;

            Assert.IsNotNull(responseCookies);
            Assert.IsTrue(authenticationService.SignInAsyncCalled);
        }
        public void ServiceFunctions_QueryService_ReturnsServiceStats()
        {
            // Arrange
            var serviceId = AddService("GET", "/api/serviceToBeQueried/1");

            InvokeService("GET", "/api/serviceToBeQueried/1", "Lorem ipsum dolor");
            InvokeService("GET", "/api/serviceToBeQueried/1", "sit amet, consectetur adipiscing");

            var request = new TestHttpRequest()
            {
                Method = "GET",
                Path   = "/__vs/services/" + serviceId
            };
            var response = new TestHttpResponse();
            var context  = new TestHttpContext(request, response);

            Task next() => Task.CompletedTask;

            // Act
            ServiceFunctions.QueryService(context, next).Wait();

            // Assert
            Assert.AreEqual(200, response.StatusCode);
            Assert.AreEqual("text/plain", response.ContentType);
            var expectedResponseBody = new StringBuilder()
                                       .AppendLine($"CallCount: 2")
                                       .AppendLine()
                                       .AppendLine("LastRequestBody:")
                                       .Append("sit amet, consectetur adipiscing")
                                       .ToString();

            Assert.AreEqual(expectedResponseBody, response.ReadBody());
        }
        public async Task LoginAutoLoginFromHeadersInvalidEncoding()
        {
            ISettingsProvider       settingsProvider        = new pm.DefaultSettingProvider(Directory.GetCurrentDirectory());
            LoginControllerSettings loginControllerSettings = settingsProvider.GetSettings <LoginControllerSettings>(nameof(LoginPlugin));

            TestHttpRequest  httpRequest  = new TestHttpRequest();
            TestHttpResponse httpResponse = new TestHttpResponse();

            IPluginClassesService pluginServices = new pm.PluginServices(_testPluginLogin) as IPluginClassesService;
            TestHttpContext       httpContext    = new TestHttpContext(httpRequest, httpResponse);

            httpRequest.SetContext(httpContext);
            MockLoginProvider loginProvider = new MockLoginProvider();

            MockClaimsProvider        claimsProvider        = new MockClaimsProvider(pluginServices);
            TestAuthenticationService authenticationService = new TestAuthenticationService();
            RequestDelegate           requestDelegate       = async(context) => { await Task.Delay(0); };

            httpRequest.Headers.Add(SharedPluginFeatures.Constants.HeaderAuthorizationName, "Basic blahblahblah");

            LoginMiddleware login = new LoginMiddleware(requestDelegate, loginProvider, settingsProvider,
                                                        claimsProvider);

            await login.Invoke(httpContext, authenticationService);

            Assert.AreEqual(400, httpContext.Response.StatusCode);
            Assert.IsFalse(authenticationService.SignInAsyncCalled);
        }
        public async Task LoginAutoLoginFromHeadersInvalidUsernameAndPassword()
        {
            ISettingsProvider       settingsProvider        = new pm.DefaultSettingProvider(Directory.GetCurrentDirectory());
            LoginControllerSettings loginControllerSettings = settingsProvider.GetSettings <LoginControllerSettings>(nameof(LoginPlugin));

            TestHttpRequest  httpRequest  = new TestHttpRequest();
            TestHttpResponse httpResponse = new TestHttpResponse();

            IPluginClassesService pluginServices = new pm.PluginServices(_testPluginLogin) as IPluginClassesService;
            TestHttpContext       httpContext    = new TestHttpContext(httpRequest, httpResponse);

            httpRequest.SetContext(httpContext);
            MockLoginProvider loginProvider = new MockLoginProvider();

            MockClaimsProvider        claimsProvider        = new MockClaimsProvider(pluginServices);
            TestAuthenticationService authenticationService = new TestAuthenticationService();
            RequestDelegate           requestDelegate       = async(context) => { await Task.Delay(0); };

            string encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("Miley:Cyrus"));

            httpRequest.Headers.Add(SharedPluginFeatures.Constants.HeaderAuthorizationName, "Basic " + encoded);

            LoginMiddleware login = new LoginMiddleware(requestDelegate, loginProvider, settingsProvider,
                                                        claimsProvider);

            await login.Invoke(httpContext, authenticationService);

            Assert.IsFalse(authenticationService.SignInAsyncCalled);
        }
        public GravatarImageTests()
        {
            HttpRequest = new TestHttpRequest();
            HttpContext = new TestHttpContext(HttpRequest);

            HtmlHelperExtensions.GetHttpContext = () => HttpContext;
        }
Exemple #12
0
        public void BadEggValidationInvalidRouteProvider()
        {
            ISettingsProvider settingsProvider = new pm.DefaultSettingProvider(Directory.GetCurrentDirectory());

            TestHttpRequest  httpRequest  = new TestHttpRequest();
            TestHttpResponse httpResponse = new TestHttpResponse();

            IPluginClassesService pluginServices       = new pm.PluginServices(_testPluginBadEgg) as IPluginClassesService;
            IPluginHelperService  pluginHelperServices = _testPluginBadEgg.GetRequiredService <IPluginHelperService>();
            IPluginTypesService   pluginTypesService   = _testPluginBadEgg.GetRequiredService <IPluginTypesService>();
            INotificationService  notificationService  = _testPluginBadEgg.GetRequiredService <INotificationService>();
            IIpValidation         iPValidation         = new TestIPValidation();

            TestHttpContext httpContext = new TestHttpContext(httpRequest, httpResponse);

            httpRequest.SetContext(httpContext);
            MockLoginProvider loginProvider = new MockLoginProvider();

            MockClaimsProvider        claimsProvider        = new MockClaimsProvider(pluginServices);
            TestAuthenticationService authenticationService = new TestAuthenticationService();
            RequestDelegate           requestDelegate       = async(context) => { await Task.Delay(0); };
            RouteDataServices         routeDataServices     = new RouteDataServices();

            BadEggMiddleware badEgg = new BadEggMiddleware(requestDelegate, null,
                                                           routeDataServices, pluginHelperServices, pluginTypesService, iPValidation,
                                                           settingsProvider, notificationService);
        }
Exemple #13
0
        public void BadEggValidationInvalidRequestDelegate()
        {
            ISettingsProvider settingsProvider = new pm.DefaultSettingProvider(Directory.GetCurrentDirectory());

            TestHttpRequest  httpRequest  = new TestHttpRequest();
            TestHttpResponse httpResponse = new TestHttpResponse();

            IPluginClassesService pluginServices       = new pm.PluginServices(_testPluginBadEgg) as IPluginClassesService;
            IPluginHelperService  pluginHelperServices = _testPluginBadEgg.GetRequiredService <IPluginHelperService>();
            IPluginTypesService   pluginTypesService   = _testPluginBadEgg.GetRequiredService <IPluginTypesService>();
            INotificationService  notificationService  = _testPluginBadEgg.GetRequiredService <INotificationService>();
            IIpValidation         iPValidation         = new TestIPValidation();

            TestHttpContext httpContext = new TestHttpContext(httpRequest, httpResponse);

            httpRequest.SetContext(httpContext);
            MockLoginProvider loginProvider = new MockLoginProvider();

            MockClaimsProvider                     claimsProvider                         = new MockClaimsProvider(pluginServices);
            TestAuthenticationService              authenticationService                  = new TestAuthenticationService();
            ActionDescriptorCollection             actionDescriptorCollection             = new ActionDescriptorCollection(new List <ActionDescriptor>(), 1);
            TestActionDescriptorCollectionProvider testActionDescriptorCollectionProvider = new TestActionDescriptorCollectionProvider(actionDescriptorCollection);
            RouteDataServices routeDataServices = new RouteDataServices();

            BadEggMiddleware badEgg = new BadEggMiddleware(null, testActionDescriptorCollectionProvider,
                                                           routeDataServices, pluginHelperServices, pluginTypesService, iPValidation,
                                                           settingsProvider, notificationService);
        }
Exemple #14
0
        public async Task BadEggValidationSuccess()
        {
            ISettingsProvider settingsProvider = new pm.DefaultSettingProvider(Directory.GetCurrentDirectory());

            TestHttpRequest  httpRequest  = new TestHttpRequest();
            TestHttpResponse httpResponse = new TestHttpResponse();

            IPluginClassesService pluginServices       = new pm.PluginServices(_testPluginBadEgg) as IPluginClassesService;
            IPluginHelperService  pluginHelperServices = _testPluginBadEgg.GetRequiredService <IPluginHelperService>();
            IPluginTypesService   pluginTypesService   = _testPluginBadEgg.GetRequiredService <IPluginTypesService>();
            INotificationService  notificationService  = _testPluginBadEgg.GetRequiredService <INotificationService>();
            IIpValidation         iPValidation         = new TestIPValidation();

            TestHttpContext httpContext = new TestHttpContext(httpRequest, httpResponse);

            httpRequest.SetContext(httpContext);
            MockLoginProvider loginProvider = new MockLoginProvider();

            MockClaimsProvider        claimsProvider                                      = new MockClaimsProvider(pluginServices);
            TestAuthenticationService authenticationService                               = new TestAuthenticationService();
            bool                                   nextDelegateCalled                     = false;
            RequestDelegate                        requestDelegate                        = async(context) => { nextDelegateCalled = true; await Task.Delay(0); };
            ActionDescriptorCollection             actionDescriptorCollection             = new ActionDescriptorCollection(new List <ActionDescriptor>(), 1);
            TestActionDescriptorCollectionProvider testActionDescriptorCollectionProvider = new TestActionDescriptorCollectionProvider(actionDescriptorCollection);
            RouteDataServices                      routeDataServices                      = new RouteDataServices();

            BadEggMiddleware badEgg = new BadEggMiddleware(requestDelegate, testActionDescriptorCollectionProvider,
                                                           routeDataServices, pluginHelperServices, pluginTypesService, iPValidation,
                                                           settingsProvider, notificationService);

            await badEgg.Invoke(httpContext);

            Assert.IsTrue(nextDelegateCalled);
        }
Exemple #15
0
        public async Task ReturnsFalse_IfNoApplicationfound()
        {
            var context = new TestHttpContext("/");
            var result  = await target.TryHandle(context);

            Assert.False(result);
        }
        public void ServiceFunctions_DeleteAllServices_ReturnsNotFoundAfterDeleting()
        {
            // Arrange
            var service1Id = AddService("GET", "/api/resource/5be5223c-70d4-4a61-aa5c-be5d60d90001");
            var service2Id = AddService("GET", "/api/resource/5be5223c-70d4-4a61-aa5c-be5d60d90002");
            var service3Id = AddService("GET", "/api/resource/5be5223c-70d4-4a61-aa5c-be5d60d90003");

            var request = new TestHttpRequest()
            {
                Method     = "DELETE",
                Path       = "/__vs/services",
                BodyString = string.Empty
            };
            var response = new TestHttpResponse();
            var context  = new TestHttpContext(request, response);

            Task next() => Task.CompletedTask;

            // Act
            ServiceFunctions.DeleteAllServices(context, next).Wait();

            // Assert
            Assert.AreEqual(200, response.StatusCode);
            Assert.AreEqual(404, InvokeService("GET", "/api/resource/5be5223c-70d4-4a61-aa5c-be5d60d90001"),
                            "Invoking service1 should result in a 404.");
            Assert.AreEqual(404, InvokeService("GET", "/api/resource/5be5223c-70d4-4a61-aa5c-be5d60d90002"),
                            "Invoking service2 should result in a 404.");
            Assert.AreEqual(404, InvokeService("GET", "/api/resource/5be5223c-70d4-4a61-aa5c-be5d60d90003"),
                            "Invoking service3 should result in a 404.");
        }
        public async Task LoginReturnsTokensIfCorrect()
        {
            var password    = _fixture.Create <string>();
            var userManager = TestHelpers.CreateUserManagerWithUser(out var user, true, password);

            var          options        = CreateOptions();
            var          tokenGenerator = TestHelpers.CreateTokenGenerator();
            const string testToken      = "abcdefghi";

            tokenGenerator.Setup(t => t.GetTokenAsync(It.Is <ApplicationUser>(u => u.Id == user.Id))).ReturnsAsync(testToken);

            var testContext = new TestHttpContext();

            var controller = new UserController(TestHelpers.CreateUserManager(), CreateEmailSender().Object, options, new NullLogger <UserController>(), tokenGenerator.Object)
            {
                ControllerContext = new ControllerContext
                {
                    HttpContext = testContext
                }
            };

            var res = await controller.Login(new LoginModel { Email = user.Email, Password = password });

            res.Should().BeOkResultWithValue(new TokenResult {
                Token = testToken
            });
        }
        public void ServiceFunctions_AddService_InvokesNextFunctionWhenMethodNotPOST()
        {
            // Arrange
            #region BodyString
            var bodyString = @"# BodyString
# This ""GET"" is irrelevant
Method: GET
Path: /api/things/53";
            #endregion

            var request = new TestHttpRequest()
            {
                // This "GET" causes the request not to match the required pattern.
                Method     = "GET",
                Path       = "/__vs/services",
                BodyString = bodyString
            };
            var response = new TestHttpResponse();
            var context  = new TestHttpContext(request, response);

            var numCallsToNext = 0;
            Task next()
            {
                numCallsToNext++;
                return(Task.CompletedTask);
            }

            // Act
            ServiceFunctions.AddService(context, next).Wait();

            // Assert
            Assert.AreEqual(1, numCallsToNext);
        }
        public void LocalizablePresenter_RedirectsOnInvalidLanguageCode()
        {
            var config           = DotvvmConfiguration.CreateDefault();
            var presenterFactory = LocalizablePresenter.BasedOnParameter("Lang");

            config.RouteTable.Add("Test", "test/Lang", "test", new { Lang = "en" }, presenterFactory);

            var context = DotvvmTestHelper.CreateContext(config);

            context.Parameters["Lang"] = "cz";
            context.Route = config.RouteTable.First();

            var httpRequest = new TestHttpContext();

            httpRequest.Request = new TestHttpRequest(httpRequest)
            {
                PathBase = ""
            };
            httpRequest.Request.Headers.Add(HostingConstants.SpaContentPlaceHolderHeaderName, new string[0]);

            context.HttpContext = httpRequest;
            var localizablePresenter = presenterFactory(config.ServiceProvider);

            Assert.ThrowsException <DotvvmInterruptRequestExecutionException>(() =>
                                                                              localizablePresenter.ProcessRequest(context));
        }
        // Adds a service and returns it's ID.
        //
        // Do not use this to test the ServiceFunctions.AddService method.
        // This was designed to help other tests and assumes that the
        // ServiceFunctions.AddService has already been tested.
        private static string AddService(string method, string path)
        {
            var bodyString = @"# BodyString
# Request
Method: {0}
Path: {1}

# Response
ContentType: application/json
StatusCode: 200

# Body
{""color"":""Red""}";

            var request = new TestHttpRequest()
            {
                Method     = "POST",
                Path       = "/__vs/services",
                BodyString = bodyString
                             .Replace("{0}", method)
                             .Replace("{1}", path)
            };
            var response = new TestHttpResponse();
            var context  = new TestHttpContext(request, response);

            Task next() => Task.CompletedTask;

            ServiceFunctions.AddService(context, next).Wait();
            return(response.ReadBody());
        }
Exemple #21
0
        public async Task Validate_TestEndCalled_ISmokeTestProviderNotRegistered_Void()
        {
            ISettingsProvider settingsProvider = new pm.DefaultSettingProvider(Directory.GetCurrentDirectory());

            TestHttpRequest httpRequest = new TestHttpRequest();

            httpRequest.Path = "/smokeTest/end/";
            TestHttpResponse httpResponse = new TestHttpResponse();

            IPluginHelperService pluginHelperServices = _testPluginSmokeTest.GetRequiredService <IPluginHelperService>();
            IPluginTypesService  pluginTypesService   = _testPluginSmokeTest.GetRequiredService <IPluginTypesService>();
            IServiceCollection   serviceCollection    = new ServiceCollection() as IServiceCollection;

            TestHttpContext httpContext = new TestHttpContext(httpRequest, httpResponse,
                                                              serviceCollection.BuildServiceProvider());
            ILogger         logger             = new Logger();
            bool            nextDelegateCalled = false;
            RequestDelegate requestDelegate    = async(context) => { nextDelegateCalled = true; await Task.Delay(0); };

            using (WebSmokeTestMiddleware sut = new WebSmokeTestMiddleware(requestDelegate, pluginHelperServices,
                                                                           pluginTypesService, settingsProvider, logger))
            {
                List <WebSmokeTestItem> smokeTests = sut.SmokeTests;

                Assert.IsTrue(smokeTests.Count > 1);

                await sut.Invoke(httpContext);

                Assert.IsFalse(nextDelegateCalled);
                Assert.AreEqual(200, httpResponse.StatusCode);
                Assert.IsNull(httpResponse.ContentType);
            }
        }
        public void ServiceFunctions_AddService_ThrowsOnNullNextFunction()
        {
            // Arrange
            HttpContext context          = new TestHttpContext();
            Func <Task> nullNextFunction = null;

            // Act
            ServiceFunctions.AddService(context, nullNextFunction).Wait();
        }
        public void ServiceFunctions_DeleteAllServices_ThrowsOnNullNextFunction()
        {
            // Arrange
            var         context          = new TestHttpContext();
            Func <Task> nullNextFunction = null;

            // Act
            ServiceFunctions.DeleteAllServices(context, nullNextFunction).Wait();
        }
Exemple #24
0
        public async Task Validate_TestStartCalled_ISmokeTestProviderRegistered_Returns_NvpCodecValues()
        {
            ISettingsProvider settingsProvider = new pm.DefaultSettingProvider(Directory.GetCurrentDirectory());

            TestHttpRequest httpRequest = new TestHttpRequest();

            httpRequest.Path = "/smokeTest/Start/";
            TestHttpResponse httpResponse = new TestHttpResponse();

            IPluginHelperService pluginHelperServices = _testPluginSmokeTest.GetRequiredService <IPluginHelperService>();
            IPluginTypesService  pluginTypesService   = _testPluginSmokeTest.GetRequiredService <IPluginTypesService>();
            IServiceCollection   serviceCollection    = new ServiceCollection() as IServiceCollection;
            NVPCodec             codecValues          = new NVPCodec();

            codecValues.Add("username", "admin");
            MockSmokeTestProvider smokeTestProvider = new MockSmokeTestProvider(codecValues);

            serviceCollection.AddSingleton <ISmokeTestProvider>(smokeTestProvider);

            TestHttpContext httpContext = new TestHttpContext(httpRequest, httpResponse,
                                                              serviceCollection.BuildServiceProvider());
            ILogger         logger             = new Logger();
            bool            nextDelegateCalled = false;
            RequestDelegate requestDelegate    = async(context) => { nextDelegateCalled = true; await Task.Delay(0); };

            using (WebSmokeTestMiddleware sut = new WebSmokeTestMiddleware(requestDelegate, pluginHelperServices,
                                                                           pluginTypesService, settingsProvider, logger))
            {
                List <WebSmokeTestItem> smokeTests = sut.SmokeTests;

                Assert.IsTrue(smokeTests.Count > 1);

                await sut.Invoke(httpContext);

                Assert.IsFalse(nextDelegateCalled);
                Assert.AreEqual(200, httpResponse.StatusCode);
                Assert.IsNull(httpResponse.ContentType);
                Assert.IsTrue(smokeTestProvider.StartCalled);

                byte[] data = new byte[httpResponse.Body.Length];
                httpResponse.Body.Position = 0;
                httpResponse.Body.Read(data, 0, data.Length);
                string test = Decrypt(Encoding.UTF8.GetString(data), EncryptionKey);

                Assert.IsFalse(String.IsNullOrEmpty(test));
                NVPCodec codec = new NVPCodec();
                codec.Decode(test);

                Assert.AreEqual(1, codec.AllKeys.Length);

                Assert.IsTrue(codec.AllKeys.Contains("username"));
                Assert.AreEqual("admin", codec["username"]);
            }
        }
Exemple #25
0
        public void GetObfuscatedServerVariablesNullRouteData()
        {
            // Arange
            var context = new TestHttpContext(null);

            // Act
            var serverVariables = QuietLog.GetObfuscatedServerVariables(context);

            // Assert
            Assert.Null(serverVariables);
        }
        public async Task Signing_ShouldGenerateCorrectSignature()
        {
            // Arrange
            var body              = "happy birthday";
            var secret            = "secret1";
            var expectedSignature = HmacSignature.CreateFromExisting("c842eb4acaa566b634f845417d8a4593928e9ec4");

            using var context = new TestHttpContext(body);

            // Act
            var actualSignature = await context.Instance.SignAsync(secret);

            // Assert
            Assert.Equal(expectedSignature, actualSignature);
        }
        public async Task Verify_SignaturesShouldMatchWhenSignedBySameKey()
        {
            // Arrange
            var body              = "happy birthday";
            var secret            = "secret1";
            var expectedSignature = "c842eb4acaa566b634f845417d8a4593928e9ec4";

            using var context = new TestHttpContext(body);

            // Act
            var result = await context.Instance.VerifySignatureAsync(expectedSignature, secret);

            // Assert
            Assert.True(result.IsValid);
        }
        public async Task Verify_Header_SignaturesShouldMatchWhenSignedBySameKeyAfterTransformation()
        {
            // Arrange
            var body   = "happy birthday";
            var secret = "secret1";

            using var context = new TestHttpContext(body);
            context.AddHeader("header", "sha1=c842eb4acaa566b634f845417d8a4593928e9ec4");

            // Act
            var result = await context.Instance.VerifySignatureFromHeaderAsync("header", secret, x => x.Substring(5));

            // Assert
            Assert.True(result.IsValid);
        }
Exemple #29
0
        public async Task CallsResponseFactoryWithConfig()
        {
            var context = new TestHttpContext($"/{clients[0].ClientId}/{nameof(SimpleConfig)}");
            var config  = new ConfigInstance <SimpleConfig>(new SimpleConfig {
                IntProperty = 43
            }, clients[0].ClientId);

            configurationService.Setup(r => r.GetAsync(typeof(SimpleConfig), It.Is <ConfigurationIdentity>(arg => arg.ClientId == clients[0].ClientId))).ReturnsAsync(config);
            responseFactory.Setup(r => r.BuildResponse(context, config.Configuration))
            .Returns(Task.FromResult(true));

            var result = await target.TryHandle(context);

            responseFactory.Verify(r => r.BuildResponse(context, config.Configuration), Times.AtLeastOnce());
        }
        // Invokes a service and returns the HTTP status code result.
        //
        // Do not use this to test the ServiceFunctions.InvokeService method.
        // This was designed to help other tests and assumes that the
        // ServiceFunctions.InvokeService has already been tested.
        private static int InvokeService(string method, string path, string bodyString = "")
        {
            var request = new TestHttpRequest()
            {
                Method     = method,
                Path       = path,
                BodyString = bodyString
            };
            var response = new TestHttpResponse();
            var context  = new TestHttpContext(request, response);

            Task next() => Task.CompletedTask;

            ServiceFunctions.InvokeService(context, next).Wait();

            return(response.StatusCode);
        }
        public void SetUp()
        {
            _mocks = new MockRepository();
            var httpContext = new TestHttpContext();
            var requestContext = new RequestContext(httpContext, new RouteData());
            var controller = _mocks.StrictMock<ControllerBase>();
            _mocks.Replay(controller);

            var viewEngine = new BooViewEngine
                             	{
                             		ViewSourceLoader = new FileSystemViewSourceLoader(VIEW_ROOT_DIRECTORY),
                             		Options = new BooViewEngineOptions()
                             	};
            viewEngine.Initialize();

            _viewEngine = new BrailViewFactory(viewEngine);
            _mocks.ReplayAll();
        }