VberAdminWebTestBase.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. using Abp.AspNetCore.TestBase;
  2. using Abp.Extensions;
  3. using Abp.Json;
  4. using Abp.Web.Models;
  5. using AngleSharp.Html.Dom;
  6. using AngleSharp.Html.Parser;
  7. using Microsoft.AspNetCore.Hosting;
  8. using Newtonsoft.Json;
  9. using Newtonsoft.Json.Serialization;
  10. using Shouldly;
  11. using System.Net;
  12. using System.Net.Http.Headers;
  13. using System.Text;
  14. using VberAdmin.EntityFrameworkCore;
  15. using VberAdmin.Models.TokenAuth;
  16. using VberAdmin.Web.Startup;
  17. using VberZero.BaseSystem.MultiTenancy;
  18. using VberZero.BaseSystem.Users;
  19. namespace VberAdmin.Web.Tests;
  20. public abstract class VberAdminWebTestBase : AbpAspNetCoreIntegratedTestBase<Startup>
  21. {
  22. protected static readonly Lazy<string> ContentRootFolder;
  23. static VberAdminWebTestBase()
  24. {
  25. ContentRootFolder = new Lazy<string>(WebContentDirectoryFinder.CalculateContentRootFolder, true);
  26. }
  27. protected override IWebHostBuilder CreateWebHostBuilder()
  28. {
  29. return base
  30. .CreateWebHostBuilder()
  31. .UseContentRoot(ContentRootFolder.Value)
  32. .UseSetting(WebHostDefaults.ApplicationKey, typeof(VberAdminWebMvcModule).Assembly.FullName);
  33. }
  34. #region Get response
  35. protected async Task<T> GetResponseAsObjectAsync<T>(string url,
  36. HttpStatusCode expectedStatusCode = HttpStatusCode.OK)
  37. {
  38. var strResponse = await GetResponseAsStringAsync(url, expectedStatusCode);
  39. return JsonConvert.DeserializeObject<T>(strResponse, new JsonSerializerSettings
  40. {
  41. ContractResolver = new CamelCasePropertyNamesContractResolver()
  42. });
  43. }
  44. protected async Task<string> GetResponseAsStringAsync(string url,
  45. HttpStatusCode expectedStatusCode = HttpStatusCode.OK)
  46. {
  47. var response = await GetResponseAsync(url, expectedStatusCode);
  48. return await response.Content.ReadAsStringAsync();
  49. }
  50. protected async Task<HttpResponseMessage> GetResponseAsync(string url,
  51. HttpStatusCode expectedStatusCode = HttpStatusCode.OK)
  52. {
  53. var response = await Client.GetAsync(url);
  54. response.StatusCode.ShouldBe(expectedStatusCode);
  55. return response;
  56. }
  57. #endregion Get response
  58. #region Authenticate
  59. /// <summary>
  60. /// /api/TokenAuth/Authenticate
  61. /// TokenAuthController
  62. /// </summary>
  63. /// <param name="tenancyName"></param>
  64. /// <param name="input"></param>
  65. /// <returns></returns>
  66. protected async Task AuthenticateAsync(string tenancyName, AuthenticateModel input)
  67. {
  68. if (tenancyName.IsNullOrWhiteSpace())
  69. {
  70. var tenant = UsingDbContext(context => context.Tenants.FirstOrDefault(t => t.TenancyName == tenancyName));
  71. if (tenant != null)
  72. {
  73. AbpSession.TenantId = tenant.Id;
  74. Client.DefaultRequestHeaders.Add("Abp.TenantId", tenant.Id.ToString()); //Set TenantId
  75. }
  76. }
  77. var response = await Client.PostAsync("/api/TokenAuth/Authenticate",
  78. new StringContent(input.ToJsonString(), Encoding.UTF8, "application/json"));
  79. response.StatusCode.ShouldBe(HttpStatusCode.OK);
  80. var result =
  81. JsonConvert.DeserializeObject<AjaxResponse<AuthenticateResultModel>>(
  82. await response.Content.ReadAsStringAsync());
  83. Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result?.Result.AccessToken);
  84. AbpSession.UserId = result?.Result.UserId;
  85. }
  86. #endregion Authenticate
  87. #region Login
  88. protected void LoginAsHostAdmin()
  89. {
  90. LoginAsHost(User.AdminUserName);
  91. }
  92. protected void LoginAsDefaultTenantAdmin()
  93. {
  94. LoginAsTenant(Tenant.DefaultTenantName, User.AdminUserName);
  95. }
  96. protected void LoginAsHost(string userName)
  97. {
  98. AbpSession.TenantId = null;
  99. var user =
  100. UsingDbContext(
  101. context =>
  102. context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName));
  103. if (user == null)
  104. {
  105. throw new Exception("There is no user: " + userName + " for host.");
  106. }
  107. AbpSession.UserId = user.Id;
  108. }
  109. protected void LoginAsTenant(string tenancyName, string userName)
  110. {
  111. var tenant = UsingDbContext(context => context.Tenants.FirstOrDefault(t => t.TenancyName == tenancyName));
  112. if (tenant == null)
  113. {
  114. throw new Exception("There is no tenant: " + tenancyName);
  115. }
  116. AbpSession.TenantId = tenant.Id;
  117. var user =
  118. UsingDbContext(
  119. context =>
  120. context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName));
  121. if (user == null)
  122. {
  123. throw new Exception("There is no user: " + userName + " for tenant: " + tenancyName);
  124. }
  125. AbpSession.UserId = user.Id;
  126. }
  127. #endregion Login
  128. #region UsingDbContext
  129. protected void UsingDbContext(Action<VberAdminDbContext> action)
  130. {
  131. using (var context = IocManager.Resolve<VberAdminDbContext>())
  132. {
  133. action(context);
  134. context.SaveChanges();
  135. }
  136. }
  137. protected T UsingDbContext<T>(Func<VberAdminDbContext, T> func)
  138. {
  139. T result;
  140. using (var context = IocManager.Resolve<VberAdminDbContext>())
  141. {
  142. result = func(context);
  143. context.SaveChanges();
  144. }
  145. return result;
  146. }
  147. protected async Task UsingDbContextAsync(Func<VberAdminDbContext, Task> action)
  148. {
  149. using (var context = IocManager.Resolve<VberAdminDbContext>())
  150. {
  151. await action(context);
  152. await context.SaveChangesAsync(true);
  153. }
  154. }
  155. protected async Task<T> UsingDbContextAsync<T>(Func<VberAdminDbContext, Task<T>> func)
  156. {
  157. T result;
  158. using (var context = IocManager.Resolve<VberAdminDbContext>())
  159. {
  160. result = await func(context);
  161. await context.SaveChangesAsync(true);
  162. }
  163. return result;
  164. }
  165. #endregion UsingDbContext
  166. #region ParseHtml
  167. protected IHtmlDocument ParseHtml(string htmlString)
  168. {
  169. return new HtmlParser().ParseDocument(htmlString);
  170. }
  171. #endregion ParseHtml
  172. }