Skip to content

Commit 5c4eafa

Browse files
authored
Merge pull request #779 from beppemarazzi/bug/validateOptionDefault
fix: default values for option arguments was not validated
2 parents ee740ce + 4f3bbba commit 5c4eafa

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

src/System.CommandLine.Tests/OptionTests.cs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
using System.CommandLine.Invocation;
55
using System.CommandLine.Parsing;
6+
using System.Linq;
67
using FluentAssertions;
78
using Xunit;
89
using Xunit.Abstractions;
@@ -311,6 +312,38 @@ public void Option_T_default_value_can_be_set()
311312
.Be(123);
312313
}
313314

315+
[Fact]
316+
public void Option_T_default_value_is_validated()
317+
{
318+
var arg = new Argument<int>(() => 123);
319+
arg.AddValidator( symbol =>
320+
symbol.Tokens
321+
.Select(t => t.Value)
322+
.Where(v => v == "123")
323+
.Select(x => "ERR")
324+
.FirstOrDefault());
325+
326+
var option = new Option("-x")
327+
{
328+
Argument = arg
329+
};
330+
331+
option
332+
.Parse("-x 123")
333+
.Errors
334+
.Select(e => e.Message)
335+
.Should()
336+
.BeEquivalentTo(new[] { "ERR" });
337+
338+
option
339+
.Parse("")
340+
.Errors
341+
.Select(e => e.Message)
342+
.Should()
343+
.BeEquivalentTo(new[] { "ERR" });
344+
345+
}
346+
314347
protected override Symbol CreateSymbol(string name) => new Option(name);
315348
}
316349
}

src/System.CommandLine/Parsing/ParseResultVisitor.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -327,13 +327,14 @@ private void PopulateDefaultValues()
327327
optionResult.GetDefaultValueFor(option.Argument),
328328
TokenType.Argument);
329329

330-
optionResult.Children.Add(
331-
new ArgumentResult(
330+
var childArgumentResult = new ArgumentResult(
332331
option.Argument,
333-
optionResult));
332+
optionResult);
334333

334+
optionResult.Children.Add(childArgumentResult);
335335
commandResult.Children.Add(optionResult);
336336
optionResult.AddToken(token);
337+
childArgumentResult.AddToken(token);
337338
_rootCommandResult.AddToSymbolMap(optionResult);
338339

339340
break;

0 commit comments

Comments
 (0)