|
| 1 | +using System.Diagnostics; |
| 2 | +using System.Net.Http.Headers; |
| 3 | +using System.Text.Json; |
| 4 | +using System.Text.Json.Serialization; |
| 5 | +using Azure.Storage.Blobs; |
| 6 | +using Azure.Storage.Blobs.Models; |
| 7 | +using Microsoft.EntityFrameworkCore; |
| 8 | +using ServiceLayer.Data; |
| 9 | +using ServiceLayer.TestUtilities; |
| 10 | + |
| 11 | +namespace ServiceLayer.IntegrationTests; |
| 12 | + |
| 13 | +[CollectionDefinition("DockerComposeCollection")] |
| 14 | +public class DockerComposeCollection : ICollectionFixture<DockerComposeFixture> |
| 15 | +{ |
| 16 | +} |
| 17 | + |
| 18 | +[Collection("DockerComposeCollection")] |
| 19 | +public class IntegrationTests |
| 20 | +{ |
| 21 | + private readonly string _azuriteAccountKey = Environment.GetEnvironmentVariable("AZURITE_ACCOUNT_KEY") |
| 22 | + ?? throw new InvalidOperationException($"Environment variable 'AZURITE_ACCOUNT_KEY' is not set."); |
| 23 | + private readonly string _azuriteAccountName = Environment.GetEnvironmentVariable("AZURITE_ACCOUNT_NAME") |
| 24 | + ?? throw new InvalidOperationException($"Environment variable 'AZURITE_ACCOUNT_NAME' is not set."); |
| 25 | + private readonly string _azuriteBlobPort = Environment.GetEnvironmentVariable("AZURITE_BLOB_PORT") |
| 26 | + ?? throw new InvalidOperationException($"Environment variable 'AZURITE_BLOB_PORT' is not set."); |
| 27 | + private readonly string _meshIngestPort = Environment.GetEnvironmentVariable("MESH_INGEST_PORT") |
| 28 | + ?? throw new InvalidOperationException($"Environment variable 'MESH_INGEST_PORT' is not set."); |
| 29 | + private readonly string _meshSandboxPort = Environment.GetEnvironmentVariable("MESH_SANDBOX_PORT") |
| 30 | + ?? throw new InvalidOperationException($"Environment variable 'MESH_SANDBOX_PORT' is not set."); |
| 31 | + private readonly string _meshBlobContainerName = Environment.GetEnvironmentVariable("MESH_BLOB_CONTAINER_NAME") |
| 32 | + ?? throw new InvalidOperationException($"Environment variable 'MESH_BLOB_CONTAINER_NAME' is not set."); |
| 33 | + private readonly string _databaseConnectionString = Environment.GetEnvironmentVariable("DATABASE_CONNECTION_STRING") |
| 34 | + ?? throw new InvalidOperationException($"Environment variable 'DATABASE_CONNECTION_STRING' is not set."); |
| 35 | + |
| 36 | + [Fact] |
| 37 | + public async Task FileSentToMeshInbox_FileIsUploadedToBlobContainerAndInsertedIntoDb() |
| 38 | + { |
| 39 | + // Arrange |
| 40 | + await WaitForHealthyService(); |
| 41 | + |
| 42 | + // Act |
| 43 | + var fileId = await SendFileToMeshInbox("KMK_20250212095121_APPT_87.dat"); |
| 44 | + |
| 45 | + // Wait to allow functions to ingest the file |
| 46 | + await Task.Delay(45000); |
| 47 | + |
| 48 | + // Assert |
| 49 | + Assert.NotNull(fileId); |
| 50 | + Assert.True(await WasFileUploadedToBlobContainer(fileId)); |
| 51 | + Assert.True(await WasFileInsertedIntoDatabase(fileId)); |
| 52 | + } |
| 53 | + |
| 54 | + private async Task WaitForHealthyService() |
| 55 | + { |
| 56 | + Console.WriteLine("Waiting for Mesh Ingest Service health check to pass..."); |
| 57 | + |
| 58 | + int attemptCounter = 0; |
| 59 | + |
| 60 | + while (attemptCounter < 10) |
| 61 | + { |
| 62 | + var response = await HttpHelper.SendHttpRequestAsync(HttpMethod.Get, $"http://localhost:{_meshIngestPort}/api/health"); |
| 63 | + |
| 64 | + if (response.IsSuccessStatusCode) |
| 65 | + { |
| 66 | + Console.WriteLine("Mesh Ingest Service is healthy and ready to start ingesting files."); |
| 67 | + return; |
| 68 | + } |
| 69 | + |
| 70 | + Console.WriteLine("Mesh Ingest Service is unhealthy"); |
| 71 | + attemptCounter++; |
| 72 | + await Task.Delay(5000); |
| 73 | + } |
| 74 | + |
| 75 | + Console.WriteLine("Max attempts reached. Mesh Ingest Service is still unhealthy."); |
| 76 | + throw new TimeoutException("Timed out waiting on Mesh Ingest Service health check"); |
| 77 | + } |
| 78 | + |
| 79 | + private async Task<string?> SendFileToMeshInbox(string fileName) |
| 80 | + { |
| 81 | + byte[] binaryData = await File.ReadAllBytesAsync($"TestData/{fileName}"); |
| 82 | + var content = new ByteArrayContent(binaryData); |
| 83 | + content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); |
| 84 | + |
| 85 | + var response = await HttpHelper.SendHttpRequestAsync( |
| 86 | + HttpMethod.Post, |
| 87 | + $"http://localhost:{_meshSandboxPort}/messageexchange/X26ABC1/outbox", |
| 88 | + content, |
| 89 | + headers => |
| 90 | + { |
| 91 | + headers.Add("Authorization", "NHSMESH X26ABC1:a42f77b9-58de-4b45-b599-2d5bf320b44d:0:202407291437:e3005627136e01706efabcfe72269bc8da3192e90a840ab344ab7f82a39bb5c6"); |
| 92 | + headers.Add("Mex-Filename", fileName); |
| 93 | + headers.Add("Mex-From", "X26ABC1"); |
| 94 | + headers.Add("Mex-To", "X26ABC1"); |
| 95 | + headers.Add("Mex-Workflowid", "API-DOCS-TEST"); |
| 96 | + } |
| 97 | + ); |
| 98 | + |
| 99 | + string responseBody = await response.Content.ReadAsStringAsync(); |
| 100 | + |
| 101 | + var responseObject = JsonSerializer.Deserialize<MeshResponse>(responseBody); |
| 102 | + |
| 103 | + return responseObject?.MessageID; |
| 104 | + } |
| 105 | + |
| 106 | + private async Task<bool> WasFileUploadedToBlobContainer(string fileId) |
| 107 | + { |
| 108 | + var blobConnectionString = $"DefaultEndpointsProtocol=http;AccountName={_azuriteAccountName};AccountKey={_azuriteAccountKey};BlobEndpoint=http://localhost:{_azuriteBlobPort}/{_azuriteAccountName}"; |
| 109 | + |
| 110 | + var containerClient = new BlobContainerClient(blobConnectionString, _meshBlobContainerName); |
| 111 | + |
| 112 | + try |
| 113 | + { |
| 114 | + var blobClient = containerClient.GetBlobClient($"NbssAppointmentEvents/{fileId}"); |
| 115 | + |
| 116 | + BlobProperties properties = await blobClient.GetPropertiesAsync(); |
| 117 | + return true; // If we get properties, the blob exists |
| 118 | + } |
| 119 | + catch (Exception ex) |
| 120 | + { |
| 121 | + Console.WriteLine($"An error occurred: {ex.Message}"); |
| 122 | + return false; |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + private async Task<bool> WasFileInsertedIntoDatabase(string fileId) |
| 127 | + { |
| 128 | + var options = new DbContextOptionsBuilder<ServiceLayerDbContext>() |
| 129 | + .UseSqlServer(_databaseConnectionString) |
| 130 | + .Options; |
| 131 | + |
| 132 | + var context = new ServiceLayerDbContext(options); |
| 133 | + |
| 134 | + return await context.MeshFiles.AnyAsync(x => x.FileId == fileId); |
| 135 | + } |
| 136 | + |
| 137 | + public class MeshResponse |
| 138 | + { |
| 139 | + [JsonPropertyName("messageID")] |
| 140 | + public required string MessageID { get; set; } |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +public class DockerComposeFixture : IAsyncLifetime |
| 145 | +{ |
| 146 | + public async Task InitializeAsync() |
| 147 | + { |
| 148 | + Console.WriteLine("Starting up docker containers..."); |
| 149 | + |
| 150 | + var startInfo = new ProcessStartInfo |
| 151 | + { |
| 152 | + FileName = "docker", |
| 153 | + Arguments = "compose --env-file .env.tests up -d svclyr-mesh-ingest mesh-sandbox azurite db db-migrations", |
| 154 | + RedirectStandardOutput = true, |
| 155 | + RedirectStandardError = true, |
| 156 | + UseShellExecute = false, |
| 157 | + CreateNoWindow = true |
| 158 | + }; |
| 159 | + |
| 160 | + using var process = Process.Start(startInfo); |
| 161 | + |
| 162 | + if (process == null) |
| 163 | + { |
| 164 | + throw new Exception("Failed to start the Docker process."); |
| 165 | + } |
| 166 | + |
| 167 | + await process.WaitForExitAsync(); |
| 168 | + |
| 169 | + if (process.ExitCode != 0) |
| 170 | + { |
| 171 | + throw new Exception($"Docker process started but failed, error: {process.StandardError.ReadToEnd()}"); |
| 172 | + } |
| 173 | + |
| 174 | + Console.WriteLine("Docker containers successfully started"); |
| 175 | + } |
| 176 | + |
| 177 | + public async Task DisposeAsync() |
| 178 | + { |
| 179 | + Console.WriteLine("Stopping docker containers..."); |
| 180 | + |
| 181 | + var stopInfo = new ProcessStartInfo |
| 182 | + { |
| 183 | + FileName = "docker", |
| 184 | + Arguments = "compose down", |
| 185 | + RedirectStandardOutput = true, |
| 186 | + RedirectStandardError = true, |
| 187 | + UseShellExecute = false, |
| 188 | + CreateNoWindow = true |
| 189 | + }; |
| 190 | + |
| 191 | + using var process = Process.Start(stopInfo); |
| 192 | + |
| 193 | + if (process == null) |
| 194 | + { |
| 195 | + throw new Exception("Failed to start the Docker process."); |
| 196 | + } |
| 197 | + |
| 198 | + await process.WaitForExitAsync(); |
| 199 | + |
| 200 | + if (process.ExitCode != 0) |
| 201 | + { |
| 202 | + throw new Exception($"Docker process started but failed, error: {process.StandardError.ReadToEnd()}"); |
| 203 | + } |
| 204 | + |
| 205 | + Console.WriteLine("Docker containers stopped"); |
| 206 | + } |
| 207 | +} |
0 commit comments