OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libgo/] [go/] [testing/] [quick/] [quick.go] - Blame information for rev 747

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 747 jeremybenn
// Copyright 2009 The Go Authors. All rights reserved.
2
// Use of this source code is governed by a BSD-style
3
// license that can be found in the LICENSE file.
4
 
5
// Package quick implements utility functions to help with black box testing.
6
package quick
7
 
8
import (
9
        "flag"
10
        "fmt"
11
        "math"
12
        "math/rand"
13
        "reflect"
14
        "strings"
15
)
16
 
17
var defaultMaxCount *int = flag.Int("quickchecks", 100, "The default number of iterations for each check")
18
 
19
// A Generator can generate random values of its own type.
20
type Generator interface {
21
        // Generate returns a random instance of the type on which it is a
22
        // method using the size as a size hint.
23
        Generate(rand *rand.Rand, size int) reflect.Value
24
}
25
 
26
// randFloat32 generates a random float taking the full range of a float32.
27
func randFloat32(rand *rand.Rand) float32 {
28
        f := rand.Float64() * math.MaxFloat32
29
        if rand.Int()&1 == 1 {
30
                f = -f
31
        }
32
        return float32(f)
33
}
34
 
35
// randFloat64 generates a random float taking the full range of a float64.
36
func randFloat64(rand *rand.Rand) float64 {
37
        f := rand.Float64()
38
        if rand.Int()&1 == 1 {
39
                f = -f
40
        }
41
        return f
42
}
43
 
44
// randInt64 returns a random integer taking half the range of an int64.
45
func randInt64(rand *rand.Rand) int64 { return rand.Int63() - 1<<62 }
46
 
47
// complexSize is the maximum length of arbitrary values that contain other
48
// values.
49
const complexSize = 50
50
 
51
// Value returns an arbitrary value of the given type.
52
// If the type implements the Generator interface, that will be used.
53
// Note: in order to create arbitrary values for structs, all the members must be public.
54
func Value(t reflect.Type, rand *rand.Rand) (value reflect.Value, ok bool) {
55
        if m, ok := reflect.Zero(t).Interface().(Generator); ok {
56
                return m.Generate(rand, complexSize), true
57
        }
58
 
59
        switch concrete := t; concrete.Kind() {
60
        case reflect.Bool:
61
                return reflect.ValueOf(rand.Int()&1 == 0), true
62
        case reflect.Float32:
63
                return reflect.ValueOf(randFloat32(rand)), true
64
        case reflect.Float64:
65
                return reflect.ValueOf(randFloat64(rand)), true
66
        case reflect.Complex64:
67
                return reflect.ValueOf(complex(randFloat32(rand), randFloat32(rand))), true
68
        case reflect.Complex128:
69
                return reflect.ValueOf(complex(randFloat64(rand), randFloat64(rand))), true
70
        case reflect.Int16:
71
                return reflect.ValueOf(int16(randInt64(rand))), true
72
        case reflect.Int32:
73
                return reflect.ValueOf(int32(randInt64(rand))), true
74
        case reflect.Int64:
75
                return reflect.ValueOf(randInt64(rand)), true
76
        case reflect.Int8:
77
                return reflect.ValueOf(int8(randInt64(rand))), true
78
        case reflect.Int:
79
                return reflect.ValueOf(int(randInt64(rand))), true
80
        case reflect.Uint16:
81
                return reflect.ValueOf(uint16(randInt64(rand))), true
82
        case reflect.Uint32:
83
                return reflect.ValueOf(uint32(randInt64(rand))), true
84
        case reflect.Uint64:
85
                return reflect.ValueOf(uint64(randInt64(rand))), true
86
        case reflect.Uint8:
87
                return reflect.ValueOf(uint8(randInt64(rand))), true
88
        case reflect.Uint:
89
                return reflect.ValueOf(uint(randInt64(rand))), true
90
        case reflect.Uintptr:
91
                return reflect.ValueOf(uintptr(randInt64(rand))), true
92
        case reflect.Map:
93
                numElems := rand.Intn(complexSize)
94
                m := reflect.MakeMap(concrete)
95
                for i := 0; i < numElems; i++ {
96
                        key, ok1 := Value(concrete.Key(), rand)
97
                        value, ok2 := Value(concrete.Elem(), rand)
98
                        if !ok1 || !ok2 {
99
                                return reflect.Value{}, false
100
                        }
101
                        m.SetMapIndex(key, value)
102
                }
103
                return m, true
104
        case reflect.Ptr:
105
                v, ok := Value(concrete.Elem(), rand)
106
                if !ok {
107
                        return reflect.Value{}, false
108
                }
109
                p := reflect.New(concrete.Elem())
110
                p.Elem().Set(v)
111
                return p, true
112
        case reflect.Slice:
113
                numElems := rand.Intn(complexSize)
114
                s := reflect.MakeSlice(concrete, numElems, numElems)
115
                for i := 0; i < numElems; i++ {
116
                        v, ok := Value(concrete.Elem(), rand)
117
                        if !ok {
118
                                return reflect.Value{}, false
119
                        }
120
                        s.Index(i).Set(v)
121
                }
122
                return s, true
123
        case reflect.String:
124
                numChars := rand.Intn(complexSize)
125
                codePoints := make([]rune, numChars)
126
                for i := 0; i < numChars; i++ {
127
                        codePoints[i] = rune(rand.Intn(0x10ffff))
128
                }
129
                return reflect.ValueOf(string(codePoints)), true
130
        case reflect.Struct:
131
                s := reflect.New(t).Elem()
132
                for i := 0; i < s.NumField(); i++ {
133
                        v, ok := Value(concrete.Field(i).Type, rand)
134
                        if !ok {
135
                                return reflect.Value{}, false
136
                        }
137
                        s.Field(i).Set(v)
138
                }
139
                return s, true
140
        default:
141
                return reflect.Value{}, false
142
        }
143
 
144
        return
145
}
146
 
