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.
 
 
 

67 lines
1.8 KiB

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