forked from OpenTabletDriver/OpenTabletDriver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConfigurationTest.cs
469 lines (397 loc) · 16.8 KB
/
ConfigurationTest.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Schema.Generation;
using OpenTabletDriver.Components;
using OpenTabletDriver.Tablet;
using Xunit;
using Xunit.Abstractions;
namespace OpenTabletDriver.Tests
{
public class ConfigurationTest
{
private readonly ITestOutputHelper _testOutputHelper;
public ConfigurationTest(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}
[Fact]
public void Configurations_Have_ExistentParsers()
{
var serviceProvider = Utility.GetServices().BuildServiceProvider();
var parserProvider = serviceProvider.GetRequiredService<IReportParserProvider>();
var configurationProvider = serviceProvider.GetRequiredService<IDeviceConfigurationProvider>();
var parsers = from configuration in configurationProvider.TabletConfigurations
from identifier in configuration.DigitizerIdentifiers.Concat(configuration.AuxiliaryDeviceIdentifiers)
orderby identifier.ReportParser
select identifier.ReportParser;
var failed = false;
foreach (var parserType in parsers.Distinct())
{
try
{
var parser = parserProvider.GetReportParser(parserType);
_testOutputHelper.WriteLine(parser.ToString());
}
catch
{
_testOutputHelper.WriteLine($"Unable to find report parser '{parserType}'");
failed = true;
}
}
Assert.False(failed);
}
[Fact]
public void Configurations_DeviceIdentifier_Equality_SelfTest()
{
var identifier = new DeviceIdentifier
{
VendorID = 1,
ProductID = 1,
DeviceStrings = new Dictionary<byte, string>
{
[1] = "Test"
},
InputReportLength = 1,
OutputReportLength = 1
};
var equality = IsEqual(identifier, identifier);
Assert.True(equality);
}
[Fact]
public void Configurations_DeviceIdentifier_Equality_NullInput_SelfTest()
{
var identifier = new DeviceIdentifier
{
VendorID = 1,
ProductID = 1,
InputReportLength = 1,
OutputReportLength = 1
};
var otherIdentifier = new DeviceIdentifier
{
VendorID = 1,
ProductID = 1,
InputReportLength = null,
OutputReportLength = 1
};
var equality = IsEqual(identifier, otherIdentifier);
Assert.True(equality);
}
[Fact]
public void Configurations_DeviceIdentifier_Equality_NullOutput_SelfTest()
{
var identifier = new DeviceIdentifier
{
VendorID = 1,
ProductID = 1,
InputReportLength = 1,
OutputReportLength = 1
};
var otherIdentifier = new DeviceIdentifier
{
VendorID = 1,
ProductID = 1,
InputReportLength = 1,
OutputReportLength = null
};
var equality = IsEqual(identifier, otherIdentifier);
Assert.True(equality);
}
[Fact]
public void Configurations_DeviceIdentifier_Equality_DeviceStrings_SelfTest()
{
// both no device strings
var identifier = new DeviceIdentifier
{
VendorID = 1,
ProductID = 1,
InputReportLength = 1,
OutputReportLength = 1
};
var otherIdentifier = new DeviceIdentifier
{
VendorID = 1,
ProductID = 1,
InputReportLength = 1,
OutputReportLength = 1
};
var equality = IsEqual(identifier, otherIdentifier);
Assert.True(equality);
// both have the same device strings
identifier = new DeviceIdentifier
{
VendorID = 1,
ProductID = 1,
DeviceStrings = new Dictionary<byte, string>
{
[1] = "Test"
},
InputReportLength = 1,
OutputReportLength = 1
};
otherIdentifier = new DeviceIdentifier
{
VendorID = 1,
ProductID = 1,
DeviceStrings = new Dictionary<byte, string>
{
[1] = "Test"
},
InputReportLength = 1,
OutputReportLength = 1
};
equality = IsEqual(identifier, otherIdentifier);
Assert.True(equality);
// one of them has no device strings
identifier = new DeviceIdentifier
{
VendorID = 1,
ProductID = 1,
DeviceStrings = new Dictionary<byte, string>
{
},
InputReportLength = 1,
OutputReportLength = 1
};
otherIdentifier = new DeviceIdentifier
{
VendorID = 1,
ProductID = 1,
DeviceStrings = new Dictionary<byte, string>
{
[1] = "Test"
},
InputReportLength = 1,
OutputReportLength = 1
};
equality = IsEqual(identifier, otherIdentifier);
Assert.True(equality);
}
[Fact]
public void Configurations_DeviceIdentifier_NonEquality_DeviceStrings_SelfTest()
{
var identifier = new DeviceIdentifier
{
VendorID = 1,
ProductID = 1,
DeviceStrings = new Dictionary<byte, string>
{
[1] = "Test1"
},
InputReportLength = 1,
OutputReportLength = 1
};
var otherIdentifier = new DeviceIdentifier
{
VendorID = 1,
ProductID = 1,
DeviceStrings = new Dictionary<byte, string>
{
[1] = "Test",
},
InputReportLength = 1,
OutputReportLength = 1
};
var equality = IsEqual(identifier, otherIdentifier);
Assert.False(equality);
}
[Fact]
public void Configurations_DeviceIdentifier_IsNotConflicting()
{
var configurationProvider = Utility.GetServices()
.BuildServiceProvider()
.GetRequiredService<IDeviceConfigurationProvider>();
var digitizerIdentificationContexts = from config in configurationProvider.TabletConfigurations
from identifier in config.DigitizerIdentifiers.Select((d, i) => new { DeviceIdentifier = d, Index = i })
select new IdentificationContext(config, identifier.DeviceIdentifier, IdentifierType.Digitizer, identifier.Index);
var auxIdentificationContexts = from config in configurationProvider.TabletConfigurations
from identifier in config.AuxiliaryDeviceIdentifiers.Select((d, i) => new { DeviceIdentifier = d, Index = i })
select new IdentificationContext(config, identifier.DeviceIdentifier, IdentifierType.Auxiliary, identifier.Index);
var identificationContexts = digitizerIdentificationContexts.Concat(auxIdentificationContexts);
// group similar identifiers
var groups = new Dictionary<IdentificationContext, List<IdentificationContext>>(IdentificationContextComparer.Default);
foreach (var identificationContext in identificationContexts)
{
ref var group = ref CollectionsMarshal.GetValueRefOrAddDefault(groups, identificationContext, out var exists);
if (group is not null)
{
AssertGroup(group, identificationContext);
group.Add(identificationContext);
}
else
{
group = new List<IdentificationContext> { identificationContext };
}
}
static void AssertGroup(List<IdentificationContext> identificationContexts, IdentificationContext identificationContext)
{
foreach (var otherIdentificationContext in identificationContexts)
{
AssertInequal(identificationContext, otherIdentificationContext);
}
}
}
private static readonly string ConfigurationProjectDir = Path.GetFullPath(Path.Join("../../../..", "OpenTabletDriver.Configurations"));
private static readonly string ConfigurationDir = Path.Join(ConfigurationProjectDir, "Configurations");
private static readonly IEnumerable<(string, string)> ConfigFiles = Directory.EnumerateFiles(ConfigurationDir, "*.json", SearchOption.AllDirectories)
.Select(f => (Path.GetRelativePath(ConfigurationDir, f), File.ReadAllText(f)));
[Fact]
public void Configurations_Verify_Configs_With_Schema()
{
var gen = new JSchemaGenerator();
var schema = gen.Generate(typeof(TabletConfiguration));
DisallowAdditionalItemsAndProperties(schema);
var failed = false;
foreach (var (tabletFilename, tabletConfigString) in ConfigFiles)
{
var tabletConfig = JObject.Parse(tabletConfigString);
if (tabletConfig.IsValid(schema, out IList<string> errors)) continue;
_testOutputHelper.WriteLine($"Tablet Configuration {tabletFilename} did not match schema:\r\n{string.Join("\r\n", errors)}\r\n");
failed = true;
}
Assert.False(failed);
}
/// <summary>
/// Ensures that configuration formatting/linting matches expectations, which are:
/// - 2 space indentation
/// - Newline at end of file
/// - Consistent newline format
/// </summary>
[Fact]
public void Configurations_Are_Linted()
{
const int maxLinesToOutput = 3;
var serializer = new JsonSerializer();
var failedFiles = 0;
var ourJsonSb = new StringBuilder();
using var strw = new StringWriter(ourJsonSb);
using var jtw = new JsonTextWriter(strw);
jtw.Formatting = Formatting.Indented;
jtw.Indentation = 2;
foreach (var (tabletFilename, theirJson) in ConfigFiles)
{
ourJsonSb.Clear();
var ourJsonObj = JsonConvert.DeserializeObject<TabletConfiguration>(theirJson);
serializer.Serialize(jtw, ourJsonObj);
ourJsonSb.AppendLine(); // otherwise we won't have an EOL at EOF
var ourJson = ourJsonSb.ToString();
var failedLines = DoesJsonMatch(ourJson, theirJson);
if (failedLines.Any() || !string.Equals(theirJson, ourJson)) // second check ensures EOL markers are equivalent
{
failedFiles++;
_testOutputHelper.WriteLine(
$"- Tablet Configuration '{tabletFilename}' lint check failed with the following errors:");
foreach (var (line, error) in failedLines.Take(maxLinesToOutput))
_testOutputHelper.WriteLine($" Line {line}: {error}");
if (failedLines.Count > maxLinesToOutput)
_testOutputHelper.WriteLine($" Truncated an additional {failedLines.Count - maxLinesToOutput} mismatching lines - wrong indent?");
else if (failedLines.Count == 0)
_testOutputHelper.WriteLine(" Generic mismatch (line endings?)");
}
}
Assert.Equal(0, failedFiles);
}
private static IList<(int, string)> DoesJsonMatch(string ourJson, string theirJson)
{
int line = 0;
var rv = new List<(int, string)>();
using var ourSr = new StringReader(ourJson);
using var theirSr = new StringReader(theirJson);
while (true)
{
var ourLine = ourSr.ReadLine();
var theirLine = theirSr.ReadLine();
line++;
if (ourLine == null && theirLine == null)
break; // success for file
var ourLineOutput = ourLine ?? "EOF";
var theirLineOutput = theirLine ?? "EOF";
if (ourLine == null || theirLine == null || !string.Equals(ourLine, theirLine))
rv.Add((line, $"Expected '{ourLineOutput}' got '{theirLineOutput}'"));
if (ourLine == null || theirLine == null)
break;
}
return rv;
}
private static void DisallowAdditionalItemsAndProperties(JSchema schema)
{
schema.AllowAdditionalItems = false;
schema.AllowAdditionalProperties = false;
schema.AllowUnevaluatedItems = false;
schema.AllowUnevaluatedProperties = false;
foreach (var child in schema.Properties)
{
if (child.Key == nameof(TabletConfiguration.Attributes)) continue;
DisallowAdditionalItemsAndProperties(child.Value);
}
}
private static void AssertInequal(IdentificationContext a, IdentificationContext b)
{
if (IsEqual(a.Identifier, b.Identifier))
{
var message = string.Format("'{0}' {1} (index: {2}) conflicts with '{3}' {4} (index: {5})",
a.TabletConfiguration.Name,
a.IdentifierType,
a.IdentifierIndex,
b.TabletConfiguration.Name,
b.IdentifierType,
b.IdentifierIndex);
throw new Exception(message);
}
}
private static bool IsEqual(DeviceIdentifier a, DeviceIdentifier b)
{
var pidMatch = a.VendorID == b.VendorID && a.ProductID == b.ProductID;
var inputMatch = a.InputReportLength == b.InputReportLength || a.InputReportLength is null || b.InputReportLength is null;
var outputMatch = a.OutputReportLength == b.OutputReportLength || a.OutputReportLength is null || b.OutputReportLength is null;
if (pidMatch && inputMatch && outputMatch)
{
if (a.DeviceStrings.Count == 0 || b.DeviceStrings.Count == 0)
return true;
var (longer, shorter) = a.DeviceStrings.Count > b.DeviceStrings.Count ? (a, b) : (b, a);
return shorter.DeviceStrings.All(kv => longer.DeviceStrings.TryGetValue(kv.Key, out var otherValue) && otherValue == kv.Value);
}
return false;
}
public enum IdentifierType
{
Digitizer,
Auxiliary
}
public record IdentificationContext(
TabletConfiguration TabletConfiguration,
DeviceIdentifier Identifier,
IdentifierType IdentifierType,
int IdentifierIndex
);
private class IdentificationContextComparer : IEqualityComparer<IdentificationContext>
{
public static readonly IdentificationContextComparer Default = new IdentificationContextComparer();
public bool Equals(IdentificationContext? x, IdentificationContext? y)
{
if (x is null && y is null)
return true;
if (x is null || y is null)
return false;
return IsEqual(x.Identifier, y.Identifier);
}
public int GetHashCode([DisallowNull] IdentificationContext obj)
{
return HashCode.Combine(
obj.Identifier.VendorID,
obj.Identifier.ProductID,
obj.Identifier.InputReportLength);
}
}
}
}