forked from aspnet/AspNetWebStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDefaultBodyModelValidatorTest.cs
More file actions
288 lines (248 loc) · 12.1 KB
/
Copy pathDefaultBodyModelValidatorTest.cs
File metadata and controls
288 lines (248 loc) · 12.1 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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Http.Controllers;
using System.Web.Http.Metadata;
using System.Web.Http.Metadata.Providers;
using System.Web.Http.ModelBinding;
using System.Xml.Linq;
using Microsoft.TestCommon;
using Moq;
namespace System.Web.Http.Validation
{
public class DefaultBodyModelValidatorTest
{
private static Person LonelyPerson;
static DefaultBodyModelValidatorTest()
{
LonelyPerson = new Person() { Name = "Reallllllllly Long Name" };
LonelyPerson.Friend = LonelyPerson;
}
public static IEnumerable<object[]> ValidationErrors
{
get
{
return new TheoryDataSet<object, Type, Dictionary<string, string>>()
{
// Primitives
{ null, typeof(Person), new Dictionary<string, string>() },
{ 14, typeof(int), new Dictionary<string, string>() },
{ "foo", typeof(string), new Dictionary<string, string>() },
// Object Traversal : make sure we can traverse the object graph without throwing
{ new ValueType() { Reference = "ref", Value = 256}, typeof(ValueType), new Dictionary<string, string>()},
{ new ReferenceType() { Reference = "ref", Value = 256}, typeof(ReferenceType), new Dictionary<string, string>()},
// Classes
{ new Person() { Name = "Rick", Profession = "Astronaut" }, typeof(Person), new Dictionary<string, string>() },
{ new Person(), typeof(Person), new Dictionary<string, string>()
{
{ "Name", "The Name field is required." },
{ "Profession", "The Profession field is required." }
}
},
{ new Person() { Name = "Rick", Friend = new Person() }, typeof(Person), new Dictionary<string, string>()
{
{ "Profession", "The Profession field is required." },
{ "Friend.Name", "The Name field is required." },
{ "Friend.Profession", "The Profession field is required." }
}
},
// Collections
{ new Person[] { new Person(), new Person() }, typeof(Person[]), new Dictionary<string, string>()
{
{ "[0].Name", "The Name field is required." },
{ "[0].Profession", "The Profession field is required." },
{ "[1].Name", "The Name field is required." },
{ "[1].Profession", "The Profession field is required." }
}
},
{ new List<Person> { new Person(), new Person() }, typeof(Person[]), new Dictionary<string, string>()
{
{ "[0].Name", "The Name field is required." },
{ "[0].Profession", "The Profession field is required." },
{ "[1].Name", "The Name field is required." },
{ "[1].Profession", "The Profession field is required." }
}
},
{ new Dictionary<string, Person> { { "Joe", new Person() } , { "Mark", new Person() } }, typeof(Dictionary<string, Person>), new Dictionary<string, string>()
{
{ "[0].Value.Name", "The Name field is required." },
{ "[0].Value.Profession", "The Profession field is required." },
{ "[1].Value.Name", "The Name field is required." },
{ "[1].Value.Profession", "The Profession field is required." }
}
},
// IValidatableObject's
{ new ValidatableModel(), typeof(ValidatableModel), new Dictionary<string, string>()
{
{ "", "Error1" },
{ "Property1", "Error2" },
{ "Property2", "Error3" },
{ "Property3", "Error3" }
}
},
{ new[] { new ValidatableModel() }, typeof(ValidatableModel[]), new Dictionary<string, string>()
{
{ "[0]", "Error1" },
{ "[0].Property1", "Error2" },
{ "[0].Property2", "Error3" },
{ "[0].Property3", "Error3" }
}
},
// Testing we don't blow up on cycles
{ LonelyPerson, typeof(Person), new Dictionary<string, string>()
{
{ "Name", "The field Name must be a string with a maximum length of 10." },
{ "Profession", "The Profession field is required." }
}
},
// Testing that we don't bubble up exceptions when property getters throw
{ new Uri("/api/values", UriKind.Relative), typeof(Uri), new Dictionary<string, string>() },
// Testing that excluded types don't result in any errors
{ typeof(string), typeof(Type), new Dictionary<string, string>() },
{ new byte[] { (byte)'a', (byte)'b' }, typeof(byte[]), new Dictionary<string, string>() },
{ XElement.Parse("<xml>abc</xml>"), typeof(XElement), new Dictionary<string, string>() }
};
}
}
[Theory]
[ReplaceCulture]
[PropertyData("ValidationErrors")]
public void ExpectedValidationErrorsRaised(object model, Type type, Dictionary<string, string> expectedErrors)
{
// Arrange
ModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();
HttpActionContext actionContext = ContextUtil.CreateActionContext();
// Act
Assert.DoesNotThrow(() =>
new DefaultBodyModelValidator().Validate(model, type, metadataProvider, actionContext, string.Empty)
);
// Assert
Dictionary<string, string> actualErrors = new Dictionary<string, string>();
foreach (KeyValuePair<string, ModelState> keyStatePair in actionContext.ModelState)
{
foreach (ModelError error in keyStatePair.Value.Errors)
{
actualErrors.Add(keyStatePair.Key, error.ErrorMessage);
}
}
Assert.Equal(expectedErrors.Count, actualErrors.Count);
foreach (KeyValuePair<string, string> keyErrorPair in expectedErrors)
{
Assert.Contains(keyErrorPair.Key, actualErrors.Keys);
Assert.Equal(keyErrorPair.Value, actualErrors[keyErrorPair.Key]);
}
}
[Fact]
public void MultipleValidationErrorsOnSameMemberReported()
{
// Arrange
ModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();
HttpActionContext actionContext = ContextUtil.CreateActionContext();
object model = new Address() { Street = "Microsoft Way" };
// Act
Assert.DoesNotThrow(() =>
new DefaultBodyModelValidator().Validate(model, typeof(Address), metadataProvider, actionContext, string.Empty)
);
// Assert
Assert.Contains("Street", actionContext.ModelState.Keys);
ModelState streetState = actionContext.ModelState["Street"];
Assert.Equal(2, streetState.Errors.Count);
}
[Fact]
public void ExcludedTypes_AreNotValidated()
{
// Arrange
ModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();
HttpActionContext actionContext = ContextUtil.CreateActionContext();
Mock<DefaultBodyModelValidator> mockValidator = new Mock<DefaultBodyModelValidator>();
mockValidator.CallBase = true;
mockValidator.Setup(validator => validator.ShouldValidateType(typeof(Person))).Returns(false);
// Act
mockValidator.Object.Validate(new Person(), typeof(Person), metadataProvider, actionContext, string.Empty);
// Assert
Assert.True(actionContext.ModelState.IsValid);
}
[Fact]
public void ExcludedPropertyTypes_AreShallowValidated()
{
// Arrange
ModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();
HttpActionContext actionContext = ContextUtil.CreateActionContext();
Mock<DefaultBodyModelValidator> mockValidator = new Mock<DefaultBodyModelValidator>();
mockValidator.CallBase = true;
mockValidator.Setup(validator => validator.ShouldValidateType(typeof(Person))).Returns(false);
// Act
mockValidator.Object.Validate(new Pet(), typeof(Pet), metadataProvider, actionContext, string.Empty);
// Assert
Assert.False(actionContext.ModelState.IsValid);
ModelState modelState = actionContext.ModelState["Owner"];
Assert.Single(modelState.Errors);
}
[Fact]
public void Validate_DoesNotUseOverridden_GetHashCodeOrEquals()
{
// Arrange
ModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();
HttpActionContext actionContext = ContextUtil.CreateActionContext();
DefaultBodyModelValidator validator = new DefaultBodyModelValidator();
object instance = new[] { new TypeThatOverridesEquals { Funny = "hehe" }, new TypeThatOverridesEquals { Funny = "hehe" } };
// Act & Assert
Assert.DoesNotThrow(
() => validator.Validate(instance, typeof(TypeThatOverridesEquals[]), metadataProvider, actionContext, String.Empty));
}
public class Person
{
[Required]
[StringLength(10)]
public string Name { get; set; }
[Required]
public string Profession { get; set; }
public Person Friend { get; set; }
}
public class Address
{
[StringLength(5)]
[RegularExpression("hehehe")]
public string Street { get; set; }
}
public struct ValueType
{
public int Value;
public string Reference;
}
public class ReferenceType
{
public static string StaticProperty { get { return "static"; } }
public int Value;
public string Reference;
}
public class Pet
{
[Required]
public Person Owner { get; set; }
}
public class ValidatableModel : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield return new ValidationResult("Error1", new string[] { });
yield return new ValidationResult("Error2", new[] { "Property1" });
yield return new ValidationResult("Error3", new[] { "Property2", "Property3" });
}
}
public class TypeThatOverridesEquals
{
[StringLength(2)]
public string Funny { get; set; }
public override bool Equals(object obj)
{
throw new InvalidOperationException();
}
public override int GetHashCode()
{
throw new InvalidOperationException();
}
}
}
}