You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

65 regels
1.8 KiB

  1. using System.Threading;
  2. using Dapper;
  3. namespace DotNetCore.CAP.MySql.Test
  4. {
  5. public abstract class DatabaseTestHost : TestHost
  6. {
  7. private static bool _sqlObjectInstalled;
  8. public static object _lock = new object();
  9. protected override void PostBuildServices()
  10. {
  11. base.PostBuildServices();
  12. lock (_lock)
  13. {
  14. if (!_sqlObjectInstalled)
  15. {
  16. InitializeDatabase();
  17. }
  18. }
  19. }
  20. public override void Dispose()
  21. {
  22. DeleteAllData();
  23. base.Dispose();
  24. }
  25. private void InitializeDatabase()
  26. {
  27. using (CreateScope())
  28. {
  29. var storage = GetService<MySqlStorage>();
  30. var token = new CancellationTokenSource().Token;
  31. CreateDatabase();
  32. storage.InitializeAsync(token).GetAwaiter().GetResult();
  33. _sqlObjectInstalled = true;
  34. }
  35. }
  36. private void CreateDatabase()
  37. {
  38. var masterConn = ConnectionUtil.GetMasterConnectionString();
  39. var databaseName = ConnectionUtil.GetDatabaseName();
  40. using (var connection = ConnectionUtil.CreateConnection(masterConn))
  41. {
  42. connection.Execute($@"
  43. DROP DATABASE IF EXISTS `{databaseName}`;
  44. CREATE DATABASE `{databaseName}`;");
  45. }
  46. }
  47. private void DeleteAllData()
  48. {
  49. var conn = ConnectionUtil.GetConnectionString();
  50. using (var connection = ConnectionUtil.CreateConnection(conn))
  51. {
  52. connection.Execute($@"
  53. TRUNCATE TABLE `cap.published`;
  54. TRUNCATE TABLE `cap.received`;");
  55. }
  56. }
  57. }
  58. }