| 1 |
// Copyright 2019 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 runtime_test |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"encoding/binary" |
| 10 |
"errors" |
| 11 |
"internal/testenv" |
| 12 |
"os/exec" |
| 13 |
"reflect" |
| 14 |
"runtime" |
| 15 |
"testing" |
| 16 |
) |
| 17 |
|
| 18 |
func TestFakeTime(t *testing.T) { |
| 19 |
if runtime.GOOS == "windows" { |
| 20 |
t.Skip("faketime not supported on windows") |
| 21 |
} |
| 22 |
if runtime.Compiler == "gccgo" { |
| 23 |
t.Skip("faketime not supported for gccgo") |
| 24 |
} |
| 25 |
|
| 26 |
// Faketime is advanced in checkdead. External linking brings in cgo, |
| 27 |
// causing checkdead not working. |
| 28 |
testenv.MustInternalLink(t) |
| 29 |
|
| 30 |
t.Parallel() |
| 31 |
|
| 32 |
exe, err := buildTestProg(t, "testfaketime", "-tags=faketime") |
| 33 |
if err != nil { |
| 34 |
t.Fatal(err) |
| 35 |
} |
| 36 |
|
| 37 |
var stdout, stderr bytes.Buffer |
| 38 |
cmd := exec.Command(exe) |
| 39 |
cmd.Stdout = &stdout |
| 40 |
cmd.Stderr = &stderr |
| 41 |
|
| 42 |
err = testenv.CleanCmdEnv(cmd).Run() |
| 43 |
if err != nil { |
| 44 |
t.Fatalf("exit status: %v\n%s", err, stderr.String()) |
| 45 |
} |
| 46 |
|
| 47 |
t.Logf("raw stdout: %q", stdout.String()) |
| 48 |
t.Logf("raw stderr: %q", stderr.String()) |
| 49 |
|
| 50 |
f1, err1 := parseFakeTime(stdout.Bytes()) |
| 51 |
if err1 != nil { |
| 52 |
t.Fatal(err1) |
| 53 |
} |
| 54 |
f2, err2 := parseFakeTime(stderr.Bytes()) |
| 55 |
if err2 != nil { |
| 56 |
t.Fatal(err2) |
| 57 |
} |
| 58 |
|
| 59 |
const time0 = 1257894000000000000 |
| 60 |
got := [][]fakeTimeFrame{f1, f2} |
| 61 |
var want = [][]fakeTimeFrame{{ |
| 62 |
{time0 + 1, "line 2\n"}, |
| 63 |
{time0 + 1, "line 3\n"}, |
| 64 |
{time0 + 1e9, "line 5\n"}, |
| 65 |
{time0 + 1e9, "2009-11-10T23:00:01Z"}, |
| 66 |
}, { |
| 67 |
{time0, "line 1\n"}, |
| 68 |
{time0 + 2, "line 4\n"}, |
| 69 |
}} |
| 70 |
if !reflect.DeepEqual(want, got) { |
| 71 |
t.Fatalf("want %v, got %v", want, got) |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
type fakeTimeFrame struct { |
| 76 |
time uint64 |
| 77 |
data string |
| 78 |
} |
| 79 |
|
| 80 |
func parseFakeTime(x []byte) ([]fakeTimeFrame, error) { |
| 81 |
var frames []fakeTimeFrame |
| 82 |
for len(x) != 0 { |
| 83 |
if len(x) < 4+8+4 { |
| 84 |
return nil, errors.New("truncated header") |
| 85 |
} |
| 86 |
const magic = "\x00\x00PB" |
| 87 |
if string(x[:len(magic)]) != magic { |
| 88 |
return nil, errors.New("bad magic") |
| 89 |
} |
| 90 |
x = x[len(magic):] |
| 91 |
time := binary.BigEndian.Uint64(x) |
| 92 |
x = x[8:] |
| 93 |
dlen := binary.BigEndian.Uint32(x) |
| 94 |
x = x[4:] |
| 95 |
data := string(x[:dlen]) |
| 96 |
x = x[dlen:] |
| 97 |
frames = append(frames, fakeTimeFrame{time, data}) |
| 98 |
} |
| 99 |
return frames, nil |
| 100 |
} |