-
Notifications
You must be signed in to change notification settings - Fork 262
Expand file tree
/
Copy pathValueParserProviderCustomTests.cs
More file actions
409 lines (329 loc) · 14.7 KB
/
Copy pathValueParserProviderCustomTests.cs
File metadata and controls
409 lines (329 loc) · 14.7 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
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
// Copyright (c) Nate McMaster.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using McMaster.Extensions.CommandLineUtils.Abstractions;
using Xunit;
namespace McMaster.Extensions.CommandLineUtils.Tests
{
public class ValueParserProviderCustomTests
{
internal class MyDateTimeOffsetParser : IValueParser
{
public Type TargetType { get; } = typeof(DateTimeOffset);
public object? Parse(string? argName, string? value, CultureInfo culture)
{
if (!DateTimeOffset.TryParse(value, culture, DateTimeStyles.None, out var result))
{
throw new FormatException($"Invalid value specified for {argName}. '{value}' is not a valid date time (with offset)");
}
return result;
}
}
// scenario: specialized domain value in the format of 1=123.456=abc
private class ComplexTupleParser : IValueParser
{
public Type TargetType { get; } = typeof(ValueTuple<int, double, string>?);
public object? Parse(string? argName, string? value, CultureInfo culture)
{
if (string.IsNullOrWhiteSpace(value))
{
return default(ValueTuple<int, double, string>?);
}
var fragments = value!.Split('=');
try
{
var item1 = double.Parse(fragments[0], CultureInfo.InvariantCulture);
var item2 = double.Parse(fragments[1], CultureInfo.InvariantCulture);
var item3 = fragments[2];
return (ValueTuple<int, double, string>?)(item1, item2, item3);
}
catch (Exception ex)
{
throw new FormatException(
$"Invalid value specified for {argName}. '{value} is not a valid time span (with offset)",
ex);
}
}
}
// scenario: for some reason I insist on using thin spaces instead of commas for the thousands delimitters
private class MyDoubleParser : IValueParser
{
// This is a trivial example but rooted in a real standard
// https://en.wikipedia.org/wiki/ISO_31-0#Numbers
private readonly NumberFormatInfo _iso80000NumberFormatInfo;
public MyDoubleParser()
{
this._iso80000NumberFormatInfo = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
// a thin space
this._iso80000NumberFormatInfo.NumberGroupSeparator = "\u2009";
}
public Type TargetType { get; } = typeof(double);
public object? Parse(string? argName, string? value, CultureInfo culture)
{
if (!double.TryParse(value, NumberStyles.Number, _iso80000NumberFormatInfo, out var result))
{
throw new FormatException($"Invalid value specified for {argName}. '{value}' is not a valid ISO80000 double");
}
return result;
}
}
private class CustomParserProgram
{
[Argument(0)]
public DateTimeOffset DateTimeOffset { get; }
[Argument(1)]
public double Double { get; }
[Argument(2)]
public ValueTuple<int, double, string>? ComplexValue { get; }
}
[Fact]
public void CustomParsersCanBeAdded()
{
var expectedDate = new DateTimeOffset(2018, 02, 16, 21, 30, 33, 45, TimeSpan.FromHours(10));
var expectedDouble = 123456.789;
ValueTuple<int, double, string>? expectedComplexValue = null;
var app = new CommandLineApplication<CustomParserProgram>();
app.ValueParsers.Add(new ComplexTupleParser());
app.ValueParsers.AddOrReplace(new MyDateTimeOffsetParser());
app.ValueParsers.AddOrReplace(new MyDoubleParser());
app.Conventions.UseAttributes();
// We're omitting the third argument to test nullable-ness. The ComplexValue type (with a value) is tested
// in the next test
var args = new[] { expectedDate.ToString("O"), "123 456.789" };
app.Parse(args);
var model = app.Model;
Assert.Equal(expectedDate, model.DateTimeOffset);
Assert.Equal(expectedDouble, model.Double);
Assert.Equal(expectedComplexValue, model.ComplexValue);
}
private class DateParserProgram
{
[Argument(0)]
public DateTimeOffset DateTimeOffset { get; }
}
[Theory]
[InlineData(nameof(DateParserProgram.DateTimeOffset), "03/30/2017 3:03:03 +04:00", "en-US")]
[InlineData(nameof(DateParserProgram.DateTimeOffset), "2017年03月30日 3:03:03 +04:00", "zh-CN")]
public void DefaultCultureCanBeChanged(string property, string test, string culture)
{
var expected = new DateTimeOffset(2017, 3, 30, 3, 3, 3, TimeSpan.FromHours(4));
var cultureInfo = new CultureInfo(culture);
var app = new CommandLineApplication<DateParserProgram>();
app.ValueParsers.ParseCulture = cultureInfo;
app.ValueParsers.AddOrReplace(new MyDateTimeOffsetParser());
app.Conventions.UseAttributes();
app.Parse(test);
var actual = Assert.IsAssignableFrom<DateTimeOffset>(typeof(DateParserProgram).GetProperty(property)?.GetMethod?.Invoke(app.Model, null));
Assert.Equal(expected, actual);
}
private class CustomParserProgramOptions
{
[Option]
public ValueTuple<int, double, string>? ComplexValue { get; }
}
[Fact]
public void CustomParsersSupportComplexGenericTypes()
{
ValueTuple<int, double, string>? expectedComplexValue = (1, 123.456, "abc");
var app = new CommandLineApplication<CustomParserProgramOptions>();
app.ValueParsers.Add(new ComplexTupleParser());
app.Conventions.UseAttributes();
var args = $"-c=1=123.456=abc";
app.Parse(args);
var model = app.Model;
Assert.Equal(expectedComplexValue, model.ComplexValue);
}
[Fact]
public void CustomParsersAreAutomaticallySingleValues()
{
var app = new CommandLineApplication<CustomParserProgram>();
app.ValueParsers.Add(new ComplexTupleParser());
app.ValueParsers.AddOrReplace(new MyDateTimeOffsetParser());
app.ValueParsers.AddOrReplace(new MyDoubleParser());
var optionMapper = CommandOptionTypeMapper.Default;
Assert.Equal(
CommandOptionType.SingleValue,
optionMapper.GetOptionType(typeof(DateTimeOffset), app.ValueParsers));
Assert.Equal(
CommandOptionType.SingleValue,
optionMapper.GetOptionType(typeof(ValueTuple<int, double, string>?), app.ValueParsers));
Assert.Equal(
CommandOptionType.SingleValue,
optionMapper.GetOptionType(typeof(double), app.ValueParsers));
}
[Subcommand(typeof(CustomParserProgramAttributesSubCommand))]
private class CustomParserProgramAttributes
{
[Option("-a")]
public DateTimeOffset MainDate { get; }
}
[Command("subcommand")]
private class CustomParserProgramAttributesSubCommand
{
[Option("-b")]
public DateTimeOffset SubDate { get; }
public Task<int> OnExecute(CommandLineApplication app)
{
return Task.FromResult(1);
}
}
[Fact]
public void CustomParsersAreAvailableToSubCommands()
{
var expectedDate = new DateTimeOffset(2018, 02, 16, 21, 30, 33, 45, TimeSpan.FromHours(10));
var app = new CommandLineApplication<CustomParserProgramAttributes>();
app.ValueParsers.AddOrReplace(new MyDateTimeOffsetParser());
app.Conventions.UseDefaultConventions();
var args = new[] { "-a", expectedDate.ToString("O"), "subcommand", "-b", expectedDate.AddSeconds(123456).ToString("O") };
var result = app.Execute(args);
Assert.Equal(1, result);
Assert.Equal(expectedDate, app.Model.MainDate);
Assert.Equal(expectedDate.AddSeconds(123456), app.Commands.OfType<CommandLineApplication<CustomParserProgramAttributesSubCommand>>().Single().Model.SubDate);
}
[Fact]
public void CustomParsersAreAvailableToBuilderSubCommands()
{
var expectedDate = new DateTimeOffset(2018, 02, 16, 21, 30, 33, 45, TimeSpan.FromHours(10));
DateTimeOffset actualMainDate = default;
DateTimeOffset actualSubDate = default;
var app = new CommandLineApplication();
app.ValueParsers.AddOrReplace(new MyDateTimeOffsetParser());
var mainDate = app.Option<DateTimeOffset>("-a", "The main date to parse", CommandOptionType.SingleValue);
app.Command("subcommand", configCmd =>
{
var subDate = configCmd.Option<DateTimeOffset>("-b", "A date for the sub command", CommandOptionType.SingleValue);
configCmd.OnExecute(() =>
{
actualMainDate = mainDate.ParsedValue;
actualSubDate = subDate.ParsedValue;
});
});
var args = new[] { "-a", expectedDate.ToString("O"), "subcommand", "-b", expectedDate.AddSeconds(123456).ToString("O") };
app.Execute(args);
Assert.Equal(expectedDate, actualMainDate);
Assert.Equal(expectedDate.AddSeconds(123456), actualSubDate);
}
private class BadValueParser : IValueParser
{
#nullable disable // Intentionally testing compatibility
public Type TargetType { get; }
#nullable enable
public object? Parse(string? argName, string? value, CultureInfo culture)
{
throw new NotImplementedException();
}
}
[Fact]
public void ThrowsIfNoType()
{
var ex = Assert.Throws<ArgumentNullException>(
() =>
{
var app = new CommandLineApplication<CustomParserProgram>();
app.ValueParsers.Add(new BadValueParser());
});
Assert.Contains("TargetType", ex.Message);
}
[Fact]
public void ThrowsIfAlreadyRegistered()
{
var ex = Assert.Throws<ArgumentException>(
() =>
{
var app = new CommandLineApplication<CustomParserProgram>();
app.ValueParsers.Add(new ComplexTupleParser());
app.ValueParsers.Add(new ComplexTupleParser());
});
Assert.Contains(
"Value parser provider for type 'System.ValueTuple`3[System.Int32,System.Double,System.String]' already exists.",
ex.Message);
}
[Fact]
public void AddThrowsIfNullParser()
{
var ex = Assert.Throws<ArgumentNullException>(
() =>
{
var app = new CommandLineApplication<CustomParserProgram>();
app.ValueParsers.Add(null!);
});
Assert.Contains("parser", ex.Message);
}
[Fact]
public void AddRangeThrowsIfNullCollection()
{
var ex = Assert.Throws<ArgumentNullException>(
() =>
{
var app = new CommandLineApplication<CustomParserProgram>();
app.ValueParsers.AddRange(null!);
});
Assert.Contains("parsers", ex.Message);
}
[Fact]
public void AddOrReplaceThrowsIfNullparser()
{
var ex = Assert.Throws<ArgumentNullException>(
() =>
{
var app = new CommandLineApplication<CustomParserProgram>();
app.ValueParsers.AddOrReplace(null!);
});
Assert.Contains("parser", ex.Message);
}
private class CustomTimeSpanParser : IValueParser<TimeSpan>
{
public Type TargetType => typeof(TimeSpan);
public TimeSpan Parse(string? argName, string? value, CultureInfo culture)
{
if (value != null && value.EndsWith("s"))
{
var seconds = int.Parse(value.Substring(0, value.Length - 1), culture);
return TimeSpan.FromSeconds(seconds);
}
return TimeSpan.Parse(value!, culture);
}
object? IValueParser.Parse(string? argName, string? value, CultureInfo culture)
=> Parse(argName, value, culture);
}
private class NullableTimeSpanOptionProgram
{
[Option("--timeout", CommandOptionType.SingleValue)]
public TimeSpan? Timeout { get; set; }
}
private class NonNullableTimeSpanOptionProgram
{
[Option("--timeout", CommandOptionType.SingleValue)]
public TimeSpan Timeout { get; set; }
}
[Fact]
public void CustomParserWorksForNullableBuiltInType()
{
var app = new CommandLineApplication<NullableTimeSpanOptionProgram>();
app.ValueParsers.AddOrReplace(new CustomTimeSpanParser());
app.Conventions.UseDefaultConventions();
app.Parse("--timeout", "15s");
Assert.Equal(TimeSpan.FromSeconds(15), app.Model.Timeout);
}
[Fact]
public void CustomParserWorksForNonNullableBuiltInType()
{
var app = new CommandLineApplication<NonNullableTimeSpanOptionProgram>();
app.ValueParsers.AddOrReplace(new CustomTimeSpanParser());
app.Conventions.UseDefaultConventions();
app.Parse("--timeout", "15s");
Assert.Equal(TimeSpan.FromSeconds(15), app.Model.Timeout);
}
[Fact]
public void NullableBuiltInTypeUsesDefaultParserWhenNoCustomParser()
{
var app = new CommandLineApplication<NullableTimeSpanOptionProgram>();
app.Conventions.UseDefaultConventions();
app.Parse("--timeout", "00:00:15");
Assert.Equal(TimeSpan.FromSeconds(15), app.Model.Timeout);
}
}
}