WePlatformTestBase.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Common;
  4. using System.Data.Entity;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using Abp;
  8. using Abp.Configuration.Startup;
  9. using Abp.Domain.Uow;
  10. using Abp.Runtime.Session;
  11. using Abp.TestBase;
  12. using WePlatform.Authorization.Users;
  13. using WePlatform.MultiTenancy;
  14. using Castle.MicroKernel.Registration;
  15. using Effort;
  16. using EntityFramework.DynamicFilters;
  17. using WePlatform.EF;
  18. using WePlatform.SeedData;
  19. using IwbZero.Authorization.Base.Users;
  20. using IwbZero.MultiTenancy;
  21. namespace WePlatform
  22. {
  23. public abstract class WePlatformTestBase : AbpIntegratedTestBase<WePlatformTestModule>
  24. {
  25. private DbConnection _hostDb;
  26. private Dictionary<int, DbConnection> _tenantDbs; //only used for db per tenant architecture
  27. protected WePlatformTestBase()
  28. {
  29. //Seed initial data for host
  30. //AbpSession.TenantId = null;
  31. //UsingDbContext(context =>
  32. //{
  33. // new InitialDbBuilder(context).Create();
  34. //});
  35. ////Seed initial data for default tenant
  36. //AbpSession.TenantId = 1;
  37. //UsingDbContext(context =>
  38. //{
  39. // new RoleAndUserCreator(context).Create();
  40. //});
  41. //UsingDbContext(context =>
  42. //{
  43. // new TestDataBuilder(context).Create();
  44. //});
  45. LoginAsDefaultTenantAdmin();
  46. }
  47. protected override void PreInitialize()
  48. {
  49. base.PreInitialize();
  50. /* You can switch database architecture here: */
  51. UseSingleDatabase();
  52. //UseDatabasePerTenant();
  53. }
  54. /* Uses single database for host and all tenants.
  55. */
  56. private void UseSingleDatabase()
  57. {
  58. _hostDb = DbConnectionFactory.CreateTransient();
  59. LocalIocManager.IocContainer.Register(
  60. Component.For<DbConnection>()
  61. .UsingFactoryMethod(() => _hostDb)
  62. .LifestyleSingleton()
  63. );
  64. }
  65. /* Uses single database for host and Default tenant,
  66. * but dedicated databases for all other tenants.
  67. */
  68. private void UseDatabasePerTenant()
  69. {
  70. _hostDb = DbConnectionFactory.CreateTransient();
  71. _tenantDbs = new Dictionary<int, DbConnection>();
  72. LocalIocManager.IocContainer.Register(
  73. Component.For<DbConnection>()
  74. .UsingFactoryMethod((kernel) =>
  75. {
  76. lock (_tenantDbs)
  77. {
  78. var currentUow = kernel.Resolve<ICurrentUnitOfWorkProvider>().Current;
  79. var abpSession = kernel.Resolve<IAbpSession>();
  80. var tenantId = currentUow != null ? currentUow.GetTenantId() : abpSession.TenantId;
  81. if (tenantId == null || tenantId == 1) //host and default tenant are stored in host db
  82. {
  83. return _hostDb;
  84. }
  85. if (!_tenantDbs.ContainsKey(tenantId.Value))
  86. {
  87. _tenantDbs[tenantId.Value] = DbConnectionFactory.CreateTransient();
  88. }
  89. return _tenantDbs[tenantId.Value];
  90. }
  91. }, true)
  92. .LifestyleTransient()
  93. );
  94. }
  95. #region UsingDbContext
  96. protected IDisposable UsingTenantId(int? tenantId)
  97. {
  98. var previousTenantId = AbpSession.TenantId;
  99. AbpSession.TenantId = tenantId;
  100. return new DisposeAction(() => AbpSession.TenantId = previousTenantId);
  101. }
  102. protected void UsingDbContext(Action<WePlatformDbContext> action)
  103. {
  104. UsingDbContext(AbpSession.TenantId, action);
  105. }
  106. protected Task UsingDbContextAsync(Func<WePlatformDbContext, Task> action)
  107. {
  108. return UsingDbContextAsync(AbpSession.TenantId, action);
  109. }
  110. protected T UsingDbContext<T>(Func<WePlatformDbContext, T> func)
  111. {
  112. return UsingDbContext(AbpSession.TenantId, func);
  113. }
  114. protected Task<T> UsingDbContextAsync<T>(Func<WePlatformDbContext, Task<T>> func)
  115. {
  116. return UsingDbContextAsync(AbpSession.TenantId, func);
  117. }
  118. protected void UsingDbContext(int? tenantId, Action<WePlatformDbContext> action)
  119. {
  120. using (UsingTenantId(tenantId))
  121. {
  122. using (var context = LocalIocManager.Resolve<WePlatformDbContext>())
  123. {
  124. context.DisableAllFilters();
  125. action(context);
  126. context.SaveChanges();
  127. }
  128. }
  129. }
  130. protected async Task UsingDbContextAsync(int? tenantId, Func<WePlatformDbContext, Task> action)
  131. {
  132. using (UsingTenantId(tenantId))
  133. {
  134. using (var context = LocalIocManager.Resolve<WePlatformDbContext>())
  135. {
  136. context.DisableAllFilters();
  137. await action(context);
  138. await context.SaveChangesAsync();
  139. }
  140. }
  141. }
  142. protected T UsingDbContext<T>(int? tenantId, Func<WePlatformDbContext, T> func)
  143. {
  144. T result;
  145. using (UsingTenantId(tenantId))
  146. {
  147. using (var context = LocalIocManager.Resolve<WePlatformDbContext>())
  148. {
  149. context.DisableAllFilters();
  150. result = func(context);
  151. context.SaveChanges();
  152. }
  153. }
  154. return result;
  155. }
  156. protected async Task<T> UsingDbContextAsync<T>(int? tenantId, Func<WePlatformDbContext, Task<T>> func)
  157. {
  158. T result;
  159. using (UsingTenantId(tenantId))
  160. {
  161. using (var context = LocalIocManager.Resolve<WePlatformDbContext>())
  162. {
  163. context.DisableAllFilters();
  164. result = await func(context);
  165. await context.SaveChangesAsync();
  166. }
  167. }
  168. return result;
  169. }
  170. #endregion
  171. #region Login
  172. protected void LoginAsHostAdmin()
  173. {
  174. LoginAsHost(UserBase.AdminUserName);
  175. }
  176. protected void LoginAsDefaultTenantAdmin()
  177. {
  178. LoginAsTenant(TenantBase.DefaultTenantName, UserBase.AdminUserName);
  179. }
  180. protected void LogoutAsDefaultTenant()
  181. {
  182. LogoutAsTenant(TenantBase.DefaultTenantName);
  183. }
  184. protected void LoginAsHost(string userName)
  185. {
  186. AbpSession.TenantId = null;
  187. var user =
  188. UsingDbContext(
  189. context =>
  190. context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName));
  191. if (user == null)
  192. {
  193. throw new Exception("There is no user: " + userName + " for host.");
  194. }
  195. AbpSession.UserId = user.Id;
  196. }
  197. protected void LogoutAsHost()
  198. {
  199. Resolve<IMultiTenancyConfig>().IsEnabled = true;
  200. AbpSession.TenantId = null;
  201. AbpSession.UserId = null;
  202. }
  203. protected void LoginAsTenant(string tenancyName, string userName)
  204. {
  205. var tenant = UsingDbContext(context => context.Tenants.FirstOrDefault(t => t.TenancyName == tenancyName));
  206. if (tenant == null)
  207. {
  208. throw new Exception("There is no tenant: " + tenancyName);
  209. }
  210. AbpSession.TenantId = tenant.Id;
  211. var user =
  212. UsingDbContext(
  213. context =>
  214. context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName));
  215. if (user == null)
  216. {
  217. throw new Exception("There is no user: " + userName + " for tenant: " + tenancyName);
  218. }
  219. AbpSession.UserId = user.Id;
  220. }
  221. protected void LogoutAsTenant(string tenancyName)
  222. {
  223. var tenant = UsingDbContext(context => context.Tenants.FirstOrDefault(t => t.TenancyName == tenancyName));
  224. if (tenant == null)
  225. {
  226. throw new Exception("There is no tenant: " + tenancyName);
  227. }
  228. AbpSession.TenantId = tenant.Id;
  229. AbpSession.UserId = null;
  230. }
  231. #endregion
  232. /// <summary>
  233. /// Gets current user if <see cref="IAbpSession.UserId"/> is not null.
  234. /// Throws exception if it's null.
  235. /// </summary>
  236. protected async Task<User> GetCurrentUserAsync()
  237. {
  238. var userId = AbpSession.GetUserId();
  239. return await UsingDbContext(context => context.Users.SingleAsync(u => u.Id == userId));
  240. }
  241. /// <summary>
  242. /// Gets current tenant if <see cref="IAbpSession.TenantId"/> is not null.
  243. /// Throws exception if there is no current tenant.
  244. /// </summary>
  245. protected async Task<Tenant> GetCurrentTenantAsync()
  246. {
  247. var tenantId = AbpSession.GetTenantId();
  248. return await UsingDbContext(context => context.Tenants.SingleAsync(t => t.Id == tenantId));
  249. }
  250. }
  251. }