-
Notifications
You must be signed in to change notification settings - Fork 86
/
SarifLogTests.cs
504 lines (430 loc) · 20.7 KB
/
SarifLogTests.cs
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using FluentAssertions.Execution;
using Moq;
using Newtonsoft.Json;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Sarif.UnitTests.Core
{
public class SarifLogTests
{
private readonly ITestOutputHelper output;
public SarifLogTests(ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public void SarifLog_DoesNotSerializeNonNullEmptyCollections()
{
var run = new Run
{
Graphs = new Graph[] { },
Artifacts = new Artifact[] { },
Invocations = new Invocation[] { },
LogicalLocations = new LogicalLocation[] { }
};
run.Graphs.Should().NotBeNull();
run.Artifacts.Should().NotBeNull();
run.Invocations.Should().NotBeNull();
run.LogicalLocations.Should().NotBeNull();
run = SerializeAndDeserialize(run);
// Certain non-null but entirely empty collections should not
// be persisted during serialization. As a result, these properties
// should be null after round-tripping, reflecting the actual
// (i.e., entirely absent) representation on disk when saved.
run.Graphs.Should().BeNull();
run.Artifacts.Should().BeNull();
run.Invocations.Should().BeNull();
run.LogicalLocations.Should().BeNull();
// If arrays are non-empty but only contain object instances
// that consist of nothing but default values, these also
// should not be persisted to disk
run.Graphs = new Graph[] { new Graph() };
run.Artifacts = new Artifact[] { new Artifact() };
run.LogicalLocations = new LogicalLocation[] { new LogicalLocation() };
// Invocations are special, they have a required property,
// ExecutionSuccessful. This means even an entirely default instance
// should be retained when serialized.
run.Invocations = new Invocation[] { new Invocation() };
run = SerializeAndDeserialize(run);
run.Graphs.Should().BeNull();
run.Artifacts.Should().BeNull();
run.LogicalLocations.Should().BeNull();
run.Invocations.Should().NotBeNull();
}
[Fact]
public void SarifLog_ApplyPoliciesShouldNotThrowWhenRunsDoesNotExist()
{
var sarifLog = new SarifLog();
Action action = () => sarifLog.ApplyPolicies();
action.Should().NotThrow();
}
[Fact]
public void SarifLog_SplitPerRun()
{
Random random = RandomSarifLogGenerator.GenerateRandomAndLog(this.output);
SarifLog sarifLog = RandomSarifLogGenerator.GenerateSarifLogWithRuns(random, 1);
int expectedLogCount = sarifLog.Runs.First().Results.Any() ? 1 : 0;
sarifLog.Split(SplittingStrategy.PerRun).Should().HaveCount(expectedLogCount);
sarifLog = RandomSarifLogGenerator.GenerateSarifLogWithRuns(random, 3);
expectedLogCount = sarifLog.Runs.Count(run => run.Results.Any());
sarifLog.Split(SplittingStrategy.PerRun).Should().HaveCount(expectedLogCount);
}
[Fact]
public void SarifLog_SplitPerResult()
{
Random random = RandomSarifLogGenerator.GenerateRandomAndLog(this.output);
SarifLog sarifLog = RandomSarifLogGenerator.GenerateSarifLogWithRuns(random, runCount: 1, resultCount: 5);
int countOfDistinctRules = sarifLog.Runs[0].Results.Select(r => r.RuleId).Distinct().Count();
IList<SarifLog> logs = sarifLog.Split(SplittingStrategy.PerResult).ToList();
logs.Count.Should().Be(countOfDistinctRules);
foreach (SarifLog log in logs)
{
// optimized partitioned log should only include rules referenced by its results
log.Runs.Count.Should().Be(1);
int ruleCount = log.Runs[0].Results.Select(r => r.RuleId).Distinct().Count();
ruleCount.Should().Be(log.Runs[0].Tool.Driver.Rules.Count);
}
}
[Fact]
public void SarifLog_SplitPerTarget()
{
Random random = RandomSarifLogGenerator.GenerateRandomAndLog(this.output);
SarifLog sarifLog = RandomSarifLogGenerator.GenerateSarifLogWithRuns(random, 1);
IList<SarifLog> logs = sarifLog.Split(SplittingStrategy.PerRunPerTarget).ToList();
logs.Count.Should().Be(
sarifLog.Runs[0].Results.Select(r => r.Locations[0].PhysicalLocation.ArtifactLocation.Uri).Distinct().Count());
foreach (SarifLog log in logs)
{
// optimized partitioned log should only include rules referenced by its results
log.Runs.Count.Should().Be(1);
int ruleCount = log.Runs[0].Results.Select(r => r.RuleId).Distinct().Count();
ruleCount.Should().Be(log.Runs[0].Tool.Driver.Rules.Count);
// verify result's RuleIndex reference to right rule
foreach (Result result in log.Runs[0].Results)
{
result.RuleId.Should().Be(
log.Runs[0].Tool.Driver.Rules.ElementAt(result.RuleIndex).Id);
}
}
}
[Fact]
public void SarifLog_SplitPerTarget_WithEmptyLocations()
{
Random random = RandomSarifLogGenerator.GenerateRandomAndLog(this.output);
SarifLog sarifLog = null;
while (true)
{
sarifLog = RandomSarifLogGenerator.GenerateSarifLogWithRuns(random, 1);
if (sarifLog.Runs[0].Results.Count > 0) { break; }
}
// set random result's location to empty
IList<Result> results = sarifLog.Runs.First().Results;
Result randomResult = results.ElementAt(random.Next(results.Count));
randomResult.Locations = null;
randomResult = results.ElementAt(random.Next(results.Count));
if (randomResult.Locations?.FirstOrDefault()?.PhysicalLocation != null)
{
randomResult.Locations.FirstOrDefault().PhysicalLocation = null;
}
randomResult = results.ElementAt(random.Next(results.Count));
if (randomResult.Locations?.FirstOrDefault()?.PhysicalLocation?.ArtifactLocation != null)
{
randomResult.Locations.FirstOrDefault().PhysicalLocation.ArtifactLocation = null;
}
randomResult = results.ElementAt(random.Next(results.Count));
if (randomResult.Locations?.FirstOrDefault()?.PhysicalLocation?.ArtifactLocation?.Uri != null)
{
randomResult.Locations.FirstOrDefault().PhysicalLocation.ArtifactLocation.Uri = null;
}
IList<SarifLog> logs = sarifLog.Split(SplittingStrategy.PerRunPerTarget).ToList();
logs.Count.Should().Be(
sarifLog.Runs[0].Results.Select(r => r.Locations?.FirstOrDefault()?.PhysicalLocation?.ArtifactLocation?.Uri).Distinct().Count());
foreach (SarifLog log in logs)
{
// optimized partitioned log should only include rules referenced by its results
log.Runs.Count.Should().Be(1);
int ruleCount = log.Runs[0].Results.Select(r => r.RuleId).Distinct().Count();
ruleCount.Should().Be(log.Runs[0].Tool.Driver.Rules.Count);
// verify result's RuleIndex reference to right rule
foreach (Result result in log.Runs[0].Results)
{
result.RuleId.Should().Be(
log.Runs[0].Tool.Driver.Rules.ElementAt(result.RuleIndex).Id);
}
}
}
[Fact]
public void SarifLog_LoadDeferred()
{
Random random = RandomSarifLogGenerator.GenerateRandomAndLog(this.output);
SarifLog sarifLog = RandomSarifLogGenerator.GenerateSarifLogWithRuns(random, 1);
string sarifLogText = JsonConvert.SerializeObject(sarifLog);
byte[] byteArray = Encoding.ASCII.GetBytes(sarifLogText);
using var stream = new MemoryStream(byteArray);
var newSarifLog = SarifLog.Load(stream, deferred: true);
newSarifLog.Runs[0].Tool.Driver.Name.Should().Be(sarifLog.Runs[0].Tool.Driver.Name);
newSarifLog.Runs[0].Results.Count.Should().Be(sarifLog.Runs[0].Results.Count);
}
[Fact]
public async Task SarifLog_PostStream_WithInvalidParameters_ShouldThrowArgumentNullException()
{
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await SarifLog.Post(postUri: null,
new MemoryStream(),
new HttpClientWrapper());
});
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await SarifLog.Post(new Uri("https://github.com/microsoft/sarif-sdk"),
null,
new HttpClientWrapper());
});
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await SarifLog.Post(new Uri("https://github.com/microsoft/sarif-sdk"),
new MemoryStream(),
(HttpClientWrapper)null);
});
}
[Fact]
public async Task SarifLog_PostFile_WithInvalidParameters_ShouldThrowException()
{
string filePath = string.Empty;
var fileSystem = new Mock<IFileSystem>();
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await SarifLog.Post(postUri: null,
filePath,
fileSystem.Object,
httpClient: (HttpClientWrapper)null);
});
filePath = "SomeFile.txt";
fileSystem
.Setup(f => f.FileExists(It.IsAny<string>()))
.Returns(false);
await Assert.ThrowsAsync<ArgumentException>(async () =>
{
await SarifLog.Post(postUri: null,
filePath,
fileSystem.Object,
httpClient: (HttpClientWrapper)null);
});
}
[Fact]
public async Task SarifLog_PostFile_PostTests()
{
using var assertionScope = new AssertionScope();
var postUri = new Uri("https://sarif-post/example.com");
var httpMock = new HttpMockHelper();
string filePath = "SomeFile.sarif";
var fileSystem = new Mock<IFileSystem>();
fileSystem
.Setup(f => f.FileExists(It.IsAny<string>()))
.Returns(true);
// This method creates a bare-bones SARIF file with no results and notifications.
var stream = (MemoryStream)CreateSarifLogStream();
fileSystem
.Setup(f => f.FileReadAllBytes(It.IsAny<string>()))
.Returns(stream.ToArray());
(bool, string) logPosted = await SarifLog.Post(postUri,
filePath,
fileSystem.Object,
httpClient: (HttpClientWrapper)null);
logPosted.Item1.Should().BeFalse("with no results or notifications");
logPosted.Item2.Should().Contain("was skipped");
string content = $"{Guid.NewGuid()}";
var httpContent = new StringContent(content, Encoding.UTF8, "text/plain");
stream = (MemoryStream)CreateSarifLogStreamWithResult();
fileSystem
.Setup(f => f.FileReadAllBytes(It.IsAny<string>()))
.Returns(stream.ToArray());
httpMock.Mock(HttpMockHelper.CreateOKResponse(httpContent));
logPosted = await SarifLog.Post(postUri,
filePath,
fileSystem.Object,
httpClient: new HttpClientWrapper(httpMock));
logPosted.Item1.Should().BeTrue("with results");
logPosted.Item2.Should().Contain("status code 'OK'");
logPosted.Item2.Should().Contain(content);
stream = (MemoryStream)CreateSarifLogStreamWithToolExecutionNotifications(FailureLevel.Error);
fileSystem
.Setup(f => f.FileReadAllBytes(It.IsAny<string>()))
.Returns(stream.ToArray());
httpMock.Mock(HttpMockHelper.CreateOKResponse(httpContent));
logPosted = await SarifLog.Post(postUri,
filePath,
fileSystem.Object,
httpClient: new HttpClientWrapper(httpMock));
logPosted.Item1.Should().BeTrue("with error level ToolExecutionNotifications");
logPosted.Item2.Should().Contain("status code 'OK'");
logPosted.Item2.Should().Contain(content);
stream = (MemoryStream)CreateSarifLogStreamWithToolExecutionNotifications(FailureLevel.Warning);
fileSystem
.Setup(f => f.FileReadAllBytes(It.IsAny<string>()))
.Returns(stream.ToArray());
logPosted = await SarifLog.Post(postUri,
filePath,
fileSystem.Object,
httpClient: new HttpClientWrapper(httpMock));
logPosted.Item1.Should().BeFalse("with warning level ToolExecutionNotifications");
logPosted.Item2.Should().Contain("was skipped");
stream = (MemoryStream)CreateSarifLogStreamWithToolExecutionNotifications(FailureLevel.Error);
fileSystem
.Setup(f => f.FileReadAllBytes(It.IsAny<string>()))
.Returns(stream.ToArray());
httpMock.Mock(HttpMockHelper.CreateBadRequestResponse());
logPosted = await SarifLog.Post(postUri,
filePath,
fileSystem.Object,
httpClient: new HttpClientWrapper(httpMock));
logPosted.Item1.Should().BeFalse("a status code of 'BadRequest' should fail the call even though we posted error-level 'ToolExcecutionNotifications'");
logPosted.Item2.Should().Contain("status code 'BadRequest'");
}
[Fact]
public void SarifLog_SaveToMemoryStreamRoundtrips()
{
SarifLog sarifLog = GetSarifLogWithMinimalUniqueData();
var memoryStream = new MemoryStream();
sarifLog.Save(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(memoryStream);
SarifLog newSarifLog = JsonConvert.DeserializeObject<SarifLog>(reader.ReadToEnd());
newSarifLog.Should().BeEquivalentTo(sarifLog);
}
[Fact]
public void SarifLog_SaveToStreamWriterRoundtrips()
{
SarifLog sarifLog = GetSarifLogWithMinimalUniqueData();
var memoryStream = new MemoryStream();
var writer = new StreamWriter(memoryStream); ;
sarifLog.Save(writer);
memoryStream.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(memoryStream);
SarifLog newSarifLog = JsonConvert.DeserializeObject<SarifLog>(reader.ReadToEnd());
newSarifLog.Should().BeEquivalentTo(sarifLog);
}
private static SarifLog GetSarifLogWithMinimalUniqueData()
{
var sarifLog = new SarifLog() { Runs = new[] { new Run() { } } };
sarifLog.Runs[0].SetProperty("test", Guid.NewGuid().ToString());
return sarifLog;
}
[Fact]
public async Task SarifLog_Post_BadRequestResponse()
{
var postUri = new Uri("https://sarif-post/example.com");
var httpMock = new HttpMockHelper();
httpMock.Mock(HttpMockHelper.CreateBadRequestResponse());
HttpResponseMessage response =
await SarifLog.Post(postUri,
CreateSarifLogStream(),
new HttpClientWrapper(httpMock));
Assert.Throws<HttpRequestException>(() =>
{
response.EnsureSuccessStatusCode();
});
}
[Fact]
public async Task SarifLog_Post_OkRequestResponseFromStream()
{
var postUri = new Uri("https://sarif-post/example.com");
var httpMock = new HttpMockHelper();
httpMock.Mock(HttpMockHelper.CreateOKResponse());
try
{
await SarifLog.Post(postUri,
CreateSarifLogStream(),
new HttpClientWrapper(httpMock));
}
catch (Exception ex)
{
Assert.True(false, $"Unhandled exception: {ex}");
}
}
[Fact]
public async Task SarifLog_Post_OkRequestResponseFromFilePath()
{
var postUri = new Uri("https://sarif-post/example.com");
var httpMock = new HttpMockHelper();
string filePath = "SomeFile.txt";
var fileSystem = new Mock<IFileSystem>();
fileSystem
.Setup(f => f.FileExists(It.IsAny<string>()))
.Returns(true);
fileSystem
.Setup(f => f.FileOpenRead(It.IsAny<string>()))
.Returns(CreateSarifLogStream());
httpMock.Mock(HttpMockHelper.CreateOKResponse());
try
{
await SarifLog.Post(postUri,
filePath,
fileSystem.Object,
new HttpClientWrapper(httpMock));
}
catch (Exception ex)
{
Assert.True(false, $"Unhandled exception: {ex}");
}
httpMock.Clear();
}
private Stream CreateSarifLogStream()
{
var memoryStream = new MemoryStream();
new SarifLog().Save(memoryStream);
memoryStream.Position = 0;
return memoryStream;
}
private Stream CreateSarifLogStreamWithResult()
{
var memoryStream = new MemoryStream();
var sarifLog = new SarifLog();
var result = new Result() { Message = new Message() { Text = "A sample result message." } };
var run = new Run();
run.Results = new Result[] { result };
sarifLog.Runs = new Run[] { run };
sarifLog.Save(memoryStream);
memoryStream.Position = 0;
return memoryStream;
}
private Stream CreateSarifLogStreamWithToolConfigurationNotifications(FailureLevel level)
{
var memoryStream = new MemoryStream();
var sarifLog = new SarifLog();
var run = new Run();
run.Invocations = new Invocation[] { new Invocation()
{ ToolConfigurationNotifications = new Notification[] { new Notification() { Level = level } } } };
sarifLog.Runs = new Run[] { run };
sarifLog.Save(memoryStream);
memoryStream.Position = 0;
return memoryStream;
}
private Stream CreateSarifLogStreamWithToolExecutionNotifications(FailureLevel level)
{
var memoryStream = new MemoryStream();
var sarifLog = new SarifLog();
var run = new Run();
run.Invocations = new Invocation[] { new Invocation()
{ ToolExecutionNotifications = new Notification[] { new Notification() { Level = level } } } };
sarifLog.Runs = new Run[] { run };
sarifLog.Save(memoryStream);
memoryStream.Position = 0;
return memoryStream;
}
private Run SerializeAndDeserialize(Run run)
{
return JsonConvert.DeserializeObject<Run>(JsonConvert.SerializeObject(run));
}
}
}