Skip to content

Commit cba140c

Browse files
committed
added example of harvesting validation errors with traverse
1 parent 81c8baf commit cba140c

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

Examples/Chapter13/ValidationStrategies.cs

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ public static partial class ValidationStrategies
1212
{
1313
// runs all validators, accumulating all validation errors
1414
public static Validator<T> HarvestErrorsTr<T>
15-
(IEnumerable<Validator<T>> validators)
15+
(params Validator<T>[] validators)
1616
=> t
1717
=> validators
1818
.Traverse(validate => validate(t))
@@ -21,29 +21,46 @@ public static Validator<T> HarvestErrorsTr<T>
2121

2222
public static partial class ValidationStrategiesTest
2323
{
24+
static Validator<string> ShouldBeLowerCase
25+
=> s
26+
=> (s == s.ToLower()) ? Valid(s) : Error($"{s} should be lower case");
27+
28+
static Validator<string> ShouldBeOfLength(int n)
29+
=> s
30+
=> (s.Length == n) ? Valid(s) : Error($"{s} should be of length {n}");
31+
32+
static Validator<string> ValidateCountryCode
33+
= HarvestErrorsTr(ShouldBeLowerCase, ShouldBeOfLength(2));
34+
35+
[TestCase("us", ExpectedResult = "Valid(us)")]
36+
[TestCase("US", ExpectedResult = "Invalid([US should be lower case])")]
37+
[TestCase("USA", ExpectedResult = "Invalid([USA should be lower case, USA should be of length 2])")]
38+
public static string TestCountryCodeValidation(string s)
39+
=> ValidateCountryCode(s).ToString();
40+
2441
public class HarvestErrors_WithTraverse_Test
2542
{
2643
[Test]
2744
public void WhenAllValidatorsSucceed_ThenSucceed() => Assert.AreEqual(
28-
actual: HarvestErrorsTr(List(Success, Success))(1),
45+
actual: HarvestErrorsTr(Success, Success)(1),
2946
expected: Valid(1)
3047
);
3148

3249
[Test]
3350
public void WhenNoValidators_ThenSucceed() => Assert.AreEqual(
34-
actual: HarvestErrorsTr(List<Validator<int>>())(1),
51+
actual: HarvestErrorsTr<int>()(1),
3552
expected: Valid(1)
3653
);
3754

3855
[Test]
3956
public void WhenOneValidatorFails_ThenFail() =>
40-
HarvestErrorsTr(List(Success, Failure))(1).Match(
57+
HarvestErrorsTr(Success, Failure)(1).Match(
4158
Valid: (_) => Assert.Fail(),
4259
Invalid: (errs) => Assert.AreEqual(1, errs.Count()));
4360

4461
[Test]
4562
public void WhenSeveralValidatorsFail_ThenFail() =>
46-
HarvestErrorsTr(List(Success, Failure, Failure, Success))(1).Match(
63+
HarvestErrorsTr(Success, Failure, Failure, Success)(1).Match(
4764
Valid: (_) => Assert.Fail(),
4865
Invalid: (errs) => Assert.AreEqual(2, errs.Count())); // all errors are returned
4966
}

0 commit comments

Comments
 (0)