-
-
Notifications
You must be signed in to change notification settings - Fork 384
Expand file tree
/
Copy pathValidateFormTest.cs
More file actions
964 lines (876 loc) · 33.8 KB
/
ValidateFormTest.cs
File metadata and controls
964 lines (876 loc) · 33.8 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
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License
// See the LICENSE file in the project root for more information.
// Maintainer: Argo Zhang(argo@live.ca) Website: https://www.blazor.zone
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.Extensions.Options;
using System.Collections.Concurrent;
using System.ComponentModel.DataAnnotations;
namespace UnitTest.Components;
public class ValidateFormTest : BootstrapBlazorTestBase
{
protected override void ConfigureServices(IServiceCollection services)
{
services.AddBootstrapBlazor();
services.ConfigureJsonLocalizationOptions(op => op.AdditionalJsonAssemblies = new[] { GetType().Assembly });
}
[Fact]
public void BootstrapBlazorDataAnnotationsValidator_Error()
{
Assert.ThrowsAny<InvalidOperationException>(() => Context.Render<BootstrapBlazorDataAnnotationsValidator>());
}
[Fact]
public async Task Validate_Ok()
{
var valid = false;
var invalid = false;
var foo = new Foo();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.ShowLabelTooltip, true);
pb.Add(a => a.Model, foo);
pb.Add(a => a.OnValidSubmit, context =>
{
valid = true;
return Task.CompletedTask;
});
pb.Add(a => a.OnInvalidSubmit, context =>
{
invalid = true;
return Task.CompletedTask;
});
pb.AddChildContent<BootstrapInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Name);
pb.Add(a => a.ValueChanged, EventCallback.Factory.Create<string?>(this, v => foo.Name = v));
pb.Add(a => a.ValueExpression, foo.GenerateValueExpression());
});
});
var form = cut.Find("form");
await cut.InvokeAsync(() => form.Submit());
Assert.True(invalid);
await cut.InvokeAsync(() =>
{
cut.Find("input").Change("Test");
form.Submit();
});
Assert.True(valid);
}
[Fact]
public void OnFieldValueChanged_Ok()
{
var changed = false;
var foo = new Foo();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.Add(a => a.OnFieldValueChanged, (fieldName, v) =>
{
changed = true;
});
pb.AddChildContent<BootstrapInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Name);
pb.Add(a => a.ValueChanged, EventCallback.Factory.Create<string?>(this, v => foo.Name = v));
pb.Add(a => a.ValueExpression, foo.GenerateValueExpression());
});
});
var form = cut.Find("form");
cut.InvokeAsync(() => cut.Find("input").Change("Test"));
cut.InvokeAsync(() => form.Submit());
Assert.True(changed);
}
[Fact]
public void ValidateAllProperties_Ok()
{
var foo = new Foo();
var invalid = false;
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.Add(a => a.ValidateAllProperties, true);
pb.Add(a => a.OnInvalidSubmit, context =>
{
invalid = true;
return Task.CompletedTask;
});
pb.AddChildContent<BootstrapInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Name);
pb.Add(a => a.ValueChanged, EventCallback.Factory.Create<string?>(this, v => foo.Name = v));
pb.Add(a => a.ValueExpression, foo.GenerateValueExpression());
});
});
var form = cut.Find("form");
cut.InvokeAsync(() => form.Submit());
Assert.True(invalid);
}
[Fact]
public void ShowRequiredMark_Ok()
{
var foo = new Foo();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.Add(a => a.ShowRequiredMark, true);
pb.AddChildContent<BootstrapInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Name);
pb.Add(a => a.ValueChanged, EventCallback.Factory.Create<string?>(this, v => foo.Name = v));
pb.Add(a => a.ValueExpression, foo.GenerateValueExpression());
});
});
cut.Contains("required=\"true\"");
cut.Render(pb =>
{
pb.Add(a => a.ShowRequiredMark, false);
});
cut.DoesNotContain("required=\"true\"");
}
[Fact]
public void ShowLabel_Ok()
{
var foo = new Foo();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.Add(a => a.ShowLabel, true);
pb.AddChildContent<BootstrapInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Name);
pb.Add(a => a.ValueChanged, EventCallback.Factory.Create<string?>(this, v => foo.Name = v));
pb.Add(a => a.ValueExpression, foo.GenerateValueExpression());
});
});
cut.Contains("label");
cut.Render(pb =>
{
pb.Add(a => a.ShowLabel, false);
});
cut.DoesNotContain("label");
}
[Fact]
public void LabelWidth_Ok()
{
var foo = new Foo();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.Add(a => a.LabelWidth, 120);
pb.AddChildContent<BootstrapInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Name);
pb.Add(a => a.ValueChanged, EventCallback.Factory.Create<string?>(this, v => foo.Name = v));
pb.Add(a => a.ValueExpression, foo.GenerateValueExpression());
});
});
cut.Contains("style=\"--bb-row-label-width: 120px;\"");
}
[Fact]
public async Task SetError_Ok()
{
var foo = new Foo();
var dummy = new Dummy();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.AddChildContent<BootstrapInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Name);
pb.Add(a => a.ValueExpression, foo.GenerateValueExpression());
});
pb.AddChildContent<DateTimePicker<DateTime?>>(pb =>
{
pb.Add(a => a.Value, dummy.Value);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(dummy, "Value", typeof(DateTime?)));
});
});
await cut.InvokeAsync(() => cut.Instance.SetError("Name", "Test_SetError"));
await cut.InvokeAsync(() => cut.Instance.SetError("Test.Name", "Test_SetError"));
await cut.InvokeAsync(() => cut.Instance.SetError<Foo>(f => f.Name, "Name_SetError"));
// 利用反射提高代码覆盖率
var method = typeof(ValidateForm).GetMethod("TryGetValidator", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
Assert.NotNull(method);
var ret = method.Invoke(cut.Instance, [typeof(Dummy), "Test", null]);
Assert.False((bool?)ret);
}
[Fact]
public async Task SetError_UnaryExpression()
{
var foo = new Foo();
var dummy = new Dummy();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, dummy);
pb.AddChildContent<DateTimePicker<DateTime?>>(pb =>
{
pb.Add(a => a.Value, foo.DateTime);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(foo, "DateTime", typeof(DateTime?)));
});
pb.AddChildContent<DateTimePicker<DateTime?>>(pb =>
{
pb.Add(a => a.Value, dummy.Value);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(dummy, "Value", typeof(DateTime?)));
});
});
await cut.InvokeAsync(() => cut.Instance.SetError<Dummy>(f => f.Value, "Name_SetError"));
// 利用反射提高代码覆盖率
var fieldInfo = cut.Instance.GetType().GetField("_validatorCache", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!;
var cache = (ConcurrentDictionary<(string FieldName, Type ModelType), (FieldIdentifier FieldIdentifier, IValidateComponent ValidateComponent)>)fieldInfo.GetValue(cut.Instance)!;
cache.Remove(("Value", typeof(Dummy)), out _);
await cut.InvokeAsync(() => cut.Instance.SetError<Dummy>(f => f.Value, "Name_SetError"));
}
[Fact]
public void MetadataTypeAttribute_Ok()
{
var foo = new Dummy();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.AddChildContent<DateTimePicker<DateTime?>>(pb =>
{
pb.Add(a => a.Value, foo.Value);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(foo, "Value", typeof(DateTime?)));
});
});
var form = cut.Find("form");
cut.InvokeAsync(() => form.Submit());
}
[Fact]
public void MetadataTypeIValidatableObject_Ok()
{
var foo = new Dummy() { Password1 = "password", Password2 = "Password2" };
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.AddChildContent<MockInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Password1);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(foo, "Password1", typeof(string)));
});
pb.AddChildContent<MockInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Password2);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(foo, "Password2", typeof(string)));
});
});
var form = cut.Find("form");
cut.InvokeAsync(() => form.Submit());
var message = cut.FindComponent<MockInput<string>>().Instance.GetErrorMessage();
Assert.Equal("两次密码必须一致。", message);
}
[Fact]
public async Task MetadataTypeIValidateCollection_Ok()
{
var model = new Dummy2() { Value1 = 0, Value2 = 0 };
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, model);
pb.AddChildContent<MockInput<int>>(pb =>
{
pb.Add(a => a.Value, model.Value1);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(model, "Value1", typeof(int)));
});
pb.AddChildContent<MockInput<int>>(pb =>
{
pb.Add(a => a.Value, model.Value2);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(model, "Value2", typeof(int)));
});
});
var form = cut.Find("form");
await cut.InvokeAsync(() => form.Submit());
var input = cut.FindComponent<MockInput<int>>();
var all = cut.FindComponents<MockInput<int>>();
var input2 = all[all.Count - 1];
Assert.Null(input.Instance.GetErrorMessage());
Assert.Equal("Value2 必须大于 0", input2.Instance.GetErrorMessage());
model.Value1 = 0;
model.Value2 = 2;
cut.Render(pb =>
{
pb.Add(a => a.Model, model);
});
await cut.InvokeAsync(() => form.Submit());
Assert.Equal("Value1 必须大于 Value2", input.Instance.GetErrorMessage());
Assert.Equal("Value1 必须大于 Value2", input2.Instance.GetErrorMessage());
}
[Fact]
public void Validate_Class_Ok()
{
var dummy = new Dummy();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, dummy);
pb.Add(a => a.ValidateAllProperties, true);
pb.AddChildContent<BootstrapInput<string>>(pb =>
{
pb.Add(a => a.Value, dummy.Foo.Name);
});
pb.AddChildContent<BootstrapInput<Foo>>(pb =>
{
pb.Add(a => a.Value, dummy.Foo);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(dummy, nameof(dummy.Foo), typeof(Foo)));
});
});
var form = cut.Find("form");
cut.InvokeAsync(() => form.Submit());
}
[Fact]
public async Task ValidateAll_Ok()
{
var invalid = false;
var dummy = new Dummy();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, dummy);
pb.Add(a => a.ValidateAllProperties, false);
pb.AddChildContent<BootstrapInput<Foo>>(pb =>
{
pb.Add(a => a.Value, dummy.Foo);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(dummy, nameof(dummy.Foo), typeof(Foo)));
});
pb.Add(a => a.OnInvalidSubmit, context =>
{
invalid = true;
return Task.CompletedTask;
});
});
var form = cut.Find("form");
await cut.InvokeAsync(() => form.Submit());
Assert.False(invalid);
cut.Render(pb =>
{
pb.Add(a => a.ValidateAllProperties, true);
});
await cut.InvokeAsync(() => form.Submit());
Assert.True(invalid);
}
[Fact]
public async Task Validate_UploadFile_Ok()
{
var foo = new Dummy() { File = "text.txt" };
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.AddChildContent<ButtonUpload<string>>(pb =>
{
pb.Add(a => a.Value, foo.File);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(foo, "File", typeof(string)));
});
});
var form = cut.Find("form");
await cut.InvokeAsync(() => form.Submit());
}
[Fact]
public async Task Validate_Localizer_Ok()
{
var foo = new MockFoo();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.AddChildContent<MockInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Name);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(foo, "Name", typeof(string)));
});
});
var form = cut.Find("form");
await cut.InvokeAsync(() => form.Submit());
var msg = cut.FindComponent<MockInput<string>>().Instance.GetErrorMessage();
Assert.Equal("Name is Required", msg);
}
[Fact]
public async Task Validate_Attribute_Ok()
{
var foo = new MockFoo();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.AddChildContent<MockInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Rule);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(foo, "Rule", typeof(string)));
});
});
var form = cut.Find("form");
await cut.InvokeAsync(() => form.Submit());
var msg = cut.FindComponent<MockInput<string>>().Instance.GetErrorMessage();
Assert.Equal("Rule is Required", msg);
}
[Fact]
public async Task Validate_MemberName_Ok()
{
var foo = new MockFoo();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.AddChildContent<MockInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Member);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(foo, "Member", typeof(string)));
});
});
var form = cut.Find("form");
await cut.InvokeAsync(() => form.Submit());
var msg = cut.FindComponent<MockInput<string>>().Instance.GetErrorMessage();
Assert.Equal("Member is Required", msg);
}
[Fact]
public void Validate_Address_Ok()
{
var foo = new MockFoo();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.AddChildContent<MockInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Address);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(foo, "Address", typeof(string)));
});
});
var form = cut.Find("form");
cut.InvokeAsync(() => form.Submit());
var msg = cut.FindComponent<MockInput<string>>().Instance.GetErrorMessage();
Assert.Equal("Address must fill", msg);
}
[Fact]
public async Task ValidateFormButton_Valid()
{
var tcs = new TaskCompletionSource<bool>();
var valid = false;
var foo = new Foo() { Name = "Test" };
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(v => v.Model, foo);
pb.Add(v => v.OnValidSubmit, context =>
{
valid = true;
tcs.SetResult(true);
return Task.CompletedTask;
});
pb.AddChildContent<BootstrapInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Name);
pb.Add(a => a.ValueExpression, foo.GenerateValueExpression());
});
pb.AddChildContent<Button>(pb =>
{
pb.Add(b => b.IsAsync, true);
pb.Add(b => b.ButtonType, ButtonType.Submit);
});
});
await cut.InvokeAsync(() => cut.Find("form").Submit());
await tcs.Task;
Assert.True(valid);
}
[Fact]
public async Task ValidateFormButton_Invalid()
{
var tcs = new TaskCompletionSource<bool>();
var valid = true;
var foo = new Foo();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(v => v.Model, foo);
pb.Add(a => a.OnInvalidSubmit, context =>
{
valid = false;
tcs.SetResult(true);
return Task.CompletedTask;
});
pb.AddChildContent<BootstrapInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Name);
pb.Add(a => a.ValueExpression, foo.GenerateValueExpression());
});
pb.AddChildContent<Button>(pb =>
{
pb.Add(b => b.IsAsync, true);
pb.Add(b => b.ButtonType, ButtonType.Submit);
});
});
await cut.InvokeAsync(() => cut.Find("form").Submit());
await tcs.Task;
Assert.False(valid);
}
[Fact]
public async Task ValidateFromCode_Ok()
{
var foo = new Foo();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.AddChildContent<BootstrapInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Address);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(foo, "Address", typeof(string)));
});
});
Assert.Contains("form-control valid", cut.Markup);
var form = cut.Find("form");
await cut.InvokeAsync(() => form.Submit());
Assert.Contains("form-control invalid is-invalid", cut.Markup);
}
[Fact]
public async Task Validate_Service_Ok()
{
var foo = new HasService();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.AddChildContent<MockInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Tag);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(foo, "Tag", typeof(string)));
pb.Add(a => a.ValidateRules, [new FormItemValidator(new HasServiceAttribute())]);
});
});
var form = cut.Find("form");
await cut.InvokeAsync(() => form.Submit());
var msg = cut.FindComponent<MockInput<string>>().Instance.GetErrorMessage();
Assert.Equal(HasServiceAttribute.Success, msg);
}
[Fact]
public async Task TestService_Ok()
{
// 自定义验证规则没有使用约定 Attribute 结尾单元测试
var foo = new HasService();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.AddChildContent<MockInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Tag2);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(foo, "Tag2", typeof(string)));
pb.Add(a => a.ValidateRules, [new FormItemValidator(new TestValidateRule())]);
});
});
var form = cut.Find("form");
await cut.InvokeAsync(() => form.Submit());
var msg = cut.FindComponent<MockInput<string>>().Instance.GetErrorMessage();
Assert.Equal("Test", msg);
}
[Fact]
public async Task RequiredValidator_Ok()
{
var foo = new HasService();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, foo);
pb.AddChildContent<MockInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Tag);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(foo, "Tag", typeof(string)));
pb.Add(a => a.ValidateRules, [new RequiredValidator()]);
});
});
var form = cut.Find("form");
await cut.InvokeAsync(() => form.Submit());
var msg = cut.FindComponent<MockInput<string>>().Instance.GetErrorMessage();
Assert.Equal(HasServiceAttribute.Success, msg);
}
[Fact]
public void DisableAutoSubmitFormByEnter_Ok()
{
var options = Context.Services.GetRequiredService<IOptionsMonitor<BootstrapBlazorOptions>>();
options.CurrentValue.DisableAutoSubmitFormByEnter = true;
var foo = new Foo() { Name = "Test" };
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(v => v.Model, foo);
pb.AddChildContent<BootstrapInput<string>>(pb =>
{
pb.Add(a => a.Value, foo.Name);
pb.Add(a => a.ValueExpression, foo.GenerateValueExpression());
});
pb.AddChildContent<Button>(pb =>
{
pb.Add(b => b.IsAsync, true);
pb.Add(b => b.ButtonType, ButtonType.Submit);
});
});
Assert.True(cut.Instance.DisableAutoSubmitFormByEnter);
cut.Render(pb =>
{
pb.Add(a => a.DisableAutoSubmitFormByEnter, false);
});
Assert.False(cut.Instance.DisableAutoSubmitFormByEnter);
}
[Fact]
public void ValidateFieldAsync_Ok()
{
var form = new ValidateForm();
var method = typeof(ValidateForm).GetMethod("ValidateFieldAsync", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
Assert.NotNull(method);
var context = new ValidationContext(new Foo());
var result = new List<ValidationResult>();
method.Invoke(form, [context, result]);
}
[Fact]
public async Task IValidatableObject_Ok()
{
var model = new MockValidataModel() { Telephone1 = "123", Telephone2 = "123" };
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, model);
pb.AddChildContent<MockInput<string>>(pb =>
{
pb.Add(a => a.Value, model.Telephone1);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(model, "Telephone1", typeof(string)));
});
pb.AddChildContent<MockInput<string>>(pb =>
{
pb.Add(a => a.Value, model.Telephone2);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(model, "Telephone2", typeof(string)));
});
});
var form = cut.Find("form");
await cut.InvokeAsync(() => form.Submit());
var message = cut.FindComponent<MockInput<string>>().Instance.GetErrorMessage();
Assert.Equal("Telephone1 and Telephone2 can not be the same", message);
}
[Fact]
public async Task IValidateCollection_Ok()
{
var model = new MockValidateCollectionModel() { Telephone1 = "123", Telephone2 = "123" };
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, model);
pb.AddChildContent<MockInput<string>>(pb =>
{
pb.Add(a => a.Value, model.Telephone1);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(model, "Telephone1", typeof(string)));
pb.Add(a => a.ValueChanged, v => model.Telephone1 = v);
});
pb.AddChildContent<MockInput<string>>(pb =>
{
pb.Add(a => a.Value, model.Telephone2);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(model, "Telephone2", typeof(string)));
pb.Add(a => a.ValueChanged, v => model.Telephone2 = v);
});
});
var form = cut.Find("form");
await cut.InvokeAsync(() => form.Submit());
var input = cut.FindComponent<MockInput<string>>();
var all = cut.FindComponents<MockInput<string>>();
var input2 = all[all.Count - 1];
Assert.Equal("Telephone1 and Telephone2 can not be the same", input.Instance.GetErrorMessage());
Assert.Equal("Telephone1 and Telephone2 can not be the same", input2.Instance.GetErrorMessage());
// 触发符合条件后联动
var inputEl = cut.Find("input");
await cut.InvokeAsync(() => inputEl.Change("1234"));
var message = input.Instance.GetErrorMessage();
Assert.Null(message);
cut.Render();
message = input2.Instance.GetErrorMessage();
Assert.Null(message);
var allInputs = cut.FindAll("input");
var inputEl2 = allInputs[all.Count - 1];
await cut.InvokeAsync(() => inputEl2.Change("1234"));
message = input2.Instance.GetErrorMessage();
Assert.Equal("Telephone1 and Telephone2 can not be the same", message);
cut.Render();
message = input.Instance.GetErrorMessage();
Assert.Equal("Telephone1 and Telephone2 can not be the same", message);
}
[Fact]
public void ShowAllInvalidResult_Ok()
{
var model = new Foo();
var cut = Context.Render<ValidateForm>(pb =>
{
pb.Add(a => a.Model, model);
pb.AddChildContent<BootstrapInput<string>>(pb =>
{
pb.Add(a => a.Value, model.Name);
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(model, "Name", typeof(string)));
});
});
cut.DoesNotContain("data-bb-invalid-result");
cut.Render(pb =>
{
pb.Add(a => a.ShowAllInvalidResult, true);
});
cut.Contains("data-bb-invalid-result");
}
private class HasServiceAttribute : ValidationAttribute
{
public const string Success = "Has Service";
private const string Error = "No Service";
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
var hasService = validationContext.GetService<IServiceProvider>();
if (hasService is null)
return new(Error);
else
return new(Success);
}
}
private class TestValidateRule : ValidationAttribute
{
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
return new("Test");
}
}
private class HasService
{
[HasService]
public string? Tag { get; set; }
[TestValidateRule]
public string? Tag2 { get; set; }
}
[MetadataType(typeof(DummyMetadata))]
private class Dummy
{
public DateTime? Value { get; set; }
public Foo Foo { get; set; } = new Foo();
[Required]
public string? File { get; set; }
public string? Password1 { get; set; }
public string? Password2 { get; set; }
}
private class DummyMetadata : IValidatableObject
{
[Required]
public DateTime? Value { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var result = new List<ValidationResult>();
if (validationContext.ObjectInstance is Dummy dy)
{
if (!string.Equals(dy.Password1, dy.Password2, StringComparison.InvariantCultureIgnoreCase))
{
result.Add(new ValidationResult("两次密码必须一致。", [nameof(Dummy.Password1), nameof(Dummy.Password2)]));
}
}
return result;
}
}
[MetadataType(typeof(Dummy2MetadataCollection))]
private class Dummy2
{
public int Value1 { get; set; }
public int Value2 { get; set; }
}
public class Dummy2MetadataCollection : IValidateCollection
{
[Required]
public int Value1 { get; set; }
[CustomValidation(typeof(Dummy2MetadataCollection), nameof(CustomValidate), ErrorMessage = "{0} 必须大于 0")]
[Required]
public int Value2 { get; set; }
private readonly List<string> _validMemberNames = [];
public List<string> GetValidMemberNames() => _validMemberNames;
private readonly List<ValidationResult> _invalidMemberNames = [];
public List<ValidationResult> GetInvalidMemberNames() => _invalidMemberNames;
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
_invalidMemberNames.Clear();
_validMemberNames.Clear();
if (validationContext.ObjectInstance is Dummy2 dummy)
{
if (dummy.Value1 < dummy.Value2)
{
_invalidMemberNames.Add(new ValidationResult("Value1 必须大于 Value2", [nameof(Dummy2.Value1), nameof(Dummy2.Value2)]));
}
else
{
_validMemberNames.AddRange([nameof(Dummy2.Value1), nameof(Dummy2.Value2)]);
}
}
return _invalidMemberNames;
}
public static ValidationResult? CustomValidate(object value, ValidationContext context)
{
ValidationResult? ret = null;
if (value is int v && v < 1)
{
ret = new ValidationResult("Value2 必须大于 0", ["Value2"]);
}
return ret;
}
}
private class MockFoo
{
[Required(ErrorMessage = "{0} is Required")]
public string? Name { get; set; }
[EmailAddress(ErrorMessage = "{0} must fill")]
[Display(Name = "Address")]
public string? Address { get; set; } = "test";
[Required()]
public string? Rule { get; set; }
[EmailAddress()]
public string? Member { get; set; } = "test";
}
private class MockValidataModel : IValidatableObject
{
public string? Telephone1 { get; set; }
public string? Telephone2 { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.Equals(Telephone1, Telephone2, StringComparison.InvariantCultureIgnoreCase))
{
yield return new ValidationResult("Telephone1 and Telephone2 can not be the same", [nameof(Telephone1), nameof(Telephone2)]);
}
}
}
private class MockValidateCollectionModel : IValidateCollection
{
/// <summary>
/// 联系电话1
/// </summary>
public string? Telephone1 { get; set; }
/// <summary>
/// 联系电话2
/// </summary>
public string? Telephone2 { get; set; }
private readonly List<string> _validMemberNames = [];
private readonly List<ValidationResult> _invalidMemberNames = [];
/// <summary>
/// <inheritdoc/>
/// </summary>
/// <param name="validationContext"></param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
_validMemberNames.Clear();
_invalidMemberNames.Clear();
if (string.Equals(Telephone1, Telephone2, StringComparison.InvariantCultureIgnoreCase))
{
var errorMessage = "Telephone1 and Telephone2 can not be the same";
if (validationContext.MemberName == nameof(Telephone1))
{
_invalidMemberNames.Add(new ValidationResult(errorMessage, [nameof(Telephone2)]));
}
else if (validationContext.MemberName == nameof(Telephone2))
{
_invalidMemberNames.Add(new ValidationResult(errorMessage, [nameof(Telephone1)]));
}
yield return new ValidationResult(errorMessage, [validationContext.MemberName!]);
}
else if (validationContext.MemberName == nameof(Telephone1))
{
_validMemberNames.Add(nameof(Telephone2));
}
else if (validationContext.MemberName == nameof(Telephone2))
{
_validMemberNames.Add(nameof(Telephone1));
}
}
/// <summary>
/// <inheritdoc/>
/// </summary>
/// <returns></returns>
public List<string> GetValidMemberNames() => _validMemberNames;
/// <summary>
/// <inheritdoc/>
/// </summary>
/// <returns></returns>
public List<ValidationResult> GetInvalidMemberNames() => _invalidMemberNames;
}
private class MockInput<TValue> : BootstrapInput<TValue>
{
public string? GetErrorMessage() => base.ErrorMessage;
}
}