This repository was archived by the owner on Jul 28, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFileExtractFunctionTests.cs
More file actions
312 lines (274 loc) · 13.1 KB
/
FileExtractFunctionTests.cs
File metadata and controls
312 lines (274 loc) · 13.1 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
using Google.Protobuf.WellKnownTypes;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Moq;
using NHS.MESH.Client.Contracts.Services;
using NHS.MESH.Client.Models;
using ServiceLayer.Data;
using ServiceLayer.Data.Models;
using ServiceLayer.Mesh.Configuration;
using ServiceLayer.Mesh.Functions;
using ServiceLayer.Mesh.Messaging;
using ServiceLayer.Mesh.Storage;
namespace ServiceLayer.Mesh.Tests.Functions;
public class FileExtractFunctionTests
{
private readonly Mock<ILogger<FileExtractFunction>> _loggerMock;
private readonly Mock<IMeshInboxService> _meshInboxServiceMock;
private readonly Mock<IFileTransformQueueClient> _fileTransformQueueClientMock;
private readonly Mock<IFileExtractQueueClient> _fileExtractQueueClientMock;
private readonly Mock<IMeshFilesBlobStore> _blobStoreMock;
private readonly ServiceLayerDbContext _dbContext;
private readonly FileExtractFunction _function;
public FileExtractFunctionTests()
{
_loggerMock = new Mock<ILogger<FileExtractFunction>>();
_meshInboxServiceMock = new Mock<IMeshInboxService>();
_fileExtractQueueClientMock = new Mock<IFileExtractQueueClient>();
_fileTransformQueueClientMock = new Mock<IFileTransformQueueClient>();
_blobStoreMock = new Mock<IMeshFilesBlobStore>();
var options = new DbContextOptionsBuilder<ServiceLayerDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.ConfigureWarnings(warnings =>
warnings.Ignore(Microsoft.EntityFrameworkCore.Diagnostics.InMemoryEventId.TransactionIgnoredWarning))
.Options;
_dbContext = new ServiceLayerDbContext(options);
var functionConfiguration = new Mock<IFileExtractFunctionConfiguration>();
functionConfiguration.Setup(c => c.NbssMeshMailboxId).Returns("test-mailbox");
_function = new FileExtractFunction(
_loggerMock.Object,
functionConfiguration.Object,
_meshInboxServiceMock.Object,
_dbContext,
_fileTransformQueueClientMock.Object,
_fileExtractQueueClientMock.Object,
_blobStoreMock.Object
);
}
[Fact]
public async Task Run_FileNotFound_ExitsSilently()
{
// Arrange
var message = new FileExtractQueueMessage { FileId = "nonexistent-file" };
// Act
await _function.Run(message);
// Assert
_loggerMock.Verify(
x => x.Log(
LogLevel.Warning,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString() == $"File with id: {message.FileId} not found in MeshFiles table."),
null,
It.IsAny<Func<It.IsAnyType, Exception?, string>>()
), Times.Once);
Assert.Equal(0, _dbContext.MeshFiles.Count());
_meshInboxServiceMock.Verify(x => x.GetHeadMessageByIdAsync(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
_blobStoreMock.Verify(x => x.UploadAsync(It.IsAny<MeshFile>(), It.IsAny<byte[]>()), Times.Never);
_fileTransformQueueClientMock.Verify(x => x.EnqueueFileTransformAsync(It.IsAny<MeshFile>()), Times.Never);
_fileTransformQueueClientMock.Verify(x => x.SendToPoisonQueueAsync(It.IsAny<FileTransformQueueMessage>()), Times.Never);
}
[Fact]
public async Task Run_FileStatusInvalid_ExitsSilently()
{
// Arrange
var file = new MeshFile
{
FileType = MeshFileType.NbssAppointmentEvents,
MailboxId = "test-mailbox",
FileId = "file-1",
Status = MeshFileStatus.Transforming, // Not eligible
LastUpdatedUtc = DateTime.UtcNow
};
_dbContext.MeshFiles.Add(file);
await _dbContext.SaveChangesAsync();
var message = new FileExtractQueueMessage { FileId = "file-1" };
// Act
await _function.Run(message);
// Assert
_loggerMock.Verify(
x => x.Log(
LogLevel.Warning,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString() == $"File with id: {message.FileId} found in MeshFiles table but is not suitable for extraction. Status: {file.Status}, LastUpdatedUtc: {file.LastUpdatedUtc.ToTimestamp()}."),
null,
It.IsAny<Func<It.IsAnyType, Exception?, string>>()
), Times.Once);
_meshInboxServiceMock.Verify(x => x.GetHeadMessageByIdAsync(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
_blobStoreMock.Verify(x => x.UploadAsync(It.IsAny<MeshFile>(), It.IsAny<byte[]>()), Times.Never);
_fileTransformQueueClientMock.Verify(x => x.EnqueueFileTransformAsync(It.IsAny<MeshFile>()), Times.Never);
_fileTransformQueueClientMock.Verify(x => x.SendToPoisonQueueAsync(It.IsAny<FileTransformQueueMessage>()), Times.Never);
}
[Fact]
public async Task Run_FileStatusExtractingButNotTimedOut_ExitsSilently()
{
// Arrange
var file = new MeshFile
{
FileType = MeshFileType.NbssAppointmentEvents,
MailboxId = "test-mailbox",
FileId = "file-2",
Status = MeshFileStatus.Extracting,
LastUpdatedUtc = DateTime.UtcNow // Not timed out
};
_dbContext.MeshFiles.Add(file);
await _dbContext.SaveChangesAsync();
var message = new FileExtractQueueMessage { FileId = "file-2" };
// Act
await _function.Run(message);
// Assert
_loggerMock.Verify(
x => x.Log(
LogLevel.Warning,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString() == $"File with id: {message.FileId} found in MeshFiles table but is not suitable for extraction. Status: {file.Status}, LastUpdatedUtc: {file.LastUpdatedUtc.ToTimestamp()}."),
null,
It.IsAny<Func<It.IsAnyType, Exception?, string>>()
), Times.Once);
_meshInboxServiceMock.Verify(x => x.GetHeadMessageByIdAsync(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
_blobStoreMock.Verify(x => x.UploadAsync(It.IsAny<MeshFile>(), It.IsAny<byte[]>()), Times.Never);
_fileTransformQueueClientMock.Verify(x => x.EnqueueFileTransformAsync(It.IsAny<MeshFile>()), Times.Never);
_fileTransformQueueClientMock.Verify(x => x.SendToPoisonQueueAsync(It.IsAny<FileTransformQueueMessage>()), Times.Never);
}
[Fact]
public async Task Run_FileValid_FileUploadedToBlobAndAcknowledgedAndEnqueued()
{
// Arrange
var originalLastUpdatedUtc = DateTime.UtcNow.AddHours(-1);
var file = new MeshFile
{
FileType = MeshFileType.NbssAppointmentEvents,
MailboxId = "test-mailbox",
FileId = "file-3",
Status = MeshFileStatus.Discovered,
LastUpdatedUtc = originalLastUpdatedUtc
};
_dbContext.MeshFiles.Add(file);
await _dbContext.SaveChangesAsync();
var content = new byte[] { 1, 2, 3 };
const string blobPath = "directory/fileName";
_meshInboxServiceMock.Setup(s => s.GetMessageByIdAsync(file.MailboxId, file.FileId))
.ReturnsAsync(new MeshResponse<GetMessageResponse>
{
IsSuccessful = true,
Response = new GetMessageResponse
{
FileAttachment = new FileAttachment { Content = content }
}
});
_blobStoreMock.Setup(s => s.UploadAsync(file, content)).ReturnsAsync(blobPath);
_meshInboxServiceMock.Setup(s => s.AcknowledgeMessageByIdAsync(file.MailboxId, file.FileId))
.ReturnsAsync(new MeshResponse<AcknowledgeMessageResponse>
{
IsSuccessful = true
});
var message = new FileExtractQueueMessage { FileId = file.FileId };
// Act
await _function.Run(message);
// Assert
_blobStoreMock.Verify(b => b.UploadAsync(It.Is<MeshFile>(f => f.FileId == file.FileId), content), Times.Once);
_meshInboxServiceMock.Verify(m => m.AcknowledgeMessageByIdAsync(file.MailboxId, file.FileId), Times.Once);
_fileTransformQueueClientMock.Verify(q => q.EnqueueFileTransformAsync(file), Times.Once);
var updatedFile = _dbContext.MeshFiles.First();
Assert.Equal(blobPath, updatedFile.BlobPath);
Assert.Equal(MeshFileStatus.Extracted, updatedFile.Status);
Assert.True(updatedFile.LastUpdatedUtc > originalLastUpdatedUtc);
}
[Fact]
public async Task Run_GetMessageFails_ErrorLoggedAndFileSentToPoisonQueue()
{
// Arrange
var fileId = "file-4";
var originalLastUpdatedUtc = DateTime.UtcNow.AddHours(-1);
var file = new MeshFile
{
FileType = MeshFileType.NbssAppointmentEvents,
MailboxId = "test-mailbox",
FileId = fileId,
Status = MeshFileStatus.Discovered,
LastUpdatedUtc = originalLastUpdatedUtc
};
_dbContext.MeshFiles.Add(file);
await _dbContext.SaveChangesAsync();
_meshInboxServiceMock.Setup(s => s.GetMessageByIdAsync(file.MailboxId, fileId))
.ReturnsAsync(new MeshResponse<GetMessageResponse>
{
IsSuccessful = false
});
var message = new FileExtractQueueMessage { FileId = fileId };
// Act
await _function.Run(message);
// Assert
_loggerMock.Verify(
x => x.Log(
LogLevel.Error,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString() == $"An exception occurred during file extraction for fileId: {fileId}"),
It.Is<InvalidOperationException>(e => e.Message.StartsWith("Mesh extraction failed: ")),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()
), Times.Once);
_blobStoreMock.Verify(b => b.UploadAsync(It.IsAny<MeshFile>(), It.IsAny<byte[]>()), Times.Never);
_meshInboxServiceMock.Verify(m => m.AcknowledgeMessageByIdAsync(file.MailboxId, file.FileId), Times.Never);
_fileTransformQueueClientMock.Verify(q => q.EnqueueFileTransformAsync(It.IsAny<MeshFile>()), Times.Never);
_fileExtractQueueClientMock.Verify(q => q.SendToPoisonQueueAsync(message), Times.Once);
var updatedFile = _dbContext.MeshFiles.First();
Assert.Null(updatedFile.BlobPath);
Assert.Equal(MeshFileStatus.FailedExtract, updatedFile.Status);
Assert.True(updatedFile.LastUpdatedUtc > originalLastUpdatedUtc);
}
[Fact]
public async Task Run_AcknowledgeMessageFails_WarningLoggedAndProcessingContinuesAsNormal()
{
// Arrange
var fileId = "file-4";
var originalLastUpdatedUtc = DateTime.UtcNow.AddHours(-1);
var file = new MeshFile
{
FileType = MeshFileType.NbssAppointmentEvents,
MailboxId = "test-mailbox",
FileId = fileId,
Status = MeshFileStatus.Discovered,
LastUpdatedUtc = originalLastUpdatedUtc
};
_dbContext.MeshFiles.Add(file);
await _dbContext.SaveChangesAsync();
var content = new byte[] { 1, 2, 3 };
const string blobPath = "directory/fileName";
_meshInboxServiceMock.Setup(s => s.GetMessageByIdAsync(file.MailboxId, fileId))
.ReturnsAsync(new MeshResponse<GetMessageResponse>
{
IsSuccessful = true,
Response = new GetMessageResponse
{
FileAttachment = new FileAttachment { Content = content }
}
});
_blobStoreMock.Setup(s => s.UploadAsync(file, content)).ReturnsAsync("directory/fileName");
_meshInboxServiceMock.Setup(s => s.AcknowledgeMessageByIdAsync(file.MailboxId, file.FileId))
.ReturnsAsync(new MeshResponse<AcknowledgeMessageResponse>
{
IsSuccessful = false
});
var message = new FileExtractQueueMessage { FileId = fileId };
// Act
await _function.Run(message);
// Assert
_loggerMock.Verify(
x => x.Log(
LogLevel.Warning,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) =>
v.ToString().StartsWith("Mesh acknowledgement failed: ") &&
v.ToString().EndsWith("This is not a fatal error so processing will continue.")),
null,
It.IsAny<Func<It.IsAnyType, Exception?, string>>()
), Times.Once);
_blobStoreMock.Verify(b => b.UploadAsync(file, content), Times.Once);
_meshInboxServiceMock.Verify(m => m.AcknowledgeMessageByIdAsync(file.MailboxId, file.FileId), Times.Once);
_fileTransformQueueClientMock.Verify(q => q.EnqueueFileTransformAsync(file), Times.Once);
_fileExtractQueueClientMock.Verify(q => q.SendToPoisonQueueAsync(message), Times.Never);
var updatedFile = _dbContext.MeshFiles.First();
Assert.Equal(blobPath, updatedFile.BlobPath);
Assert.Equal(MeshFileStatus.Extracted, updatedFile.Status);
Assert.True(updatedFile.LastUpdatedUtc > originalLastUpdatedUtc);
}
}