147
// A Config structure contains options for running a test.
148
type Config struct {
149
        // MaxCount sets the maximum number of iterations. If zero,
150
        // MaxCountScale is used.
151
        MaxCount int
152
        // MaxCountScale is a non-negative scale factor applied to the default
153
        // maximum. If zero, the default is unchanged.
154
        MaxCountScale float64
155
        // If non-nil, rand is a source of random numbers. Otherwise a default
156
        // pseudo-random source will be used.
157
        Rand *rand.Rand
158
        // If non-nil, Values is a function which generates a slice of arbitrary
159
        // Values that are congruent with the arguments to the function being
160
        // tested. Otherwise, Values is used to generate the values.
161
        Values func([]reflect.Value, *rand.Rand)
162
}
163
 
164
var defaultConfig Config
165
 
166
// getRand returns the *rand.Rand to use for a given Config.
167
func (c *Config) getRand() *rand.Rand {
168
        if c.Rand == nil {
169
                return rand.New(rand.NewSource(0))
170
        }
171
        return c.Rand
172
}
173
 
174
// getMaxCount returns the maximum number of iterations to run for a given
175
// Config.
176
func (c *Config) getMaxCount() (maxCount int) {
177
        maxCount = c.MaxCount
178
        if maxCount == 0 {
179
                if c.MaxCountScale != 0 {
180
                        maxCount = int(c.MaxCountScale * float64(*defaultMaxCount))
181
                } else {
182
                        maxCount = *defaultMaxCount
183
                }
184
        }
185
 
186
        return
187
}
188
 
189
// A SetupError is the result of an error in the way that check is being
190
// used, independent of the functions being tested.
191
type SetupError string
192
 
193
func (s SetupError) Error() string { return string(s) }
194
 
195
// A CheckError is the result of Check finding an error.
196
type CheckError struct {
197
        Count int
198
        In    []interface{}
199
}
200
 
201
func (s *CheckError) Error() string {
202
        return fmt.Sprintf("#%d: failed on input %s", s.Count, toString(s.In))
203
}
204
 
205
// A CheckEqualError is the result CheckEqual finding an error.
206
type CheckEqualError struct {
207
        CheckError
208
        Out1 []interface{}
209
        Out2 []interface{}
210
}
211
 
212
func (s *CheckEqualError) Error() string {
213
        return fmt.Sprintf("#%d: failed on input %s. Output 1: %s. Output 2: %s", s.Count, toString(s.In), toString(s.Out1), toString(s.Out2))
214
}
215
 
