-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCreateCohortDistributionTests.cs
More file actions
386 lines (325 loc) · 15.6 KB
/
CreateCohortDistributionTests.cs
File metadata and controls
386 lines (325 loc) · 15.6 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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
namespace NHS.CohortManager.Tests.UnitTests.CreateCohortDistributionTests;
using System.Net;
using System.Text;
using System.Text.Json;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Moq;
using Common;
using Microsoft.Extensions.Logging;
using NHS.CohortManager.CohortDistributionService;
using NHS.CohortManager.CohortDistribution;
using NHS.CohortManager.Tests.TestUtils;
using Model;
using Model.Enums;
using Data.Database;
using DataServices.Client;
using System.Linq.Expressions;
[TestClass]
public class CreateCohortDistributionTests
{
private readonly Mock<ICallFunction> _callFunction = new();
private readonly Mock<ILogger<CreateCohortDistribution>> _logger = new();
private readonly Mock<ICohortDistributionHelper> _cohortDistributionHelper = new();
private readonly CreateCohortDistribution _sut;
private readonly Mock<IExceptionHandler> _exceptionHandler = new();
private readonly CreateCohortDistributionRequestBody _requestBody;
private readonly Mock<IAzureQueueStorageHelper> _azureQueueStorageHelper = new();
private readonly Mock<HttpWebResponse> _sendToCohortDistributionResponse = new();
private Mock<HttpRequestData> _request;
private readonly SetupRequest _setupRequest = new();
private CohortDistributionParticipant _cohortDistributionParticipant;
private Mock<IDataServiceClient<ParticipantManagement>> _participantManagementClientMock = new();
public CreateCohortDistributionTests()
{
Environment.SetEnvironmentVariable("RetrieveParticipantDataURL", "RetrieveParticipantDataURL");
Environment.SetEnvironmentVariable("AllocateScreeningProviderURL", "AllocateScreeningProviderURL");
Environment.SetEnvironmentVariable("TransformDataServiceURL", "TransformDataServiceURL");
Environment.SetEnvironmentVariable("AddCohortDistributionURL", "AddCohortDistributionURL");
Environment.SetEnvironmentVariable("IsExtractedToBSSelect", "IsExtractedToBSSelect");
Environment.SetEnvironmentVariable("IgnoreParticipantExceptions", "IgnoreParticipantExceptions");
_requestBody = new CreateCohortDistributionRequestBody()
{
NhsNumber = "1234567890",
ScreeningService = "BSS",
};
_request = _setupRequest.Setup(JsonSerializer.Serialize(_requestBody));
_cohortDistributionParticipant = new()
{
ParticipantId = "1234",
NhsNumber = "5678",
ScreeningServiceId = "Screening123",
Postcode = "AB1 2CD"
};
_cohortDistributionHelper
.Setup(x => x.RetrieveParticipantDataAsync(It.IsAny<CreateCohortDistributionRequestBody>()))
.ReturnsAsync(_cohortDistributionParticipant);
_cohortDistributionHelper
.Setup(x => x.ValidateCohortDistributionRecordAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CohortDistributionParticipant>()))
.ReturnsAsync(new ValidationExceptionLog {CreatedException = false, IsFatal = false});
_participantManagementClientMock
.Setup(x => x.GetSingle(It.IsAny<string>()))
.ReturnsAsync(new ParticipantManagement {ExceptionFlag = 0});
_participantManagementClientMock
.Setup(x => x.Update(It.IsAny<ParticipantManagement>()))
.ReturnsAsync(true);
_sut = new CreateCohortDistribution(_logger.Object, _callFunction.Object, _cohortDistributionHelper.Object,
_exceptionHandler.Object, _azureQueueStorageHelper.Object,
_participantManagementClientMock.Object);
}
[TestMethod]
[DataRow(null, "BSS")]
[DataRow("1234567890", null)]
public async Task RunAsync_MissingFieldsOnRequestBody_ReturnBadRequest(string nhsNumber, string screeningService)
{
// Arrange
_requestBody.NhsNumber = nhsNumber;
_requestBody.ScreeningService = screeningService;
_request = _setupRequest.Setup(JsonSerializer.Serialize(_requestBody));
// Act
await _sut.RunAsync(_requestBody);
// Assert
_logger.Verify(x => x.Log(It.Is<LogLevel>(l => l == LogLevel.Error),
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString().Contains("One or more of the required parameters is missing")),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception, string>>()),
Times.Once);
}
[TestMethod]
public async Task RunAsync_RetrieveParticipantDataRequestFails_ReturnBadRequest()
{
// Arrange
Exception caughtException = null;
_request = _setupRequest.Setup(JsonSerializer.Serialize(_requestBody));
_cohortDistributionHelper
.Setup(x => x.RetrieveParticipantDataAsync(It.IsAny<CreateCohortDistributionRequestBody>()))
.Throws(new Exception("some error"));
// Act
try
{
await _sut.RunAsync(_requestBody);
}
catch (Exception ex)
{
caughtException = ex;
}
// Assert
_logger.Verify(x => x.Log(It.Is<LogLevel>(l => l == LogLevel.Error),
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString().Contains("Create Cohort Distribution failed")),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception, string>>()),
Times.Once);
Assert.IsNotNull(caughtException);
Assert.AreEqual("some error", caughtException.Message);
}
[TestMethod]
public async Task RunAsync_AllocateServiceProviderToParticipantRequestFails_ReturnsBadRequest()
{
// Arrange
Exception caughtException = null;
_request = _setupRequest.Setup(JsonSerializer.Serialize(_requestBody));
CohortDistributionParticipant cohortParticipant = new()
{
ScreeningServiceId = "screeningservice",
NhsNumber = "11111111",
RecordType = "NEW",
};
_participantManagementClientMock
.Setup(c => c.GetSingleByFilter(It.IsAny<Expression<Func<ParticipantManagement, bool>>>()))
.ReturnsAsync(new ParticipantManagement {ExceptionFlag = 0});
_cohortDistributionHelper
.Setup(x => x.RetrieveParticipantDataAsync(It.IsAny<CreateCohortDistributionRequestBody>()))
.ReturnsAsync(new CohortDistributionParticipant() {ScreeningServiceId = "screeningservice", Postcode = "POSTCODE"});
_cohortDistributionHelper
.Setup(x => x.AllocateServiceProviderAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new Exception("some error"));
// Assert
try
{
await _sut.RunAsync(_requestBody);
}
catch (Exception ex)
{
caughtException = ex;
}
// Assert
_logger.Verify(x => x.Log(It.Is<LogLevel>(l => l == LogLevel.Error),
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString().Contains("Create Cohort Distribution failed")),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception, string>>()),
Times.Once);
Assert.IsNotNull(caughtException);
Assert.AreEqual("some error", caughtException.Message);
}
[TestMethod]
public async Task RunAsync_TransformDataServiceRequestFails_ReturnEarly()
{
// Arrange
_cohortDistributionHelper
.Setup(x => x.AllocateServiceProviderAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync("");
_cohortDistributionHelper
.Setup(x => x.TransformParticipantAsync(It.IsAny<string>(), It.IsAny<CohortDistributionParticipant>()))
.ReturnsAsync((CohortDistributionParticipant)null);
_participantManagementClientMock
.Setup(c => c.GetSingleByFilter(It.IsAny<Expression<Func<ParticipantManagement, bool>>>()))
.ReturnsAsync(new ParticipantManagement {ExceptionFlag = 0});
// Act
await _sut.RunAsync(_requestBody);
// Assert
_callFunction.Verify(x => x.SendPost("AddCohortDistributionURL", It.IsAny<string>()), Times.Never);
}
[TestMethod]
public async Task RunAsync_AddCohortDistributionRequestFails_LogError()
{
// Arrange
Exception caughtException = null;
_request = _setupRequest.Setup(JsonSerializer.Serialize(_requestBody));
_cohortDistributionHelper
.Setup(x => x.AllocateServiceProviderAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync("");
_cohortDistributionHelper
.Setup(x => x.TransformParticipantAsync(It.IsAny<string>(), It.IsAny<CohortDistributionParticipant>()))
.ReturnsAsync(new CohortDistributionParticipant());
_participantManagementClientMock
.Setup(c => c.GetSingleByFilter(It.IsAny<Expression<Func<ParticipantManagement, bool>>>()))
.ReturnsAsync(new ParticipantManagement { ExceptionFlag = 0 });
_callFunction
.Setup(call => call.SendPost(It.Is<string>(s => s.Contains("AddCohortDistributionURL")), It.IsAny<string>()))
.Throws(new Exception("an error happened"));
try
{
//Act
await _sut.RunAsync(_requestBody);
}
catch (Exception ex)
{
caughtException = ex;
}
// Assert
_logger.Verify(x => x.Log(It.Is<LogLevel>(l => l == LogLevel.Error),
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString().Contains("Create Cohort Distribution failed")),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception, string>>()),
Times.Once);
Assert.IsNotNull(caughtException);
Assert.AreEqual("an error happened", caughtException.Message);
}
[TestMethod]
public async Task RunAsync_AllSuccessfulRequests_AddsToCOhort()
{
// Arrange
_cohortDistributionHelper
.Setup(x => x.AllocateServiceProviderAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync("");
_cohortDistributionHelper
.Setup(x => x.TransformParticipantAsync(It.IsAny<string>(), It.IsAny<CohortDistributionParticipant>()))
.ReturnsAsync(new CohortDistributionParticipant());
_sendToCohortDistributionResponse
.Setup(x => x.StatusCode)
.Returns(HttpStatusCode.OK);
_callFunction
.Setup(call => call.SendPost(It.Is<string>(s => s.Contains("AddCohortDistributionURL")), It.IsAny<string>()))
.ReturnsAsync(_sendToCohortDistributionResponse.Object);
_participantManagementClientMock
.Setup(c => c.GetSingleByFilter(It.IsAny<Expression<Func<ParticipantManagement, bool>>>()))
.ReturnsAsync(new ParticipantManagement() { ExceptionFlag = 0 });
var response = MockHelpers.CreateMockHttpResponseData(HttpStatusCode.OK);
_callFunction
.Setup(call => call.SendPost(It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(response);
// Act
await _sut.RunAsync(_requestBody);
// Assert
_logger.Verify(x => x.Log(It.Is<LogLevel>(l => l == LogLevel.Information),
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString().Contains("Participant has been successfully put on the cohort distribution table")),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception, string>>()),
Times.Once);
}
[TestMethod]
public async Task RunAsync_ParticipantHasException_CreatesSystemExceptionLog()
{
// Arrange
_request = _setupRequest.Setup(JsonSerializer.Serialize(_requestBody));
_cohortDistributionHelper
.Setup(x => x.TransformParticipantAsync(It.IsAny<string>(), It.IsAny<CohortDistributionParticipant>()))
.ReturnsAsync(new CohortDistributionParticipant());
var response = new Mock<HttpWebResponse>();
response.Setup(r => r.StatusCode).Returns(HttpStatusCode.BadRequest);
_callFunction.Setup(x => x.SendPost(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(response.Object);
_participantManagementClientMock
.Setup(c => c.GetSingleByFilter(It.IsAny<Expression<Func<ParticipantManagement, bool>>>()))
.ReturnsAsync(new ParticipantManagement() {ExceptionFlag = 1});
// Act
await _sut.RunAsync(_requestBody);
// Assert
_exceptionHandler.Verify(x => x.CreateSystemExceptionLog(
It.IsAny<Exception>(),
It.IsAny<Participant>(),
It.IsAny<string>()),
Times.Once);
}
[TestMethod]
public async Task RunAsync_ValidationRuleTriggered_UpdateExceptionFlagAndLog()
{
// Arrange
_cohortDistributionHelper
.Setup(x => x.ValidateCohortDistributionRecordAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CohortDistributionParticipant>()))
.ReturnsAsync(new ValidationExceptionLog { CreatedException = true, IsFatal = false });
_cohortDistributionHelper
.Setup(x => x.AllocateServiceProviderAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync("");
var response = new Mock<HttpWebResponse>();
response.Setup(r => r.StatusCode).Returns(HttpStatusCode.OK);
_callFunction.Setup(x => x.SendPost("AddCohortDistributionURL", It.IsAny<string>())).ReturnsAsync(response.Object);
_participantManagementClientMock
.Setup(c => c.GetSingleByFilter(It.IsAny<Expression<Func<ParticipantManagement, bool>>>()))
.ReturnsAsync(new ParticipantManagement() { ExceptionFlag = 0 });
// Act
await _sut.RunAsync(_requestBody);
// Assert
_exceptionHandler.Verify(x => x.CreateRecordValidationExceptionLog(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>()
), Times.Once);
_participantManagementClientMock
.Verify(x => x.Update(It.IsAny<ParticipantManagement>()), Times.Once);
}
[TestMethod]
public async Task RunAsync_ParticipantHasExceptionAndEnvironmentVariableFalse_CreateExceptionAndReturn()
{
// Arrange
Environment.SetEnvironmentVariable("IgnoreParticipantExceptions", "false");
_cohortDistributionParticipant.ExceptionFlag = 1;
_cohortDistributionHelper
.Setup(x => x.RetrieveParticipantDataAsync(It.IsAny<CreateCohortDistributionRequestBody>()))
.ReturnsAsync(_cohortDistributionParticipant);
_cohortDistributionHelper
.Setup(x => x.AllocateServiceProviderAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync("");
// Act
await _sut.RunAsync(_requestBody);
// Assert
_logger.Verify(x => x.Log(
LogLevel.Error,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString().Contains($"Unable to add to cohort distribution")),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception, string>>()));
_cohortDistributionHelper
.Verify(x => x.ValidateCohortDistributionRecordAsync(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<CohortDistributionParticipant>()),
Times.Never);
}
}