Specifies the numeric range constraints for the value of a data field.
public void Setup() { var attribute = new RangeAttribute(5, 10); attribute.ErrorMessage = "test message"; this.validator = new ValidationAttributeValidator(attribute); }
public void RangeAttribute_valid_with_length_non_zero() { var an = new RangeAttribute(5); Assert.AreEqual(5, an.Min); Assert.IsFalse(an.IsValid(null, typeof(string))); Assert.IsFalse(an.IsValid(string.Empty, typeof(string))); Assert.IsTrue(an.IsValid("44", typeof(string))); Assert.IsFalse(an.IsValid("invalid", typeof(string))); }
public void RangeAttribute_validating_zero_min_length() { var an = new RangeAttribute(0); Assert.AreEqual(0, an.Min); Assert.IsTrue(an.IsValid(1, null)); Assert.IsFalse(an.IsValid(string.Empty, typeof(string))); Assert.IsTrue(an.IsValid("0", typeof(string))); Assert.IsTrue(an.IsValid(Int64.MaxValue, typeof(Int64))); }
/// <summary> /// Creates a new instance; returns <c>null</c> if <paramref name="range"/> is <c>null</c>. /// </summary> /// <param name="obj">The object the metadata is provided for or <c>null</c> for struct fields.</param> /// <param name="type">The type of the range the range metadata is provided for.</param> /// <param name="range">The range metadata for the field.</param> public static RangeMetadata Create(object obj, Type type, RangeAttribute range) { if (range == null) { return(null); } var metadataType = typeof(RangeMetadata <>).MakeGenericType(type); return((RangeMetadata)Activator.CreateInstance(metadataType, obj, type, null, range)); }
protected void ReadRangeOptionalAttribute() { var rangeAttrList = base.fieldInfo.GetCustomAttributes(typeof(RangeAttribute), true); if (rangeAttrList.Length > 0) { rangeAttribute = (RangeAttribute)rangeAttrList[0]; } checkedForRange = true; }
static int RecurseBuildParameterInfo(List <VFXParameterInfo> infos, System.Type type, string path, object obj) { if (!type.IsValueType) { return(0); } int count = 0; var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public); var subList = new List <VFXParameterInfo>(); foreach (var field in fields) { var info = new VFXParameterInfo(field.Name, field.FieldType.Name); var subObj = field.GetValue(obj); info.path = path + "_" + field.Name; var tooltip = field.GetCustomAttributes(typeof(TooltipAttribute), true).FirstOrDefault() as TooltipAttribute; if (tooltip != null) { info.tooltip = tooltip.tooltip; } var fieldName = VisualEffectSerializationUtility.GetTypeField(field.FieldType); if (fieldName != null) { info.sheetType = fieldName; RangeAttribute attr = field.GetCustomAttributes(true).OfType <RangeAttribute>().FirstOrDefault(); if (attr != null) { info.min = attr.min; info.max = attr.max; } info.descendantCount = 0; info.defaultValue = new VFXSerializableObject(field.FieldType, subObj); } else { if (field.FieldType == typeof(VFXCoordinateSpace)) // For space { continue; } info.descendantCount = RecurseBuildParameterInfo(subList, field.FieldType, info.path, subObj); } infos.Add(info); infos.AddRange(subList); subList.Clear(); count++; } return(count); }
/// <summary> /// Creates a new instance; returns <c>null</c> if <paramref name="range"/> is <c>null</c>. /// </summary> /// <param name="obj">The object the metadata is provided for or <c>null</c> for struct fields.</param> /// <param name="field">The field the range metadata is provided for.</param> /// <param name="range">The range metadata for the field.</param> public static RangeMetadata Create(object obj, FieldInfo field, RangeAttribute range) { if (range == null) { return(null); } var metadataType = typeof(RangeMetadata <>).MakeGenericType(field.FieldType); return((RangeMetadata)Activator.CreateInstance(metadataType, obj, field.FieldType, field, range)); }
/// <summary> /// 初始化一个<see cref="PropertyMetadata"/>类型的新实例 /// </summary> public PropertyMetadata(PropertyInfo property) { if (property == null) { return; } Name = property.Name; TypeName = property.PropertyType.FullName; Display = property.GetDescription(); RequiredAttribute required = property.GetAttribute <RequiredAttribute>(); if (required != null) { IsRequired = !required.AllowEmptyStrings; } StringLengthAttribute stringLength = property.GetAttribute <StringLengthAttribute>(); if (stringLength != null) { MaxLength = stringLength.MaximumLength; MinLength = stringLength.MinimumLength; } else { MaxLength = property.GetAttribute <MaxLengthAttribute>()?.Length; MinLength = property.GetAttribute <MinLengthAttribute>()?.Length; } RangeAttribute range = property.GetAttribute <RangeAttribute>(); if (range != null) { Range = new[] { range.Minimum, range.Maximum }; Max = range.Maximum; Min = range.Minimum; } IsNullable = property.PropertyType.IsNullableType(); if (IsNullable) { TypeName = property.PropertyType.GetUnNullableType().FullName; } //枚举类型,作为数值类型返回 if (property.PropertyType.IsEnum) { Type enumType = property.PropertyType; Array values = enumType.GetEnumValues(); Enum[] enumItems = values.Cast <Enum>().ToArray(); if (enumItems.Length > 0) { EnumMetadatas = enumItems.Select(m => new EnumMetadata(m)).ToArray(); } } }
/// <summary> /// <seealso cref="Hinode.Tests.Extensions.TestRangeAttributeExtensions.ClampByDoublePasses()"/> /// </summary> /// <param name="target"></param> /// <param name="value"></param> /// <returns></returns> public static double Clamp(this RangeAttribute target, double value) { if (value < target.min) { value = target.min; } if (value > target.max) { value = target.max; } return(value); }
public void MinGreaterMaxTest() { // arrange object value = 7; // act var attr = new RangeAttribute(2, 1); SingleReport result = attr.Validate(value); // assert Assert.AreEqual(false, result.IsValid); }
public void CornerDigitTest() { // arrange object value = 7; // act var attr = new RangeAttribute(1, 7); SingleReport result = attr.Validate(value); // assert Assert.AreEqual(true, result.IsValid); }
public void OutOfRangeTest() { // arrange object value = 10; // act var attr = new RangeAttribute(1, 7); SingleReport result = attr.Validate(value); // assert Assert.AreEqual(false, result.IsValid); }
void ParseStatEffects() { _statEffects = new Dictionary<string, RangeAttribute>(); var statEffectsJson = sourceData["stat_effects"].AsArray; foreach (JSONNode statEffectJson in statEffectsJson) { var statKey = statEffectJson["key"].Value; var min = statEffectJson["range"].AsArray[0].AsFloat; var max = statEffectJson["range"].AsArray[1].AsFloat; _statEffects[statKey] = new RangeAttribute(min, max); } }
private const string DateFormat = "yyyy-MM-dd"; // Compatible with HTML date inputs public static IEnumerable <SelectOption> OptionsFromRange(this RangeAttribute range, bool useUnderlyingEnumType = false, double step = 1.0) { if (range != null) { if (range.Minimum is int imin && range.Maximum is int imax) { return(OptionsFromRange(imin, imax)); } else if (range.Minimum is double dmin && range.Maximum is double dmax) { return(OptionsFromRange(dmin, dmax, step)); }
/// <summary> /// 执行,按实际结果返回 /// </summary> /// <param name="letter">客户端递交的参数信息</param> /// <returns></returns> public static object Exec(Letter letter) { //1.创建对象,即$api.get("account/single")中的account IViewAPI execObj = ExecuteMethod.CreateInstance(letter); //2.获取要执行的方法,即$api.get("account/single")中的single MethodInfo method = getMethod(execObj.GetType(), letter); //清除缓存 if (letter.HTTP_METHOD.Equals("put", StringComparison.CurrentCultureIgnoreCase)) { CacheAttribute.Remove(method, letter); } //3#.验证方法的特性,一是验证Http动词,二是验证是否登录后操作,三是验证权限 //----验证Http谓词访问限制 HttpAttribute.Verify(letter.HTTP_METHOD, method); //LoginAttribute.Verify(method); //----范围控制,本机或局域网,或同域 bool isRange = RangeAttribute.Verify(method, letter); //----验证是否需要登录 LoginAttribute loginattr = LoginAttribute.Verify(method, letter); //4.构建执行该方法所需要的参数 object[] parameters = getInvokeParam(method, letter); //5.执行方法,返回结果 object objResult = null; //结果 //只有get方式时,才使用缓存 CacheAttribute cache = null; //if (letter.HTTP_METHOD.Equals("put", StringComparison.CurrentCultureIgnoreCase)) // CacheAttribute.Remove(method, letter); if (letter.HTTP_METHOD.Equals("get", StringComparison.CurrentCultureIgnoreCase)) { cache = CacheAttribute.GetAttr <CacheAttribute>(method); } if (cache != null) { objResult = CacheAttribute.GetResult(method, letter); if (objResult == null) { objResult = method.Invoke(execObj, parameters); CacheAttribute.Insert(cache.Expires, method, letter, objResult); } } else { objResult = method.Invoke(execObj, parameters); } //将执行结果写入日志 LoginAttribute.LogWrite(loginattr, objResult); return(objResult); }
public static void CommaDecimalExtremaAndInvalidValues(Type type, string min, string max, string value) { using (new TempCulture("en-US")) { RangeAttribute range = new RangeAttribute(type, min, max); Assert.Throws <ArgumentException>(() => range.IsValid(value)); } using (new TempCulture("fr-FR")) { Assert.False(new RangeAttribute(type, min, max).IsValid(value)); } }
public static void DotDecimalExtremaAndNonStringValues(Type type, string min, string max, object value) { using (new TempCulture("en-US")) { Assert.True(new RangeAttribute(type, min, max).IsValid(value)); } using (new TempCulture("fr-FR")) { RangeAttribute range = new RangeAttribute(type, min, max); Assert.Throws <ArgumentException>(() => range.IsValid(value)); } }
public static void ParseCommaSeparatorInvariantExtremaInCommaSeparatorCultures(Type type, string min, string max) { using (new TempCulture("en-US")) { RangeAttribute range = new RangeAttribute(type, min, max); Assert.Throws <ArgumentException>(() => range.IsValid(null)); } using (new TempCulture("fr-FR")) { Assert.True(new RangeAttribute(type, min, max).IsValid(null)); } }
public void RangeAdapter_SetsErrorMessage() { RangeAttribute attribute = new RangeAttribute(0, 128); ModelMetadata metadata = new DataAnnotationsModelMetadataProvider() .GetMetadataForProperty(null, typeof(AdaptersModel), "Range"); new RangeAdapter(metadata, new ControllerContext(), attribute); String actual = attribute.ErrorMessage; String expected = Validations.Range; Assert.Equal(expected, actual); }
public static void ParseCommaSeparatorExtremaInCommaSeparatorCultures(Type type, string min, string max) { using (new ThreadCultureChange("en-US")) { var range = new RangeAttribute(type, min, max); AssertExtensions.Throws <ArgumentException>("value", () => range.IsValid(null)); } using (new ThreadCultureChange("fr-FR")) { Assert.True(new RangeAttribute(type, min, max).IsValid(null)); } }
/// <summary> /// Gets the range information for the <paramref name="obj" />'s <paramref name="field" /> if it cannot be determined /// automatically by S#. /// Returns <c>false</c> to indicate that no range information is available. /// </summary> /// <param name="obj">The object the range should be determined for.</param> /// <param name="field">The field the range should be determined for.</param> /// <param name="range">Returns the range, if available.</param> protected internal override bool TryGetRange(object obj, FieldInfo field, out RangeAttribute range) { if (!_rangeFields.Contains(field.Name)) { range = null; return(false); } var capacity = ((IDictionary)obj).Count; range = new RangeAttribute(field.Name == "freeList" ? -1 : 0, capacity, OverflowBehavior.Error); return(true); }
public static void CommaDecimalExtremaAndNonStringValues(Type type, string min, string max, object value) { using (new ThreadCultureChange("en-US")) { var range = new RangeAttribute(type, min, max); AssertExtensions.Throws <ArgumentException>("value", () => range.IsValid(value)); } using (new ThreadCultureChange("fr-FR")) { Assert.True(new RangeAttribute(type, min, max).IsValid(value)); } }
Context PropertyInfoContext(bool isDefined, Type rangeType = null, string minValue = null, string maxValue = null) { return (c => c.Given(string.Format("range attribute isDefined:{0} of type {1} between: {2} and {3}", isDefined, rangeType, minValue, maxValue), x => { A.CallTo(() => Member.IsDefined(typeof(RangeAttribute))).Returns(isDefined); RangeAttribute = isDefined ? new RangeAttribute(rangeType, minValue, maxValue) : null; A.CallTo(() => Member.GetCustomAttribute <RangeAttribute> ()).Returns(RangeAttribute); })); }
public static void ParseCommaSeparatorInvariantExtremaInCommaSeparatorCultures(Type type, string min, string max) { RemoteInvoke((t, m1, m2) => { Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US"); RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2); AssertExtensions.Throws <ArgumentException>("value", () => range.IsValid(null)); Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR"); Assert.True(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(null)); }, type.ToString(), min, max).Dispose(); }
private static void DrawAttributeGUI(object obj, FieldInfo f) { LogicComponentBase td = obj as LogicComponentBase; NoShowInEditorAttribute ns = GetAttribute <NoShowInEditorAttribute>(f); if (ns != null) { return; } InternalValueAttribute tempAtt = GetAttribute <InternalValueAttribute>(f); if (tempAtt != null) { DrawUseInternalValueGUI(td, f); return; } InternalValueMenuAttribute tempAtt1 = GetAttribute <InternalValueMenuAttribute>(f); if (tempAtt1 != null) { object value = f.GetValue(obj); if (value is string) { value = DrawInternalValueMenu(f.Name, value.ToString(), tempAtt1.menuTypeNames); f.SetValue(obj, value); return; } } RangeAttribute tempAtt2 = GetAttribute <RangeAttribute>(f); if (tempAtt2 != null) { object value = f.GetValue(obj); if (value is float) { value = EditorGUILayout.Slider(f.Name, (float)value, tempAtt2.min, tempAtt2.max); } else if (value is int) { value = EditorGUILayout.IntSlider(f.Name, (int)value, (int)tempAtt2.min, (int)tempAtt2.max); } f.SetValue(obj, value); return; } object value1 = EditorDrawGUIUtil.DrawBaseValue(f.Name, f.GetValue(obj)); f.SetValue(obj, value1); }
/// <summary> /// Enforces that a value falls within a specified range. /// </summary> /// <typeparam name="T">The type of the value to compare.</typeparam> /// <param name="value">The argument value to be checked.</param> /// <param name="minimum">The minimum value of the specified range.</param> /// <param name="maximum">The maximum value of the specified range.</param> /// <param name="argumentName">The name of the argument.</param> /// <exception cref="ArgumentNullException"><paramref name="argumentName" /> is <c>null</c>.</exception> /// <exception cref="ArgumentException"><paramref name="argumentName" /> is empty or contains only whitespace characters.</exception> /// <exception cref="ValidationException"> /// <paramref name="value" /> does not fall within the specified range. It is /// either less than <paramref name="minimum" /> value or larger than <paramref name="maximum" /> value specified. /// </exception> public static void Range <T>(T value, T minimum, T maximum, string argumentName) where T : IComparable, IComparable <T> { ValidateArgumentName(argumentName); var validator = new RangeAttribute(typeof(T), minimum.ToString(), maximum.ToString()); if (validator.IsValid(value)) { return; } throw new ValidationException($"The value of '{argumentName}' does not fall within the range of minimum: {minimum} and maximum: {maximum}."); }
void ParseStatEffects() { _statEffects = new Dictionary <string, RangeAttribute>(); var statEffectsJson = sourceData["stat_effects"].AsArray; foreach (JSONNode statEffectJson in statEffectsJson) { var statKey = statEffectJson["key"].Value; var min = statEffectJson["range"].AsArray[0].AsFloat; var max = statEffectJson["range"].AsArray[1].AsFloat; _statEffects[statKey] = new RangeAttribute(min, max); } }
public static void CommaDecimalExtremaAndInvalidValues(Type type, string min, string max, string value) { RemoteInvoke((t, m1, m2, v) => { Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US"); RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2); AssertExtensions.Throws <ArgumentException>("value", () => range.IsValid(v)); Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR"); Assert.False(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(v)); }, type.ToString(), min, max, value).Dispose(); }
/// <summary> /// Gets the range information for the <paramref name="obj" />'s <paramref name="field" /> if it cannot be determined /// automatically by S#. /// Returns <c>false</c> to indicate that no range information is available. /// </summary> /// <param name="obj">The object the range should be determined for.</param> /// <param name="field">The field the range should be determined for.</param> /// <param name="range">Returns the range, if available.</param> protected internal override bool TryGetRange(object obj, FieldInfo field, out RangeAttribute range) { if (field.Name != "_size") { range = null; return(false); } var capacityProperty = obj.GetType().GetProperty("Capacity"); var capacity = (int)capacityProperty.GetValue(obj); range = new RangeAttribute(0, capacity, OverflowBehavior.Error); return(true); }
public void OnFloatEditorGUILayout(object target) { float value = GetValue <float>(target); if (attributesByName.ContainsKey(rangeAttributeType)) { RangeAttribute range = attributesByName[rangeAttributeType] as RangeAttribute; this.SetValue(target, UnityEditor.EditorGUILayout.Slider(name, value, range.min, range.max)); } else { this.SetValue(target, UnityEditor.EditorGUILayout.FloatField(name, this.GetValue <float>(target))); } }
public void Given_RangeAttribute_When_Visit_Invoked_Then_It_Should_Return_Result(int min, int max) { var name = "hello"; var acceptor = new OpenApiSchemaAcceptor(); var type = new KeyValuePair <string, Type>(name, typeof(decimal)); var attribute = new RangeAttribute(min, max); this._visitor.Visit(acceptor, type, this._strategy, attribute); acceptor.Schemas.Should().ContainKey(name); acceptor.Schemas[name].Type.Should().Be("number"); acceptor.Schemas[name].Minimum.Should().Be(min); acceptor.Schemas[name].Maximum.Should().Be(max); }
//------------------------------------------------------------------------/ // Methods: Unity Attributes //------------------------------------------------------------------------/ public static bool OnRangeAttribute(Attribute attribute, SerializedProperty property) { RangeAttribute range = attribute as RangeAttribute; if (property.propertyType == SerializedPropertyType.Integer) { EditorGUILayout.IntSlider(property, (int)range.min, (int)range.max); } else if (property.propertyType == SerializedPropertyType.Float) { EditorGUILayout.Slider(property, range.min, range.max); } return(true); }
private ValidationAttribute CopyAttribute(ValidationAttribute attribute) { ValidationAttribute result = null; if (attribute is RangeAttribute) { var attr = (RangeAttribute)attribute; result = new RangeAttribute((double)attr.Minimum, (double)attr.Maximum); } if (attribute is RegularExpressionAttribute) { var attr = (RegularExpressionAttribute)attribute; result = new RegularExpressionAttribute(attr.Pattern); } if (attribute is RequiredAttribute) { result = new RequiredAttribute(); } if (attribute is StringLengthAttribute) { var attr = (StringLengthAttribute)attribute; result = new StringLengthAttribute(attr.MaximumLength) { MinimumLength = attr.MinimumLength }; } if (attribute is CompareAttribute) { var attr = (CompareAttribute)attribute; result = new CompareAttribute(attr.OtherProperty); } if (attribute is DataTypeAttribute) { var attr = (DataTypeAttribute)attribute; result = new DataTypeAttribute(attr.DataType); } if (result == null && attribute.GetType().GetInterfaces().Contains(typeof(ICloneable))) { result = ((ICloneable)attribute).Clone() as ValidationAttribute; } return(result); }
public Rarity(JSONNode json) { Key = json["key"].Value; Name = json["name"].Value; Chance = json["chance"].AsFloat; Color = tpd.HexToColor(json["color"].Value); var multipliers = json["multiplier"].AsArray; statMultiplierRange = new RangeAttribute(multipliers[0].AsFloat, multipliers[1].AsFloat); var modifierChances = json["modifier_chances"].AsArray; prefixChance = modifierChances[0].AsFloat; suffixChance = modifierChances[1].AsFloat; }
/// <summary> /// Enforces that a value falls within a specified range. /// </summary> /// <typeparam name="T">The type of the value to compare.</typeparam> /// <param name="value">The argument value to be checked.</param> /// <param name="minimum">The minimum value of the specified range.</param> /// <param name="maximum">The maximum value of the specified range.</param> /// <param name="argumentName">The name of the argument.</param> /// <returns>The value that has been successfully checked.</returns> /// <exception cref="ArgumentNullException"><paramref name="argumentName" /> is <c>null</c>.</exception> /// <exception cref="ArgumentException"><paramref name="argumentName" /> is empty or contains only whitespace characters.</exception> /// <exception cref="ValidationException"> /// <paramref name="value" /> does not fall within the specified range. It is /// either less than <paramref name="minimum" /> value or larger than <paramref name="maximum" /> value specified. /// </exception> public static T Range<T>(T value, T minimum, T maximum, [InvokerParameterName] [NotNull] string argumentName) where T : IComparable, IComparable<T> { ValidateArgumentName(argumentName); var validator = new RangeAttribute(typeof(T), minimum.ToString(), maximum.ToString()); if (validator.IsValid(value)) { return value; } var errorMessage = $"The value of '{argumentName}' does not fall within the range of minimum: {minimum} and maximum: {maximum}."; throw new ValidationException(errorMessage, new ArgumentException(errorMessage, argumentName)); }
public void ClientRulesWithRangeAttribute() { // Arrange var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(string), "Length"); var context = new ControllerContext(); var attribute = new RangeAttribute(typeof(decimal), "0", "100"); var adapter = new RangeAttribute4Adapter(metadata, context, attribute); // Act var rules = adapter.GetClientValidationRules() .OrderBy(r => r.ValidationType) .ToArray(); // Assert Assert.AreEqual(1, rules.Length); Assert.AreEqual("range", rules[0].ValidationType); Assert.AreEqual(2, rules[0].ValidationParameters.Count); Assert.AreEqual(0m, rules[0].ValidationParameters["minimum"]); Assert.AreEqual(100m, rules[0].ValidationParameters["maximum"]); Assert.AreEqual(@"The field Length must be between 0 and 100.", rules[0].ErrorMessage); }
protected override IEnumerable<TestCase> InvalidValues() { RangeAttribute intRange = new RangeAttribute(1, 3); yield return new TestCase(intRange, 0); yield return new TestCase(intRange, 4); yield return new TestCase(intRange, "abc"); yield return new TestCase(intRange, new object()); // Implements IConvertible (throws NotSupportedException - is caught) yield return new TestCase(intRange, new IConvertibleImplementor() { IntThrow = new NotSupportedException() }); RangeAttribute doubleRange = new RangeAttribute(1.0, 3.0); yield return new TestCase(doubleRange, 0.9999999); yield return new TestCase(doubleRange, 3.0000001); yield return new TestCase(doubleRange, "abc"); yield return new TestCase(doubleRange, new object()); // Implements IConvertible (throws NotSupportedException - is caught) yield return new TestCase(doubleRange, new IConvertibleImplementor() { DoubleThrow = new NotSupportedException() }); RangeAttribute stringIntRange = new RangeAttribute(typeof(int), "1", "3"); yield return new TestCase(stringIntRange, 0); yield return new TestCase(stringIntRange, "0"); yield return new TestCase(stringIntRange, 4); yield return new TestCase(stringIntRange, "4"); yield return new TestCase(stringIntRange, "abc"); yield return new TestCase(stringIntRange, new object()); // Implements IConvertible (throws NotSupportedException - is caught) yield return new TestCase(stringIntRange, new IConvertibleImplementor() { IntThrow = new NotSupportedException() }); RangeAttribute stringDoubleRange = new RangeAttribute(typeof(double), (1.0).ToString("F1"), (3.0).ToString("F1")); yield return new TestCase(stringDoubleRange, 0.9999999); yield return new TestCase(stringDoubleRange, (0.9999999).ToString()); yield return new TestCase(stringDoubleRange, 3.0000001); yield return new TestCase(stringDoubleRange, (3.0000001).ToString()); yield return new TestCase(stringDoubleRange, "abc"); yield return new TestCase(stringDoubleRange, new object()); // Implements IConvertible (throws NotSupportedException - is caught) yield return new TestCase(stringDoubleRange, new IConvertibleImplementor() { DoubleThrow = new NotSupportedException() }); }
protected override IEnumerable<TestCase> ValidValues() { RangeAttribute intRange = new RangeAttribute(1, 3); yield return new TestCase(intRange, null); yield return new TestCase(intRange, string.Empty); yield return new TestCase(intRange, 1); yield return new TestCase(intRange, 2); yield return new TestCase(intRange, 3); yield return new TestCase(new RangeAttribute(1, 1), 1); RangeAttribute doubleRange = new RangeAttribute(1.0, 3.0); yield return new TestCase(doubleRange, null); yield return new TestCase(doubleRange, string.Empty); yield return new TestCase(doubleRange, 1.0); yield return new TestCase(doubleRange, 2.0); yield return new TestCase(doubleRange, 3.0); yield return new TestCase(new RangeAttribute(1.0, 1.0), 1); RangeAttribute stringIntRange = new RangeAttribute(typeof(int), "1", "3"); yield return new TestCase(stringIntRange, null); yield return new TestCase(stringIntRange, string.Empty); yield return new TestCase(stringIntRange, 1); yield return new TestCase(stringIntRange, "1"); yield return new TestCase(stringIntRange, 2); yield return new TestCase(stringIntRange, "2"); yield return new TestCase(stringIntRange, 3); yield return new TestCase(stringIntRange, "3"); RangeAttribute stringDoubleRange = new RangeAttribute(typeof(double), (1.0).ToString("F1"), (3.0).ToString("F1")); yield return new TestCase(stringDoubleRange, null); yield return new TestCase(stringDoubleRange, string.Empty); yield return new TestCase(stringDoubleRange, 1.0); yield return new TestCase(stringDoubleRange, (1.0).ToString("F1")); yield return new TestCase(stringDoubleRange, 2.0); yield return new TestCase(stringDoubleRange, (2.0).ToString("F1")); yield return new TestCase(stringDoubleRange, 3.0); yield return new TestCase(stringDoubleRange, (3.0).ToString("F1")); }
public static void Validate_MinimumGreaterThanMaximum_ThrowsInvalidOperationException() { var attribute = new RangeAttribute(3, 1); Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object()))); attribute = new RangeAttribute(3.0, 1.0); Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object()))); attribute = new RangeAttribute(typeof(int), "3", "1"); Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object()))); attribute = new RangeAttribute(typeof(double), (3.0).ToString("F1"), (1.0).ToString("F1")); Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object()))); attribute = new RangeAttribute(typeof(string), "z", "a"); Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object()))); }
public static void Validate_ConversionOverflows_ThrowsOverflowException(Type type, string minimum, string maximum, object value) { RangeAttribute attribute = new RangeAttribute(type, minimum, maximum); Assert.Throws<OverflowException>(() => attribute.Validate(value, new ValidationContext(new object()))); }
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="obj">The object the exception should be raised for.</param> /// <param name="field">The field the exception should be raised for.</param> /// <param name="range">The allowed range of the field.</param> internal RangeViolationException(object obj, FieldInfo field, RangeAttribute range) { Object = obj; Field = field; Range = range; }
public static void Ctor_Double_Double() { var attribute = new RangeAttribute(1.0, 3.0); Assert.Equal(1.0, attribute.Minimum); Assert.Equal(3.0, attribute.Maximum); Assert.Equal(typeof(double), attribute.OperandType); }
public static void Ctor_Int_Int() { var attribute = new RangeAttribute(1, 3); Assert.Equal(1, attribute.Minimum); Assert.Equal(3, attribute.Maximum); Assert.Equal(typeof(int), attribute.OperandType); }
public static void Validate_IConvertibleThrowsCustomException_IsNotCaught() { RangeAttribute attribute = new RangeAttribute(typeof(int), "1", "1"); Assert.Throws<ArithmeticException>(() => attribute.Validate(new IConvertibleImplementor() { IntThrow = new ArithmeticException() }, new ValidationContext(new object()))); }
public static void Validate_DoubleConversionOverflows_ThrowsOverflowException(double minimum, double maximum, object value) { RangeAttribute attribute = new RangeAttribute(minimum, maximum); Assert.Throws<OverflowException>(() => attribute.Validate(value, new ValidationContext(new object()))); }
public static void Validate_MinimumOrMaximumCantBeConvertedToType_ThrowsFormatException(Type type, string minimum, string maximum) { RangeAttribute attribute = new RangeAttribute(type, minimum, maximum); Assert.Throws<FormatException>(() => attribute.Validate("Any", new ValidationContext(new object()))); }
/// <summary> /// Gets the range information for the <paramref name="obj" />'s <paramref name="field" /> if it cannot be determined /// automatically by S#. /// Returns <c>false</c> to indicate that no range information is available. /// </summary> /// <param name="obj">The object the range should be determined for.</param> /// <param name="field">The field the range should be determined for.</param> /// <param name="range">Returns the range, if available.</param> protected internal virtual bool TryGetRange(object obj, FieldInfo field, out RangeAttribute range) { range = null; return false; }
public static void Validate_InvalidOperandType_ThrowsInvalidOperationException(Type type) { var attribute = new RangeAttribute(type, "someMinimum", "someMaximum"); Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object()))); }
public static void Ctor_Type_String_String(Type type) { var attribute = new RangeAttribute(type, "SomeMinimum", "SomeMaximum"); Assert.Equal("SomeMinimum", attribute.Minimum); Assert.Equal("SomeMaximum", attribute.Maximum); Assert.Equal(type, attribute.OperandType); }
/// <summary> /// Gets the range information for the <paramref name="obj" />'s <paramref name="field" /> if it cannot be determined /// automatically by S#. /// Returns <c>false</c> to indicate that no range information is available. /// </summary> /// <param name="obj">The object the range should be determined for.</param> /// <param name="field">The field the range should be determined for.</param> /// <param name="range">Returns the range, if available.</param> protected internal override bool TryGetRange(object obj, FieldInfo field, out RangeAttribute range) { if (field.Name != "_size") { range = null; return false; } var capacityProperty = obj.GetType().GetProperty("Capacity"); var capacity = (int)capacityProperty.GetValue(obj); range = new RangeAttribute(0, capacity, OverflowBehavior.Error); return true; }
public static void Validate_MinimumOrMaximumNull_ThrowsInvalidOperationException(string minimum, string maximum) { RangeAttribute attribute = new RangeAttribute(typeof(int), minimum, maximum); Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object()))); }
public void RangeAttribute_valid_with_min_length_not_zero() { var an = new RangeAttribute(1, 5); Assert.AreEqual(1, an.Min); Assert.AreEqual(5, an.Max); Assert.IsFalse(an.IsValid(null, typeof(string))); Assert.IsFalse(an.IsValid(string.Empty, typeof(string))); Assert.IsTrue(an.IsValid("4", typeof(string))); Assert.IsFalse(an.IsValid("28", typeof(string))); }