-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathFileWritingFormatterBaseTests.cs
More file actions
350 lines (303 loc) · 15.3 KB
/
FileWritingFormatterBaseTests.cs
File metadata and controls
350 lines (303 loc) · 15.3 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
#nullable enable
using FluentAssertions;
using Io.Cucumber.Messages.Types;
using Moq;
using Reqnroll.Formatters;
using Reqnroll.Formatters.Configuration;
using Reqnroll.Formatters.PubSub;
using Reqnroll.Formatters.RuntimeSupport;
using Reqnroll.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace Reqnroll.RuntimeTests.Formatters;
public class FileWritingFormatterBaseTests
{
private class TestFileWritingFormatter : FileWritingFormatterBase
{
public bool OnTargetFileStreamInitializedCalled = false;
public bool OnTargetFileStreamDisposingCalled = false;
public bool WriteToFileCalled = false;
public bool OnCancellationCalled = false;
public bool FlushTargetFileStreamCalled = false;
public string? LastOutputPath;
public Envelope? LastEnvelope;
public CancellationToken? LastToken;
public bool ThrowOnCreateTargetFileStream = false;
public bool ThrowOnWriteToFile = false;
public bool ThrowOnFlush = false;
public bool ThrowOnTargetFileStreamInitialized = false;
public bool ThrowOnTargetFileStreamDisposing = false;
public bool ThrowOnOnCancellation = false;
public bool ThrowOnFinalizeInitialization = false;
public bool FinalizeInitializationCalled = false;
public Stream? LastStream;
protected override TimeSpan DisposeTimeout => TimeSpan.FromMilliseconds(100);
protected override TimeSpan DisposeCancellationTimeout => TimeSpan.FromMilliseconds(100);
public TestFileWritingFormatter(IFormattersConfigurationProvider config, IFormatterLog logger, IFileSystem fileSystem)
: base(config, logger, fileSystem, "testPlugin", ".txt", "default.txt") { }
protected override void OnTargetFileStreamInitialized(Stream targetFileStream)
{
OnTargetFileStreamInitializedCalled = true;
LastStream = targetFileStream;
if (ThrowOnTargetFileStreamInitialized) throw new System.Exception("fail");
}
protected override void OnTargetFileStreamDisposing()
{
OnTargetFileStreamDisposingCalled = true;
if (ThrowOnTargetFileStreamDisposing) throw new System.Exception("fail");
}
protected override async Task WriteToFile(Envelope envelope, CancellationToken cancellationToken)
{
WriteToFileCalled = true;
LastEnvelope = envelope;
LastToken = cancellationToken;
if (ThrowOnWriteToFile) throw new System.Exception("fail");
await Task.CompletedTask;
}
protected override Task OnCancellation()
{
OnCancellationCalled = true;
if (ThrowOnOnCancellation) throw new System.Exception("fail");
return Task.CompletedTask;
}
protected override async Task FlushTargetFileStream(CancellationToken cancellationToken)
{
FlushTargetFileStreamCalled = true;
if (ThrowOnFlush) throw new System.Exception("fail");
await base.FlushTargetFileStream(cancellationToken);
}
protected override Stream CreateTargetFileStream(string outputPath)
{
if (ThrowOnCreateTargetFileStream) throw new System.Exception("fail");
return new MemoryStream();
}
protected override void FinalizeInitialization(string outputPath, IDictionary<string, object> formatterConfiguration, Action<bool> onInitialized)
{
FinalizeInitializationCalled = true;
if (ThrowOnFinalizeInitialization) throw new System.Exception("fail");
base.FinalizeInitialization(outputPath, formatterConfiguration, onInitialized);
LastOutputPath = outputPath;
}
public async Task PostEnvelopeAsync(Envelope envelope)
{
await PostedMessages.Writer.WriteAsync(envelope);
}
public string TestConfiguredOutputFilePath(IDictionary<string, object> formatterConfiguration)
{
return ConfiguredOutputFilePath(formatterConfiguration);
}
}
private readonly Mock<IFormattersConfigurationProvider> _configMock = new();
private readonly Mock<IFormatterLog> _loggerMock = new();
private readonly Mock<IFileSystem> _fileSystemMock = new();
private readonly TestFileWritingFormatter _sut;
public FileWritingFormatterBaseTests()
{
_configMock.Setup(c => c.ResolveTemplatePlaceholders(It.IsAny<string>()))
.Returns((string s) => s); // Default to identity function for tests
_sut = new TestFileWritingFormatter(_configMock.Object, _loggerMock.Object, _fileSystemMock.Object);
}
[Fact]
public void LaunchInner_InvalidPathCharacters_HandlesGracefully()
{
_fileSystemMock.Setup(f => f.DirectoryExists(It.IsAny<string>())).Returns(true);
var config = new Dictionary<string, object> { { "outputFilePath", "invalid\0path.txt" } };
_sut.LaunchInner(config, enabled => enabled.Should().BeFalse());
_loggerMock.Verify(l => l.WriteMessage(It.Is<string>(s => s.Contains( "is invalid or missing."))), Times.Once);
}
[Fact]
public void LaunchInner_EmptyFileName_UsesDefaultFileName()
{
_fileSystemMock.Setup(f => f.DirectoryExists(It.IsAny<string>())).Returns(true);
var config = new Dictionary<string, object> { { "outputFilePath", "somedir/" } };
_sut.LaunchInner(config, enabled => enabled.Should().BeTrue());
_sut.LastOutputPath.Should().EndWith("default.txt");
}
[Fact]
public void LaunchInner_InvalidFile_DisablesFormatter()
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return; // Skip this test on non-Windows platforms as it checks for invalid file names specific to Windows.
}
_fileSystemMock.Setup(f => f.DirectoryExists(It.IsAny<string>())).Returns(true);
_configMock.Setup(c => c.Enabled).Returns(true);
var config = new Dictionary<string, object> { { "outputFilePath", "invalid|file.txt" } };
_sut.LaunchInner(config, enabled => enabled.Should().BeFalse());
_loggerMock.Verify(l => l.WriteMessage(It.Is<string>(s => s.Contains("invalid or missing"))), Times.Once);
}
[Fact]
public void LaunchInner_CreatesDirectoryIfNotExists()
{
_fileSystemMock.Setup(f => f.DirectoryExists(It.IsAny<string>())).Returns(false);
_configMock.Setup(c => c.Enabled).Returns(true);
var config = new Dictionary<string, object> { { "outputFilePath", "dir/file.txt" } };
_sut.LaunchInner(config, _ => { });
_fileSystemMock.Verify(f => f.CreateDirectory(It.IsAny<string>()), Times.Once);
}
[Fact]
public void LaunchInner_HandlesExceptionOnCreateDirectory()
{
_fileSystemMock.Setup(f => f.DirectoryExists(It.IsAny<string>())).Returns(false);
_fileSystemMock.Setup(f => f.CreateDirectory(It.IsAny<string>())).Throws(new System.Exception("fail"));
var config = new Dictionary<string, object> { { "outputFilePath", "dir/file.txt" } };
_sut.LaunchInner(config, enabled => enabled.Should().BeFalse());
_loggerMock.Verify(l => l.WriteMessage(It.Is<string>(s => s.Contains("occurred creating the destination directory"))), Times.Once);
}
[Fact]
public void LaunchInner_ValidConfig_InitializesFileStream()
{
_fileSystemMock.Setup(f => f.DirectoryExists(It.IsAny<string>())).Returns(true);
var config = new Dictionary<string, object> { { "outputFilePath", "file.txt" } };
_sut.LaunchInner(config, enabled => enabled.Should().BeTrue());
_sut.OnTargetFileStreamInitializedCalled.Should().BeTrue();
_sut.LastOutputPath.Should().NotBeNull();
}
[Fact]
public async Task ConsumeAndFormatMessagesBackgroundTask_HandlesNullTargetFileStream()
{
// Arrange: set a flag so that the SUT sets TargetFileStream to null during initialization
_sut.ThrowOnCreateTargetFileStream = true; // Use this flag to simulate failure and set TargetFileStream to null
var config = new Dictionary<string, object> { { "outputFilePath", "file.txt" } };
_sut.LaunchInner(config, _ => { });
// Act: invoke the background task
var method = _sut.GetType().BaseType!.GetMethod("ConsumeAndFormatMessagesBackgroundTask", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (method != null)
{
var task = method.Invoke(_sut, new object[] { CancellationToken.None }) as Task;
if (task != null)
{
try { await task; } catch { /* ignore exceptions for this test */ }
}
}
// Assert: logger should have been called with the expected message
_loggerMock.Verify(l => l.WriteMessage(It.Is<string>(s => s.Contains("filestream is not open"))), Times.Once);
}
[Fact]
public async Task ConsumeAndFormatMessagesBackgroundTask_HandlesOperationCanceledException()
{
// Arrange: set up a valid file stream and post a message
_fileSystemMock.Setup(f => f.DirectoryExists(It.IsAny<string>())).Returns(true);
var config = new Dictionary<string, object> { { "outputFilePath", "file.txt" } };
_sut.LaunchInner(config, _ => { });
var envelope = Envelope.Create(new TestRunStarted(new Io.Cucumber.Messages.Types.Timestamp(0, 0), ""));
await _sut.PostEnvelopeAsync(envelope);
// Act: cancel the token before running the background task
var tokenSource = new CancellationTokenSource();
tokenSource.Cancel();
var method = _sut.GetType().BaseType!.GetMethod("ConsumeAndFormatMessagesBackgroundTask", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (method != null)
{
var task = method.Invoke(_sut, new object[] { tokenSource.Token }) as Task;
if (task != null)
{
await task;
}
}
// Assert: should log cancellation
_loggerMock.Verify(l => l.WriteMessage(It.Is<string>(s => s.Contains("has been cancelled"))), Times.AtLeastOnce);
_sut.OnCancellationCalled.Should().BeTrue();
}
[Fact]
public void Dispose_CallsDisposeFileStreamAndBaseDispose()
{
_fileSystemMock.Setup(f => f.DirectoryExists(It.IsAny<string>())).Returns(true);
var config = new Dictionary<string, object> { { "outputFilePath", "file.txt" } };
_sut.LaunchInner(config, _ => { });
_sut.Dispose();
_sut.OnTargetFileStreamDisposingCalled.Should().BeTrue();
}
[Fact]
public void LaunchFormatter_Should_Create_Local_Path_When_No_Path_Provided_in_Configuration()
{
var sp = Path.DirectorySeparatorChar;
_configMock.Setup(c => c.Enabled).Returns(true);
_configMock.Setup(c => c.GetFormatterConfigurationByName("testPlugin")).Returns(new Dictionary<string, object> { { "outputFilePath", "aFileName.txt" } });
_fileSystemMock.Setup(fs => fs.DirectoryExists(It.IsAny<string>())).Returns(true);
_sut.LaunchFormatter(new Mock<ICucumberMessageBroker>().Object);
_sut.Dispose();
_sut.LastOutputPath.Should().NotBeNull();
_sut.LastOutputPath.Should().Be($".{sp}aFileName.txt");
}
[Fact]
public void LaunchFormatter_Should_Apply_Default_Extension_When_Filename_Has_No_Extension()
{
var sp = Path.DirectorySeparatorChar;
_configMock.Setup(c => c.Enabled).Returns(true);
_configMock.Setup(c => c.GetFormatterConfigurationByName("testPlugin")).Returns(new Dictionary<string, object> { { "outputFilePath", "myoutput" } });
_fileSystemMock.Setup(fs => fs.DirectoryExists(It.IsAny<string>())).Returns(true);
_sut.LaunchFormatter(new Mock<ICucumberMessageBroker>().Object);
_sut.Dispose();
_sut.LastOutputPath.Should().NotBeNull();
_sut.LastOutputPath.Should().EndWith($".{sp}myoutput.txt");
}
[Fact]
public void LaunchFormatter_Should_Not_Apply_Default_Extension_When_Filename_Has_Extension()
{
var sp = Path.DirectorySeparatorChar;
_configMock.Setup(c => c.Enabled).Returns(true);
_configMock.Setup(c => c.GetFormatterConfigurationByName("testPlugin")).Returns(new Dictionary<string, object> { { "outputFilePath", "myoutput.log" } });
_fileSystemMock.Setup(fs => fs.DirectoryExists(It.IsAny<string>())).Returns(true);
_sut.LaunchFormatter(new Mock<ICucumberMessageBroker>().Object);
_sut.Dispose();
_sut.LastOutputPath.Should().NotBeNull();
_sut.LastOutputPath!.Should().NotContain(".txt");
}
[Fact]
public async Task PublishAsync_Should_Write_Envelopes()
{
_configMock.Setup(c => c.Enabled).Returns(true);
_configMock.Setup(c => c.GetFormatterConfigurationByName("testPlugin"))
.Returns(new Dictionary<string, object> { { "outputFilePath", @"C:\/valid\/path/output.txt" } });
_fileSystemMock.Setup(fs => fs.DirectoryExists(It.IsAny<string>())).Returns(true);
var message = Envelope.Create(new TestRunStarted(new Io.Cucumber.Messages.Types.Timestamp(1, 0), "started"));
_sut.LaunchFormatter(new Mock<ICucumberMessageBroker>().Object);
await _sut.PublishAsync(message);
await _sut.CloseAsync();
_sut.LastEnvelope.Should().Be(message);
}
[Fact]
public void LaunchFormatter_Should_Create_Directory_If_Not_Exists()
{
_configMock.Setup(c => c.Enabled).Returns(true);
_configMock.Setup(c => c.GetFormatterConfigurationByName("testPlugin"))
.Returns(new Dictionary<string, object> { { "outputFilePath", "outputFilePath" } });
_fileSystemMock.Setup(fs => fs.DirectoryExists(It.IsAny<string>())).Returns(false);
_sut.LaunchFormatter(new Mock<ICucumberMessageBroker>().Object);
_sut.Dispose();
_fileSystemMock.Verify(fs => fs.CreateDirectory(It.IsAny<string>()), Times.Once);
}
[Fact]
public async Task Publish_FollowedBy_Dispose_Should_Cause_CancelToken_to_Fire()
{
_configMock.Setup(c => c.Enabled).Returns(true);
_configMock.Setup(c => c.GetFormatterConfigurationByName("testPlugin"))
.Returns(new Dictionary<string, object> { { "outputFilePath", @"C:\/valid\/path/output.txt" } });
_fileSystemMock.Setup(fs => fs.DirectoryExists(It.IsAny<string>())).Returns(true);
var message = Envelope.Create(new TestRunStarted(new Io.Cucumber.Messages.Types.Timestamp(1, 0), "started"));
_sut.LaunchFormatter(new Mock<ICucumberMessageBroker>().Object);
await _sut.PublishAsync(message);
_sut.Dispose();
_sut.LastEnvelope.Should().Be(message);
_sut.OnCancellationCalled.Should().BeTrue();
}
[Fact]
public void ConfiguredOutputFilePath_MissingKey_ReturnsEmptyString()
{
var config = new Dictionary<string, object>();
var result = _sut.TestConfiguredOutputFilePath(config);
result.Should().BeEmpty();
}
[Fact]
public void ConfiguredOutputFilePath_NullValue_ReturnsEmptyString()
{
var config = new Dictionary<string, object> { { "outputFilePath", null! } };
var result = _sut.TestConfiguredOutputFilePath(config);
result.Should().BeEmpty();
}
}