Skip to content

Commit 4205eed

Browse files
author
Wayfarer
committed
cleanup a bit
1 parent 46adf55 commit 4205eed

22 files changed

Lines changed: 215 additions & 177 deletions

CommonLibraryGui.Tests/AuroraTests.cs

Lines changed: 69 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -18,45 +18,40 @@
1818
namespace CommonLibraryGuiTests
1919
{
2020
/// <summary>
21-
/// Some Basic tests for the Aurora Engine and the image Combining
21+
/// Some Basic tests for the Aurora Engine and the image Combining
2222
/// </summary>
23-
[TestFixture] // Added for explicit NUnit discovery
23+
[TestFixture]
24+
[Apartment(ApartmentState.STA)]
2425
public sealed class AuroraTests
2526
{
26-
/// <summary>
27-
/// The codebase
28-
/// </summary>
29-
private static readonly string Codebase = Directory.GetCurrentDirectory();
30-
31-
/// <summary>
32-
/// The executable folder
33-
/// </summary>
34-
private static readonly DirectoryInfo ExeFolder = new(Path.GetDirectoryName(Codebase) ?? string.Empty);
27+
private string _sampleImagesFolder;
3528

36-
/// <summary>
37-
/// The project folder
38-
/// </summary>
39-
private static readonly DirectoryInfo ProjectFolder = ExeFolder.Parent?.Parent;
29+
[SetUp]
30+
public void Setup()
31+
{
32+
// Resolve the path dynamically based on the test execution directory
33+
var baseDirectory = TestContext.CurrentContext.TestDirectory;
34+
_sampleImagesFolder = Path.Combine(baseDirectory, "Image");
4035

41-
/// <summary>
42-
/// The sample images folder
43-
/// </summary>
44-
private static readonly DirectoryInfo SampleImagesFolder = new(Path.Combine(ProjectFolder.FullName, "Image"));
36+
if (!Directory.Exists(_sampleImagesFolder))
37+
{
38+
Assert.Ignore($"The Image folder could not be found at: {_sampleImagesFolder}. " +
39+
"Ensure the 'Image' folder is set to 'Copy to Output Directory'.");
40+
}
41+
}
4542

4643
/// <summary>
47-
/// Test Aurora.
44+
/// Test Aurora.
4845
/// </summary>
4946
[Test]
50-
[Apartment(ApartmentState.STA)]
5147
public void Aurora()
5248
{
53-
var bmResultLayerOther = new Bitmap(Path.Combine(SampleImagesFolder.FullName, "result_layer_other.png"));
54-
var bmResultBase = new Bitmap(Path.Combine(SampleImagesFolder.FullName, "result_base.png"));
49+
using var bmResultLayerOther = LoadBitmap("result_layer_other.png");
50+
using var bmResultBase = LoadBitmap("result_base.png");
5551

5652
var compare = new ImageAnalysis();
5753

58-
//new Test with UI
59-
//generate texture Dictionary, and all the other data;
54+
// Generate texture Dictionary, and all the other data
6055
var map = new Dictionary<int, List<int>>
6156
{
6257
{ 0, new List<int> { 0 } },
@@ -71,40 +66,20 @@ public void Aurora()
7166
{
7267
AuroraTextures = new Dictionary<int, Texture>
7368
{
74-
{
75-
0,
76-
new Texture
77-
{
78-
Layer = 0, Id = 0, Path = Path.Combine(SampleImagesFolder.FullName, "Tile.png")
79-
}
80-
},
81-
{
82-
1,
83-
new Texture
84-
{
85-
Layer = 1, Id = 1, Path = Path.Combine(SampleImagesFolder.FullName, "layerOne.png")
86-
}
87-
},
88-
{
89-
2,
90-
new Texture
91-
{
92-
Layer = 1, Id = 1, Path = Path.Combine(SampleImagesFolder.FullName, "LayerTwo.png")
93-
}
94-
}
69+
{ 0, new Texture { Layer = 0, Id = 0, Path = Path.Combine(_sampleImagesFolder, "Tile.png") } },
70+
{ 1, new Texture { Layer = 1, Id = 1, Path = Path.Combine(_sampleImagesFolder, "layerOne.png") } },
71+
{ 2, new Texture { Layer = 1, Id = 1, Path = Path.Combine(_sampleImagesFolder, "LayerTwo.png") } }
9572
},
9673
AuroraTextureSize = 100,
9774
AuroraHeight = 2,
9875
AuroraWidth = 3,
9976
AuroraMap = map
10077
};
10178

102-
//way hacky but works for for now....
10379
aurora.Initiate();
10480

10581
var data = compare.CompareImages(bmResultBase, aurora.BitmapLayerOne);
10682

107-
// NUnit Syntax: Assert.That(actual, Is.EqualTo(expected))
10883
Assert.That(data.Similarity, Is.EqualTo(100), $"Map was not correct: {data.Similarity}");
10984

11085
map = new Dictionary<int, List<int>>
@@ -120,13 +95,13 @@ public void Aurora()
12095
aurora.AuroraMap = map;
12196
aurora.Initiate();
12297

123-
aurora.BitmapLayerOne.Save($"{SampleImagesFolder}/example.png", ImageFormat.Png);
98+
aurora.BitmapLayerOne.Save(Path.Combine(_sampleImagesFolder, "example.png"), ImageFormat.Png);
12499

125100
data = compare.CompareImages(bmResultLayerOther, aurora.BitmapLayerOne);
126101

127102
Assert.That(data.Similarity, Is.EqualTo(100), $"Aurora Map was not correct: {data.Similarity}");
128103

129-
//test remove
104+
// Test remove
130105
aurora.AuroraRemove = new KeyValuePair<int, int>(0, 2);
131106
aurora.AuroraRemove = new KeyValuePair<int, int>(0, 1);
132107
aurora.AuroraRemove = new KeyValuePair<int, int>(1, 1);
@@ -137,55 +112,39 @@ public void Aurora()
137112

138113
data = compare.CompareImages(bmResultBase, aurora.BitmapLayerOne);
139114

140-
aurora.BitmapLayerOne.Save($"{SampleImagesFolder}/example.png", ImageFormat.Png);
115+
aurora.BitmapLayerOne.Save(Path.Combine(_sampleImagesFolder, "example.png"), ImageFormat.Png);
141116

142117
Assert.That(data.Similarity, Is.EqualTo(100), $"Aurora Map remove was not correct: {data.Similarity}");
143118
}
144119

145120
/// <summary>
146-
/// Test Polaris.
121+
/// Test Polaris.
147122
/// </summary>
148123
[Test]
149-
[Apartment(ApartmentState.STA)]
150124
public void Polaris()
151125
{
152-
var bmResultLayerOther = new Bitmap(Path.Combine(SampleImagesFolder.FullName, "result_layer_other.png"));
153-
var bmResultBase = new Bitmap(Path.Combine(SampleImagesFolder.FullName, "result_base.png"));
126+
using var bmResultLayerOther = LoadBitmap("result_layer_other.png");
127+
using var bmResultBase = LoadBitmap("result_base.png");
154128

155129
var compare = new ImageAnalysis();
156130

157131
var polaris = new Polaris
158132
{
159133
PolarisTextures = new Dictionary<int, Texture>
160134
{
161-
{
162-
0,
163-
new Texture
164-
{
165-
Layer = 0, Id = 0, Path = Path.Combine(SampleImagesFolder.FullName, "Tile.png")
166-
}
167-
},
168-
{
169-
1,
170-
new Texture
171-
{
172-
Layer = 1, Id = 1, Path = Path.Combine(SampleImagesFolder.FullName, "layerOne.png")
173-
}
174-
},
175-
{
176-
2,
177-
new Texture
178-
{
179-
Layer = 1, Id = 1, Path = Path.Combine(SampleImagesFolder.FullName, "LayerTwo.png")
180-
}
181-
}
135+
{ 0, new Texture { Layer = 0, Id = 0, Path = Path.Combine(_sampleImagesFolder, "Tile.png") } },
136+
{ 1, new Texture { Layer = 1, Id = 1, Path = Path.Combine(_sampleImagesFolder, "layerOne.png") } },
137+
{ 2, new Texture { Layer = 1, Id = 1, Path = Path.Combine(_sampleImagesFolder, "LayerTwo.png") } }
182138
},
183139
PolarisTextureSize = 100,
184140
PolarisHeight = 2,
185141
PolarisWidth = 3
186142
};
187143

188144
polaris.Initiate();
145+
146+
// Note: If BitmapLayerThree is managed by Polaris and needs disposal,
147+
// do not dispose it here while it is in use.
189148
var blank = polaris.BitmapLayerThree;
190149

191150
// 0
@@ -207,7 +166,7 @@ public void Polaris()
207166
// 5
208167
polaris.AddTile(new KeyValuePair<int, int>(5, 0));
209168

210-
polaris.BitmapLayerOne.Save($"{SampleImagesFolder}/example Polaris.png", ImageFormat.Png);
169+
polaris.BitmapLayerOne.Save(Path.Combine(_sampleImagesFolder, "example Polaris.png"), ImageFormat.Png);
211170

212171
var data = compare.CompareImages(bmResultLayerOther, polaris.BitmapLayerOne);
213172
Assert.That(data.Similarity, Is.EqualTo(100), $"Map Polaris was not correct: {data.Similarity}");
@@ -239,7 +198,7 @@ public void Polaris()
239198
var check = lst.Equal(map[i], EnumerableCompare.IgnoreOrder);
240199
if (!check)
241200
{
242-
Assert.Fail("wrong map"); // Native NUnit Fail
201+
Assert.Fail("wrong map");
243202
}
244203
}
245204

@@ -255,7 +214,7 @@ public void Polaris()
255214
data = compare.CompareImages(blank, polaris.BitmapLayerThree);
256215
Assert.That(data.Similarity, Is.EqualTo(100), $"Map Polaris was not correct: {data.Similarity}");
257216

258-
// this is a duplicate so this should not be added
217+
// This is a duplicate so this should not be added
259218
polaris.AddDisplay(new KeyValuePair<int, int>(0, 0));
260219

261220
for (var i = 0; i <= 5; i++)
@@ -268,5 +227,36 @@ public void Polaris()
268227
}
269228
}
270229
}
230+
231+
/// <summary>
232+
/// Loads the bitmap.
233+
/// </summary>
234+
/// <param name="fileName">Name of the file.</param>
235+
/// <returns>A new Bitmap object.</returns>
236+
/// <exception cref="FileNotFoundException">Thrown if the file does not exist.</exception>
237+
private Bitmap LoadBitmap(string fileName)
238+
{
239+
var path = Path.Combine(_sampleImagesFolder, fileName);
240+
241+
if (!File.Exists(path))
242+
{
243+
throw new FileNotFoundException($"Bitmap file not found: {path}");
244+
}
245+
246+
// Check if file is empty
247+
var fileInfo = new FileInfo(path);
248+
if (fileInfo.Length == 0)
249+
{
250+
throw new InvalidDataException($"The file is 0 bytes and cannot be loaded as an image: {path}");
251+
}
252+
253+
// Open with FileShare.ReadWrite to prevent locking issues
254+
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
255+
{
256+
// We create a copy so the stream can be closed immediately
257+
var bitmap = new Bitmap(stream);
258+
return new Bitmap(bitmap);
259+
}
260+
}
271261
}
272262
}
-189 Bytes
Loading
-48 Bytes
Loading

