-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuerySchemaMetadataIntegrationTests.cs
More file actions
300 lines (248 loc) · 11.3 KB
/
QuerySchemaMetadataIntegrationTests.cs
File metadata and controls
300 lines (248 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
using JD.Efcpt.Build.Tasks;
using JD.Efcpt.Build.Tests.Infrastructure;
using Microsoft.Data.SqlClient;
using Testcontainers.MsSql;
using TinyBDD;
using TinyBDD.Xunit;
using Xunit;
using Xunit.Abstractions;
using Task = System.Threading.Tasks.Task;
namespace JD.Efcpt.Build.Tests.Integration;
[Feature("QuerySchemaMetadata task: queries real SQL Server database schema")]
[Collection(nameof(AssemblySetup))]
public sealed class QuerySchemaMetadataIntegrationTests(ITestOutputHelper output) : TinyBddXunitBase(output)
{
private sealed record TestContext(
MsSqlContainer Container,
string ConnectionString,
TestBuildEngine Engine,
string OutputDir) : IDisposable
{
public void Dispose()
{
Container.DisposeAsync().AsTask().Wait();
if (Directory.Exists(OutputDir))
Directory.Delete(OutputDir, true);
}
}
private sealed record TaskResult(
TestContext Context,
QuerySchemaMetadata Task,
bool Success);
[Scenario("Queries schema from real SQL Server and produces deterministic fingerprint")]
[Fact]
public async Task Queries_schema_and_produces_deterministic_fingerprint()
{
await Given("SQL Server with test schema", SetupDatabaseWithSchema)
.When("execute QuerySchemaMetadata task", ExecuteQuerySchemaMetadata)
.Then("task succeeds", r => r.Success)
.And("fingerprint is generated", r => !string.IsNullOrEmpty(r.Task.SchemaFingerprint))
.And("schema model file exists", r => File.Exists(Path.Combine(r.Context.OutputDir, "schema-model.json")))
.Finally(r => r.Context.Dispose())
.AssertPassed();
}
[Scenario("Identical schema produces identical fingerprint")]
[Fact]
public async Task Identical_schema_produces_identical_fingerprint()
{
await Given("SQL Server with test schema", SetupDatabaseWithSchema)
.When("execute task twice", ExecuteTaskTwice)
.Then("both tasks succeed", r => r.Item1.Success && r.Item2.Success)
.And("fingerprints are identical", r => r.Item1.Task.SchemaFingerprint == r.Item2.Task.SchemaFingerprint)
.Finally(r => r.Item1.Context.Dispose())
.AssertPassed();
}
[Scenario("Schema change produces different fingerprint")]
[Fact]
public async Task Schema_change_produces_different_fingerprint()
{
await Given("SQL Server with initial schema", SetupDatabaseWithSchema)
.When("execute task, modify schema, execute again", ExecuteTaskModifySchemaExecuteAgain)
.Then("both tasks succeed", r => r.Item1.Success && r.Item2.Success)
.And("fingerprints are different", r => r.Item1.Task.SchemaFingerprint != r.Item2.Task.SchemaFingerprint)
.Finally(r => r.Item1.Context.Dispose())
.AssertPassed();
}
[Scenario("Captures schema elements: tables, columns, indexes")]
[Fact]
public async Task Captures_complete_schema_elements()
{
await Given("SQL Server with comprehensive schema", SetupComprehensiveSchema)
.When("execute QuerySchemaMetadata task", ExecuteQuerySchemaMetadata)
.Then("task succeeds", r => r.Success)
.And("schema model contains expected tables", VerifySchemaModelContainsTables)
.Finally(r => r.Context.Dispose())
.AssertPassed();
}
[Scenario("Handles empty database gracefully")]
[Fact]
public async Task Handles_empty_database_gracefully()
{
await Given("SQL Server with empty database", SetupEmptyDatabase)
.When("execute QuerySchemaMetadata task", ExecuteQuerySchemaMetadata)
.Then("task succeeds", r => r.Success)
.And("fingerprint is generated for empty schema", r => !string.IsNullOrEmpty(r.Task.SchemaFingerprint))
.Finally(r => r.Context.Dispose())
.AssertPassed();
}
[Scenario("Fails gracefully with invalid connection string")]
[Fact]
public async Task Fails_gracefully_with_invalid_connection_string()
{
await Given("invalid connection string", SetupInvalidConnectionString)
.When("execute QuerySchemaMetadata task", ExecuteQuerySchemaMetadata)
.Then("task fails", r => !r.Success)
.And("error is logged", r => r.Context.Engine.Errors.Count > 0)
.Finally(r => r.Context.Dispose())
.AssertPassed();
}
// ========== Setup Methods ==========
private static async Task<TestContext> SetupDatabaseWithSchema()
{
var container = new MsSqlBuilder("mcr.microsoft.com/mssql/server:2022-latest")
.Build();
await container.StartAsync();
var connectionString = container.GetConnectionString();
await CreateTestSchema(connectionString);
var engine = new TestBuildEngine();
var outputDir = Path.Combine(Path.GetTempPath(), $"efcpt-test-{Guid.NewGuid()}");
Directory.CreateDirectory(outputDir);
return new TestContext(container, connectionString, engine, outputDir);
}
private static async Task<TestContext> SetupComprehensiveSchema()
{
var container = new MsSqlBuilder("mcr.microsoft.com/mssql/server:2022-latest")
.Build();
await container.StartAsync();
var connectionString = container.GetConnectionString();
await CreateComprehensiveSchema(connectionString);
var engine = new TestBuildEngine();
var outputDir = Path.Combine(Path.GetTempPath(), $"efcpt-test-{Guid.NewGuid()}");
Directory.CreateDirectory(outputDir);
return new TestContext(container, connectionString, engine, outputDir);
}
private static async Task<TestContext> SetupEmptyDatabase()
{
var container = new MsSqlBuilder("mcr.microsoft.com/mssql/server:2022-latest")
.Build();
await container.StartAsync();
var connectionString = container.GetConnectionString();
// Don't create any schema - leave database empty
var engine = new TestBuildEngine();
var outputDir = Path.Combine(Path.GetTempPath(), $"efcpt-test-{Guid.NewGuid()}");
Directory.CreateDirectory(outputDir);
return new TestContext(container, connectionString, engine, outputDir);
}
private static Task<TestContext> SetupInvalidConnectionString()
{
var container = new MsSqlBuilder("mcr.microsoft.com/mssql/server:2022-latest")
.Build();
// Don't start the container - connection will fail
var invalidConnectionString = "Server=invalid;Database=test;User Id=sa;Password=invalid;TrustServerCertificate=true";
var engine = new TestBuildEngine();
var outputDir = Path.Combine(Path.GetTempPath(), $"efcpt-test-{Guid.NewGuid()}");
Directory.CreateDirectory(outputDir);
return Task.FromResult(new TestContext(container, invalidConnectionString, engine, outputDir));
}
private static async Task CreateTestSchema(string connectionString)
{
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
await using var command = connection.CreateCommand();
command.CommandText = """
CREATE TABLE Users (
Id INT PRIMARY KEY IDENTITY(1,1),
Username NVARCHAR(100) NOT NULL,
Email NVARCHAR(255) NOT NULL,
CreatedAt DATETIME2 NOT NULL DEFAULT GETUTCDATE()
);
""";
await command.ExecuteNonQueryAsync();
}
private static async Task CreateComprehensiveSchema(string connectionString)
{
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
await using var command = connection.CreateCommand();
command.CommandText = """
-- Users table with primary key and unique index
CREATE TABLE Users (
Id INT PRIMARY KEY IDENTITY(1,1),
Username NVARCHAR(100) NOT NULL,
Email NVARCHAR(255) NOT NULL,
Age INT NULL,
CreatedAt DATETIME2 NOT NULL DEFAULT GETUTCDATE(),
CONSTRAINT UQ_Users_Username UNIQUE (Username),
CONSTRAINT CK_Users_Age CHECK (Age >= 18)
);
CREATE INDEX IX_Users_Email ON Users (Email);
-- Orders table with foreign key
CREATE TABLE Orders (
Id INT PRIMARY KEY IDENTITY(1,1),
UserId INT NOT NULL,
OrderDate DATETIME2 NOT NULL DEFAULT GETUTCDATE(),
TotalAmount DECIMAL(18,2) NOT NULL,
CONSTRAINT FK_Orders_Users FOREIGN KEY (UserId) REFERENCES Users(Id)
);
CREATE INDEX IX_Orders_UserId ON Orders (UserId);
CREATE INDEX IX_Orders_OrderDate ON Orders (OrderDate DESC);
-- Products table
CREATE TABLE Products (
Id INT PRIMARY KEY IDENTITY(1,1),
Name NVARCHAR(200) NOT NULL,
Description NVARCHAR(MAX) NULL,
Price DECIMAL(18,2) NOT NULL,
Stock INT NOT NULL DEFAULT 0
);
""";
await command.ExecuteNonQueryAsync();
}
private static async Task ModifySchema(string connectionString)
{
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
await using var command = connection.CreateCommand();
command.CommandText = "ALTER TABLE Users ADD LastLoginAt DATETIME2 NULL;";
await command.ExecuteNonQueryAsync();
}
// ========== Execute Methods ==========
private static TaskResult ExecuteQuerySchemaMetadata(TestContext context)
{
var task = new QuerySchemaMetadata
{
BuildEngine = context.Engine,
ConnectionString = context.ConnectionString,
OutputDir = context.OutputDir,
LogVerbosity = "minimal"
};
var success = task.Execute();
return new TaskResult(context, task, success);
}
private static Task<(TaskResult, TaskResult)> ExecuteTaskTwice(TestContext context)
{
var result1 = ExecuteQuerySchemaMetadata(context);
var result2 = ExecuteQuerySchemaMetadata(context);
return Task.FromResult((result1, result2));
}
private static async Task<(TaskResult, TaskResult)> ExecuteTaskModifySchemaExecuteAgain(TestContext context)
{
var result1 = ExecuteQuerySchemaMetadata(context);
// Modify the schema
await ModifySchema(context.ConnectionString);
var result2 = ExecuteQuerySchemaMetadata(context);
return (result1, result2);
}
// ========== Verification Methods ==========
private static bool VerifySchemaModelContainsTables(TaskResult result)
{
var schemaModelPath = Path.Combine(result.Context.OutputDir, "schema-model.json");
if (!File.Exists(schemaModelPath))
return false;
var json = File.ReadAllText(schemaModelPath);
// Verify the JSON contains expected table names
// Note: Foreign keys and check constraints not available via GetSchema
return json.Contains("Users") &&
json.Contains("Orders") &&
json.Contains("Products");
}
}