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.
 
 
 

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