Communication.Tests/SimpleLogServerTests.cs

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ private async Task<bool> TrySendTcpMessageAsync(int port, string message)
7474
await using var stream = client.GetStream();
7575
// Important: Add NewLine (\n) so ReadLineAsync fires!
7676
var data = Encoding.UTF8.GetBytes(message + Environment.NewLine);
77-
await stream.WriteAsync(data, 0, data.Length);
77+
await stream.WriteAsync(data);
7878
await stream.FlushAsync();
7979

8080
return true; // Success!
@@ -110,7 +110,7 @@ public async Task InterfaceConstructor_ShouldUseProcessorClass()
110110
Assert.IsTrue(connected, "Could not connect to the server (Timeout).");
111111

112112
// Wait for the processor to get the message (Polling with timeout)
113-
string received = null;
113+
string? received = null;
114114
for (var i = 0; i < 20; i++) // Try for 2 seconds (20 * 100ms)
115115
{
116116
if (fakeProcessor.LastMessage != null)
@@ -167,8 +167,32 @@ public async Task Server_ShouldDisconnect_SlowClients()
167167

168168
// Assert
169169
var buffer = new byte[10];
170-
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
171-
Assert.AreEqual(0, bytesRead, "Server should have closed the connection due to timeout.");
170+
var disconnected = false;
171+
var timeout = DateTime.Now.AddSeconds(2);
172+
173+
// Poll for a bit to allow the TCP stack to finish the handshake
174+
while (DateTime.Now < timeout)
175+
{
176+
// Try to read one byte; if the connection is closed, this will return 0 or throw
177+
try
178+
{
179+
var bytesRead = await stream.ReadAsync(buffer, 0, 1);
180+
if (bytesRead == 0)
181+
{
182+
disconnected = true;
183+
break;
184+
}
185+
}
186+
catch (Exception) // Socket might throw if connection is abruptly reset
187+
{
188+
disconnected = true;
189+
break;
190+
}
191+
192+
await Task.Delay(100); // Give the OS a moment to process the closing
193+
}
194+
195+
Assert.IsTrue(disconnected, "Server failed to close the connection in time.");
172196
}
173197