216
// Check looks for an input to f, any function that returns bool,
217
// such that f returns false.  It calls f repeatedly, with arbitrary
218
// values for each argument.  If f returns false on a given input,
219
// Check returns that input as a *CheckError.
220
// For example:
221
//
222
//      func TestOddMultipleOfThree(t *testing.T) {
223
//              f := func(x int) bool {
224
//                      y := OddMultipleOfThree(x)
225
//                      return y%2 == 1 && y%3 == 0
226
//              }
227
//              if err := quick.Check(f, nil); err != nil {
228
//                      t.Error(err)
229
//              }
230
//      }
231
func Check(function interface{}, config *Config) (err error) {
232
        if config == nil {
233
                config = &defaultConfig
234
        }
235
 
236
        f, fType, ok := functionAndType(function)
237
        if !ok {
238
                err = SetupError("argument is not a function")
239
                return
240
        }
241
 
242
        if fType.NumOut() != 1 {
243
                err = SetupError("function returns more than one value.")
244
                return
245
        }
246
        if fType.Out(0).Kind() != reflect.Bool {
247
                err = SetupError("function does not return a bool")
248
                return
249
        }
250
 
251
        arguments := make([]reflect.Value, fType.NumIn())
252
        rand := config.getRand()
253
        maxCount := config.getMaxCount()
254
 
255
        for i := 0; i < maxCount; i++ {
256
                err = arbitraryValues(arguments, fType, config, rand)
257
                if err != nil {
258
                        return
259
                }
260
 
261
                if !f.Call(arguments)[0].Bool() {
262
                        err = &CheckError{i + 1, toInterfaces(arguments)}
263
                        return
264
                }
265
        }
266
 
267
        return
268
}
269
 
270
// CheckEqual looks for an input on which f and g return different results.
271
// It calls f and g repeatedly with arbitrary values for each argument.
272
// If f and g return different answers, CheckEqual returns a *CheckEqualError
273
// describing the input and the outputs.
274
func CheckEqual(f, g interface{}, config *Config) (err error) {
275
        if config == nil {
276
                config = &defaultConfig
277
        }
278
 
279
        x, xType, ok := functionAndType(f)
280
        if !ok {
281
                err = SetupError("f is not a function")
282
                return
283
        }
284
        y, yType, ok := functionAndType(g)
285
        if !ok {
286
                err = SetupError("g is not a function")
287
                return
288
        }
289
 
290
        if xType != yType {
291
                err = SetupError("functions have different types")
292
                return
293
        }
294
 
295
        arguments := make([]reflect.Value, xType.NumIn())
296
        rand := config.getRand()
297
        maxCount := config.getMaxCount()
298
 
299
        for i := 0; i < maxCount; i++ {
300
                err = arbitraryValues(arguments, xType, config, rand)
301
                if err != nil {
302
                        return
303
                }
304
 
305
                xOut := toInterfaces(x.Call(arguments))
306
                yOut := toInterfaces(y.Call(arguments))
307
 
308
                if !reflect.DeepEqual(xOut, yOut) {
309
                        err = &CheckEqualError{CheckError{i + 1, toInterfaces(arguments)}, xOut, yOut}
310
                        return
311
                }
312
        }
313
 
314
        return
315
}
316
 
317
// arbitraryValues writes Values to args such that args contains Values
318
// suitable for calling f.
319
func arbitraryValues(args []reflect.Value, f reflect.Type, config *Config, rand *rand.Rand) (err error) {
320
        if config.Values != nil {
321
                config.Values(args, rand)
322
                return
323
        }
324
 
325
        for j := 0; j < len(args); j++ {
326
                var ok bool
327
                args[j], ok = Value(f.In(j), rand)
328
                if !ok {
329
                        err = SetupError(fmt.Sprintf("cannot create arbitrary value of type %s for argument %d", f.In(j), j))
330
                        return
331
                }
332
        }
333
 
334
        return
335
}
336
 
337
func functionAndType(f interface{}) (v reflect.Value, t reflect.Type, ok bool) {
338
        v = reflect.ValueOf(f)
339
        ok = v.Kind() == reflect.Func
340
        if !ok {
341
                return
342
        }
343
        t = v.Type()
344
        return
345
}
346
 
347
func toInterfaces(values []reflect.Value) []interface{} {
348
        ret := make([]interface{}, len(values))
349
        for i, v := range values {
350
                ret[i] = v.Interface()
351
        }
352
        return ret
353
}
354
 
355
func toString(interfaces []interface{}) string {
356
        s := make([]string, len(interfaces))
357
        for i, v := range interfaces {
358
                s[i] = fmt.Sprintf("%#v", v)
359
        }
360
        return strings.Join(s, ", ")
361
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.