Skip to content

Commit

Permalink
fix: treat null as 'true' by default when parsing Nullable<bool> type…
Browse files Browse the repository at this point in the history
…s on command options (#397)
  • Loading branch information
TheConstructor committed Nov 7, 2020
1 parent e621724 commit 4f686fe
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ internal static class StockValueParsers
switch (value)
{
case null:
return default;
return true;
case "T":
case "t":
return true;
Expand Down
48 changes: 46 additions & 2 deletions test/CommandLineUtils.Tests/ValueParserProviderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using Xunit;

namespace McMaster.Extensions.CommandLineUtils.Tests
{
using System.Reflection;

public class ValueParserProviderTests
{
public enum Color
Expand Down Expand Up @@ -45,6 +44,12 @@ private class Program
[Option("--bool-opt", CommandOptionType.SingleValue)]
public bool? BoolOpt { get; }

[Option("--bool-with-optional-value", CommandOptionType.SingleOrNoValue)]
public bool BoolWithOptionalValue { get; }

[Option("--bool-opt-with-optional-value", CommandOptionType.SingleOrNoValue)]
public (bool, bool?) BoolOptWithOptionalValue { get; }

[Option("--int32-opt")]
public int? Int32Opt { get; }

Expand Down Expand Up @@ -300,6 +305,45 @@ public void ParsesNullableBool(string arg, bool? result)
Assert.Equal(result, parsed.BoolOpt);
}

[Theory]
[InlineData("true", true)]
[InlineData("True", true)]
[InlineData("False", false)]
[InlineData("false", false)]
public void ParsesBoolWithOptionalValue(string arg, bool result)
{
var parsed = CommandLineParser.ParseArgs<Program>($"--bool-with-optional-value:{arg}");
Assert.Equal(result, parsed.BoolWithOptionalValue);
}

[Fact]
public void ParsesBoolWithoutOptionalValue()
{
var parsed = CommandLineParser.ParseArgs<Program>("--bool-with-optional-value");
Assert.True(parsed.BoolWithOptionalValue);
}

[Theory]
[InlineData("", null)]
[InlineData("true", true)]
[InlineData("True", true)]
[InlineData("False", false)]
[InlineData("false", false)]
public void ParsesNullableBoolWithOptionalValue(string arg, bool? result)
{
var parsed = CommandLineParser.ParseArgs<Program>($"--bool-opt-with-optional-value:{arg}");
Assert.True(parsed.BoolOptWithOptionalValue.Item1);
Assert.Equal(result, parsed.BoolOptWithOptionalValue.Item2);
}

[Fact]
public void ParsesNullableBoolWithoutOptionalValue()
{
var parsed = CommandLineParser.ParseArgs<Program>("--bool-opt-with-optional-value");
Assert.True(parsed.BoolOptWithOptionalValue.Item1);
Assert.Null(parsed.BoolOptWithOptionalValue.Item2);
}

[Theory]
[InlineData("4294967295", uint.MaxValue)]
[InlineData("1", 1)]
Expand Down

0 comments on commit 4f686fe

Please sign in to comment.