174198
/// <inheritdoc />
@@ -184,7 +208,7 @@ private class FakeLogProcessor : ILogProcessor
184208
/// <value>
185209
/// The last message.
186210
/// </value>
187-
public string LastMessage { get; private set; }
211+
public string? LastMessage { get; private set; }
188212

189213
/// <summary>
190214
/// Processes the received message (e.g., save to DB, log to file).

Communication/HttpWireTracingHandler.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
8484
}
8585

8686
// Buffer content safely so we don't disrupt the stream
87-
await request.Content.LoadIntoBufferAsync();
87+
await request.Content.LoadIntoBufferAsync(cancellationToken);
8888
var reqBody = await request.Content.ReadAsStringAsync();
8989
if (!string.IsNullOrEmpty(reqBody))
9090
{

Communication/SimpleLogServer.cs

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,21 +27,11 @@ namespace Communication
2727
/// </summary>
2828
public sealed class SimpleLogServer : IDisposable
2929
{
30-
/// <summary>
31-
/// The internal server
32-
/// </summary>
33-
private readonly LogCollectorServer _internalServer;
34-
3530
/// <summary>
3631
/// The CTS
3732
/// </summary>
3833
private readonly CancellationTokenSource _cts;
3934

40-
/// <summary>
41-
/// The server task
42-
/// </summary>
43-
private Task _serverTask;
44-
4535
/// <summary>
4636
/// The TCP log server
4737
/// </summary>

Core.Apps/FileManager/FileLockScanner.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ public sealed class FileLockScanner : ICommand, IRegistryProducer
4646
/// <summary>
4747
/// The store key
4848
/// </summary>
49-
private string StoreKey = "lockedfiles";
49+
private readonly string StoreKey = "lockedfiles";
5050

5151
/// <summary>
5252
/// Initializes a new instance of the <see cref="FileLockScanner"/> class.

0 commit comments

Comments
 (0)