/
ForEachRuleTests.cs
701 lines (567 loc) · 23.3 KB
/
ForEachRuleTests.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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
#region License
// Copyright (c) .NET Foundation and contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
#endregion
namespace FluentValidation.Tests {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Internal;
using Validators;
using Xunit;
public class ForEachRuleTests {
private object _lock = new object();
private int _counter;
private Person _person;
public ForEachRuleTests() {
_counter = 0;
_person = new Person() {
Orders = new List<Order>() {
new Order { Amount = 5},
new Order { ProductName = "Foo"}
}
};
}
[Fact]
public void Executes_rule_for_each_item_in_collection() {
var validator = new TestValidator {
v => v.RuleForEach(x => x.NickNames).NotNull()
};
var person = new Person {
NickNames = new[] {null, "foo", null}
};
var result = validator.Validate(person);
result.Errors.Count.ShouldEqual(2);
}
[Fact]
public void Correctly_gets_collection_indices() {
var validator = new TestValidator {
v => v.RuleForEach(x => x.NickNames).NotNull()
};
var person = new Person {
NickNames = new[] {null, "foo", null}
};
var result = validator.Validate(person);
result.Errors[0].PropertyName.ShouldEqual("NickNames[0]");
result.Errors[1].PropertyName.ShouldEqual("NickNames[2]");
}
[Fact]
public void Overrides_indexer() {
var validator = new TestValidator {
v => v.RuleForEach(x => x.NickNames)
.OverrideIndexer((x, collection, element, index) => {
return "<" + index + ">";
})
.NotNull()
};
var person = new Person {
NickNames = new[] {null, "foo", null}
};
var result = validator.Validate(person);
result.Errors[0].PropertyName.ShouldEqual("NickNames<0>");
result.Errors[1].PropertyName.ShouldEqual("NickNames<2>");
}
[Fact]
public async Task Overrides_indexer_async() {
var validator = new TestValidator {
v => v.RuleForEach(x => x.NickNames)
.OverrideIndexer((x, collection, element, index) => {
return "<" + index + ">";
})
.MustAsync((x, elem, ct) => Task.FromResult(elem != null))
};
var person = new Person {
NickNames = new[] {null, "foo", null}
};
var result = await validator.ValidateAsync(person);
result.Errors[0].PropertyName.ShouldEqual("NickNames<0>");
result.Errors[1].PropertyName.ShouldEqual("NickNames<2>");
}
[Fact]
public async Task Executes_rule_for_each_item_in_collection_async() {
var validator = new TestValidator {
v => v.RuleForEach(x => x.NickNames).SetAsyncValidator(new MyAsyncNotNullValidator<Person,string>())
};
var person = new Person {
NickNames = new[] {null, "foo", null}
};
var result = await validator.ValidateAsync(person);
result.Errors.Count.ShouldEqual(2);
}
[Fact]
public async Task Correctly_gets_collection_indices_async() {
var validator = new TestValidator {
v => v.RuleForEach(x => x.NickNames).SetAsyncValidator(new MyAsyncNotNullValidator<Person,string>())
};
var person = new Person {
NickNames = new[] {null, "foo", null}
};
var result = await validator.ValidateAsync(person);
result.Errors[0].PropertyName.ShouldEqual("NickNames[0]");
result.Errors[1].PropertyName.ShouldEqual("NickNames[2]");
}
class request {
public Person person = null;
}
private class MyAsyncNotNullValidator<T,TProperty> : IAsyncPropertyValidator<T,TProperty> {
private IPropertyValidator<T, TProperty> _inner = new NotNullValidator<T, TProperty>();
public Task<bool> IsValidAsync(ValidationContext<T> context, TProperty value, CancellationToken cancellation) {
return Task.FromResult(_inner.IsValid(context, value));
}
public string Name => _inner.Name;
public string GetDefaultMessageTemplate(string errorCode) => _inner.GetDefaultMessageTemplate(errorCode);
}
[Fact]
public void Nested_collection_for_null_property_should_not_throw_null_reference() {
var validator = new InlineValidator<request>();
validator.When(r => r.person != null, () => { validator.RuleForEach(x => x.person.NickNames).NotNull(); });
var result = validator.Validate(new request());
result.Errors.Count.ShouldEqual(0);
}
[Fact]
public void Should_not_scramble_property_name_when_using_collection_validators_several_levels_deep() {
var v = new ApplicationViewModelValidator();
var result = v.Validate(new ApplicationViewModel());
result.Errors.Single().PropertyName.ShouldEqual("TradingExperience[0].Questions[0].SelectedAnswerID");
}
[Fact]
public async Task Should_not_scramble_property_name_when_using_collection_validators_several_levels_deep_with_ValidateAsync() {
var v = new ApplicationViewModelValidator();
var result = await v.ValidateAsync(new ApplicationViewModel());
result.Errors.Single().PropertyName.ShouldEqual("TradingExperience[0].Questions[0].SelectedAnswerID");
}
[Fact]
public void Uses_useful_error_message_when_used_on_non_property() {
var validator = new InlineValidator<Person>();
validator.RuleForEach(x => x.NickNames.AsEnumerable()).NotNull();
bool thrown = false;
try {
validator.Validate(new Person {NickNames = new string[] {null, null}});
}
catch (System.InvalidOperationException ex) {
thrown = true;
ex.Message.ShouldEqual("Could not infer property name for expression: x => x.NickNames.AsEnumerable(). Please explicitly specify a property name by calling OverridePropertyName as part of the rule chain. Eg: RuleForEach(x => x).NotNull().OverridePropertyName(\"MyProperty\")");
}
thrown.ShouldBeTrue();
}
[Fact]
public async Task RuleForEach_async_RunsTasksSynchronously() {
var validator = new InlineValidator<Person>();
var result = new List<bool>();
validator.RuleForEach(x => x.Children).MustAsync(async (person, token) =>
await ExclusiveDelay(1)
.ContinueWith(t => result.Add(t.Result), token)
.ContinueWith(t => true, token)
);
await validator.ValidateAsync(new Person() {
Children = new List<Person> {new Person(), new Person() }
});
Assert.NotEmpty(result);
Assert.All(result, Assert.True);
}
[Fact]
public void Can_use_cascade_with_RuleForEach() {
var validator = new InlineValidator<Person>();
#pragma warning disable 618
validator.RuleForEach(x => x.NickNames)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotNull()
.NotEqual("foo");
#pragma warning restore 618
var result = validator.Validate(new Person {NickNames = new string[] {null}});
result.Errors.Count.ShouldEqual(1);
}
[Fact]
public void Nested_conditions_Rule_For() {
var validator = new InlineValidator<request>();
validator.When(r => true, () => {
validator.When(r => r.person?.NickNames?.Any() == true, () => {
validator.RuleFor(r => r.person.NickNames)
.Must(nn => true)
.WithMessage("Failed RuleFor");
});
});
var result = validator.Validate(new request());
result.IsValid.ShouldBeTrue();
}
[Fact]
public void Nested_conditions_Rule_For_Each() {
var validator = new InlineValidator<request>();
validator.When(x => true, () => {
validator.When(r => r.person?.NickNames?.Any() == true, () => {
validator.RuleForEach(x => x.person.NickNames)
.Must(nn => true)
.WithMessage("Failed RuleForEach");
});
});
var result = validator.Validate(new request());
result.Errors.Count.ShouldEqual(0);
}
[Fact]
public void Regular_rules_can_drop_into_RuleForEach() {
var validator = new TestValidator();
validator.RuleFor(x => x.Children)
.Must(x => x.Count > 2).WithMessage("Foo")
.ForEach(forEachElement => {
forEachElement.NotNull().WithMessage("Bar");
});
var result = validator.Validate(new Person {Children = new List<Person> {null, null}});
result.Errors.Count.ShouldEqual(3);
result.Errors[0].ErrorMessage.ShouldEqual("Foo");
result.Errors[0].PropertyName.ShouldEqual("Children");
result.Errors[1].ErrorMessage.ShouldEqual("Bar");
result.Errors[1].PropertyName.ShouldEqual("Children[0]");
result.Errors[2].ErrorMessage.ShouldEqual("Bar");
result.Errors[2].PropertyName.ShouldEqual("Children[1]");
}
[Fact]
public void Resets_state_correctly_between_rules() {
var v = new InlineValidator<Person>();
v.RuleForEach(x => x.NickNames).NotNull();
v.RuleFor(x => x.Forename).NotNull();
// The ValidationContext is reinitialized for each item in the collection
// Specifically, the PropertyChain is reset and modified.
// After the collection has been validated, the PropertyChain should be reset to its original value.
// We can test this by checking the final output of the property names for subsequent rules after the RuleForEach.
var result = v.Validate(new Person() {NickNames = new[] {null, "Foo", null}, Forename = null});
result.Errors.Count.ShouldEqual(3);
result.Errors[0].PropertyName.ShouldEqual("NickNames[0]");
result.Errors[1].PropertyName.ShouldEqual("NickNames[2]");
result.Errors[2].PropertyName.ShouldEqual("Forename");
}
[Fact]
public async Task Resets_state_correctly_between_rules_async() {
var v = new InlineValidator<Person>();
v.RuleForEach(x => x.NickNames).NotNull();
v.RuleFor(x => x.Forename).NotNull();
// The ValidationContext is reinitialized for each item in the collection
// Specifically, the PropertyChain is reset and modified.
// After the collection has been validated, the PropertyChain should be reset to its original value.
// We can test this by checking the final output of the property names for subsequent rules after the RuleForEach.
var result = await v.ValidateAsync(new Person() {NickNames = new[] {null, "Foo", null}, Forename = null});
result.Errors.Count.ShouldEqual(3);
result.Errors[0].PropertyName.ShouldEqual("NickNames[0]");
result.Errors[1].PropertyName.ShouldEqual("NickNames[2]");
result.Errors[2].PropertyName.ShouldEqual("Forename");
}
public class ApplicationViewModel {
public List<ApplicationGroup> TradingExperience { get; set; } = new List<ApplicationGroup> {new ApplicationGroup()};
}
public class ApplicationGroup {
public List<Question> Questions = new List<Question> {new Question()};
}
public class Question {
public int SelectedAnswerID { get; set; }
}
public class ApplicationViewModelValidator : AbstractValidator<ApplicationViewModel> {
public ApplicationViewModelValidator() {
RuleForEach(x => x.TradingExperience)
.SetValidator(new AppropriatenessGroupViewModelValidator());
}
}
public class AppropriatenessGroupViewModelValidator : AbstractValidator<ApplicationGroup> {
public AppropriatenessGroupViewModelValidator() {
RuleForEach(m => m.Questions)
.SetValidator(new AppropriatenessQuestionViewModelValidator());
}
}
public class AppropriatenessQuestionViewModelValidator : AbstractValidator<Question> {
public AppropriatenessQuestionViewModelValidator() {
RuleFor(m => m.SelectedAnswerID)
.SetValidator(new AppropriatenessAnswerViewModelRequiredValidator<Question, int>());
;
}
}
public class AppropriatenessAnswerViewModelRequiredValidator<T,TProperty> : PropertyValidator<T,TProperty> {
public override string Name => "AppropriatenessAnswerViewModelRequiredValidator";
public override bool IsValid(ValidationContext<T> context, TProperty value) {
return false;
}
}
private async Task<bool> ExclusiveDelay(int milliseconds) {
lock (_lock) {
if (_counter != 0) return false;
_counter += 1;
}
await Task.Delay(milliseconds);
lock (_lock) {
_counter -= 1;
}
return true;
}
[Fact]
public void Validates_collection() {
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleForEach(x => x.Orders).SetValidator(new OrderValidator())
};
var results = validator.Validate(_person);
results.Errors.Count.ShouldEqual(3);
results.Errors[1].PropertyName.ShouldEqual("Orders[0].ProductName");
results.Errors[2].PropertyName.ShouldEqual("Orders[1].Amount");
}
[Fact]
public void Collection_should_be_explicitly_included_with_expression() {
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleForEach(x => x.Orders).SetValidator(new OrderValidator())
};
var results = validator.Validate(_person, v => v.IncludeProperties(x => x.Orders));
results.Errors.Count.ShouldEqual(2);
}
[Fact]
public void Collection_should_be_explicitly_included_with_string() {
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleForEach(x => x.Orders).SetValidator(new OrderValidator())
};
var results = validator.Validate(_person, v => v.IncludeProperties("Orders"));
results.Errors.Count.ShouldEqual(2);
}
[Fact]
public void Collection_should_be_excluded() {
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleForEach(x => x.Orders).SetValidator(new OrderValidator())
};
var results = validator.Validate(_person, v => v.IncludeProperties(x => x.Forename));
results.Errors.Count.ShouldEqual(0);
}
[Fact]
public void Condition_should_work_with_child_collection() {
var validator = new TestValidator() {
v => v.RuleForEach(x => x.Orders).SetValidator(new OrderValidator()).When(x => x.Orders.Count == 3 /*there are only 2*/)
};
var result = validator.Validate(_person);
result.IsValid.ShouldBeTrue();
}
[Fact]
public async Task Async_condition_should_work_with_child_collection() {
var validator = new TestValidator() {
v => v.RuleForEach(x => x.Orders).SetValidator(new OrderValidator()).WhenAsync( (x,c) => Task.FromResult(x.Orders.Count == 3) /*there are only 2*/)
};
var result = await validator.ValidateAsync(_person);
result.IsValid.ShouldBeTrue();
}
[Fact]
public void Skips_null_items() {
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleForEach(x => x.Orders).SetValidator(new OrderValidator())
};
_person.Orders[0] = null;
var results = validator.Validate(_person);
results.Errors.Count.ShouldEqual(2); //2 errors - 1 for person, 1 for 2nd Order.
}
[Fact]
public void Can_validate_collection_using_validator_for_base_type() {
var validator = new TestValidator() {
v => v.RuleForEach(x => x.Orders).SetValidator(new OrderInterfaceValidator())
};
var result = validator.Validate(_person);
result.IsValid.ShouldBeFalse();
}
[Fact]
public void Can_specify_condition_for_individual_collection_elements() {
var validator = new TestValidator {
v => v.RuleForEach(x => x.Orders)
.Where(x => x.ProductName != null)
.SetValidator(new OrderValidator())
};
var results = validator.Validate(_person);
results.Errors.Count.ShouldEqual(1);
}
[Fact]
public void Should_override_property_name() {
var validator = new TestValidator {
v => v.RuleForEach(x => x.Orders).SetValidator(new OrderValidator())
.OverridePropertyName("Orders2")
};
var results = validator.Validate(_person);
results.Errors[0].PropertyName.ShouldEqual("Orders2[0].ProductName");
}
[Fact]
public void Top_level_collection() {
var v = new InlineValidator<IEnumerable<Order>>();
v.RuleForEach(x => x).SetValidator(new OrderValidator());
var orders = new List<Order> {
new Order(),
new Order()
};
var result = v.Validate(orders);
result.Errors.Count.ShouldEqual(4);
result.Errors[0].PropertyName.ShouldEqual("x[0].ProductName");
}
[Fact]
public void Validates_child_validator_synchronously() {
var validator = new ComplexValidationTester.TracksAsyncCallValidator<Person>();
var childValidator = new ComplexValidationTester.TracksAsyncCallValidator<Person>();
childValidator.RuleFor(x => x.Forename).NotNull();
validator.RuleForEach(x => x.Children).SetValidator(childValidator);
validator.Validate(new Person() { Children = new List<Person> { new Person() }});
childValidator.WasCalledAsync.ShouldEqual(false);
}
[Fact]
public async Task Validates_child_validator_asynchronously() {
var validator = new ComplexValidationTester.TracksAsyncCallValidator<Person>();
var childValidator = new ComplexValidationTester.TracksAsyncCallValidator<Person>();
childValidator.RuleFor(x => x.Forename).NotNull();
validator.RuleForEach(x => x.Children).SetValidator(childValidator);
await validator.ValidateAsync(new Person() {Children = new List<Person> {new Person()}});
childValidator.WasCalledAsync.ShouldEqual(true);
}
[Fact]
public void Can_access_colletion_index() {
var validator = new InlineValidator<Person>();
validator.RuleForEach(x => x.Orders).NotNull().WithMessage("{CollectionIndex}");
var result = validator.Validate(new Person {Orders = new List<Order>() {new Order(), null}});
result.IsValid.ShouldBeFalse();
result.Errors[0].ErrorMessage.ShouldEqual("1");
}
[Fact]
public async Task Can_access_colletion_index_async() {
var validator = new InlineValidator<Person>();
validator.RuleForEach(x => x.Orders).MustAsync((x, ct) => Task.FromResult(x != null)).WithMessage("{CollectionIndex}");
var result = await validator.ValidateAsync(new Person {Orders = new List<Order>() {new Order(), null}});
result.IsValid.ShouldBeFalse();
result.Errors[0].ErrorMessage.ShouldEqual("1");
}
[Fact]
public void When_runs_outside_RuleForEach_loop() {
// Shouldn't throw an exception if the condition is run outside the loop.
var validator = new InlineValidator<Tuple<Person>>();
validator.RuleForEach(x => x.Item1.Orders).Must(x => false)
.When(x => x.Item1 != null);
var result = validator.Validate(Tuple.Create((Person) null));
result.IsValid.ShouldBeTrue();
result = validator.Validate(Tuple.Create(new Person() { Orders = new List<Order> { new Order() }}));
result.IsValid.ShouldBeFalse();
}
[Fact]
public async Task When_runs_outside_RuleForEach_loop_async() {
// Shouldn't throw an exception if the condition is run outside the loop.
var validator = new InlineValidator<Tuple<Person>>();
validator.RuleForEach(x => x.Item1.Orders)
.MustAsync((x,c) => Task.FromResult(false))
.When(x => x.Item1 != null);
var result = await validator.ValidateAsync(Tuple.Create((Person) null));
result.IsValid.ShouldBeTrue();
result = await validator.ValidateAsync(Tuple.Create(new Person() { Orders = new List<Order> { new Order() }}));
result.IsValid.ShouldBeFalse();
}
[Fact]
public void Can_access_parent_index() {
var personValidator = new InlineValidator<Person>();
var orderValidator = new InlineValidator<Order>();
orderValidator.RuleFor(order => order.ProductName)
.NotEmpty()
.WithMessage("{CollectionIndex} must not be empty");
// Two rules - one for each collection syntax.
personValidator.RuleFor(x => x.Orders)
.NotEmpty()
.ForEach(order => {
order.SetValidator(orderValidator);
});
personValidator.RuleForEach(x => x.Orders).SetValidator(orderValidator);
var result = personValidator.Validate(new Person() {
Orders = new List<Order> {
new Order() { ProductName = "foo"},
new Order(),
new Order() { ProductName = "bar" }
}
});
result.IsValid.ShouldBeFalse();
result.Errors[0].ErrorMessage.ShouldEqual("1 must not be empty");
result.Errors[0].ErrorMessage.ShouldEqual("1 must not be empty");
}
[Fact]
public async Task Can_access_parent_index_async() {
var personValidator = new InlineValidator<Person>();
var orderValidator = new InlineValidator<Order>();
orderValidator.RuleFor(order => order.ProductName)
.NotEmpty()
.WithMessage("{CollectionIndex} must not be empty");
// Two rules - one for each collection syntax.
personValidator.RuleFor(x => x.Orders)
.NotEmpty()
.ForEach(order => {
order.SetValidator(orderValidator);
});
personValidator.RuleForEach(x => x.Orders).SetValidator(orderValidator);
var result = await personValidator.ValidateAsync(new Person() {
Orders = new List<Order> {
new Order() { ProductName = "foo"},
new Order(),
new Order() { ProductName = "bar" }
}
});
result.IsValid.ShouldBeFalse();
result.Errors[0].ErrorMessage.ShouldEqual("1 must not be empty");
result.Errors[0].ErrorMessage.ShouldEqual("1 must not be empty");
}
[Fact]
public void Failing_condition_should_prevent_multiple_components_running_and_not_throw() {
// https://github.com/FluentValidation/FluentValidation/issues/1698
var validator = new InlineValidator<Person>();
validator.RuleForEach(x => x.Orders)
.NotNull()
.NotNull()
.When(x => x.Orders.Count > 0);
var result = validator.Validate(new Person());
result.IsValid.ShouldBeTrue();
}
[Fact]
public async Task Failing_condition_should_prevent_multiple_components_running_and_not_throw_async() {
// https://github.com/FluentValidation/FluentValidation/issues/1698
var validator = new InlineValidator<Person>();
validator.RuleForEach(x => x.Orders)
.MustAsync((o, ct) => Task.FromResult(o != null))
.MustAsync((o, ct) => Task.FromResult(o != null))
.When(x => x.Orders.Count > 0);
var result = await validator.ValidateAsync(new Person());
result.IsValid.ShouldBeTrue();
}
[Fact]
public void Shouldnt_throw_exception_when_configuring_rule_after_ForEach() {
var validator = new InlineValidator<Person>();
validator.RuleFor(x => x.Orders)
.ForEach(o => {
o.Must(v => true);
})
.Must((val) => true)
.WithMessage("what");
// The RuleBuilder is RuleBuilder<Person, IList<Order>>
// after the ForEach, it's returned as an IRuleBuilderOptions<Person, IEnumerable<Order>>
var result = validator.Validate(new Person() {
Orders = new List<Order>() { new Order()}
});
result.IsValid.ShouldBeTrue();
}
public class OrderValidator : AbstractValidator<Order> {
public OrderValidator() {
RuleFor(x => x.ProductName).NotEmpty();
RuleFor(x => x.Amount).NotEqual(0);
}
}
public class OrderInterfaceValidator : AbstractValidator<IOrder> {
public OrderInterfaceValidator() {
RuleFor(x => x.Amount).NotEqual(0);
}
}
}
}