/src/NUnit/framework/Attributes/RandomAttribute.cs
C# | 102 lines | 60 code | 10 blank | 32 comment | 2 complexity | 6cdd6b04fc58d4d29784d9c4cdcde84f MD5 | raw file
1// **************************************************************** 2// Copyright 2008, Charlie Poole 3// This is free software licensed under the NUnit license. You may 4// obtain a copy of the license at http://nunit.org 5// **************************************************************** 6 7using System; 8using System.Collections; 9using System.Reflection; 10 11namespace NUnit.Framework 12{ 13 /// <summary> 14 /// RandomAttribute is used to supply a set of random values 15 /// to a single parameter of a parameterized test. 16 /// </summary> 17 public class RandomAttribute : ValuesAttribute 18 { 19 enum SampleType 20 { 21 Raw, 22 IntRange, 23 DoubleRange 24 } 25 26 SampleType sampleType; 27 private int count; 28 private int min, max; 29 private double dmin, dmax; 30 31 /// <summary> 32 /// Construct a set of doubles from 0.0 to 1.0, 33 /// specifying only the count. 34 /// </summary> 35 /// <param name="count"></param> 36 public RandomAttribute(int count) 37 { 38 this.count = count; 39 this.sampleType = SampleType.Raw; 40 } 41 42 /// <summary> 43 /// Construct a set of doubles from min to max 44 /// </summary> 45 /// <param name="min"></param> 46 /// <param name="max"></param> 47 /// <param name="count"></param> 48 public RandomAttribute(double min, double max, int count) 49 { 50 this.count = count; 51 this.dmin = min; 52 this.dmax = max; 53 this.sampleType = SampleType.DoubleRange; 54 } 55 56 /// <summary> 57 /// Construct a set of ints from min to max 58 /// </summary> 59 /// <param name="min"></param> 60 /// <param name="max"></param> 61 /// <param name="count"></param> 62 public RandomAttribute(int min, int max, int count) 63 { 64 this.count = count; 65 this.min = min; 66 this.max = max; 67 this.sampleType = SampleType.IntRange; 68 } 69 70 /// <summary> 71 /// Get the collection of values to be used as arguments 72 /// </summary> 73 public override IEnumerable GetData(ParameterInfo parameter) 74 { 75 Randomizer r = Randomizer.GetRandomizer(parameter); 76 IList values; 77 78 switch (sampleType) 79 { 80 default: 81 case SampleType.Raw: 82 values = r.GetDoubles(count); 83 break; 84 case SampleType.IntRange: 85 values = r.GetInts(min, max, count); 86 break; 87 case SampleType.DoubleRange: 88 values = r.GetDoubles(dmin, dmax, count); 89 break; 90 } 91 92 // Copy the random values into the data array 93 // and call the base class which may need to 94 // convert them to another type. 95 this.data = new object[values.Count]; 96 for (int i = 0; i < values.Count; i++) 97 this.data[i] = values[i]; 98 99 return base.GetData(parameter); 100 } 101 } 102}