-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeliveryEstimateControllerIntegrationTests.cs
More file actions
351 lines (309 loc) · 13.9 KB
/
Copy pathDeliveryEstimateControllerIntegrationTests.cs
File metadata and controls
351 lines (309 loc) · 13.9 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ParcelTracking.Application.DTOs.EstimatedDelivery;
using ParcelTracking.Domain.Entities;
using ParcelTracking.Domain.Enums;
using ParcelTracking.Infrastructure.Data;
using Xunit;
namespace ParcelTracking.API.IntegrationTests
{
/// <summary>
/// Integration tests for the DeliveryEstimate Controller endpoints.
///
/// These tests require a PostgreSQL database. To run with Docker:
/// docker run -d --name parceltrack-test-db -e POSTGRES_USER=test -e POSTGRES_PASSWORD=test -e POSTGRES_DB=parceltracking_test -p 5433:5432 postgres:15
///
/// Then update the connection string in this test class to point to your database instance.
/// </summary>
public class DeliveryEstimateControllerIntegrationTests : IAsyncLifetime
{
private WebApplicationFactory<Program>? _factory;
private HttpClient? _client;
private string? _connectionString;
public async Task InitializeAsync()
{
// Use a connection string pointing to a running Postgres instance
// Set via environment variable or use default test database
_connectionString = Environment.GetEnvironmentVariable("PARCELTRACK_TEST_DB")
?? "Host=localhost;Port=5433;Database=parceltracking_test;Username=test;Password=test;Pooling=false;";
try
{
_factory = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
builder.ConfigureAppConfiguration((context, cfg) =>
{
var inMemConfig = new Dictionary<string, string?>
{
{"ConnectionStrings:DefaultConnection", _connectionString}
};
cfg.AddInMemoryCollection(inMemConfig);
});
});
_client = _factory.CreateClient();
// Ensure database is created and migrated
var options = new DbContextOptionsBuilder<ParcelTrackingDbContext>()
.UseNpgsql(_connectionString)
.Options;
using (var db = new ParcelTrackingDbContext(options))
{
db.Database.EnsureCreated();
}
}
catch (Exception)
{
// If Docker PostgreSQL is not available, silently skip these tests
_connectionString = null;
_factory?.Dispose();
_factory = null;
_client = null;
}
}
public async Task DisposeAsync()
{
_client?.Dispose();
_factory?.Dispose();
}
[Fact]
public async Task GetEstimate_WithValidParcelId_Returns200WithEstimate()
{
// Skip test if Docker database is not available
if (_client == null || _connectionString == null)
{
throw new SkipTestException("PostgreSQL database not available. Start Docker container with: docker run -d --name parceltrack-test-db -e POSTGRES_USER=test -e POSTGRES_PASSWORD=test -e POSTGRES_DB=parceltracking_test -p 5433:5432 postgres:15");
}
// Arrange: seed test data
var options = new DbContextOptionsBuilder<ParcelTrackingDbContext>()
.UseNpgsql(_connectionString)
.Options;
Guid parcelId;
using (var db = new ParcelTrackingDbContext(options))
{
// Clear existing data
db.TrackingEvents.RemoveRange(db.TrackingEvents);
db.Parcels.RemoveRange(db.Parcels);
db.Addresses.RemoveRange(db.Addresses);
await db.SaveChangesAsync();
var shipper = new Address
{
Id = Guid.NewGuid(),
CountryCode = "US",
City = "New York",
Street1 = "123 Main St"
};
var recipient = new Address
{
Id = Guid.NewGuid(),
CountryCode = "US",
City = "Los Angeles",
Street1 = "456 Oak Ave"
};
var parcel = new Parcel
{
Id = Guid.NewGuid(),
TrackingNumber = "TEST_ESTIMATE_001",
ShipperAddressId = shipper.Id,
RecipientAddressId = recipient.Id,
ServiceType = ServiceType.Standard,
Status = ParcelStatus.InTransit,
CreatedAt = DateTime.UtcNow.AddDays(-2),
Weight = 1.5m,
WeightUnit = WeightUnit.Kg,
Length = 30,
Width = 20,
Height = 10,
DimensionUnit = DimensionUnit.Cm,
DeclaredValue = 100.00m,
Currency = "USD"
};
db.Addresses.Add(shipper);
db.Addresses.Add(recipient);
db.Parcels.Add(parcel);
await db.SaveChangesAsync();
parcelId = parcel.Id;
}
// Act
var response = await _client.GetAsync($"/api/v1/DeliveryEstimate/{parcelId}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var estimate = await response.Content.ReadFromJsonAsync<EstimatedDeliveryDto>();
estimate.Should().NotBeNull();
estimate.ServiceType.Should().Be("Standard");
estimate.IsInternational.Should().BeFalse();
estimate.Confidence.Should().Be("Medium"); // InTransit status
estimate.EarliestDelivery.Should().BeAfter(DateOnly.FromDateTime(DateTime.UtcNow));
estimate.LatestDelivery.Should().BeOnOrAfter(estimate.EarliestDelivery);
}
[Fact]
public async Task GetEstimate_WithInvalidParcelId_Returns404()
{
// Skip test if Docker database is not available
if (_client == null || _connectionString == null)
{
throw new SkipTestException("PostgreSQL database not available. Start Docker container with: docker run -d --name parceltrack-test-db -e POSTGRES_USER=test -e POSTGRES_PASSWORD=test -e POSTGRES_DB=parceltracking_test -p 5433:5432 postgres:15");
}
// Act
var response = await _client.GetAsync($"/api/v1/DeliveryEstimate/{Guid.NewGuid()}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
var problemDetails = await response.Content.ReadFromJsonAsync<ProblemDetails>();
problemDetails.Should().NotBeNull();
problemDetails.Title.Should().Be("Parcel Not Found");
problemDetails.Status.Should().Be(404);
}
[Fact]
public async Task GetEstimate_WithDeliveredParcel_ReturnsActualDeliveryDate()
{
// Skip test if Docker database is not available
if (_client == null || _connectionString == null)
{
throw new SkipTestException("PostgreSQL database not available. Start Docker container with: docker run -d --name parceltrack-test-db -e POSTGRES_USER=test -e POSTGRES_PASSWORD=test -e POSTGRES_DB=parceltracking_test -p 5433:5432 postgres:15");
}
// Arrange: seed test data
var options = new DbContextOptionsBuilder<ParcelTrackingDbContext>()
.UseNpgsql(_connectionString)
.Options;
Guid parcelId;
var actualDeliveryDate = new DateTimeOffset(2023, 12, 15, 14, 30, 0, TimeSpan.Zero);
using (var db = new ParcelTrackingDbContext(options))
{
// Clear existing data
db.TrackingEvents.RemoveRange(db.TrackingEvents);
db.Parcels.RemoveRange(db.Parcels);
db.Addresses.RemoveRange(db.Addresses);
await db.SaveChangesAsync();
var shipper = new Address
{
Id = Guid.NewGuid(),
CountryCode = "US",
City = "New York",
Street1 = "123 Main St"
};
var recipient = new Address
{
Id = Guid.NewGuid(),
CountryCode = "CA",
City = "Toronto",
Street1 = "456 Oak Ave"
};
var parcel = new Parcel
{
Id = Guid.NewGuid(),
TrackingNumber = "TEST_DELIVERED_001",
ShipperAddressId = shipper.Id,
RecipientAddressId = recipient.Id,
ServiceType = ServiceType.Express,
Status = ParcelStatus.Delivered,
ActualDeliveryDate = actualDeliveryDate,
CreatedAt = DateTime.UtcNow.AddDays(-5),
Weight = 2.0m,
WeightUnit = WeightUnit.Kg,
Length = 40,
Width = 30,
Height = 20,
DimensionUnit = DimensionUnit.Cm,
DeclaredValue = 200.00m,
Currency = "USD"
};
db.Addresses.Add(shipper);
db.Addresses.Add(recipient);
db.Parcels.Add(parcel);
await db.SaveChangesAsync();
parcelId = parcel.Id;
}
// Act
var response = await _client.GetAsync($"/api/v1/DeliveryEstimate/{parcelId}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var estimate = await response.Content.ReadFromJsonAsync<EstimatedDeliveryDto>();
estimate.Should().NotBeNull();
estimate.EarliestDelivery.Should().Be(DateOnly.FromDateTime(actualDeliveryDate.DateTime));
estimate.LatestDelivery.Should().Be(DateOnly.FromDateTime(actualDeliveryDate.DateTime));
estimate.Confidence.Should().Be("High");
estimate.ServiceType.Should().Be("Express");
estimate.IsInternational.Should().BeTrue(); // US to CA
}
[Fact]
public async Task GetEstimate_WithInternationalParcel_ReturnsCorrectEstimate()
{
// Skip test if Docker database is not available
if (_client == null || _connectionString == null)
{
throw new SkipTestException("PostgreSQL database not available. Start Docker container with: docker run -d --name parceltrack-test-db -e POSTGRES_USER=test -e POSTGRES_PASSWORD=test -e POSTGRES_DB=parceltracking_test -p 5433:5432 postgres:15");
}
// Arrange: seed test data
var options = new DbContextOptionsBuilder<ParcelTrackingDbContext>()
.UseNpgsql(_connectionString)
.Options;
Guid parcelId;
using (var db = new ParcelTrackingDbContext(options))
{
// Clear existing data
db.TrackingEvents.RemoveRange(db.TrackingEvents);
db.Parcels.RemoveRange(db.Parcels);
db.Addresses.RemoveRange(db.Addresses);
await db.SaveChangesAsync();
var shipper = new Address
{
Id = Guid.NewGuid(),
CountryCode = "US",
City = "New York",
Street1 = "123 Main St"
};
var recipient = new Address
{
Id = Guid.NewGuid(),
CountryCode = "GB",
City = "London",
Street1 = "456 Oak Ave"
};
var parcel = new Parcel
{
Id = Guid.NewGuid(),
TrackingNumber = "TEST_INTL_001",
ShipperAddressId = shipper.Id,
RecipientAddressId = recipient.Id,
ServiceType = ServiceType.Overnight,
Status = ParcelStatus.LabelCreated,
CreatedAt = DateTime.UtcNow,
Weight = 0.5m,
WeightUnit = WeightUnit.Kg,
Length = 25,
Width = 15,
Height = 5,
DimensionUnit = DimensionUnit.Cm,
DeclaredValue = 50.00m,
Currency = "USD"
};
db.Addresses.Add(shipper);
db.Addresses.Add(recipient);
db.Parcels.Add(parcel);
await db.SaveChangesAsync();
parcelId = parcel.Id;
}
// Act
var response = await _client.GetAsync($"/api/v1/DeliveryEstimate/{parcelId}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var estimate = await response.Content.ReadFromJsonAsync<EstimatedDeliveryDto>();
estimate.Should().NotBeNull();
estimate.ServiceType.Should().Be("Overnight");
estimate.IsInternational.Should().BeTrue(); // US to GB
estimate.Confidence.Should().Be("Low"); // LabelCreated status
estimate.EarliestDelivery.Should().BeAfter(DateOnly.FromDateTime(DateTime.UtcNow));
estimate.LatestDelivery.Should().BeOnOrAfter(estimate.EarliestDelivery);
}
}
}