public static RouteData GetRouteDataFor(this RouteCollection collection, string url, bool isPost = false) { var context = new HttpContextMock(); context.HttpRequest .SetupGet(r => r.ApplicationPath) .Returns("/"); context.HttpRequest .SetupGet(r => r.AppRelativeCurrentExecutionFilePath) .Returns(url); context.HttpRequest .SetupGet(r => r.PathInfo) .Returns(string.Empty); if (isPost) { context.HttpRequest .SetupGet(r => r.HttpMethod) .Returns("POST"); } context.HttpResponse .Setup(r => r.ApplyAppPathModifier(It.IsAny<string>())) .Returns<string>(r => { return r; }); return collection.GetRouteData(context.Object); }
public void SetUp() { contextMock = new HttpContextMock(); var files = Rhino.Mocks.MockRepository.GenerateMock<HttpFileCollectionBase>(); files.Stub(x => x.Count).Return(0); contextMock.Request.Stub(x => x.Files).Return(files); }
public void ShouldAllowSettingQueryViaDictionary() { var httpContextMock = HttpContextMock.Default(); var name = Any.String(); var value = Any.String(); httpContextMock.Request().WithQuery(new QueryCollection(new Dictionary <string, StringValues> { [name] = value })); httpContextMock.Request().RealInstance.Query[name].Should().BeEquivalentTo(new StringValues(value)); }
public void WriteResponse() { var stream = new MemoryStream(Encoding.UTF8.GetBytes("test contents")); using (var result = new StreamResult(stream)) { var contextMock = new HttpContextMock(); result.WriteResponse(contextMock.response); Assert.Equals(contextMock.response.StatusCode, 200); Assert.Equals(contextMock.response.ContentType, "application/octet-stream"); Assert.Equals(contextMock.response.GetContentsFromBody(), "test contents"); } }
public void can_add_a_value_to_the_application_object() { var mockHttpContext = new HttpContextMock(); const int clientAccountId = 123; mockHttpContext.HttpApplicationState.Setup(x => x.Add("test", clientAccountId)); mockHttpContext.HttpApplicationState.Setup(x => x["test"]).Returns(clientAccountId); mockHttpContext.Object.Application.Add("test", clientAccountId); Assert.NotNull(mockHttpContext.Object.Application); Assert.Equal(123, mockHttpContext.Object.Application["test"]); mockHttpContext.HttpApplicationState.VerifyAll(); }
public void can_call_modify_client_web_method() { var mockHttpContext = new HttpContextMock(); var clientAccountIdList = new List<int>(); mockHttpContext.HttpApplicationState.Setup(x => x["ClientAccounts"]).Returns(clientAccountIdList); var ses = new MyWebService(mockHttpContext.Object); Assert.Equal("Client Account Modification Complete", ses.ModifyClientAccount(0)); mockHttpContext.HttpApplicationState.VerifyAll(); }
public void throws_exception_when_trying_to_modify_an_account_that_is_already_processing() { var mockHttpContext = new HttpContextMock(); const int clientAccountId = 123; var clientAccountIdList = new List<int>() { clientAccountId }; mockHttpContext.HttpApplicationState.Setup(x => x["ClientAccounts"]).Returns((object x) => clientAccountIdList).AtMost(2); var ses = new MyWebService(mockHttpContext.Object); Assert.Throws<ApplicationException>(() => ses.ModifyClientAccount(clientAccountId)); mockHttpContext.HttpApplicationState.VerifyAll(); }
public void ShouldAllowRewindingRequestBody() { var httpContextMock = HttpContextMock.Default(); httpContextMock.Request().WithStringBody(Any.String()); using var streamReader = new StreamReader(httpContextMock.Request().RealInstance.Body); using var streamReader2 = new StreamReader(httpContextMock.Request().RealInstance.Body); var content = streamReader.ReadToEnd(); httpContextMock.Request().RewindBody(); var content2 = streamReader2.ReadToEnd(); content.Should().Be(content2); }
public void WithRequestAsObjectShouldWorkWithSetRequestAction() { var httpContext = new HttpContextMock(); httpContext.Request.Form = new FormCollection(new Dictionary <string, StringValues> { ["Test"] = "TestValue" }); MyController <MvcController> .Instance() .WithHttpRequest(httpContext.Request) .Calling(c => c.WithRequest()) .ShouldReturn() .Ok(); }
public void WriteResponse() { var formats = new[] { Formatting.None, Formatting.Indented }; foreach (var format in formats) { var result = new JsonResult(new { a = 1 }, format); var contextMock = new HttpContextMock(); var exceptedResult = JsonConvert.SerializeObject(new { a = 1 }, format); result.WriteResponse(contextMock.response); Assert.Equals(contextMock.response.StatusCode, 200); Assert.Equals(contextMock.response.ContentType, result.ContentType); Assert.Equals(contextMock.response.GetContentsFromBody(), exceptedResult); } }
public void WithRequestAsObjectShouldWorkWithSetRequestAction() { var httpContext = new HttpContextMock(); httpContext.Request.Form = new FormCollection(new Dictionary <string, StringValues> { ["Test"] = "TestValue" }); MyViewComponent <HttpRequestComponent> .Instance() .WithHttpRequest(httpContext.Request) .InvokedWith(c => c.Invoke()) .ShouldReturn() .View(); }
public void WriteResponse() { var image = new Bitmap(123, 456); var result = new ImageResult(image); var contextMock = new HttpContextMock(); result.WriteResponse(contextMock.response); contextMock.response.body.Seek(0, SeekOrigin.Begin); Assert.Equals(contextMock.response.StatusCode, 200); Assert.Equals(contextMock.response.ContentType, "image/jpeg"); var imageVerify = Image.FromStream(contextMock.response.body); Assert.Equals(imageVerify.Width, 123); Assert.Equals(imageVerify.Height, 456); }
public void SendVerificationCodeSuccessful() { // Arrange string testUserName = "******"; Mock <User> mockUserModel = new Mock <User>(); Mock <CosmoMongerMembershipUser> mockUser = new Mock <CosmoMongerMembershipUser>(mockUserModel.Object); mockUser.Expect(m => m.SendVerificationCode(It.IsRegex("http://www.cosmomonger.com/Account/VerifyEmail?username=TestUser&verificationCode=.*"))) .AtMostOnce().Verifiable(); Mock <MembershipProvider> mockMembership = new Mock <MembershipProvider>(); mockMembership.Expect <MembershipUser>(m => m.GetUser(testUserName, false)) .Returns(mockUser.Object).AtMostOnce().Verifiable(); // Mock the HTTP request also HttpRequestMock mockRequest = new HttpRequestMock(); Uri mockUrl = new Uri("http://www.cosmomonger.com/Account/SendVerificationCode?username=TestUser"); mockRequest.Expect(r => r.Url) .Returns(mockUrl); mockRequest.Expect(r => r.HttpMethod) .Returns("GET"); mockRequest.Expect(r => r.AppRelativeCurrentExecutionFilePath) .Returns("~/Account/"); HttpContextMock mockHttpContext = new HttpContextMock(); mockHttpContext.Expect(c => c.Request) .Returns(mockRequest.Object); RouteCollection routeCollection = new RouteCollection(); MvcApplication.RegisterRoutes(routeCollection); RouteData route = routeCollection.GetRouteData(mockHttpContext.Object); AccountController controller = new AccountController(mockMembership.Object); controller.ControllerContext = new ControllerContext(mockHttpContext.Object, route, new Mock <ControllerBase>().Object); controller.Url = new UrlHelper(new RequestContext(mockHttpContext.Object, route)); // Act ViewResult result = (ViewResult)controller.SendVerificationCode(testUserName); // Assert Assert.That(result.ViewName, Is.EqualTo("SentVerificationCode"), "Should have returned the SentVerificationCode view"); }
public void ShouldAllowSettingBytesBody() { var httpContextMock = HttpContextMock.Default(); var content = Any.Array <byte>(3); httpContextMock.Request().WithBytesBody(content); var result = new List <byte> { (byte)httpContextMock.Request().RealInstance.Body.ReadByte(), (byte)httpContextMock.Request().RealInstance.Body.ReadByte(), (byte)httpContextMock.Request().RealInstance.Body.ReadByte() }; result.Should().Equal(content); httpContextMock.Request().RealInstance.Body.Length.Should().Be(3); }
public async Task <AddTodoItemAdapterResponse> AttemptToAddTodoItem(Func <HttpRequestMock, HttpRequestMock> customize) { var httpContextMock = HttpContextMock.Default(); await _adapter.AddTodoEndpoint.Handle( customize(httpContextMock.Request() .AppendPathSegment("todo") .WithHeader("Authorization", $"Bearer {TestTokens.GenerateToken()}") .WithHeader("Content-Type", MediaTypeNames.Application.Json) .WithHeader("Accept", MediaTypeNames.Application.Json) .WithQueryParam("customerId", Any.String()) .WithJsonBody(new { title = "Meeting", content = "there's a meeting you need to attend" })).RealInstance, httpContextMock.Response().RealInstance, new CancellationToken() ); var httpResponseMock = httpContextMock.Response(); return(new AddTodoItemAdapterResponse(httpResponseMock)); }
protected override void EstablishContext() { base.EstablishContext(); var script = new StringBuilder(); script.AppendLine("class {0} < Controller".FormattedWith(_controllerName)); script.AppendLine(" def my_action"); script.AppendLine(" \"Can't see ninjas\".to_clr_string"); script.AppendLine(" end"); script.AppendLine("end"); _rubyEngine.ExecuteScript(script.ToString()); var rubyClass = _rubyEngine.GetRubyClass(_controllerName); var httpContext = new HttpContextMock().Object; var requestContext = new RequestContext(httpContext, new RouteData()); var controller = _rubyEngine.CreateInstance<RubyController>(rubyClass); controller.InternalInitialize(new ControllerConfiguration { Context = requestContext, Engine = _rubyEngine, RubyClass = rubyClass }); _controllerContext = new ControllerContext(requestContext, controller); }
private RouteContext GetRouteContext(string url, string method = "GET", string queryString = null, string body = null, string contentType = null) { var httpContext = new HttpContextMock(); httpContext.Request.Path = new PathString(url); httpContext.Request.QueryString = new QueryString(queryString); httpContext.Request.Method = method; httpContext.Request.ContentType = contentType; if (body != null) { httpContext.Request.Body = new MemoryStream(); var streamWriter = new StreamWriter(httpContext.Request.Body); streamWriter.Write(body); streamWriter.Flush(); httpContext.Request.Body.Position = 0; } return new RouteContext(httpContext); }
private RouteContext GetRouteContext(string url, string method = "GET", string queryString = null, string body = null, string contentType = null) { var httpContext = new HttpContextMock(); httpContext.Request.Path = new PathString(url); httpContext.Request.QueryString = new QueryString(queryString); httpContext.Request.Method = method; httpContext.Request.ContentType = contentType; if (body != null) { httpContext.Request.Body = new MemoryStream(); var streamWriter = new StreamWriter(httpContext.Request.Body); streamWriter.Write(body); streamWriter.Flush(); httpContext.Request.Body.Position = 0; } return new RouteContext(httpContext); }
public static TModel ReadFromStream <TModel>(Stream stream, string contentType, Encoding encoding) { stream.Restart(); // formatters do not support non HTTP context processing var httpContext = new HttpContextMock(); httpContext.Request.Body = stream; httpContext.Request.ContentType = contentType; var typeOfModel = typeof(TModel); var modelMetadataProvider = TestServiceProvider.GetRequiredService <IModelMetadataProvider>(); var modelMetadata = modelMetadataProvider.GetMetadataForType(typeOfModel); var inputFormatterContext = new InputFormatterContext( httpContext, string.Empty, new ModelStateDictionary(), modelMetadata, (str, enc) => new StreamReader(httpContext.Request.Body, encoding)); var inputFormatter = inputFormatters.GetOrAdd(contentType, _ => { var mvcOptions = TestServiceProvider.GetRequiredService <IOptions <MvcOptions> >(); var formatter = mvcOptions.Value?.InputFormatters?.FirstOrDefault(f => f.CanRead(inputFormatterContext)); ServiceValidator.ValidateFormatterExists(formatter, contentType); return(formatter); }); var result = AsyncHelper.RunSync(() => inputFormatter.ReadAsync(inputFormatterContext)).Model; try { return((TModel)result); } catch (Exception) { throw new InvalidDataException($"Expected stream content to be formatted to {typeOfModel.ToFriendlyTypeName()} when using '{contentType}', but instead received {result.GetName()}."); } }
protected override void EstablishContext() { base.EstablishContext(); var script = new StringBuilder(); script.AppendLine("class {0} < Controller".FormattedWith(_controllerName)); script.AppendLine(" def my_action"); script.AppendLine(" \"Can't see ninjas\".to_clr_string"); script.AppendLine(" end"); script.AppendLine("end"); _rubyEngine.ExecuteScript(script.ToString()); _rubyClass = _rubyEngine.GetRubyClass(_controllerName); _httpContextMock = new HttpContextMock(); var httpContext = _httpContextMock.Object; // EstablishHttpContext(httpContext); _requestContext = new RequestContext(httpContext, new RouteData()); }
public void WriteResponse() { using (var layout = new TestDirectoryLayout()) { Application.Ioc.Unregister <TemplateManager>(); Application.Ioc.RegisterMany <TemplateManager>(ReuseType.Singleton); layout.WritePluginFile("PluginA", "templates/__test_a.html", "test a {{ name }}"); layout.WritePluginFile("PluginB", "templates/__test_b.html", "test b {{ name }}"); var result = new TemplateResult("__test_a.html", new { name = "asd" }); var contextMock = new HttpContextMock(); result.WriteResponse(contextMock.response); Assert.Equals(contextMock.response.StatusCode, 200); Assert.Equals(contextMock.response.ContentType, "text/html"); Assert.Equals(contextMock.response.GetContentsFromBody(), "test a asd"); result = new TemplateResult("__test_b.html", new { name = "asd" }); contextMock = new HttpContextMock(); result.WriteResponse(contextMock.response); Assert.Equals(contextMock.response.StatusCode, 200); Assert.Equals(contextMock.response.ContentType, "text/html"); Assert.Equals(contextMock.response.GetContentsFromBody(), "test b asd"); } }
static HttpContextMock GetHttpContext(string appPath, string requestPath, string httpMethod) { HttpContextMock httpContext = new HttpContextMock(); if (!string.IsNullOrEmpty(appPath)) { httpContext.HttpRequest.SetupGet(r => r.ApplicationPath).Returns(appPath); } else { httpContext.HttpRequest.SetupGet(r => r.ApplicationPath).Returns("http://test.com"); } if (!string.IsNullOrEmpty(requestPath)) { httpContext.HttpRequest.SetupGet(r => r.AppRelativeCurrentExecutionFilePath).Returns(requestPath); } httpContext.HttpRequest.SetupGet(r => r.PathInfo).Returns(string.Empty); if (!string.IsNullOrEmpty(httpMethod)) { httpContext.HttpRequest.SetupGet(r => r.HttpMethod).Returns(httpMethod); } httpContext.HttpResponse.Setup(r => r.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(r => r.Contains(AppPathModifier) ? r : AppPathModifier + r); return httpContext; }
public void WithRequestAsObjectShouldWorkWithSetRequestActionForPocoController() { MyApplication .StartsFrom <DefaultStartup>() .WithServices(services => { services.AddHttpContextAccessor(); }); var httpContext = new HttpContextMock(); httpContext.Request.Form = new FormCollection(new Dictionary <string, StringValues> { ["Test"] = "TestValue" }); MyController <FullPocoController> .Instance() .WithHttpRequest(httpContext.Request) .Calling(c => c.WithRequest()) .ShouldReturn() .Ok(); MyApplication.StartsFrom <DefaultStartup>(); }
public void Run() { var extensionConfigPath = arguments["extension"].Trim(); var workingDirectory = arguments["directory"].Trim(); if (!File.Exists(extensionConfigPath)) { log.ErrorFormat("The extension configuration file '{0}' doesn't exist", extensionConfigPath); return; } if (!Directory.Exists(workingDirectory)) { log.ErrorFormat("Directory '{0}' doesn't exist", workingDirectory); return; } var builder = new ExtensionBuilder(); var fileInfo = new FileInfo(extensionConfigPath); var extensionConfig = ProjectConfiguration.Create(fileInfo.FullName); if (string.IsNullOrEmpty(extensionConfig.Name)) { log.ErrorFormat("The extension needs a name, build cancelled"); return; } log.InfoFormat("Building extension {0}.", extensionConfig.Name); var extensionFile = Path.Combine(fileInfo.DirectoryName, extensionConfig.Name + ".zip"); builder.BuildExtension(fileInfo.DirectoryName, extensionFile); var projectFiles = Directory .GetFiles(workingDirectory, "Project.config", SearchOption.AllDirectories) .Where(s => s != fileInfo.FullName && !s.Contains(@"\bin\")); foreach (var projectFile in projectFiles) { var projectInfo = new FileInfo(projectFile); var projectConfig = ProjectConfiguration.Create(projectInfo.FullName); if (projectConfig.Dependencies.Contains(extensionConfig.Name)) { var httpContext = new HttpContextMock("/"); var projectContext = new SageContext(httpContext, delegate(string path) { path = path.ReplaceAll("^~?/", string.Empty).ReplaceAll("/", "\\"); if (!Path.IsPathRooted(path)) path = Path.Combine(projectInfo.DirectoryName, path); return path; }, projectConfig); string installPath = Path.Combine(projectContext.Path.ExtensionPath, Path.GetFileName(extensionFile)); File.Copy(extensionFile, installPath, true); } } }
protected HttpTestContext() { TestHelper.ExecuteTestCleanup(); this.httpContextMock = TestHelper.CreateHttpContextMock(); }
public void WithRequestAsObjectShouldWorkWithSetRequestAction() { var httpContext = new HttpContextMock(); httpContext.Request.Form = new FormCollection(new Dictionary<string, StringValues> { ["Test"] = "TestValue" }); MyController<MvcController> .Instance() .WithHttpRequest(httpContext.Request) .Calling(c => c.WithRequest()) .ShouldReturn() .Ok(); }
public bool ParseArguments(string[] args) { arguments = new NameValueCollection(); foreach (string arg in args) { if (arg.StartsWith("-targetpath:")) { arguments["targetPath"] = arg.Substring(12).Trim('"'); } if (arg.StartsWith("-category:")) { arguments["category"] = arg.Substring(10).Trim('"'); } if (arg.StartsWith("-reportpath:")) { arguments["reportpath"] = arg.Substring(12).Trim('"'); } if (arg.StartsWith("-emitsummary:")) { arguments["emitSummary"] = arg.Substring(13) == "1" ? "1" : "0"; } if (arg.StartsWith("-merge:")) { arguments["mergeAssets"] = arg.Substring(7).ContainsAnyOf("yes", "1", "true") ? "1" : "0"; } } if (arguments["targetPath"] != null && arguments["category"] != null) { HttpContextMock httpContext = new HttpContextMock("sage"); context = new SageContext(httpContext, arguments["category"], this.MapPath); categoryPath = context.Path.GetPhysicalCategoryPath(arguments["category"]); return true; } return false; }
public void WithRequestAsObjectShouldWorkWithSetRequestAction() { var httpContext = new HttpContextMock(); httpContext.Request.Form = new FormCollection(new Dictionary<string, StringValues> { ["Test"] = "TestValue" }); MyViewComponent<HttpRequestComponent> .Instance() .WithHttpRequest(httpContext.Request) .InvokedWith(c => c.Invoke()) .ShouldReturn() .View(); }
public UnitTestContext(AuthenticationScheme authenticationScheme, Action <CertificateAuthenticationOptions> certificateAuthenticationOptionsConfigurer, HttpContextMock httpContext, LoggerFactoryMock loggerFactory, SystemClockMock systemClock, UrlEncoder urlEncoder) { this.AuthenticationScheme = authenticationScheme ?? throw new ArgumentNullException(nameof(authenticationScheme)); this.CertificateAuthenticationOptionsMonitor = new OptionsMonitorMock <CertificateAuthenticationOptions>(certificateAuthenticationOptionsConfigurer); this.HttpContext = httpContext ?? throw new ArgumentNullException(nameof(httpContext)); this.LoggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); this.SystemClock = systemClock ?? throw new ArgumentNullException(nameof(systemClock)); this.UrlEncoder = urlEncoder ?? throw new ArgumentNullException(nameof(urlEncoder)); }
/// <summary> /// Tests the specified URL against all configured routes and displays a view that shows the results as an HTML table. /// </summary> /// <param name="url">The URL to test</param> /// <param name="httpMethod">The HTTP request method to test with.</param> /// <returns>The HTML string that contains the table with the test results.</returns> public string Index(string url, string httpMethod) { if (!Context.IsDeveloperRequest) { Response.StatusCode = 404; return string.Empty; } url = MakeAppRelative(url ?? string.Empty); httpMethod = httpMethod ?? "GET"; var httpContext = new HttpContextMock(url, httpMethod); var httpMethodOptions = FormatOptions(httpMethod, new[] { "GET", "POST", "PUT", "DELETE", "HEAD" }); var routeDataText = GetRoutesText(httpContext); return string.Format(HtmlFormat, url, httpMethodOptions, routeDataText); }
public void ShouldContainEmptyBodyInResponse() { var httpContextMock = HttpContextMock.Default(); httpContextMock.Response().BodyString().Should().BeEmpty(); }
protected HttpTestContext() { TestHelper.ExecuteTestCleanup(); this.httpContextMock = TestHelper.CreateHttpContextMock(); }
public void Setup() { _resolver = new Mock<IRepositoryResolver>(); _resolver.Setup(x => x.GetRepository(It.IsAny<string>())) .Returns(new Repository(TestUtils.GetRepositoryPath("Test"))); _controller = new RepositoryController(new Mock<ISettingsProvider>().Object, _resolver.Object, null); _executingContext = new Mock<ActionExecutingContext>(); _executingContext.Setup(x => x.Controller).Returns(_controller); _actionParameters = new Dictionary<string, object>(); _executingContext.Setup(x => x.ActionParameters).Returns(_actionParameters); _actionParameters.Add("request", new RepositoryNavigationRequest()); _routeData = new RouteData(); _executingContext.Setup(x => x.RouteData).Returns(_routeData); var requestContext = new Mock<RequestContext>(); var httpContext = new HttpContextMock(); requestContext.Setup(x => x.HttpContext).Returns(httpContext.Object); _executingContext.Setup(x => x.HttpContext).Returns(httpContext.Object); _filter = new RepositoryRequestAttribute { RepositoryResolver = _resolver.Object }; }
private static string GetRoutesText(HttpContextMock fakeContext) { var sb = new StringBuilder(); foreach (Route route in RouteTable.Routes) { RouteData rd = route.GetRouteData(fakeContext); var isMatch = false; var match = rd == null ? "No" : "Yes"; // Get values var values = "N/A"; if (rd != null) { isMatch = true; values = FormatValues(rd.Values); } // Get defaults var defaults = FormatValues(route.Defaults); // Get constraints var constraints = FormatValues(route.Constraints); // Get dataTokens var dataTokens = FormatValues(route.DataTokens); // Create table row var name = route is LowerCaseRoute ? ((LowerCaseRoute)route).Name : "No name"; var row = FormatRow(isMatch, match, name, route.Url, defaults, constraints, dataTokens, values); sb.Append(row); } return sb.ToString(); }