github.com/x04/go/src@v0.0.0-20200202162449-3d481ceb3525/runtime/time_test.go (about)

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