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.
 
 
 

82 rivejä
2.8 KiB

  1. using System;
  2. using System.Data;
  3. using System.Data.SqlClient;
  4. using Dapper;
  5. using DotNetCore.CAP.SqlServer.Diagnostics;
  6. using Microsoft.Extensions.Logging;
  7. using Microsoft.Extensions.Options;
  8. using Moq;
  9. namespace DotNetCore.CAP.SqlServer.Test
  10. {
  11. public abstract class DatabaseTestHost : IDisposable
  12. {
  13. protected ILogger<SqlServerStorage> Logger;
  14. protected IOptions<CapOptions> CapOptions;
  15. protected IOptions<SqlServerOptions> SqlSeverOptions;
  16. protected DiagnosticProcessorObserver DiagnosticProcessorObserver;
  17. public bool SqlObjectInstalled;
  18. protected DatabaseTestHost()
  19. {
  20. Logger = new Mock<ILogger<SqlServerStorage>>().Object;
  21. var capOptions = new Mock<IOptions<CapOptions>>();
  22. capOptions.Setup(x => x.Value).Returns(new CapOptions());
  23. CapOptions = capOptions.Object;
  24. var options = new Mock<IOptions<SqlServerOptions>>();
  25. options.Setup(x => x.Value).Returns(new SqlServerOptions { ConnectionString = ConnectionUtil.GetConnectionString() });
  26. SqlSeverOptions = options.Object;
  27. DiagnosticProcessorObserver = new DiagnosticProcessorObserver(new Mock<IDispatcher>().Object);
  28. InitializeDatabase();
  29. }
  30. public void Dispose()
  31. {
  32. DeleteAllData();
  33. }
  34. private void InitializeDatabase()
  35. {
  36. var masterConn = ConnectionUtil.GetMasterConnectionString();
  37. var databaseName = ConnectionUtil.GetDatabaseName();
  38. using (var connection = ConnectionUtil.CreateConnection(masterConn))
  39. {
  40. connection.Execute($@"
  41. IF NOT EXISTS (SELECT * FROM sysdatabases WHERE name = N'{databaseName}')
  42. CREATE DATABASE [{databaseName}];");
  43. }
  44. new SqlServerStorage(Logger, CapOptions, SqlSeverOptions, DiagnosticProcessorObserver).InitializeAsync().GetAwaiter().GetResult();
  45. SqlObjectInstalled = true;
  46. }
  47. private void DeleteAllData()
  48. {
  49. var conn = ConnectionUtil.GetConnectionString();
  50. using (var connection = new SqlConnection(conn))
  51. {
  52. var commands = new[] {
  53. "DISABLE TRIGGER ALL ON ?",
  54. "ALTER TABLE ? NOCHECK CONSTRAINT ALL",
  55. "DELETE FROM ?",
  56. "ALTER TABLE ? CHECK CONSTRAINT ALL",
  57. "ENABLE TRIGGER ALL ON ?"
  58. };
  59. foreach (var command in commands)
  60. {
  61. connection.Execute(
  62. "sp_MSforeachtable",
  63. new { command1 = command },
  64. commandType: CommandType.StoredProcedure);
  65. }
  66. }
  67. }
  68. }
  69. }