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.
 
 
 

68 rivejä
1.8 KiB

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