HtmlGenerationTest.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Net.Http.Headers;
  10. using System.Reflection;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using Microsoft.AspNetCore.Hosting;
  14. using Microsoft.AspNetCore.Mvc.Testing;
  15. using Microsoft.AspNetCore.Testing;
  16. using Xunit;
  17. namespace Microsoft.AspNetCore.Mvc.FunctionalTests
  18. {
  19. public class HtmlGenerationTest :
  20. IClassFixture<MvcTestFixture<HtmlGenerationWebSite.Startup>>,
  21. IClassFixture<MvcEncodedTestFixture<HtmlGenerationWebSite.Startup>>
  22. {
  23. private static readonly Assembly _resourcesAssembly = typeof(HtmlGenerationTest).GetTypeInfo().Assembly;
  24. public HtmlGenerationTest(
  25. MvcTestFixture<HtmlGenerationWebSite.Startup> fixture,
  26. MvcEncodedTestFixture<HtmlGenerationWebSite.Startup> encodedFixture)
  27. {
  28. Factory = fixture.Factories.FirstOrDefault() ?? fixture.WithWebHostBuilder(ConfigureWebHostBuilder);
  29. Client = fixture.CreateDefaultClient();
  30. EncodedClient = encodedFixture.CreateDefaultClient();
  31. }
  32. private static void ConfigureWebHostBuilder(IWebHostBuilder builder) =>
  33. builder.UseStartup<HtmlGenerationWebSite.Startup>();
  34. public HttpClient Client { get; }
  35. public HttpClient EncodedClient { get; }
  36. public WebApplicationFactory<HtmlGenerationWebSite.Startup> Factory { get; }
  37. public static TheoryData<string, string> WebPagesData
  38. {
  39. get
  40. {
  41. var data = new TheoryData<string, string>
  42. {
  43. { "Customer", "/Customer/HtmlGeneration_Customer" },
  44. { "Index", null },
  45. { "Product", null },
  46. { "Link", null },
  47. { "Script", null },
  48. // Testing attribute values with boolean and null values
  49. { "AttributesWithBooleanValues", null },
  50. // Testing SelectTagHelper with Html.BeginForm
  51. { "CreateWarehouse", "/HtmlGeneration_Home/CreateWarehouse" },
  52. // Testing the HTML helpers with FormTagHelper
  53. { "EditWarehouse", null },
  54. { "Form", "/HtmlGeneration_Home/Form" },
  55. // Testing MVC tag helpers invoked in the editor templates from HTML helpers
  56. { "EmployeeList", "/HtmlGeneration_Home/EmployeeList" },
  57. // Testing the EnvironmentTagHelper
  58. { "Environment", null },
  59. // Testing InputTagHelper with File
  60. { "Input", null },
  61. // Test ability to generate nearly identical HTML with MVC tag and HTML helpers.
  62. // Only attribute order should differ.
  63. { "Order", "/HtmlGeneration_Order/Submit" },
  64. { "OrderUsingHtmlHelpers", "/HtmlGeneration_Order/Submit" },
  65. // Testing PartialTagHelper
  66. { "PartialTagHelperWithoutModel", null },
  67. { "Warehouse", null },
  68. // Testing InputTagHelpers invoked in the partial views
  69. { "ProductList", "/HtmlGeneration_Product" },
  70. { "ProductListUsingTagHelpers", "/HtmlGeneration_Product" },
  71. { "ProductListUsingTagHelpersWithNullModel", "/HtmlGeneration_Product" },
  72. };
  73. return data;
  74. }
  75. }
  76. [Fact]
  77. public async Task EnumValues_SerializeCorrectly()
  78. {
  79. // Arrange & Act
  80. var response = await Client.GetStringAsync("http://localhost/HtmlGeneration_Home/Enum");
  81. // Assert
  82. Assert.Equal($"Vrijdag{Environment.NewLine}Month: FirstOne", response, ignoreLineEndingDifferences: true);
  83. }
  84. [Theory(Skip = "https://github.com/dotnet/aspnetcore/issues/34599")]
  85. [MemberData(nameof(WebPagesData))]
  86. public async Task HtmlGenerationWebSite_GeneratesExpectedResults(string action, string antiforgeryPath)
  87. {
  88. // Arrange
  89. var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
  90. var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home." + action + ".html";
  91. var expectedContent =
  92. await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
  93. // Act
  94. // The host is not important as everything runs in memory and tests are isolated from each other.
  95. var response = await Client.GetAsync("http://localhost/HtmlGeneration_Home/" + action);
  96. var responseContent = await response.Content.ReadAsStringAsync();
  97. // Assert
  98. Assert.Equal(HttpStatusCode.OK, response.StatusCode);
  99. Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);
  100. responseContent = responseContent.Trim();
  101. if (antiforgeryPath == null)
  102. {
  103. ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
  104. Assert.Equal(expectedContent.Trim(), responseContent, ignoreLineEndingDifferences: true);
  105. }
  106. else
  107. {
  108. var forgeryToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseContent, antiforgeryPath);
  109. if (ResourceFile.GenerateBaselines)
  110. {
  111. // Reverse usual substitution and insert a format item into the new file content.
  112. responseContent = responseContent.Replace(forgeryToken, "{0}");
  113. ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
  114. }
  115. else
  116. {
  117. expectedContent = string.Format(CultureInfo.InvariantCulture, expectedContent, forgeryToken);
  118. Assert.Equal(expectedContent.Trim(), responseContent, ignoreLineEndingDifferences: true);
  119. }
  120. }
  121. }
  122. [Fact(Skip = "https://github.com/dotnet/aspnetcore/issues/34599")]
  123. public async Task HtmlGenerationWebSite_GeneratesExpectedResults_WithImageData()
  124. {
  125. await HtmlGenerationWebSite_GeneratesExpectedResults("Image", antiforgeryPath: null);
  126. }
  127. [Fact]
  128. public async Task HtmlGenerationWebSite_LinkGeneration_With21CompatibilityBehavior()
  129. {
  130. // Arrange
  131. var client = Factory
  132. .WithWebHostBuilder(builder => builder.UseStartup<HtmlGenerationWebSite.StartupWithoutEndpointRouting>())
  133. .CreateDefaultClient();
  134. var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
  135. var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home.Index21Compat.html";
  136. var expectedContent =
  137. await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
  138. // Act
  139. // The host is not important as everything runs in memory and tests are isolated from each other.
  140. var response = await client.GetAsync("http://localhost/HtmlGeneration_Home/");
  141. var responseContent = await response.Content.ReadAsStringAsync();
  142. // Assert
  143. Assert.Equal(HttpStatusCode.OK, response.StatusCode);
  144. Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);
  145. responseContent = responseContent.Trim();
  146. ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent);
  147. }
  148. public static TheoryData<string, string> EncodedPagesData
  149. {
  150. get
  151. {
  152. return new TheoryData<string, string>
  153. {
  154. { "AttributesWithBooleanValues", null },
  155. { "EditWarehouse", null },
  156. { "Index", null },
  157. { "Order", "/HtmlGeneration_Order/Submit" },
  158. { "OrderUsingHtmlHelpers", "/HtmlGeneration_Order/Submit" },
  159. { "Product", null },
  160. };
  161. }
  162. }
  163. [Theory]
  164. [MemberData(nameof(EncodedPagesData))]
  165. public async Task HtmlGenerationWebSite_GenerateEncodedResults(string action, string antiforgeryPath)
  166. {
  167. // Arrange
  168. var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
  169. var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home." + action + ".Encoded.html";
  170. var expectedContent =
  171. await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
  172. // Act
  173. // The host is not important as everything runs in memory and tests are isolated from each other.
  174. var response = await EncodedClient.GetAsync("http://localhost/HtmlGeneration_Home/" + action);
  175. var responseContent = await response.Content.ReadAsStringAsync();
  176. // Assert
  177. Assert.Equal(HttpStatusCode.OK, response.StatusCode);
  178. Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);
  179. responseContent = responseContent.Trim();
  180. if (antiforgeryPath == null)
  181. {
  182. ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent);
  183. }
  184. else
  185. {
  186. ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent, token: AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseContent, antiforgeryPath));
  187. }
  188. }
  189. [ConditionalTheory]
  190. [InlineData("Link", null)]
  191. [InlineData("Script", null)]
  192. [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/10423")]
  193. public Task HtmlGenerationWebSite_GenerateEncodedResultsNotReadyForHelix(string action, string antiforgeryPath)
  194. => HtmlGenerationWebSite_GenerateEncodedResults(action, antiforgeryPath);
  195. // Testing how ModelMetadata is handled as ViewDataDictionary instances are created.
  196. [Theory]
  197. [InlineData("AtViewModel")]
  198. [InlineData("NullViewModel")]
  199. [InlineData("ViewModel")]
  200. public async Task CheckViewData_GeneratesExpectedResults(string action)
  201. {
  202. // Arrange
  203. var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
  204. var outputFile = "compiler/resources/HtmlGenerationWebSite.CheckViewData." + action + ".html";
  205. var expectedContent =
  206. await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
  207. // Act
  208. var response = await Client.GetAsync("http://localhost/CheckViewData/" + action);
  209. var responseContent = await response.Content.ReadAsStringAsync();
  210. // Assert
  211. Assert.Equal(HttpStatusCode.OK, response.StatusCode);
  212. Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);
  213. responseContent = responseContent.Trim();
  214. ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent);
  215. }
  216. [Fact]
  217. public async Task ValidationTagHelpers_GeneratesExpectedSpansAndDivs()
  218. {
  219. // Arrange
  220. var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Customer.Index.html";
  221. var expectedContent =
  222. await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
  223. var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Customer/HtmlGeneration_Customer");
  224. var nameValueCollection = new List<KeyValuePair<string, string>>
  225. {
  226. new KeyValuePair<string,string>("Number", string.Empty),
  227. new KeyValuePair<string,string>("Name", string.Empty),
  228. new KeyValuePair<string,string>("Email", string.Empty),
  229. new KeyValuePair<string,string>("PhoneNumber", string.Empty),
  230. new KeyValuePair<string,string>("Password", string.Empty)
  231. };
  232. request.Content = new FormUrlEncodedContent(nameValueCollection);
  233. // Act
  234. var response = await Client.SendAsync(request);
  235. var responseContent = await response.Content.ReadAsStringAsync();
  236. // Assert
  237. Assert.Equal(HttpStatusCode.OK, response.StatusCode);
  238. responseContent = responseContent.Trim();
  239. ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent, token: AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseContent, "Customer/HtmlGeneration_Customer"));
  240. }
  241. [Fact]
  242. public async Task ClientValidators_AreGeneratedDuringInitialRender()
  243. {
  244. // Arrange
  245. var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Customer/HtmlGeneration_Customer/CustomerWithRecords");
  246. // Act
  247. var response = await Client.SendAsync(request);
  248. // Assert
  249. var document = await response.GetHtmlDocumentAsync();
  250. var numberInput = document.RequiredQuerySelector("input[id=Number]");
  251. Assert.Equal("true", numberInput.GetAttribute("data-val"));
  252. Assert.Equal("The field Number must be between 1 and 100.", numberInput.GetAttribute("data-val-range"));
  253. Assert.Equal("The Number field is required.", numberInput.GetAttribute("data-val-required"));
  254. var passwordInput = document.RequiredQuerySelector("input[id=Password]");
  255. Assert.Equal("true", passwordInput.GetAttribute("data-val"));
  256. Assert.Equal("The Password field is required.", passwordInput.GetAttribute("data-val-required"));
  257. var addressInput = document.RequiredQuerySelector("input[id=Address]");
  258. Assert.Equal("true", addressInput.GetAttribute("data-val"));
  259. Assert.Equal("The Address field is required.", addressInput.GetAttribute("data-val-required"));
  260. }
  261. [Fact]
  262. public async Task ValidationTagHelpers_UsingRecords()
  263. {
  264. // Arrange
  265. var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Customer/HtmlGeneration_Customer/CustomerWithRecords");
  266. var nameValueCollection = new List<KeyValuePair<string, string>>
  267. {
  268. new KeyValuePair<string,string>("Number", string.Empty),
  269. new KeyValuePair<string,string>("Name", string.Empty),
  270. new KeyValuePair<string,string>("Email", string.Empty),
  271. new KeyValuePair<string,string>("PhoneNumber", string.Empty),
  272. new KeyValuePair<string,string>("Password", string.Empty),
  273. new KeyValuePair<string,string>("Address", string.Empty),
  274. };
  275. request.Content = new FormUrlEncodedContent(nameValueCollection);
  276. // Act
  277. var response = await Client.SendAsync(request);
  278. // Assert
  279. var document = await response.GetHtmlDocumentAsync();
  280. var validation = document.RequiredQuerySelector("span[data-valmsg-for=Number]");
  281. Assert.Equal("The value '' is invalid.", validation.TextContent);
  282. validation = document.QuerySelector("span[data-valmsg-for=Name]");
  283. Assert.Null(validation);
  284. validation = document.QuerySelector("span[data-valmsg-for=Email]");
  285. Assert.Equal("field-validation-valid", validation.ClassName);
  286. validation = document.QuerySelector("span[data-valmsg-for=Password]");
  287. Assert.Equal("The Password field is required.", validation.TextContent);
  288. validation = document.QuerySelector("span[data-valmsg-for=Address]");
  289. Assert.Equal("The Address field is required.", validation.TextContent);
  290. }
  291. [Fact]
  292. public async Task CacheTagHelper_CanCachePortionsOfViewsPartialViewsAndViewComponents()
  293. {
  294. // Arrange
  295. var assertFile =
  296. "compiler/resources/CacheTagHelper_CanCachePortionsOfViewsPartialViewsAndViewComponents.Assert";
  297. var outputFile1 = assertFile + "1.txt";
  298. var expected1 =
  299. await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile1, sourceFile: false);
  300. var outputFile2 = assertFile + "2.txt";
  301. var expected2 =
  302. await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile2, sourceFile: false);
  303. var outputFile3 = assertFile + "3.txt";
  304. var expected3 =
  305. await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile3, sourceFile: false);
  306. // Act - 1
  307. // Verify that content gets cached based on vary-by-params
  308. var targetUrl = "/catalog?categoryId=1&correlationid=1";
  309. var request = RequestWithLocale(targetUrl, "North");
  310. var response1 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync();
  311. request = RequestWithLocale(targetUrl, "North");
  312. var response2 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync();
  313. // Assert - 1
  314. ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile1, expected1, response1.Trim());
  315. if (!ResourceFile.GenerateBaselines)
  316. {
  317. Assert.Equal(expected1, response2.Trim(), ignoreLineEndingDifferences: true);
  318. }
  319. // Act - 2
  320. // Verify content gets changed in partials when one of the vary by parameters is changed
  321. targetUrl = "/catalog?categoryId=3&correlationid=2";
  322. request = RequestWithLocale(targetUrl, "North");
  323. var response3 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync();
  324. request = RequestWithLocale(targetUrl, "North");
  325. var response4 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync();
  326. // Assert - 2
  327. ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile2, expected2, response3.Trim());
  328. if (!ResourceFile.GenerateBaselines)
  329. {
  330. Assert.Equal(expected2, response4.Trim(), ignoreLineEndingDifferences: true);
  331. }
  332. // Act - 3
  333. // Verify content gets changed in a View Component when the Vary-by-header parameters is changed
  334. targetUrl = "/catalog?categoryId=3&correlationid=3";
  335. request = RequestWithLocale(targetUrl, "East");
  336. var response5 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync();
  337. request = RequestWithLocale(targetUrl, "East");
  338. var response6 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync();
  339. // Assert - 3
  340. ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile3, expected3, response5.Trim());
  341. if (!ResourceFile.GenerateBaselines)
  342. {
  343. Assert.Equal(expected3, response6.Trim(), ignoreLineEndingDifferences: true);
  344. }
  345. }
  346. [Fact]
  347. public async Task CacheTagHelper_ExpiresContent_BasedOnExpiresParameter()
  348. {
  349. // Arrange & Act - 1
  350. var response1 = await Client.GetStringAsync("/catalog/2");
  351. // Assert - 1
  352. var expected1 = "Cached content for 2";
  353. Assert.Equal(expected1, response1.Trim());
  354. // Act - 2
  355. await Task.Delay(TimeSpan.FromSeconds(2));
  356. var response2 = await Client.GetStringAsync("/catalog/3");
  357. // Assert - 2
  358. var expected2 = "Cached content for 3";
  359. Assert.Equal(expected2, response2.Trim());
  360. }
  361. [Fact]
  362. public async Task CacheTagHelper_UsesVaryByCookie_ToVaryContent()
  363. {
  364. // Arrange & Act - 1
  365. var response1 = await Client.GetStringAsync("/catalog/cart?correlationid=1");
  366. // Assert - 1
  367. var expected1 = "Cart content for 1";
  368. Assert.Equal(expected1, response1.Trim());
  369. // Act - 2
  370. var request = new HttpRequestMessage(HttpMethod.Get, "/catalog/cart?correlationid=2");
  371. request.Headers.Add("Cookie", "CartId=10");
  372. var response2 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync();
  373. // Assert - 2
  374. var expected2 = "Cart content for 2";
  375. Assert.Equal(expected2, response2.Trim());
  376. // Act - 3
  377. // Resend the cookieless request and cached result from the first response.
  378. var response3 = await Client.GetStringAsync("/catalog/cart?correlationid=3");
  379. // Assert - 3
  380. Assert.Equal(expected1, response3.Trim());
  381. }
  382. [Fact]
  383. public async Task CacheTagHelper_VariesByRoute()
  384. {
  385. // Arrange & Act - 1
  386. var response1 = await Client.GetStringAsync(
  387. "/catalog/north-west/confirm-payment?confirmationId=1");
  388. // Assert - 1
  389. var expected1 = "Welcome Guest. Your confirmation id is 1. (Region north-west)";
  390. Assert.Equal(expected1, response1.Trim());
  391. // Act - 2
  392. var response2 = await Client.GetStringAsync(
  393. "/catalog/south-central/confirm-payment?confirmationId=2");
  394. // Assert - 2
  395. var expected2 = "Welcome Guest. Your confirmation id is 2. (Region south-central)";
  396. Assert.Equal(expected2, response2.Trim());
  397. // Act 3
  398. var response3 = await Client.GetStringAsync(
  399. "/catalog/north-west/Silver/confirm-payment?confirmationId=4");
  400. var expected3 = "Welcome Silver member. Your confirmation id is 4. (Region north-west)";
  401. Assert.Equal(expected3, response3.Trim());
  402. // Act 4
  403. var response4 = await Client.GetStringAsync(
  404. "/catalog/north-west/Gold/confirm-payment?confirmationId=5");
  405. var expected4 = "Welcome Gold member. Your confirmation id is 5. (Region north-west)";
  406. Assert.Equal(expected4, response4.Trim());
  407. // Act - 4
  408. // Resend the responses and expect cached results.
  409. response1 = await Client.GetStringAsync(
  410. "/catalog/north-west/confirm-payment?confirmationId=301");
  411. response2 = await Client.GetStringAsync(
  412. "/catalog/south-central/confirm-payment?confirmationId=402");
  413. response3 = await Client.GetStringAsync(
  414. "/catalog/north-west/Silver/confirm-payment?confirmationId=503");
  415. response4 = await Client.GetStringAsync(
  416. "/catalog/north-west/Gold/confirm-payment?confirmationId=608");
  417. // Assert - 4
  418. Assert.Equal(expected1, response1.Trim());
  419. Assert.Equal(expected2, response2.Trim());
  420. Assert.Equal(expected3, response3.Trim());
  421. Assert.Equal(expected4, response4.Trim());
  422. }
  423. [Fact]
  424. public async Task CacheTagHelper_VariesByUserId()
  425. {
  426. // Arrange & Act - 1
  427. var response1 = await Client.GetStringAsync("/catalog/past-purchases/test1?correlationid=1");
  428. var response2 = await Client.GetStringAsync("/catalog/past-purchases/test1?correlationid=2");
  429. // Assert - 1
  430. var expected1 = "Past purchases for user test1 (1)";
  431. Assert.Equal(expected1, response1.Trim());
  432. Assert.Equal(expected1, response2.Trim());
  433. // Act - 2
  434. var response3 = await Client.GetStringAsync("/catalog/past-purchases/test2?correlationid=3");
  435. var response4 = await Client.GetStringAsync("/catalog/past-purchases/test2?correlationid=4");
  436. // Assert - 2
  437. var expected2 = "Past purchases for user test2 (3)";
  438. Assert.Equal(expected2, response3.Trim());
  439. Assert.Equal(expected2, response4.Trim());
  440. }
  441. [Fact]
  442. [QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/36765")]
  443. public async Task CacheTagHelper_BubblesExpirationOfNestedTagHelpers()
  444. {
  445. // Arrange & Act - 1
  446. var response1 = await Client.GetStringAsync("/categories/Books?correlationId=1");
  447. // Assert - 1
  448. var expected1 =
  449. @"Category: Books
  450. Products: Book1, Book2 (1)";
  451. Assert.Equal(expected1, response1.Trim(), ignoreLineEndingDifferences: true);
  452. // Act - 2
  453. var response2 = await Client.GetStringAsync("/categories/Electronics?correlationId=2");
  454. // Assert - 2
  455. var expected2 =
  456. @"Category: Electronics
  457. Products: Book1, Book2 (1)";
  458. Assert.Equal(expected2, response2.Trim(), ignoreLineEndingDifferences: true);
  459. // Act - 3
  460. // Trigger an expiration of the nested content.
  461. var content = @"[{ ""productName"": ""Music Systems"" },{ ""productName"": ""Televisions"" }]";
  462. var requestMessage = new HttpRequestMessage(HttpMethod.Post, "/categories/Electronics");
  463. requestMessage.Content = new StringContent(content, Encoding.UTF8, "application/json");
  464. (await Client.SendAsync(requestMessage)).EnsureSuccessStatusCode();
  465. var response3 = await Client.GetStringAsync("/categories/Electronics?correlationId=3");
  466. // Assert - 3
  467. var expected3 =
  468. @"Category: Electronics
  469. Products: Music Systems, Televisions (3)";
  470. Assert.Equal(expected3, response3.Trim(), ignoreLineEndingDifferences: true);
  471. }
  472. [Fact]
  473. public async Task CacheTagHelper_DoesNotCacheIfDisabled()
  474. {
  475. // Arrange & Act
  476. var response1 = await Client.GetStringAsync("/catalog/GetDealPercentage/20?isEnabled=true");
  477. var response2 = await Client.GetStringAsync("/catalog/GetDealPercentage/40?isEnabled=true");
  478. var response3 = await Client.GetStringAsync("/catalog/GetDealPercentage/30?isEnabled=false");
  479. // Assert
  480. Assert.Equal("Deal percentage is 20", response1.Trim());
  481. Assert.Equal("Deal percentage is 20", response2.Trim());
  482. Assert.Equal("Deal percentage is 30", response3.Trim());
  483. }
  484. [Fact]
  485. public async Task EditorTemplateWithNoModel_RendersWithCorrectMetadata()
  486. {
  487. // Arrange
  488. var expected =
  489. "<label class=\"control-label col-md-2\" for=\"Name\">ItemName</label>" + Environment.NewLine +
  490. "<input id=\"Name\" name=\"Name\" type=\"text\" value=\"\" />" + Environment.NewLine + Environment.NewLine +
  491. "<label class=\"control-label col-md-2\" for=\"Id\">ItemNo</label>" + Environment.NewLine +
  492. "<input data-val=\"true\" data-val-required=\"The ItemNo field is required.\" id=\"Id\" name=\"Id\" type=\"text\" value=\"\" />" +
  493. Environment.NewLine + Environment.NewLine;
  494. // Act
  495. var response = await Client.GetStringAsync("http://localhost/HtmlGeneration_Home/ItemUsingSharedEditorTemplate");
  496. // Assert
  497. Assert.Equal(expected, response, ignoreLineEndingDifferences: true);
  498. }
  499. [Fact]
  500. public async Task EditorTemplateWithSpecificModel_RendersWithCorrectMetadata()
  501. {
  502. // Arrange
  503. var expected = "<label for=\"Description\">ItemDesc</label>" + Environment.NewLine +
  504. "<input id=\"Description\" name=\"Description\" type=\"text\" value=\"\" />" + Environment.NewLine + Environment.NewLine;
  505. // Act
  506. var response = await Client.GetStringAsync("http://localhost/HtmlGeneration_Home/ItemUsingModelSpecificEditorTemplate");
  507. // Assert
  508. Assert.Equal(expected, response, ignoreLineEndingDifferences: true);
  509. }
  510. // We want to make sure that for 'weird' model expressions involving:
  511. // - fields
  512. // - statics
  513. // - private
  514. //
  515. // These tests verify that we don't throw, and can evaluate the expression to get the model
  516. // value. One quirk of behavior for these cases is that we can't return a correct model metadata
  517. // instance (this is true for anything other than a public instance property). We're not overly
  518. // concerned with that, and so the accuracy of the model metadata is not verified by the test.
  519. [Theory]
  520. [InlineData("GetWeirdWithHtmlHelpers")]
  521. [InlineData("GetWeirdWithTagHelpers")]
  522. public async Task WeirdModelExpressions_CanAccessModelValues(string action)
  523. {
  524. // Arrange
  525. var url = "http://localhost/HtmlGeneration_WeirdExpressions/" + action;
  526. // Act
  527. var response = await Client.GetStringAsync(url);
  528. // Assert
  529. Assert.Contains("Hello, Field World!", response);
  530. Assert.Contains("Hello, Static World!", response);
  531. Assert.Contains("Hello, Private World!", response);
  532. }
  533. [Fact]
  534. public async Task PartialTagHelper_AllowsPassingModelValue()
  535. {
  536. // Arrange
  537. var url = "/HtmlGeneration_Home/StatusMessage";
  538. // Act
  539. var document = await Client.GetHtmlDocumentAsync(url);
  540. // Assert
  541. var banner = document.RequiredQuerySelector(".banner");
  542. Assert.Equal("Some status message", banner.TextContent);
  543. }
  544. [Fact]
  545. public async Task PartialTagHelper_AllowsPassingNullModelValue()
  546. {
  547. // Regression test for https://github.com/aspnet/Mvc/issues/7667.
  548. // Arrange
  549. var url = "/HtmlGeneration_Home/NullStatusMessage";
  550. // Act
  551. var document = await Client.GetHtmlDocumentAsync(url);
  552. // Assert
  553. var banner = document.RequiredQuerySelector(".banner");
  554. Assert.Empty(banner.TextContent);
  555. }
  556. [Fact]
  557. public async Task PartialTagHelper_AllowsUsingFallback()
  558. {
  559. // Arrange
  560. var url = "/Customer/PartialWithFallback";
  561. // Act
  562. var document = await Client.GetHtmlDocumentAsync(url);
  563. // Assert
  564. var content = document.RequiredQuerySelector("#content");
  565. Assert.Equal("Hello from fallback", content.TextContent);
  566. }
  567. [Fact]
  568. public async Task PartialTagHelper_AllowsUsingOptional()
  569. {
  570. // Arrange
  571. var url = "/Customer/PartialWithOptional";
  572. // Act
  573. var document = await Client.GetHtmlDocumentAsync(url);
  574. // Assert
  575. var content = document.RequiredQuerySelector("#content");
  576. Assert.Empty(content.TextContent);
  577. }
  578. [Fact]
  579. public async Task ValidationProviderAttribute_ValidationTagHelpers_GeneratesExpectedDataAttributes()
  580. {
  581. // Act
  582. var document = await Client.GetHtmlDocumentAsync("HtmlGeneration_Home/ValidationProviderAttribute");
  583. // Assert
  584. var firstName = document.RequiredQuerySelector("#FirstName");
  585. Assert.Equal("true", firstName.GetAttribute("data-val"));
  586. Assert.Equal("The FirstName field is required.", firstName.GetAttribute("data-val-required"));
  587. Assert.Equal("The field FirstName must be a string with a maximum length of 5.", firstName.GetAttribute("data-val-length"));
  588. Assert.Equal("5", firstName.GetAttribute("data-val-length-max"));
  589. Assert.Equal("The field FirstName must match the regular expression '[A-Za-z]*'.", firstName.GetAttribute("data-val-regex"));
  590. Assert.Equal("[A-Za-z]*", firstName.GetAttribute("data-val-regex-pattern"));
  591. var lastName = document.RequiredQuerySelector("#LastName");
  592. Assert.Equal("true", lastName.GetAttribute("data-val"));
  593. Assert.Equal("The LastName field is required.", lastName.GetAttribute("data-val-required"));
  594. Assert.Equal("The field LastName must be a string with a maximum length of 6.", lastName.GetAttribute("data-val-length"));
  595. Assert.Equal("6", lastName.GetAttribute("data-val-length-max"));
  596. Assert.False(lastName.HasAttribute("data-val-regex"));
  597. }
  598. [Fact]
  599. public async Task ValidationProviderAttribute_ValidationTagHelpers_GeneratesExpectedSpansAndDivsOnValidationError()
  600. {
  601. // Arrange
  602. var request = new HttpRequestMessage(HttpMethod.Post, "HtmlGeneration_Home/ValidationProviderAttribute");
  603. request.Content = new FormUrlEncodedContent(new Dictionary<string, string>
  604. {
  605. { "FirstName", "TestFirstName" },
  606. });
  607. // Act
  608. var response = await Client.SendAsync(request);
  609. // Assert
  610. await response.AssertStatusCodeAsync(HttpStatusCode.OK);
  611. var document = await response.GetHtmlDocumentAsync();
  612. Assert.Collection(
  613. document.QuerySelectorAll("div.validation-summary-errors ul li"),
  614. item => Assert.Equal("The field FirstName must be a string with a maximum length of 5.", item.TextContent),
  615. item => Assert.Equal("The LastName field is required.", item.TextContent));
  616. }
  617. private static HttpRequestMessage RequestWithLocale(string url, string locale)
  618. {
  619. var request = new HttpRequestMessage(HttpMethod.Get, url);
  620. request.Headers.Add("Locale", locale);
  621. return request;
  622. }
  623. }
  624. }