-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostgresLampRepositoryTests.cs
More file actions
371 lines (315 loc) · 13.3 KB
/
PostgresLampRepositoryTests.cs
File metadata and controls
371 lines (315 loc) · 13.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using DotNet.Testcontainers.Builders;
using LampControlApi.Domain.Entities;
using LampControlApi.Domain.Repositories;
using LampControlApi.Infrastructure.Database;
using LampControlApi.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Testcontainers.PostgreSql;
namespace LampControlApi.Tests.Infrastructure
{
/// <summary>
/// Integration tests for PostgresLampRepository using Testcontainers.
/// </summary>
[TestClass]
public class PostgresLampRepositoryTests
{
private PostgreSqlContainer? postgres;
private LampControlDbContext? context;
private PostgresLampRepository? repository;
/// <summary>
/// Initializes the test by starting a PostgreSQL container and setting up the database context.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
[TestInitialize]
public async Task InitializeAsync()
{
this.postgres = new PostgreSqlBuilder()
.WithImage("postgres:16-alpine")
.WithDatabase("lampcontrol_test")
.WithUsername("test")
.WithPassword("test")
.WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(5432))
.Build();
await this.postgres.StartAsync();
var options = new DbContextOptionsBuilder<LampControlDbContext>()
.UseNpgsql(this.postgres.GetConnectionString())
.Options;
this.context = new LampControlDbContext(options);
// Apply actual schema from schema.sql file (including triggers)
var repositoryRoot = FindRepositoryRoot();
var schemaPath = Path.Combine(
repositoryRoot,
"database",
"sql",
"postgresql",
"schema.sql");
var schemaSql = await File.ReadAllTextAsync(schemaPath);
await this.context.Database.ExecuteSqlRawAsync(schemaSql);
this.repository = new PostgresLampRepository(
this.context,
NullLogger<PostgresLampRepository>.Instance);
}
/// <summary>
/// Cleanup test resources.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
[TestCleanup]
public async Task CleanupAsync()
{
if (this.context != null)
{
await this.context.DisposeAsync();
}
if (this.postgres != null)
{
await this.postgres.DisposeAsync();
}
}
/// <summary>
/// Test creating a lamp in PostgreSQL.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[TestMethod]
public async Task CreateAsync_ShouldPersistLamp()
{
// Arrange
var lamp = LampEntity.Create(status: true);
// Act
var created = await this.repository!.CreateAsync(lamp);
// Assert
Assert.IsNotNull(created);
Assert.AreEqual(lamp.Id, created.Id);
Assert.IsTrue(created.Status);
Assert.IsTrue(created.CreatedAt > DateTimeOffset.MinValue);
Assert.IsTrue(created.UpdatedAt > DateTimeOffset.MinValue);
// Verify persistence by retrieving
var retrieved = await this.repository.GetByIdAsync(created.Id);
Assert.IsNotNull(retrieved);
Assert.AreEqual(created.Id, retrieved.Id);
Assert.AreEqual(created.Status, retrieved.Status);
}
/// <summary>
/// Test getting all lamps from PostgreSQL.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[TestMethod]
public async Task GetAllAsync_ShouldReturnAllLamps()
{
// Arrange
var lamp1 = LampEntity.Create(status: true);
var lamp2 = LampEntity.Create(status: false);
await this.repository!.CreateAsync(lamp1);
await this.repository.CreateAsync(lamp2);
// Act
var allLamps = await this.repository.GetAllAsync();
// Assert
Assert.IsNotNull(allLamps);
Assert.AreEqual(2, allLamps.Count);
}
/// <summary>
/// Test getting a lamp by ID from PostgreSQL.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[TestMethod]
public async Task GetByIdAsync_ShouldReturnLamp_WhenExists()
{
// Arrange
var lamp = LampEntity.Create(status: true);
var created = await this.repository!.CreateAsync(lamp);
// Act
var retrieved = await this.repository.GetByIdAsync(created.Id);
// Assert
Assert.IsNotNull(retrieved);
Assert.AreEqual(created.Id, retrieved.Id);
Assert.AreEqual(created.Status, retrieved.Status);
}
/// <summary>
/// Test getting a non-existent lamp by ID from PostgreSQL.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[TestMethod]
public async Task GetByIdAsync_ShouldReturnNull_WhenNotExists()
{
// Arrange
var nonExistentId = Guid.NewGuid();
// Act
var retrieved = await this.repository!.GetByIdAsync(nonExistentId);
// Assert
Assert.IsNull(retrieved);
}
/// <summary>
/// Test updating a lamp in PostgreSQL.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[TestMethod]
public async Task UpdateAsync_ShouldModifyLamp()
{
// Arrange
var lamp = LampEntity.Create(status: false);
var created = await this.repository!.CreateAsync(lamp);
// Act
var updatedLamp = created.WithUpdatedStatus(newStatus: true);
var result = await this.repository.UpdateAsync(updatedLamp);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(created.Id, result.Id);
Assert.IsTrue(result.Status);
Assert.IsTrue(result.UpdatedAt > created.UpdatedAt);
// Verify persistence
var retrieved = await this.repository.GetByIdAsync(created.Id);
Assert.IsNotNull(retrieved);
Assert.IsTrue(retrieved.Status);
}
/// <summary>
/// Test updating a non-existent lamp in PostgreSQL.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[TestMethod]
public async Task UpdateAsync_ShouldReturnNull_WhenNotExists()
{
// Arrange
var nonExistentLamp = LampEntity.Create(status: true);
// Act
var result = await this.repository!.UpdateAsync(nonExistentLamp);
// Assert
Assert.IsNull(result);
}
/// <summary>
/// Test deleting a lamp from PostgreSQL (soft delete).
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[TestMethod]
public async Task DeleteAsync_ShouldSoftDeleteLamp()
{
// Arrange
var lamp = LampEntity.Create(status: true);
var created = await this.repository!.CreateAsync(lamp);
// Act
var deleted = await this.repository.DeleteAsync(created.Id);
// Assert
Assert.IsTrue(deleted);
// Verify soft delete - lamp should not be retrievable
var retrieved = await this.repository.GetByIdAsync(created.Id);
Assert.IsNull(retrieved);
}
/// <summary>
/// Test deleting a non-existent lamp from PostgreSQL.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[TestMethod]
public async Task DeleteAsync_ShouldReturnFalse_WhenNotExists()
{
// Arrange
var nonExistentId = Guid.NewGuid();
// Act
var deleted = await this.repository!.DeleteAsync(nonExistentId);
// Assert
Assert.IsFalse(deleted);
}
/// <summary>
/// Test that soft-deleted lamps are not returned by GetAllAsync.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[TestMethod]
public async Task GetAllAsync_ShouldNotReturnDeletedLamps()
{
// Arrange
var lamp1 = LampEntity.Create(status: true);
var lamp2 = LampEntity.Create(status: false);
var created1 = await this.repository!.CreateAsync(lamp1);
await this.repository.CreateAsync(lamp2);
// Delete one lamp
await this.repository.DeleteAsync(created1.Id);
// Act
var allLamps = await this.repository.GetAllAsync();
// Assert
Assert.IsNotNull(allLamps);
Assert.AreEqual(1, allLamps.Count);
}
/// <summary>
/// Test that ListAsync returns the correct page of lamps from PostgreSQL.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[TestMethod]
public async Task ListAsync_ShouldReturnPagedResults()
{
// Arrange - create 5 lamps
for (var i = 0; i < 5; i++)
{
await this.repository!.CreateAsync(LampEntity.Create(status: i % 2 == 0));
}
// Act
var page1 = await this.repository!.ListAsync(limit: 2, offset: 0);
var page2 = await this.repository.ListAsync(limit: 2, offset: 2);
var page3 = await this.repository.ListAsync(limit: 2, offset: 4);
// Assert
Assert.AreEqual(2, page1.Count);
Assert.AreEqual(2, page2.Count);
Assert.AreEqual(1, page3.Count);
}
/// <summary>
/// Test that ListAsync does not return soft-deleted lamps.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[TestMethod]
public async Task ListAsync_ShouldNotReturnDeletedLamps()
{
// Arrange
var lamp1 = await this.repository!.CreateAsync(LampEntity.Create(status: true));
await this.repository.CreateAsync(LampEntity.Create(status: false));
await this.repository.DeleteAsync(lamp1.Id);
// Act
var result = await this.repository.ListAsync(limit: 10, offset: 0);
// Assert
Assert.AreEqual(1, result.Count);
}
/// <summary>
/// Test that ListAsync returns lamps ordered by created_at then id.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[TestMethod]
public async Task ListAsync_ShouldReturnLampsOrderedByCreatedAt()
{
// Arrange
await this.repository!.CreateAsync(LampEntity.Create(status: true));
await this.repository.CreateAsync(LampEntity.Create(status: false));
await this.repository.CreateAsync(LampEntity.Create(status: true));
// Act
var result = await this.repository.ListAsync(limit: 3, offset: 0);
var list = result.ToList();
// Assert - should be oldest first
Assert.AreEqual(3, list.Count);
Assert.IsTrue(list[0].CreatedAt <= list[1].CreatedAt);
Assert.IsTrue(list[1].CreatedAt <= list[2].CreatedAt);
}
/// <summary>
/// Finds the repository root by searching upward for the .git directory.
/// This is more robust than using relative paths with multiple ".." operators.
/// </summary>
/// <returns>The absolute path to the repository root.</returns>
/// <exception cref="DirectoryNotFoundException">Thrown when the repository root cannot be found.</exception>
private static string FindRepositoryRoot()
{
var currentDirectory = new DirectoryInfo(Directory.GetCurrentDirectory());
while (currentDirectory != null)
{
// Check if .git exists in current directory (directory for normal repos, file for worktrees)
var gitPath = Path.Combine(currentDirectory.FullName, ".git");
if (Directory.Exists(gitPath) || File.Exists(gitPath))
{
return currentDirectory.FullName;
}
// Move up to parent directory
currentDirectory = currentDirectory.Parent;
}
throw new DirectoryNotFoundException(
"Could not find repository root. Ensure tests are run from within the repository.");
}
}
}