public void Setup() { _autoSubstitute = AutoSubstituteContainer.Create(); _h = _autoSubstitute.ResolveAndSubstituteFor<HtmlHelpers<TestFieldViewModel>>(); _t = _autoSubstitute.Resolve<IFormTemplate>(); _t.BeginForm(Action, Method, _htmlAttributes, Enctype).Returns(_beginHtml); _t.EndForm().Returns(_endHtml); }
public async Task <Post> CreatePreviewEditPostAsync(ForumReply forumReplyEntity) { var form = new MultipartFormDataContent { { new StringContent("updatepost"), "action" }, { new StringContent(forumReplyEntity.PostId.ToString()), "postid" }, { new StringContent(HtmlHelpers.HtmlEncode(forumReplyEntity.Message)), "message" }, { new StringContent(forumReplyEntity.ParseUrl.ToString()), "parseurl" }, { new StringContent("2097152"), "MAX_FILE_SIZE" }, { new StringContent("Preview Post"), "preview" } }; var result = await _webManager.PostFormDataAsync(EndPoints.EditPost, form); var document = _webManager.Parser.Parse(result.ResultHtml); return(new Post { PostHtml = document.QuerySelector(".postbody").InnerHtml }); }
public async Task Post_EditStudent() { // Arrange string studentId = "1"; string url = $"/students/edit/{studentId}"; HttpResponseMessage editPageResponse = await _client.GetAsync(url); IHtmlDocument editPage = await HtmlHelpers.GetDocumentAsync(editPageResponse); IHtmlInputElement firstNameInput = (IHtmlInputElement)editPage.QuerySelector("#student_FirstName"); IHtmlInputElement lastNameInput = (IHtmlInputElement)editPage.QuerySelector("#student_LastName"); IHtmlInputElement slackInput = (IHtmlInputElement)editPage.QuerySelector("#student_SlackHandle"); IHtmlSelectElement cohortIdSelect = (IHtmlSelectElement)editPage.QuerySelector("#student_CohortId"); string firstName = firstNameInput.Value; string lastName = lastNameInput.Value; string slack = slackInput.Value; string cohortId = cohortIdSelect.Value; // Act firstName = firstName + "!!!!"; HttpResponseMessage response = await _client.SendAsync( editPage, new Dictionary <string, string> { { "student_FirstName", firstName }, { "student_LastName", lastName }, { "student_SlackHandle", slack }, { "student_CohortId", cohortId } }); // Assert response.EnsureSuccessStatusCode(); IHtmlDocument indexPage = await HtmlHelpers.GetDocumentAsync(response); Assert.Contains( indexPage.QuerySelectorAll("td"), td => td.TextContent.Contains(firstName)); }
public ActionResult Search_User(string p_keysearch, int p_CurrentPage, string p_column, string p_type_sort) { try { string p_name = ""; string p_type = "-1"; string p_status = "-1"; string p_Custom_Id = "-1"; int p_start = NaviCommon.Common.RecordOnpage * (p_CurrentPage - 1) + 1; int p_end = NaviCommon.Common.RecordOnpage * p_CurrentPage; string[] arrKey = p_keysearch.Split('|'); if (arrKey.Length > 0) { p_name = arrKey[0]; p_type = arrKey[1]; p_status = arrKey[2]; p_Custom_Id = arrKey[3]; } if (String.IsNullOrEmpty(p_name)) { p_name = "-1"; } UserInfo_BL _UserInfo_BL = new UserInfo_BL(); decimal p_totalrecord = 0; List <User_Info> _lst = _UserInfo_BL.UserInfo_Search(p_name, p_type, p_status, p_Custom_Id, p_column, p_type_sort, p_start.ToString(), p_end.ToString(), ref p_totalrecord); ViewBag.Paging = HtmlHelpers.PagingData(p_CurrentPage, NaviCommon.Common.RecordOnpage, (int)p_totalrecord, "Tài khoản"); ViewBag.SumRecord = p_totalrecord; ViewBag.FromRow = p_start; ViewBag.Obj = _lst; return(PartialView("PartialViewTableslistUser")); } catch (Exception ex) { NaviCommon.Common.log.Error(ex.ToString()); return(PartialView("PartialViewTableslistUser")); } }
public async Task ShouldHavePassWhenDeleteAndReturnRedirectToRootAsync() { //arrange var client = CreateHttpClient(); //actual var homePage = await client.GetAsync("/"); var html = await HtmlHelpers.GetDocumentAsync(homePage); var response = await client.SendAsync((IHtmlFormElement)html.QuerySelector("form[id='todos']"), (IHtmlButtonElement)html.QuerySelector("form[id='todos']") .QuerySelector("div[class='panel-body']") .QuerySelector("button")); //assert Assert.AreEqual(HttpStatusCode.OK, homePage.StatusCode); Assert.AreEqual(HttpStatusCode.Redirect, response.StatusCode); Assert.AreEqual("/", response.Headers.Location.OriginalString); }
public static HtmlTag CreateTextareaElementFor <TModel, TR>( HtmlHelpers <TModel> html, Expression <Func <TModel, TR> > prop, object htmlAttributes) where TModel : class { var propertyInfo = prop.AsPropertyInfo(); if (propertyInfo == null) { return(null); } var name = propertyInfo.Name; var tag = new HtmlTag("textarea"). WithAttribute("name", name.ToLowerInvariant()); tag.WithAttributes(htmlAttributes); tag.ApplyInnerTextProperty(html.Model, propertyInfo.Name); return(tag); }
public async Task WebpackEntryWithJSOnlyAttribute_ShouldPrintJSOnly() { // Arrange var page1 = await _client.GetAsync("/Test/WebpackEntryWithJSOnlyAttributeTest"); var content = await HtmlHelpers.GetDocumentAsync(page1); var scripts = HtmlHelpers.GetScripts(content); var links = HtmlHelpers.GetLinks(content); // Act // Assert Assert.Equal(1, scripts.Count); Assert.Equal(0, links.Count); Assert.Single(scripts, script => script.Source.Contains("page-c")); }
public bool ValidateToken(string token, string methodToCall, out string errorMessage) { errorMessage = string.Empty; string result = null; var requestContent = "/?token=" + token + "&methodTocall=" + methodToCall; var url = ConfigurationManager.AppSettings["AuththenticationDomain"] + "/" + "api/Authenticate/ValidateToken" + requestContent; result = HtmlHelpers.PostAPIRequest(url, requestContent); if (result.Contains("Success")) { return(true); } else { errorMessage = result; return(false); } }
public async Task TrainingProvider_CorrectlyDisplaysRecruitButton(string accountId) { var client = BuildClient(); var response = await client.GetAsync($"accounts/{accountId}/apprenticeships/123/providers"); var content = await HtmlHelpers.GetDocumentAsync(response); var recruitButtonElement = content.QuerySelector(".recruit-button"); if (accountId == "ACCOUNT_WITH_LEGAL_ENTITIES") { Assert.NotNull(recruitButtonElement); } if (accountId == "ACCOUNT_WITHOUT_LEGAL_ENTITIES") { Assert.Null(recruitButtonElement); } }
private static void AppendValidationResults <TModel>(HtmlHelpers <TModel> htmlHelper, HtmlTag tag) { var validationResult = htmlHelper.RenderContext.Context.ModelValidationResult; var name = tag.Attribute("name").Value; if (validationResult == null) { return; } if (validationResult.Errors.Any(error => error.Key.Equals(name, StringComparison.InvariantCultureIgnoreCase))) { var classAttr = tag.Attribute("class"); var @class = classAttr != null ? string.Concat(classAttr.Value, " input-error") : "input-error"; tag.RemoveAttribute("class").WithAttribute("class", @class); } }
public static IHtmlString ValidationMessageFor <T>(this HtmlHelpers <T> helper, List <ErrorModel> Errors, string PropertyName) { if (!Errors.Any()) { return(new NonEncodedHtmlString("")); } string span = String.Empty; foreach (var item in Errors) { if (item.Name == PropertyName) { span += "<span class=\"field-validation-error\">" + item.ErrorMessage + "</span>"; break; } } return(new NonEncodedHtmlString(span)); }
public static IHtmlString GetNavbarUrl(this HtmlHelpers helper, NancyContext context, string url, string title, string fontIcon) { var returnString = string.Empty; var content = GetLinkUrl(GetBaseUrl()); if (!string.IsNullOrEmpty(content)) { url = $"/{content}{url}"; } if (context.Request.Path == url) { returnString = $"<li class=\"active\"><a href=\"{url}\"><i class=\"fa fa-{fontIcon}\"></i> {title}</a></li>"; } else { returnString = $"<li><a href=\"{url}\"><i class=\"fa fa-{fontIcon}\"></i> {title}</a></li>"; } return(helper.Raw(returnString)); }
private static IEnumerable <KeyValuePair <XPath, ContentLengthMetric> > EvaluateDocumentMetric(DataInfo info) { var root = HtmlHelpers.GetBody(info.Data); if (root == null) { return(Enumerable.Empty <KeyValuePair <XPath, ContentLengthMetric> >()); } FilterNodes(root); return(root.GetAllTags() .ToDictionary(x => x, x => x.GetClearTextLength()) .Where(x => x.Value > 0) .Select(x => new KeyValuePair <XPath, ContentLengthMetric>( new XPath(x.Key), new ContentLengthMetric(x, info.Url)))); //.ToDictionary(x => new XPath(x.Key), x => new ContentLengthMetric(x, info.Url)); }
public static IHtmlString GetSidebarUrl(this HtmlHelpers helper, NancyContext context, string url, string title) { var returnString = string.Empty; var content = GetLinkUrl(GetBaseUrl()); if (!string.IsNullOrEmpty(content)) { url = $"/{content}{url}"; } if (context.Request.Path == url) { returnString = $"<a class=\"list-group-item active\" href=\"{url}\">{title}</a>"; } else { returnString = $"<a class=\"list-group-item\" href=\"{url}\">{title}</a>"; } return(helper.Raw(returnString)); }
private static HtmlTag CreateCheckboxForBool <TModel>(HtmlHelpers <TModel> html, PropertyInfo property, object htmlAttributes) where TModel : class { var name = property.Name; var check = new HtmlTag("input"). WithAttribute("type", HtmlInputType.Checkbox.ToString().ToLowerInvariant()). WithAttribute("name", name.ToLowerInvariant()). WithAttribute("value", true.ToString()); var propValue = html.Model != null && property.CanRead ? (bool)Convert.ToBoolean(property.GetValue(html.Model)) : GetDefaultBoolValue(property); if (propValue) { check.WithEmptyAttribute("checked"); } return(check); }
public static IHtmlString LabeledCheckBox <TModel>(this HtmlHelpers <TModel> htmlHelper, Expression <Func <TModel, bool> > property) { var member = property.GetMember(); var path = property.ToMemberPath(); var display = member.GetDisplay(); bool value = htmlHelper.Model.Read(property); var formGroup = Tags.Div().Classes(BootstrapClass.FormGroup).Content( Tags.Div().Content( Tags.Div().Classes(BootstrapClass.Checkbox).Content( Tags.Label().Content( Tags.Input.CheckBox().Checked(value).Name(path).Content(display.Name) ) ) ) ); return(formGroup); }
public async override Task <ProductMetadata> GetProductMetadataFromUrl(ChromeDriver driver, Product product) { driver.Navigate().GoToUrl(product.Link); var json = driver.ExecuteScript("return JSON.stringify(window.state.pdp.detailsState.response.body.products)").ToString(); var images = coach_bags_selenium.Outnet.OutnetProduct.FromJson(json) .SelectMany(p => p.ToEntity(this).Images) .ToArray(); var html = await HtmlHelpers.GetDocumentFromSource(driver.PageSource); var tags = html.QuerySelectorAll("#TECHNICAL_DESCRIPTION p") .Select(p => p.TextContent.Trim()) .ToArray(); return(new ProductMetadata { Images = images, Tags = tags, }); }
public static IHtmlString AlertMessages <TModel>(this HtmlHelpers <TModel> htmlHelper) { const string message = @"<div class=""alert alert-{0}"">{1}</div>"; var alertsDynamicValue = htmlHelper.RenderContext.Context.ViewBag.Alerts; var alerts = (AlertMessageStore)(alertsDynamicValue.HasValue ? alertsDynamicValue.Value : null); if (alerts == null || !alerts.Messages.Any()) { return(new NonEncodedHtmlString(String.Empty)); } var builder = new StringBuilder(); foreach (var messageDetail in alerts.Messages) { builder.AppendFormat(message, messageDetail.Key, messageDetail.Value); } return(new NonEncodedHtmlString(builder.ToString())); }
public static IHtmlString SimplePager <TModel>(this HtmlHelpers <TModel> htmlHelper, IPagedList pagedList, string baseUrl) { var pagerBuilder = new StringBuilder(); pagerBuilder.Append(@"<div class=""pager"">"); pagerBuilder.Append(@"<ul>"); pagerBuilder.AppendFormat(@"<li class=""previous {0}"">", !pagedList.HasPreviousPage ? "disabled" : ""); pagerBuilder.AppendFormat(@"<a href=""{0}"">← Prev</a>", pagedList.HasPreviousPage ? String.Format("{0}page={1}", baseUrl, pagedList.PageNumber - 1) : "#"); pagerBuilder.Append(@"</li>"); pagerBuilder.AppendFormat(@"<li class=""next {0}"">", !pagedList.HasNextPage ? "disabled" : ""); pagerBuilder.AppendFormat(@"<a href=""{0}"">Next →</a>", pagedList.HasNextPage ? String.Format("{0}page={1}", baseUrl, pagedList.PageNumber + 1) : "#"); pagerBuilder.Append(@"</li>"); pagerBuilder.Append(@"</ul>"); pagerBuilder.Append(@"</div>"); return(new NonEncodedHtmlString(pagerBuilder.ToString())); }
public async Task Get_IndexReturnsSuccessAndCorrectContentType() { // Arrange string url = "/department"; // Act HttpResponseMessage response = await _client.GetAsync(url); IHtmlDocument indexPage = await HtmlHelpers.GetDocumentAsync(response); // Assert response.EnsureSuccessStatusCode(); // Status Code 200-299 Assert.Contains(indexPage.QuerySelectorAll("td"), d => d.TextContent.Contains("Sales")); Assert.Contains(indexPage.QuerySelectorAll("td"), d => d.TextContent.Contains("100000")); }
public async Task Get_CreateDepartmentForm() { //Arrange string url = "/department/create"; //Act HttpResponseMessage response = await _client.GetAsync(url); //Assert response.EnsureSuccessStatusCode(); IHtmlDocument createPage = await HtmlHelpers.GetDocumentAsync(response); Assert.Contains( createPage.QuerySelectorAll("input"), i => i.Id == "Name"); Assert.Contains( createPage.QuerySelectorAll("input"), i => i.Id == "Budget"); }
public async Task AddItemsToCart_ShoppingCartHasCorrectAmountOfItems() { // Arrange var client = _factory.CreateClient(); // Act await client.GetAsync("/Home/AddToCart/1"); await client.GetAsync("/Home/AddToCart/2"); var response = await client.GetAsync("/Home/AddToCart/3"); var html = await HtmlHelpers.GetDocumentAsync(response); var elements = html.QuerySelectorAll(".shopping-cart-items li.product-item"); // Assert response.EnsureSuccessStatusCode(); // Status Code 200-299 Assert.Equal(3, elements.Length); }
public async Task <Result> SendPostAsync(ForumReply forumReplyEntity, CancellationToken token = default) { if (forumReplyEntity == null) { throw new ArgumentNullException(nameof(forumReplyEntity)); } using var form = new MultipartFormDataContent { { new StringContent("postreply"), "action" }, { new StringContent(forumReplyEntity.ThreadId), "threadid" }, { new StringContent(forumReplyEntity.FormKey), "formkey" }, { new StringContent(forumReplyEntity.FormCookie), "form_cookie" }, { new StringContent(HtmlHelpers.HtmlEncode(forumReplyEntity.Message)), "message" }, { new StringContent(forumReplyEntity.ParseUrl.ToString()), "parseurl" }, { new StringContent("2097152"), "MAX_FILE_SIZE" }, { new StringContent("Submit Reply"), "submit" }, }; return(await this.webManager.PostFormDataAsync(EndPoints.NewReply, form, token).ConfigureAwait(false)); }
public async void Post_DeletePage_InvalidPost_ReturnsBadRequest() { /* GET the "delete" page first, just like a web browser would. * We need this for the validation token and anti-forgery cookie */ var defaultPage = await client.GetAsync("/Blog/Delete?id=1"); var content = await HtmlHelpers.GetDocumentAsync(defaultPage); var response = await client.SendAsync( (IHtmlFormElement)content.QuerySelector("form"), (IHtmlInputElement)content.QuerySelector("input[type='submit']"), new Dictionary <string, string> { // This should cause a BadRequest since POST and url IDs don't match ["BlogPost.Id"] = "2" }); Assert.Equal(HttpStatusCode.OK, defaultPage.StatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }
public async Task Then_The_Correct_Error_Message_Is_Displayed(string fileName, string fileContentType, string fileContent, DataImportType importType, string errorMessage, int errorSummaryIndex) { var client = _factory.CreateClient(); var pageResponse = await client.GetAsync("/DataImport"); var pageContent = await HtmlHelpers.GetDocumentAsync(pageResponse); var file = Substitute.For <IFile>(); file.Name.Returns(fileName); file.Type.Returns(fileContentType); file.Body.Returns(fileContent != null ? new MemoryStream(Encoding.UTF8.GetBytes(fileContent)) : null); var input = (IHtmlInputElement)pageContent.QuerySelector("input[type=file][name=File]"); input?.Files.Add(file); var response = await client.SendAsync( (IHtmlFormElement)pageContent.QuerySelector("form"), (IHtmlButtonElement)pageContent.GetElementById("tl-upload"), new Dictionary <string, string> { ["SelectedImportType"] = importType.ToString() }); Assert.Equal(HttpStatusCode.OK, pageResponse.StatusCode); response.EnsureSuccessStatusCode(); var responseContent = await HtmlHelpers.GetDocumentAsync(response); var errorSummaryList = responseContent.QuerySelector(".govuk-error-summary div ul"); errorSummaryList.Children[errorSummaryIndex].TextContent.Should().Be(errorMessage); AssertError(responseContent, "File", errorMessage); Assert.Null(response.Headers.Location?.OriginalString); }
public static Dictionary <List <HtmlNode>, double> GetSimilarTrees(HtmlNode rootNode, int level, double minSimilarity = 0.5) { var groups = new List <SimilarityCollection>(); var lastNodeTrees = HtmlHelpers.GetMaxDepthNodes(rootNode, level) .Select(GenerateTree); foreach (var nodeTree in lastNodeTrees) { var found = false; foreach (var group in groups) { var c = nodeTree.CompareTrees(group.Value[0]); if (c < minSimilarity) { continue; } group.Value.Add(nodeTree); group.SumSimilarity += c; found = true; } if (found) { continue; } var newPair = new SimilarityCollection(); newPair.Value.Add(nodeTree); groups.Add(newPair); } return(groups .Where(p => p.Value.Count > 1) .ToDictionary( pair => pair.Value.Select(x => x.OrigNode).ToList(), pair => pair.Average )); }
public async Task Post() { /* * This information comes from https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.1#basic-tests-with-the-default-webapplicationfactory * * Any POST request to the SUT must satisfy the antiforgery check that's automatically made by the app's data protection antiforgery system. * In order to arrange for a test's POST request, the test app must: * Make a request for the page. * Parse the antiforgery cookie and request validation token from the response. * Make the POST request with the antiforgery cookie and request validation token in place. * * The SendAsync helper extension methods (Helpers/HttpClientExtensions.cs) and the GetDocumentAsync helper method (Helpers/HtmlHelpers.cs) * in the sample app use the AngleSharp parser to handle the antiforgery check with the following methods: * GetDocumentAsync – Receives the HttpResponseMessage and returns an IHtmlDocument. * GetDocumentAsync uses a factory that prepares a virtual response based on the original HttpResponseMessage * SendAsync extension methods for the HttpClient compose an HttpRequestMessage and call SendAsync(HttpRequestMessage) to submit requests to the SUT. * Overloads for SendAsync accept the HTML form (IHtmlFormElement) and the following: * Submit button of the form (IHtmlElement) * Form values collection (IEnumerable<KeyValuePair<string, string>>) * Submit button (IHtmlElement) and form values (IEnumerable<KeyValuePair<string, string>>) */ // Arrange var client = _factory.CreateClient(); var summaryPage = await client.GetAsync("/Summary"); var content = await HtmlHelpers.GetDocumentAsync(summaryPage); content.Forms[0].Elements["InvestmentPercentage"].TextContent = "15"; content.Forms[0].Elements["AnnualSalary"].TextContent = "106,156"; // Act //var response = await client.PostAsync("/Summary", //(IHtmlFormElement)content.QuerySelector("form[id='messages']"), //(IHtmlButtonElement)content.QuerySelector("button[id='deleteAllBtn']")); //// Assert //Assert.Equal(HttpStatusCode.OK, defaultPage.StatusCode); //Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); //Assert.Equal("/", response.Headers.Location.OriginalString); }
public async Task LiteralEntryWithDependency_ShouldPrintTheLiteralEntryAndItsDependency() { var page1 = await _client.GetAsync("/Test/LiteralEntryWithDependencyTest"); var content = await HtmlHelpers.GetDocumentAsync(page1); var scripts = HtmlHelpers.GetScripts(content); // Act // Assert Assert.Equal(2, scripts.Count); Assert.Single(scripts, script => !string.IsNullOrEmpty(script.TextContent) && script.TextContent.Contains("console.log('simple entry')")); Assert.Single(scripts, script => !string.IsNullOrEmpty(script.Source) && script.Source.Contains("page-a")); }
public async void Post_EditPage_InvalidBlogPost_ReturnsOK() { /* GET the "edit" page first, just like a web browser would. * We need this for the validation token and anti-forgery cookie */ var defaultPage = await client.GetAsync("/Blog/Edit?id=1"); var content = await HtmlHelpers.GetDocumentAsync(defaultPage); var response = await client.SendAsync( (IHtmlFormElement)content.QuerySelector("form"), (IHtmlInputElement)content.QuerySelector("input[type='submit']"), new Dictionary <string, string> { // We need to blank the Content field, as the existing one is sent otherwise ["BlogPost.Title"] = "Changed Title", ["BlogPost.Content"] = "" }); Assert.Equal(HttpStatusCode.OK, defaultPage.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode); }
protected override void CollectReceiveParametersFromSource(string content) { HtmlDocument html = new HtmlDocument(); html.LoadHtml(content); var title = html.DocumentNode.SelectSingleNode("//head/title"); if (title != null) { Title = title.InnerText; BlogName = Title; } var link = HtmlHelpers.GetLinkNode(html, LinkbackTargetUrl); if (link != null) { Excerpt = link.ParentNode.InnerText.Trim(); } }
public static IHtmlString ValidationSummary <T>(this HtmlHelpers <T> helpers) { var sb = new StringBuilder(); if (!helpers.RenderContext.Context.ModelValidationResult.IsValid) { sb.AppendLine("<ul>"); foreach (var error in helpers.RenderContext.Context.ModelValidationResult.Errors) { foreach (var memberName in error.MemberNames) { sb.AppendLine(string.Format("<li>{0}</li>", error.GetMessage(memberName))); } } sb.AppendLine("</ul>"); } return(new NonEncodedHtmlString(sb.ToString())); }
public void Setup() { var autoSubstitute = AutoSubstituteContainer.Create(); _h = autoSubstitute.Resolve<HtmlHelpers<TestFieldViewModel>>(); }
public HtmlHelpersSelectExtensionsFixture() { this.model = new TestModel { TestEnum = SelectListItemExtensionsFixture.TestEnum.Two }; this.helpers = new HtmlHelpers<TestModel>(null, null, model); this.defaultOption = SelectListItemExtensionsFixture.TestEnum.Three.ToString(); }