Debian Codegraph @

util/util_test.go

raw
1 /*
2 * util_test.go - Tests the util package
3 *
4 * Copyright 2017 Google Inc.
5 * Author: Joe Richey ([email protected])
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
8 * use this file except in compliance with the License. You may obtain a copy of
9 * the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 * License for the specific language governing permissions and limitations under
17 * the License.
18 */
19
20 package util
21
22 import (
23 "bytes"
24 "testing"
25 "unsafe"
26 )
27
28 const offset = 3
29
30 var (
31 byteArr = []byte{'a', 'b', 'c', 'd'}
32 ptrArr = []*int{&a, &b, &c, &d}
33 a = 1
34 b = 2
35 c = 3
36 d = 4
37 )
38
39 // Make sure the address behaves well under slicing
40 func TestPtrOffset(t *testing.T) {
41 i1 := uintptr(Ptr(byteArr[offset:]))
42 i2 := uintptr(Ptr(byteArr))
43
44 if i1 != i2+offset {
45 t.Errorf("pointers %v and %v do not have an offset of %v", i1, i2, offset)
46 }
47 }
48
49 // Tests that the ByteSlice method essentially reverses the Ptr method
50 func TestByteSlice(t *testing.T) {
51 ptr := Ptr(byteArr)
52 generatedArr := ByteSlice(ptr)[:len(byteArr)]
53
54 if !bytes.Equal(byteArr, generatedArr) {
55 t.Errorf("generated array (%v) and original array (%v) do not agree",
56 generatedArr, byteArr)
57 }
58 }
59
60 // Tests that the PointerSlice method correctly handles Go Pointers
61 func TestPointerSlice(t *testing.T) {
62 arrPtr := unsafe.Pointer(&ptrArr[0])
63
64 // Convert an array of unsafe pointers to int pointers.
65 for i, ptr := range PointerSlice(arrPtr)[:len(ptrArr)] {
66 if ptrArr[i] != (*int)(ptr) {
67 t.Errorf("generated array and original array disagree at %d", i)
68 }
69 }
70 }
71
72 // Make sure NeverError actually panics
73 func TestNeverErrorPanic(t *testing.T) {
74 defer func() {
75 if r := recover(); r == nil {
76 t.Errorf("NeverError did not panic")
77 }
78 }()
79
80 err := SystemError("Hello")
81 NeverError(err)
82 }
83
84 // Make sure NeverError doesn't panic on nil
85 func TestNeverErrorNoPanic(t *testing.T) {
86 defer func() {
87 if r := recover(); r != nil {
88 t.Errorf("NeverError panicked")
89 }
90 }()
91
92 NeverError(nil)
93 }
94
95 func TestIsKernelVersionAtLeast(t *testing.T) {
96 // Even just running Go requires at least v2.6.23, so...
97 if !IsKernelVersionAtLeast(2, 6) {
98 t.Error("IsKernelVersionAtLeast() is broken")
99 }
100 }