ImageServerWebTestBase.cs 6.9 KB

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