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

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libgo/] [go/] [reflect/] [all_test.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 reflect_test
6
 
7
import (
8
        "bytes"
9
        "encoding/base64"
10
        "fmt"
11
        "io"
12
        "os"
13
        . "reflect"
14
        /*      "runtime" */
15
        "testing"
16
        "unsafe"
17
)
18
 
19
func TestBool(t *testing.T) {
20
        v := ValueOf(true)
21
        if v.Bool() != true {
22
                t.Fatal("ValueOf(true).Bool() = false")
23
        }
24
}
25
 
26
type integer int
27
type T struct {
28
        a int
29
        b float64
30
        c string
31
        d *int
32
}
33
 
34
type pair struct {
35
        i interface{}
36
        s string
37
}
38
 
39
func isDigit(c uint8) bool { return '0' <= c && c <= '9' }
40
 
41
func assert(t *testing.T, s, want string) {
42
        if s != want {
43
                t.Errorf("have %#q want %#q", s, want)
44
        }
45
}
46
 
47
func typestring(i interface{}) string { return TypeOf(i).String() }
48
 
49
var typeTests = []pair{
50
        {struct{ x int }{}, "int"},
51
        {struct{ x int8 }{}, "int8"},
52
        {struct{ x int16 }{}, "int16"},
53
        {struct{ x int32 }{}, "int32"},
54
        {struct{ x int64 }{}, "int64"},
55
        {struct{ x uint }{}, "uint"},
56
        {struct{ x uint8 }{}, "uint8"},
57
        {struct{ x uint16 }{}, "uint16"},
58
        {struct{ x uint32 }{}, "uint32"},
59
        {struct{ x uint64 }{}, "uint64"},
60
        {struct{ x float32 }{}, "float32"},
61
        {struct{ x float64 }{}, "float64"},
62
        {struct{ x int8 }{}, "int8"},
63
        {struct{ x (**int8) }{}, "**int8"},
64
        {struct{ x (**integer) }{}, "**reflect_test.integer"},
65
        {struct{ x ([32]int32) }{}, "[32]int32"},
66
        {struct{ x ([]int8) }{}, "[]int8"},
67
        {struct{ x (map[string]int32) }{}, "map[string]int32"},
68
        {struct{ x (chan<- string) }{}, "chan<- string"},
69
        {struct {
70
                x struct {
71
                        c chan *int32
72
                        d float32
73
                }
74
        }{},
75
                "struct { c chan *int32; d float32 }",
76
        },
77
        {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
78
        {struct {
79
                x struct {
80
                        c func(chan *integer, *int8)
81
                }
82
        }{},
83
                "struct { c func(chan *reflect_test.integer, *int8) }",
84
        },
85
        {struct {
86
                x struct {
87
                        a int8
88
                        b int32
89
                }
90
        }{},
91
                "struct { a int8; b int32 }",
92
        },
93
        {struct {
94
                x struct {
95
                        a int8
96
                        b int8
97
                        c int32
98
                }
99
        }{},
100
                "struct { a int8; b int8; c int32 }",
101
        },
102
        {struct {
103
                x struct {
104
                        a int8
105
                        b int8
106
                        c int8
107
                        d int32
108
                }
109
        }{},
110
                "struct { a int8; b int8; c int8; d int32 }",
111
        },
112
        {struct {
113
                x struct {
114
                        a int8
115
                        b int8
116
                        c int8
117
                        d int8
118
                        e int32
119
                }
120
        }{},
121
                "struct { a int8; b int8; c int8; d int8; e int32 }",
122
        },
123
        {struct {
124
                x struct {
125
                        a int8
126
                        b int8
127
                        c int8
128
                        d int8
129
                        e int8
130
                        f int32
131
                }
132
        }{},
133
                "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
134
        },
135
        {struct {
136
                x struct {
137
                        a int8 `reflect:"hi there"`
138
                }
139
        }{},
140
                `struct { a int8 "reflect:\"hi there\"" }`,
141
        },
142
        {struct {
143
                x struct {
144
                        a int8 `reflect:"hi \x00there\t\n\"\\"`
145
                }
146
        }{},
147
                `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
148
        },
149
        {struct {
150
                x struct {
151
                        f func(args ...int)
152
                }
153
        }{},
154
                "struct { f func(...int) }",
155
        },
156
        {struct {
157
                x (interface {
158
                        a(func(func(int) int) func(func(int)) int)
159
                        b()
160
                })
161
        }{},
162
                "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
163
        },
164
}
165
 
166
var valueTests = []pair{
167
        {new(int8), "8"},
168
        {new(int16), "16"},
169
        {new(int32), "32"},
170
        {new(int64), "64"},
171
        {new(uint8), "8"},
172
        {new(uint16), "16"},
173
        {new(uint32), "32"},
174
        {new(uint64), "64"},
175
        {new(float32), "256.25"},
176
        {new(float64), "512.125"},
177
        {new(string), "stringy cheese"},
178
        {new(bool), "true"},
179
        {new(*int8), "*int8(0)"},
180
        {new(**int8), "**int8(0)"},
181
        {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
182
        {new(**integer), "**reflect_test.integer(0)"},
183
        {new(map[string]int32), "map[string]int32{}"},
184
        {new(chan<- string), "chan<- string"},
185
        {new(func(a int8, b int32)), "func(int8, int32)(0)"},
186
        {new(struct {
187
                c chan *int32
188
                d float32
189
        }),
190
                "struct { c chan *int32; d float32 }{chan *int32, 0}",
191
        },
192
        {new(struct{ c func(chan *integer, *int8) }),
193
                "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
194
        },
195
        {new(struct {
196
                a int8
197
                b int32
198
        }),
199
                "struct { a int8; b int32 }{0, 0}",
200
        },
201
        {new(struct {
202
                a int8
203
                b int8
204
                c int32
205
        }),
206
                "struct { a int8; b int8; c int32 }{0, 0, 0}",
207
        },
208
}
209
 
210
func testType(t *testing.T, i int, typ Type, want string) {
211
        s := typ.String()
212
        if s != want {
213
                t.Errorf("#%d: have %#q, want %#q", i, s, want)
214
        }
215
}
216
 
217
func TestTypes(t *testing.T) {
218
        for i, tt := range typeTests {
219
                testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
220
        }
221
}
222
 
223
func TestSet(t *testing.T) {
224
        for i, tt := range valueTests {
225
                v := ValueOf(tt.i)
226
                v = v.Elem()
227
                switch v.Kind() {
228
                case Int:
229
                        v.SetInt(132)
230
                case Int8:
231
                        v.SetInt(8)
232
                case Int16:
233
                        v.SetInt(16)
234
                case Int32:
235
                        v.SetInt(32)
236
                case Int64:
237
                        v.SetInt(64)
238
                case Uint:
239
                        v.SetUint(132)
240
                case Uint8:
241
                        v.SetUint(8)
242
                case Uint16:
243
                        v.SetUint(16)
244
                case Uint32:
245
                        v.SetUint(32)
246
                case Uint64:
247
                        v.SetUint(64)
248
                case Float32:
249
                        v.SetFloat(256.25)
250
                case Float64:
251
                        v.SetFloat(512.125)
252
                case Complex64:
253
                        v.SetComplex(532.125 + 10i)
254
                case Complex128:
255
                        v.SetComplex(564.25 + 1i)
256
                case String:
257
                        v.SetString("stringy cheese")
258
                case Bool:
259
                        v.SetBool(true)
260
                }
261
                s := valueToString(v)
262
                if s != tt.s {
263
                        t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
264
                }
265
        }
266
}
267
 
268
func TestSetValue(t *testing.T) {
269
        for i, tt := range valueTests {
270
                v := ValueOf(tt.i).Elem()
271
                switch v.Kind() {
272
                case Int:
273
                        v.Set(ValueOf(int(132)))
274
                case Int8:
275
                        v.Set(ValueOf(int8(8)))
276
                case Int16:
277
                        v.Set(ValueOf(int16(16)))
278
                case Int32:
279
                        v.Set(ValueOf(int32(32)))
280
                case Int64:
281
                        v.Set(ValueOf(int64(64)))
282
                case Uint:
283
                        v.Set(ValueOf(uint(132)))
284
                case Uint8:
285
                        v.Set(ValueOf(uint8(8)))
286
                case Uint16:
287
                        v.Set(ValueOf(uint16(16)))
288
                case Uint32:
289
                        v.Set(ValueOf(uint32(32)))
290
                case Uint64:
291
                        v.Set(ValueOf(uint64(64)))
292
                case Float32:
293
                        v.Set(ValueOf(float32(256.25)))
294
                case Float64:
295
                        v.Set(ValueOf(512.125))
296
                case Complex64:
297
                        v.Set(ValueOf(complex64(532.125 + 10i)))
298
                case Complex128:
299
                        v.Set(ValueOf(complex128(564.25 + 1i)))
300
                case String:
301
                        v.Set(ValueOf("stringy cheese"))
302
                case Bool:
303
                        v.Set(ValueOf(true))
304
                }
305
                s := valueToString(v)
306
                if s != tt.s {
307
                        t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
308
                }
309
        }
310
}
311
 
312
var _i = 7
313
 
314
var valueToStringTests = []pair{
315
        {123, "123"},
316
        {123.5, "123.5"},
317
        {byte(123), "123"},
318
        {"abc", "abc"},
319
        {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
320
        {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
321
        {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
322
        {&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[10]int(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
323
        {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
324
        {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
325
}
326
 
327
func TestValueToString(t *testing.T) {
328
        for i, test := range valueToStringTests {
329
                s := valueToString(ValueOf(test.i))
330
                if s != test.s {
331
                        t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
332
                }
333
        }
334
}
335
 
336
func TestArrayElemSet(t *testing.T) {
337
        v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
338
        v.Index(4).SetInt(123)
339
        s := valueToString(v)
340
        const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
341
        if s != want {
342
                t.Errorf("[10]int: have %#q want %#q", s, want)
343
        }
344
 
345
        v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
346
        v.Index(4).SetInt(123)
347
        s = valueToString(v)
348
        const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
349
        if s != want1 {
350
                t.Errorf("[]int: have %#q want %#q", s, want1)
351
        }
352
}
353
 
354
func TestPtrPointTo(t *testing.T) {
355
        var ip *int32
356
        var i int32 = 1234
357
        vip := ValueOf(&ip)
358
        vi := ValueOf(&i).Elem()
359
        vip.Elem().Set(vi.Addr())
360
        if *ip != 1234 {
361
                t.Errorf("got %d, want 1234", *ip)
362
        }
363
 
364
        ip = nil
365
        vp := ValueOf(&ip).Elem()
366
        vp.Set(Zero(vp.Type()))
367
        if ip != nil {
368
                t.Errorf("got non-nil (%p), want nil", ip)
369
        }
370
}
371
 
372
func TestPtrSetNil(t *testing.T) {
373
        var i int32 = 1234
374
        ip := &i
375
        vip := ValueOf(&ip)
376
        vip.Elem().Set(Zero(vip.Elem().Type()))
377
        if ip != nil {
378
                t.Errorf("got non-nil (%d), want nil", *ip)
379
        }
380
}
381
 
382
func TestMapSetNil(t *testing.T) {
383
        m := make(map[string]int)
384
        vm := ValueOf(&m)
385
        vm.Elem().Set(Zero(vm.Elem().Type()))
386
        if m != nil {
387
                t.Errorf("got non-nil (%p), want nil", m)
388
        }
389
}
390
 
391
func TestAll(t *testing.T) {
392
        testType(t, 1, TypeOf((int8)(0)), "int8")
393
        testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
394
 
395
        typ := TypeOf((*struct {
396
                c chan *int32
397
                d float32
398
        })(nil))
399
        testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
400
        etyp := typ.Elem()
401
        testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
402
        styp := etyp
403
        f := styp.Field(0)
404
        testType(t, 5, f.Type, "chan *int32")
405
 
406
        f, present := styp.FieldByName("d")
407
        if !present {
408
                t.Errorf("FieldByName says present field is absent")
409
        }
410
        testType(t, 6, f.Type, "float32")
411
 
412
        f, present = styp.FieldByName("absent")
413
        if present {
414
                t.Errorf("FieldByName says absent field is present")
415
        }
416
 
417
        typ = TypeOf([32]int32{})
418
        testType(t, 7, typ, "[32]int32")
419
        testType(t, 8, typ.Elem(), "int32")
420
 
421
        typ = TypeOf((map[string]*int32)(nil))
422
        testType(t, 9, typ, "map[string]*int32")
423
        mtyp := typ
424
        testType(t, 10, mtyp.Key(), "string")
425
        testType(t, 11, mtyp.Elem(), "*int32")
426
 
427
        typ = TypeOf((chan<- string)(nil))
428
        testType(t, 12, typ, "chan<- string")
429
        testType(t, 13, typ.Elem(), "string")
430
 
431
        // make sure tag strings are not part of element type
432
        typ = TypeOf(struct {
433
                d []uint32 `reflect:"TAG"`
434
        }{}).Field(0).Type
435
        testType(t, 14, typ, "[]uint32")
436
}
437
 
438
func TestInterfaceGet(t *testing.T) {
439
        var inter struct {
440
                E interface{}
441
        }
442
        inter.E = 123.456
443
        v1 := ValueOf(&inter)
444
        v2 := v1.Elem().Field(0)
445
        assert(t, v2.Type().String(), "interface {}")
446
        i2 := v2.Interface()
447
        v3 := ValueOf(i2)
448
        assert(t, v3.Type().String(), "float64")
449
}
450
 
451
func TestInterfaceValue(t *testing.T) {
452
        var inter struct {
453
                E interface{}
454
        }
455
        inter.E = 123.456
456
        v1 := ValueOf(&inter)
457
        v2 := v1.Elem().Field(0)
458
        assert(t, v2.Type().String(), "interface {}")
459
        v3 := v2.Elem()
460
        assert(t, v3.Type().String(), "float64")
461
 
462
        i3 := v2.Interface()
463
        if _, ok := i3.(float64); !ok {
464
                t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
465
        }
466
}
467
 
468
func TestFunctionValue(t *testing.T) {
469
        var x interface{} = func() {}
470
        v := ValueOf(x)
471
        if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
472
                t.Fatalf("TestFunction returned wrong pointer")
473
        }
474
        assert(t, v.Type().String(), "func()")
475
}
476
 
477
var appendTests = []struct {
478
        orig, extra []int
479
}{
480
        {make([]int, 2, 4), []int{22}},
481
        {make([]int, 2, 4), []int{22, 33, 44}},
482
}
483
 
484
func sameInts(x, y []int) bool {
485
        if len(x) != len(y) {
486
                return false
487
        }
488
        for i, xx := range x {
489
                if xx != y[i] {
490
                        return false
491
                }
492
        }
493
        return true
494
}
495
 
496
func TestAppend(t *testing.T) {
497
        for i, test := range appendTests {
498
                origLen, extraLen := len(test.orig), len(test.extra)
499
                want := append(test.orig, test.extra...)
500
                // Convert extra from []int to []Value.
501
                e0 := make([]Value, len(test.extra))
502
                for j, e := range test.extra {
503
                        e0[j] = ValueOf(e)
504
                }
505
                // Convert extra from []int to *SliceValue.
506
                e1 := ValueOf(test.extra)
507
                // Test Append.
508
                a0 := ValueOf(test.orig)
509
                have0 := Append(a0, e0...).Interface().([]int)
510
                if !sameInts(have0, want) {
511
                        t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
512
                }
513
                // Check that the orig and extra slices were not modified.
514
                if len(test.orig) != origLen {
515
                        t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
516
                }
517
                if len(test.extra) != extraLen {
518
                        t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
519
                }
520
                // Test AppendSlice.
521
                a1 := ValueOf(test.orig)
522
                have1 := AppendSlice(a1, e1).Interface().([]int)
523
                if !sameInts(have1, want) {
524
                        t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
525
                }
526
                // Check that the orig and extra slices were not modified.
527
                if len(test.orig) != origLen {
528
                        t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
529
                }
530
                if len(test.extra) != extraLen {
531
                        t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
532
                }
533
        }
534
}
535
 
536
func TestCopy(t *testing.T) {
537
        a := []int{1, 2, 3, 4, 10, 9, 8, 7}
538
        b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
539
        c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
540
        for i := 0; i < len(b); i++ {
541
                if b[i] != c[i] {
542
                        t.Fatalf("b != c before test")
543
                }
544
        }
545
        a1 := a
546
        b1 := b
547
        aa := ValueOf(&a1).Elem()
548
        ab := ValueOf(&b1).Elem()
549
        for tocopy := 1; tocopy <= 7; tocopy++ {
550
                aa.SetLen(tocopy)
551
                Copy(ab, aa)
552
                aa.SetLen(8)
553
                for i := 0; i < tocopy; i++ {
554
                        if a[i] != b[i] {
555
                                t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
556
                                        tocopy, i, a[i], i, b[i])
557
                        }
558
                }
559
                for i := tocopy; i < len(b); i++ {
560
                        if b[i] != c[i] {
561
                                if i < len(a) {
562
                                        t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
563
                                                tocopy, i, a[i], i, b[i], i, c[i])
564
                                } else {
565
                                        t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
566
                                                tocopy, i, b[i], i, c[i])
567
                                }
568
                        } else {
569
                                t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
570
                        }
571
                }
572
        }
573
}
574
 
575
func TestCopyArray(t *testing.T) {
576
        a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
577
        b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
578
        c := b
579
        aa := ValueOf(&a).Elem()
580
        ab := ValueOf(&b).Elem()
581
        Copy(ab, aa)
582
        for i := 0; i < len(a); i++ {
583
                if a[i] != b[i] {
584
                        t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
585
                }
586
        }
587
        for i := len(a); i < len(b); i++ {
588
                if b[i] != c[i] {
589
                        t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
590
                } else {
591
                        t.Logf("elem %d is okay\n", i)
592
                }
593
        }
594
}
595
 
596
func TestBigUnnamedStruct(t *testing.T) {
597
        b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
598
        v := ValueOf(b)
599
        b1 := v.Interface().(struct {
600
                a, b, c, d int64
601
        })
602
        if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
603
                t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
604
        }
605
}
606
 
607
type big struct {
608
        a, b, c, d, e int64
609
}
610
 
611
func TestBigStruct(t *testing.T) {
612
        b := big{1, 2, 3, 4, 5}
613
        v := ValueOf(b)
614
        b1 := v.Interface().(big)
615
        if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
616
                t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
617
        }
618
}
619
 
620
type Basic struct {
621
        x int
622
        y float32
623
}
624
 
625
type NotBasic Basic
626
 
627
type DeepEqualTest struct {
628
        a, b interface{}
629
        eq   bool
630
}
631
 
632
var deepEqualTests = []DeepEqualTest{
633
        // Equalities
634
        {1, 1, true},
635
        {int32(1), int32(1), true},
636
        {0.5, 0.5, true},
637
        {float32(0.5), float32(0.5), true},
638
        {"hello", "hello", true},
639
        {make([]int, 10), make([]int, 10), true},
640
        {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
641
        {Basic{1, 0.5}, Basic{1, 0.5}, true},
642
        {error(nil), error(nil), true},
643
        {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
644
 
645
        // Inequalities
646
        {1, 2, false},
647
        {int32(1), int32(2), false},
648
        {0.5, 0.6, false},
649
        {float32(0.5), float32(0.6), false},
650
        {"hello", "hey", false},
651
        {make([]int, 10), make([]int, 11), false},
652
        {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
653
        {Basic{1, 0.5}, Basic{1, 0.6}, false},
654
        {Basic{1, 0}, Basic{2, 0}, false},
655
        {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
656
        {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
657
        {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
658
        {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
659
        {nil, 1, false},
660
        {1, nil, false},
661
 
662
        // Nil vs empty: not the same.
663
        {[]int{}, []int(nil), false},
664
        {[]int{}, []int{}, true},
665
        {[]int(nil), []int(nil), true},
666
        {map[int]int{}, map[int]int(nil), false},
667
        {map[int]int{}, map[int]int{}, true},
668
        {map[int]int(nil), map[int]int(nil), true},
669
 
670
        // Mismatched types
671
        {1, 1.0, false},
672
        {int32(1), int64(1), false},
673
        {0.5, "hello", false},
674
        {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
675
        {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
676
        {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
677
        {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
678
}
679
 
680
func TestDeepEqual(t *testing.T) {
681
        for _, test := range deepEqualTests {
682
                if r := DeepEqual(test.a, test.b); r != test.eq {
683
                        t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq)
684
                }
685
        }
686
}
687
 
688
func TestTypeOf(t *testing.T) {
689
        for _, test := range deepEqualTests {
690
                v := ValueOf(test.a)
691
                if !v.IsValid() {
692
                        continue
693
                }
694
                typ := TypeOf(test.a)
695
                if typ != v.Type() {
696
                        t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
697
                }
698
        }
699
}
700
 
701
type Recursive struct {
702
        x int
703
        r *Recursive
704
}
705
 
706
func TestDeepEqualRecursiveStruct(t *testing.T) {
707
        a, b := new(Recursive), new(Recursive)
708
        *a = Recursive{12, a}
709
        *b = Recursive{12, b}
710
        if !DeepEqual(a, b) {
711
                t.Error("DeepEqual(recursive same) = false, want true")
712
        }
713
}
714
 
715
type _Complex struct {
716
        a int
717
        b [3]*_Complex
718
        c *string
719
        d map[float64]float64
720
}
721
 
722
func TestDeepEqualComplexStruct(t *testing.T) {
723
        m := make(map[float64]float64)
724
        stra, strb := "hello", "hello"
725
        a, b := new(_Complex), new(_Complex)
726
        *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
727
        *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
728
        if !DeepEqual(a, b) {
729
                t.Error("DeepEqual(complex same) = false, want true")
730
        }
731
}
732
 
733
func TestDeepEqualComplexStructInequality(t *testing.T) {
734
        m := make(map[float64]float64)
735
        stra, strb := "hello", "helloo" // Difference is here
736
        a, b := new(_Complex), new(_Complex)
737
        *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
738
        *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
739
        if DeepEqual(a, b) {
740
                t.Error("DeepEqual(complex different) = true, want false")
741
        }
742
}
743
 
744
type UnexpT struct {
745
        m map[int]int
746
}
747
 
748
func TestDeepEqualUnexportedMap(t *testing.T) {
749
        // Check that DeepEqual can look at unexported fields.
750
        x1 := UnexpT{map[int]int{1: 2}}
751
        x2 := UnexpT{map[int]int{1: 2}}
752
        if !DeepEqual(&x1, &x2) {
753
                t.Error("DeepEqual(x1, x2) = false, want true")
754
        }
755
 
756
        y1 := UnexpT{map[int]int{2: 3}}
757
        if DeepEqual(&x1, &y1) {
758
                t.Error("DeepEqual(x1, y1) = true, want false")
759
        }
760
}
761
 
762
func check2ndField(x interface{}, offs uintptr, t *testing.T) {
763
        s := ValueOf(x)
764
        f := s.Type().Field(1)
765
        if f.Offset != offs {
766
                t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
767
        }
768
}
769
 
770
// Check that structure alignment & offsets viewed through reflect agree with those
771
// from the compiler itself.
772
func TestAlignment(t *testing.T) {
773
        type T1inner struct {
774
                a int
775
        }
776
        type T1 struct {
777
                T1inner
778
                f int
779
        }
780
        type T2inner struct {
781
                a, b int
782
        }
783
        type T2 struct {
784
                T2inner
785
                f int
786
        }
787
 
788
        x := T1{T1inner{2}, 17}
789
        check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
790
 
791
        x1 := T2{T2inner{2, 3}, 17}
792
        check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
793
}
794
 
795
func Nil(a interface{}, t *testing.T) {
796
        n := ValueOf(a).Field(0)
797
        if !n.IsNil() {
798
                t.Errorf("%v should be nil", a)
799
        }
800
}
801
 
802
func NotNil(a interface{}, t *testing.T) {
803
        n := ValueOf(a).Field(0)
804
        if n.IsNil() {
805
                t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
806
        }
807
}
808
 
809
func TestIsNil(t *testing.T) {
810
        // These implement IsNil.
811
        // Wrap in extra struct to hide interface type.
812
        doNil := []interface{}{
813
                struct{ x *int }{},
814
                struct{ x interface{} }{},
815
                struct{ x map[string]int }{},
816
                struct{ x func() bool }{},
817
                struct{ x chan int }{},
818
                struct{ x []string }{},
819
        }
820
        for _, ts := range doNil {
821
                ty := TypeOf(ts).Field(0).Type
822
                v := Zero(ty)
823
                v.IsNil() // panics if not okay to call
824
        }
825
 
826
        // Check the implementations
827
        var pi struct {
828
                x *int
829
        }
830
        Nil(pi, t)
831
        pi.x = new(int)
832
        NotNil(pi, t)
833
 
834
        var si struct {
835
                x []int
836
        }
837
        Nil(si, t)
838
        si.x = make([]int, 10)
839
        NotNil(si, t)
840
 
841
        var ci struct {
842
                x chan int
843
        }
844
        Nil(ci, t)
845
        ci.x = make(chan int)
846
        NotNil(ci, t)
847
 
848
        var mi struct {
849
                x map[int]int
850
        }
851
        Nil(mi, t)
852
        mi.x = make(map[int]int)
853
        NotNil(mi, t)
854
 
855
        var ii struct {
856
                x interface{}
857
        }
858
        Nil(ii, t)
859
        ii.x = 2
860
        NotNil(ii, t)
861
 
862
        var fi struct {
863
                x func(t *testing.T)
864
        }
865
        Nil(fi, t)
866
        fi.x = TestIsNil
867
        NotNil(fi, t)
868
}
869
 
870
func TestInterfaceExtraction(t *testing.T) {
871
        var s struct {
872
                W io.Writer
873
        }
874
 
875
        s.W = os.Stdout
876
        v := Indirect(ValueOf(&s)).Field(0).Interface()
877
        if v != s.W.(interface{}) {
878
                t.Error("Interface() on interface: ", v, s.W)
879
        }
880
}
881
 
882
func TestNilPtrValueSub(t *testing.T) {
883
        var pi *int
884
        if pv := ValueOf(pi); pv.Elem().IsValid() {
885
                t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
886
        }
887
}
888
 
889
func TestMap(t *testing.T) {
890
        m := map[string]int{"a": 1, "b": 2}
891
        mv := ValueOf(m)
892
        if n := mv.Len(); n != len(m) {
893
                t.Errorf("Len = %d, want %d", n, len(m))
894
        }
895
        keys := mv.MapKeys()
896
        newmap := MakeMap(mv.Type())
897
        for k, v := range m {
898
                // Check that returned Keys match keys in range.
899
                // These aren't required to be in the same order.
900
                seen := false
901
                for _, kv := range keys {
902
                        if kv.String() == k {
903
                                seen = true
904
                                break
905
                        }
906
                }
907
                if !seen {
908
                        t.Errorf("Missing key %q", k)
909
                }
910
 
911
                // Check that value lookup is correct.
912
                vv := mv.MapIndex(ValueOf(k))
913
                if vi := vv.Int(); vi != int64(v) {
914
                        t.Errorf("Key %q: have value %d, want %d", k, vi, v)
915
                }
916
 
917
                // Copy into new map.
918
                newmap.SetMapIndex(ValueOf(k), ValueOf(v))
919
        }
920
        vv := mv.MapIndex(ValueOf("not-present"))
921
        if vv.IsValid() {
922
                t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
923
        }
924
 
925
        newm := newmap.Interface().(map[string]int)
926
        if len(newm) != len(m) {
927
                t.Errorf("length after copy: newm=%d, m=%d", newm, m)
928
        }
929
 
930
        for k, v := range newm {
931
                mv, ok := m[k]
932
                if mv != v {
933
                        t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
934
                }
935
        }
936
 
937
        newmap.SetMapIndex(ValueOf("a"), Value{})
938
        v, ok := newm["a"]
939
        if ok {
940
                t.Errorf("newm[\"a\"] = %d after delete", v)
941
        }
942
 
943
        mv = ValueOf(&m).Elem()
944
        mv.Set(Zero(mv.Type()))
945
        if m != nil {
946
                t.Errorf("mv.Set(nil) failed")
947
        }
948
}
949
 
950
func TestChan(t *testing.T) {
951
        for loop := 0; loop < 2; loop++ {
952
                var c chan int
953
                var cv Value
954
 
955
                // check both ways to allocate channels
956
                switch loop {
957
                case 1:
958
                        c = make(chan int, 1)
959
                        cv = ValueOf(c)
960
                case 0:
961
                        cv = MakeChan(TypeOf(c), 1)
962
                        c = cv.Interface().(chan int)
963
                }
964
 
965
                // Send
966
                cv.Send(ValueOf(2))
967
                if i := <-c; i != 2 {
968
                        t.Errorf("reflect Send 2, native recv %d", i)
969
                }
970
 
971
                // Recv
972
                c <- 3
973
                if i, ok := cv.Recv(); i.Int() != 3 || !ok {
974
                        t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
975
                }
976
 
977
                // TryRecv fail
978
                val, ok := cv.TryRecv()
979
                if val.IsValid() || ok {
980
                        t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
981
                }
982
 
983
                // TryRecv success
984
                c <- 4
985
                val, ok = cv.TryRecv()
986
                if !val.IsValid() {
987
                        t.Errorf("TryRecv on ready chan got nil")
988
                } else if i := val.Int(); i != 4 || !ok {
989
                        t.Errorf("native send 4, TryRecv %d, %t", i, ok)
990
                }
991
 
992
                // TrySend fail
993
                c <- 100
994
                ok = cv.TrySend(ValueOf(5))
995
                i := <-c
996
                if ok {
997
                        t.Errorf("TrySend on full chan succeeded: value %d", i)
998
                }
999
 
1000
                // TrySend success
1001
                ok = cv.TrySend(ValueOf(6))
1002
                if !ok {
1003
                        t.Errorf("TrySend on empty chan failed")
1004
                } else {
1005
                        if i = <-c; i != 6 {
1006
                                t.Errorf("TrySend 6, recv %d", i)
1007
                        }
1008
                }
1009
 
1010
                // Close
1011
                c <- 123
1012
                cv.Close()
1013
                if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1014
                        t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1015
                }
1016
                if i, ok := cv.Recv(); i.Int() != 0 || ok {
1017
                        t.Errorf("after close Recv %d, %t", i.Int(), ok)
1018
                }
1019
        }
1020
 
1021
        // check creation of unbuffered channel
1022
        var c chan int
1023
        cv := MakeChan(TypeOf(c), 0)
1024
        c = cv.Interface().(chan int)
1025
        if cv.TrySend(ValueOf(7)) {
1026
                t.Errorf("TrySend on sync chan succeeded")
1027
        }
1028
        if v, ok := cv.TryRecv(); v.IsValid() || ok {
1029
                t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1030
        }
1031
 
1032
        // len/cap
1033
        cv = MakeChan(TypeOf(c), 10)
1034
        c = cv.Interface().(chan int)
1035
        for i := 0; i < 3; i++ {
1036
                c <- i
1037
        }
1038
        if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1039
                t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1040
        }
1041
 
1042
}
1043
 
1044
// Difficult test for function call because of
1045
// implicit padding between arguments.
1046
func dummy(b byte, c int, d byte) (i byte, j int, k byte) {
1047
        return b, c, d
1048
}
1049
 
1050
func TestFunc(t *testing.T) {
1051
        ret := ValueOf(dummy).Call([]Value{ValueOf(byte(10)), ValueOf(20), ValueOf(byte(30))})
1052
        if len(ret) != 3 {
1053
                t.Fatalf("Call returned %d values, want 3", len(ret))
1054
        }
1055
 
1056
        i := byte(ret[0].Uint())
1057
        j := int(ret[1].Int())
1058
        k := byte(ret[2].Uint())
1059
        if i != 10 || j != 20 || k != 30 {
1060
                t.Errorf("Call returned %d, %d, %d; want 10, 20, 30", i, j, k)
1061
        }
1062
}
1063
 
1064
type Point struct {
1065
        x, y int
1066
}
1067
 
1068
// This will be index 0.
1069
func (p Point) AnotherMethod(scale int) int {
1070
        return -1
1071
}
1072
 
1073
// This will be index 1.
1074
func (p Point) Dist(scale int) int {
1075
        //      println("Point.Dist", p.x, p.y, scale)
1076
        return p.x*p.x*scale + p.y*p.y*scale
1077
}
1078
 
1079
func TestMethod(t *testing.T) {
1080
        // Non-curried method of type.
1081
        p := Point{3, 4}
1082
        i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1083
        if i != 250 {
1084
                t.Errorf("Type Method returned %d; want 250", i)
1085
        }
1086
 
1087
        m, ok := TypeOf(p).MethodByName("Dist")
1088
        if !ok {
1089
                t.Fatalf("method by name failed")
1090
        }
1091
        m.Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1092
        if i != 250 {
1093
                t.Errorf("Type MethodByName returned %d; want 250", i)
1094
        }
1095
 
1096
        i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(10)})[0].Int()
1097
        if i != 250 {
1098
                t.Errorf("Pointer Type Method returned %d; want 250", i)
1099
        }
1100
 
1101
        m, ok = TypeOf(&p).MethodByName("Dist")
1102
        if !ok {
1103
                t.Fatalf("ptr method by name failed")
1104
        }
1105
        i = m.Func.Call([]Value{ValueOf(&p), ValueOf(10)})[0].Int()
1106
        if i != 250 {
1107
                t.Errorf("Pointer Type MethodByName returned %d; want 250", i)
1108
        }
1109
 
1110
        // Curried method of value.
1111
        tfunc := TypeOf(func(int) int(nil))
1112
        v := ValueOf(p).Method(1)
1113
        if tt := v.Type(); tt != tfunc {
1114
                t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1115
        }
1116
        i = v.Call([]Value{ValueOf(10)})[0].Int()
1117
        if i != 250 {
1118
                t.Errorf("Value Method returned %d; want 250", i)
1119
        }
1120
        v = ValueOf(p).MethodByName("Dist")
1121
        if tt := v.Type(); tt != tfunc {
1122
                t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1123
        }
1124
        i = v.Call([]Value{ValueOf(10)})[0].Int()
1125
        if i != 250 {
1126
                t.Errorf("Value MethodByName returned %d; want 250", i)
1127
        }
1128
 
1129
        // Curried method of pointer.
1130
        v = ValueOf(&p).Method(1)
1131
        if tt := v.Type(); tt != tfunc {
1132
                t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1133
        }
1134
        i = v.Call([]Value{ValueOf(10)})[0].Int()
1135
        if i != 250 {
1136
                t.Errorf("Pointer Value Method returned %d; want 250", i)
1137
        }
1138
        v = ValueOf(&p).MethodByName("Dist")
1139
        if tt := v.Type(); tt != tfunc {
1140
                t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1141
        }
1142
        i = v.Call([]Value{ValueOf(10)})[0].Int()
1143
        if i != 250 {
1144
                t.Errorf("Pointer Value MethodByName returned %d; want 250", i)
1145
        }
1146
 
1147
        // Curried method of interface value.
1148
        // Have to wrap interface value in a struct to get at it.
1149
        // Passing it to ValueOf directly would
1150
        // access the underlying Point, not the interface.
1151
        var s = struct {
1152
                X interface {
1153
                        Dist(int) int
1154
                }
1155
        }{p}
1156
        pv := ValueOf(s).Field(0)
1157
        v = pv.Method(0)
1158
        if tt := v.Type(); tt != tfunc {
1159
                t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1160
        }
1161
        i = v.Call([]Value{ValueOf(10)})[0].Int()
1162
        if i != 250 {
1163
                t.Errorf("Interface Method returned %d; want 250", i)
1164
        }
1165
        v = pv.MethodByName("Dist")
1166
        if tt := v.Type(); tt != tfunc {
1167
                t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1168
        }
1169
        i = v.Call([]Value{ValueOf(10)})[0].Int()
1170
        if i != 250 {
1171
                t.Errorf("Interface MethodByName returned %d; want 250", i)
1172
        }
1173
}
1174
 
1175
func TestInterfaceSet(t *testing.T) {
1176
        p := &Point{3, 4}
1177
 
1178
        var s struct {
1179
                I interface{}
1180
                P interface {
1181
                        Dist(int) int
1182
                }
1183
        }
1184
        sv := ValueOf(&s).Elem()
1185
        sv.Field(0).Set(ValueOf(p))
1186
        if q := s.I.(*Point); q != p {
1187
                t.Errorf("i: have %p want %p", q, p)
1188
        }
1189
 
1190
        pv := sv.Field(1)
1191
        pv.Set(ValueOf(p))
1192
        if q := s.P.(*Point); q != p {
1193
                t.Errorf("i: have %p want %p", q, p)
1194
        }
1195
 
1196
        i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
1197
        if i != 250 {
1198
                t.Errorf("Interface Method returned %d; want 250", i)
1199
        }
1200
}
1201
 
1202
type T1 struct {
1203
        a string
1204
        int
1205
}
1206
 
1207
func TestAnonymousFields(t *testing.T) {
1208
        var field StructField
1209
        var ok bool
1210
        var t1 T1
1211
        type1 := TypeOf(t1)
1212
        if field, ok = type1.FieldByName("int"); !ok {
1213
                t.Error("no field 'int'")
1214
        }
1215
        if field.Index[0] != 1 {
1216
                t.Error("field index should be 1; is", field.Index)
1217
        }
1218
}
1219
 
1220
type FTest struct {
1221
        s     interface{}
1222
        name  string
1223
        index []int
1224
        value int
1225
}
1226
 
1227
type D1 struct {
1228
        d int
1229
}
1230
type D2 struct {
1231
        d int
1232
}
1233
 
1234
type S0 struct {
1235
        A, B, C int
1236
        D1
1237
        D2
1238
}
1239
 
1240
type S1 struct {
1241
        B int
1242
        S0
1243
}
1244
 
1245
type S2 struct {
1246
        A int
1247
        *S1
1248
}
1249
 
1250
type S1x struct {
1251
        S1
1252
}
1253
 
1254
type S1y struct {
1255
        S1
1256
}
1257
 
1258
type S3 struct {
1259
        S1x
1260
        S2
1261
        D, E int
1262
        *S1y
1263
}
1264
 
1265
type S4 struct {
1266
        *S4
1267
        A int
1268
}
1269
 
1270
var fieldTests = []FTest{
1271
        {struct{}{}, "", nil, 0},
1272
        {struct{}{}, "Foo", nil, 0},
1273
        {S0{A: 'a'}, "A", []int{0}, 'a'},
1274
        {S0{}, "D", nil, 0},
1275
        {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
1276
        {S1{B: 'b'}, "B", []int{0}, 'b'},
1277
        {S1{}, "S0", []int{1}, 0},
1278
        {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
1279
        {S2{A: 'a'}, "A", []int{0}, 'a'},
1280
        {S2{}, "S1", []int{1}, 0},
1281
        {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
1282
        {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
1283
        {S2{}, "D", nil, 0},
1284
        {S3{}, "S1", nil, 0},
1285
        {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
1286
        {S3{}, "B", nil, 0},
1287
        {S3{D: 'd'}, "D", []int{2}, 0},
1288
        {S3{E: 'e'}, "E", []int{3}, 'e'},
1289
        {S4{A: 'a'}, "A", []int{1}, 'a'},
1290
        {S4{}, "B", nil, 0},
1291
}
1292
 
1293
func TestFieldByIndex(t *testing.T) {
1294
        for _, test := range fieldTests {
1295
                s := TypeOf(test.s)
1296
                f := s.FieldByIndex(test.index)
1297
                if f.Name != "" {
1298
                        if test.index != nil {
1299
                                if f.Name != test.name {
1300
                                        t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
1301
                                }
1302
                        } else {
1303
                                t.Errorf("%s.%s found", s.Name(), f.Name)
1304
                        }
1305
                } else if len(test.index) > 0 {
1306
                        t.Errorf("%s.%s not found", s.Name(), test.name)
1307
                }
1308
 
1309
                if test.value != 0 {
1310
                        v := ValueOf(test.s).FieldByIndex(test.index)
1311
                        if v.IsValid() {
1312
                                if x, ok := v.Interface().(int); ok {
1313
                                        if x != test.value {
1314
                                                t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
1315
                                        }
1316
                                } else {
1317
                                        t.Errorf("%s%v value not an int", s.Name(), test.index)
1318
                                }
1319
                        } else {
1320
                                t.Errorf("%s%v value not found", s.Name(), test.index)
1321
                        }
1322
                }
1323
        }
1324
}
1325
 
1326
func TestFieldByName(t *testing.T) {
1327
        for _, test := range fieldTests {
1328
                s := TypeOf(test.s)
1329
                f, found := s.FieldByName(test.name)
1330
                if found {
1331
                        if test.index != nil {
1332
                                // Verify field depth and index.
1333
                                if len(f.Index) != len(test.index) {
1334
                                        t.Errorf("%s.%s depth %d; want %d", s.Name(), test.name, len(f.Index), len(test.index))
1335
                                } else {
1336
                                        for i, x := range f.Index {
1337
                                                if x != test.index[i] {
1338
                                                        t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
1339
                                                }
1340
                                        }
1341
                                }
1342
                        } else {
1343
                                t.Errorf("%s.%s found", s.Name(), f.Name)
1344
                        }
1345
                } else if len(test.index) > 0 {
1346
                        t.Errorf("%s.%s not found", s.Name(), test.name)
1347
                }
1348
 
1349
                if test.value != 0 {
1350
                        v := ValueOf(test.s).FieldByName(test.name)
1351
                        if v.IsValid() {
1352
                                if x, ok := v.Interface().(int); ok {
1353
                                        if x != test.value {
1354
                                                t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
1355
                                        }
1356
                                } else {
1357
                                        t.Errorf("%s.%s value not an int", s.Name(), test.name)
1358
                                }
1359
                        } else {
1360
                                t.Errorf("%s.%s value not found", s.Name(), test.name)
1361
                        }
1362
                }
1363
        }
1364
}
1365
 
1366
func TestImportPath(t *testing.T) {
1367
        tests := []struct {
1368
                t    Type
1369
                path string
1370
        }{
1371
                {TypeOf(&base64.Encoding{}).Elem(), "libgo_encoding.base64"},
1372
                {TypeOf(uint(0)), ""},
1373
                {TypeOf(map[string]int{}), ""},
1374
                {TypeOf((*error)(nil)).Elem(), ""},
1375
        }
1376
        for _, test := range tests {
1377
                if path := test.t.PkgPath(); path != test.path {
1378
                        t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
1379
                }
1380
        }
1381
}
1382
 
1383
func TestVariadicType(t *testing.T) {
1384
        // Test example from Type documentation.
1385
        var f func(x int, y ...float64)
1386
        typ := TypeOf(f)
1387
        if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
1388
                sl := typ.In(1)
1389
                if sl.Kind() == Slice {
1390
                        if sl.Elem() == TypeOf(0.0) {
1391
                                // ok
1392
                                return
1393
                        }
1394
                }
1395
        }
1396
 
1397
        // Failed
1398
        t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
1399
        s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
1400
        for i := 0; i < typ.NumIn(); i++ {
1401
                s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
1402
        }
1403
        t.Error(s)
1404
}
1405
 
1406
type inner struct {
1407
        x int
1408
}
1409
 
1410
type outer struct {
1411
        y int
1412
        inner
1413
}
1414
 
1415
func (*inner) m() {}
1416
func (*outer) m() {}
1417
 
1418
func TestNestedMethods(t *testing.T) {
1419
        typ := TypeOf((*outer)(nil))
1420
        if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).m).Pointer() {
1421
                t.Errorf("Wrong method table for outer: (m=%p)", (*outer).m)
1422
                for i := 0; i < typ.NumMethod(); i++ {
1423
                        m := typ.Method(i)
1424
                        t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
1425
                }
1426
        }
1427
}
1428
 
1429
type InnerInt struct {
1430
        X int
1431
}
1432
 
1433
type OuterInt struct {
1434
        Y int
1435
        InnerInt
1436
}
1437
 
1438
func (i *InnerInt) M() int {
1439
        return i.X
1440
}
1441
 
1442
func TestEmbeddedMethods(t *testing.T) {
1443
        typ := TypeOf((*OuterInt)(nil))
1444
        if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
1445
                t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
1446
                for i := 0; i < typ.NumMethod(); i++ {
1447
                        m := typ.Method(i)
1448
                        t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
1449
                }
1450
        }
1451
 
1452
        i := &InnerInt{3}
1453
        if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
1454
                t.Errorf("i.M() = %d, want 3", v)
1455
        }
1456
 
1457
        o := &OuterInt{1, InnerInt{2}}
1458
        if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
1459
                t.Errorf("i.M() = %d, want 2", v)
1460
        }
1461
 
1462
        f := (*OuterInt).M
1463
        if v := f(o); v != 2 {
1464
                t.Errorf("f(o) = %d, want 2", v)
1465
        }
1466
}
1467
 
1468
func TestPtrTo(t *testing.T) {
1469
        var i int
1470
 
1471
        typ := TypeOf(i)
1472
        for i = 0; i < 100; i++ {
1473
                typ = PtrTo(typ)
1474
        }
1475
        for i = 0; i < 100; i++ {
1476
                typ = typ.Elem()
1477
        }
1478
        if typ != TypeOf(i) {
1479
                t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(i))
1480
        }
1481
}
1482
 
1483
func TestAddr(t *testing.T) {
1484
        var p struct {
1485
                X, Y int
1486
        }
1487
 
1488
        v := ValueOf(&p)
1489
        v = v.Elem()
1490
        v = v.Addr()
1491
        v = v.Elem()
1492
        v = v.Field(0)
1493
        v.SetInt(2)
1494
        if p.X != 2 {
1495
                t.Errorf("Addr.Elem.Set failed to set value")
1496
        }
1497
 
1498
        // Again but take address of the ValueOf value.
1499
        // Exercises generation of PtrTypes not present in the binary.
1500
        q := &p
1501
        v = ValueOf(&q).Elem()
1502
        v = v.Addr()
1503
        v = v.Elem()
1504
        v = v.Elem()
1505
        v = v.Addr()
1506
        v = v.Elem()
1507
        v = v.Field(0)
1508
        v.SetInt(3)
1509
        if p.X != 3 {
1510
                t.Errorf("Addr.Elem.Set failed to set value")
1511
        }
1512
 
1513
        // Starting without pointer we should get changed value
1514
        // in interface.
1515
        qq := p
1516
        v = ValueOf(&qq).Elem()
1517
        v0 := v
1518
        v = v.Addr()
1519
        v = v.Elem()
1520
        v = v.Field(0)
1521
        v.SetInt(4)
1522
        if p.X != 3 { // should be unchanged from last time
1523
                t.Errorf("somehow value Set changed original p")
1524
        }
1525
        p = v0.Interface().(struct {
1526
                X, Y int
1527
        })
1528
        if p.X != 4 {
1529
                t.Errorf("Addr.Elem.Set valued to set value in top value")
1530
        }
1531
 
1532
        // Verify that taking the address of a type gives us a pointer
1533
        // which we can convert back using the usual interface
1534
        // notation.
1535
        var s struct {
1536
                B *bool
1537
        }
1538
        ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
1539
        *(ps.(**bool)) = new(bool)
1540
        if s.B == nil {
1541
                t.Errorf("Addr.Interface direct assignment failed")
1542
        }
1543
}
1544
 
1545
/* gccgo does do allocations here.
1546
 
1547
func noAlloc(t *testing.T, n int, f func(int)) {
1548
        // once to prime everything
1549
        f(-1)
1550
        memstats := new(runtime.MemStats)
1551
        runtime.ReadMemStats(memstats)
1552
        oldmallocs := memstats.Mallocs
1553
 
1554
        for j := 0; j < n; j++ {
1555
                f(j)
1556
        }
1557
        // A few allocs may happen in the testing package when GOMAXPROCS > 1, so don't
1558
        // require zero mallocs.
1559
        runtime.ReadMemStats(memstats)
1560
        mallocs := memstats.Mallocs - oldmallocs
1561
        if mallocs > 5 {
1562
                t.Fatalf("%d mallocs after %d iterations", mallocs, n)
1563
        }
1564
}
1565
 
1566
func TestAllocations(t *testing.T) {
1567
        noAlloc(t, 100, func(j int) {
1568
                var i interface{}
1569
                var v Value
1570
                i = 42 + j
1571
                v = ValueOf(i)
1572
                if int(v.Int()) != 42+j {
1573
                        panic("wrong int")
1574
                }
1575
        })
1576
}
1577
 
1578
*/
1579
 
1580
func TestSmallNegativeInt(t *testing.T) {
1581
        i := int16(-1)
1582
        v := ValueOf(i)
1583
        if v.Int() != -1 {
1584
                t.Errorf("int16(-1).Int() returned %v", v.Int())
1585
        }
1586
}
1587
 
1588
func TestSlice(t *testing.T) {
1589
        xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
1590
        v := ValueOf(xs).Slice(3, 5).Interface().([]int)
1591
        if len(v) != 2 {
1592
                t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
1593
        }
1594
        if cap(v) != 5 {
1595
                t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
1596
        }
1597
        if !DeepEqual(v[0:5], xs[3:]) {
1598
                t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
1599
        }
1600
 
1601
        xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
1602
        v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
1603
        if len(v) != 3 {
1604
                t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
1605
        }
1606
        if cap(v) != 6 {
1607
                t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
1608
        }
1609
        if !DeepEqual(v[0:6], xa[2:]) {
1610
                t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
1611
        }
1612
}
1613
 
1614
func TestVariadic(t *testing.T) {
1615
        var b bytes.Buffer
1616
        V := ValueOf
1617
 
1618
        b.Reset()
1619
        V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
1620
        if b.String() != "hello, 42 world" {
1621
                t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
1622
        }
1623
 
1624
        b.Reset()
1625
        V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
1626
        if b.String() != "hello, 42 world" {
1627
                t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
1628
        }
1629
}
1630
 
1631
var tagGetTests = []struct {
1632
        Tag   StructTag
1633
        Key   string
1634
        Value string
1635
}{
1636
        {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
1637
        {`protobuf:"PB(1,2)"`, `foo`, ``},
1638
        {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
1639
        {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
1640
        {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
1641
}
1642
 
1643
func TestTagGet(t *testing.T) {
1644
        for _, tt := range tagGetTests {
1645
                if v := tt.Tag.Get(tt.Key); v != tt.Value {
1646
                        t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
1647
                }
1648
        }
1649
}
1650
 
1651
func TestBytes(t *testing.T) {
1652
        type B []byte
1653
        x := B{1, 2, 3, 4}
1654
        y := ValueOf(x).Bytes()
1655
        if !bytes.Equal(x, y) {
1656
                t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
1657
        }
1658
        if &x[0] != &y[0] {
1659
                t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
1660
        }
1661
}
1662
 
1663
func TestSetBytes(t *testing.T) {
1664
        type B []byte
1665
        var x B
1666
        y := []byte{1, 2, 3, 4}
1667
        ValueOf(&x).Elem().SetBytes(y)
1668
        if !bytes.Equal(x, y) {
1669
                t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
1670
        }
1671
        if &x[0] != &y[0] {
1672
                t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
1673
        }
1674
}
1675
 
1676
type Private struct {
1677
        x int
1678
        y **int
1679
}
1680
 
1681
func (p *Private) m() {
1682
}
1683
 
1684
type Public struct {
1685
        X int
1686
        Y **int
1687
}
1688
 
1689
func (p *Public) M() {
1690
}
1691
 
1692
func TestUnexported(t *testing.T) {
1693
        var pub Public
1694
        v := ValueOf(&pub)
1695
        isValid(v.Elem().Field(0))
1696
        isValid(v.Elem().Field(1))
1697
        isValid(v.Elem().FieldByName("X"))
1698
        isValid(v.Elem().FieldByName("Y"))
1699
        isValid(v.Type().Method(0).Func)
1700
        isNonNil(v.Elem().Field(0).Interface())
1701
        isNonNil(v.Elem().Field(1).Interface())
1702
        isNonNil(v.Elem().FieldByName("X").Interface())
1703
        isNonNil(v.Elem().FieldByName("Y").Interface())
1704
        isNonNil(v.Type().Method(0).Func.Interface())
1705
 
1706
        var priv Private
1707
        v = ValueOf(&priv)
1708
        isValid(v.Elem().Field(0))
1709
        isValid(v.Elem().Field(1))
1710
        isValid(v.Elem().FieldByName("x"))
1711
        isValid(v.Elem().FieldByName("y"))
1712
        isValid(v.Type().Method(0).Func)
1713
        shouldPanic(func() { v.Elem().Field(0).Interface() })
1714
        shouldPanic(func() { v.Elem().Field(1).Interface() })
1715
        shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
1716
        shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
1717
        shouldPanic(func() { v.Type().Method(0).Func.Interface() })
1718
}
1719
 
1720
func shouldPanic(f func()) {
1721
        defer func() {
1722
                if recover() == nil {
1723
                        panic("did not panic")
1724
                }
1725
        }()
1726
        f()
1727
}
1728
 
1729
func isNonNil(x interface{}) {
1730
        if x == nil {
1731
                panic("nil interface")
1732
        }
1733
}
1734
 
1735
func isValid(v Value) {
1736
        if !v.IsValid() {
1737
                panic("zero Value")
1738
        }
1739
}

powered by: WebSVN 2.1.0

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