golang.org/x/playground@v0.0.0-20230418134305-14ebe15bcd59/play_test.go (about)

     1  // Copyright 2015 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 main
     6  
     7  import (
     8  	"encoding/binary"
     9  	"reflect"
    10  	"testing"
    11  	"time"
    12  )
    13  
    14  func TestDecode(t *testing.T) {
    15  	r := new(Recorder)
    16  	stdout := r.Stdout()
    17  	stderr := r.Stderr()
    18  
    19  	stdout.Write([]byte("head"))
    20  	stdout.Write(pbWrite(0, "one"))
    21  	stdout.Write(pbWrite(0, "two"))
    22  
    23  	stderr.Write(pbWrite(1*time.Second, "three"))
    24  	stderr.Write(pbWrite(2*time.Second, "five"))
    25  	stdout.Write(pbWrite(2*time.Second-time.Nanosecond, "four"))
    26  	stderr.Write(pbWrite(2*time.Second, "six"))
    27  
    28  	stdout.Write([]byte("middle"))
    29  	stdout.Write(pbWrite(3*time.Second, "seven"))
    30  	stdout.Write([]byte("tail"))
    31  
    32  	want := []Event{
    33  		{"headonetwo", "stdout", 0},
    34  		{"three", "stderr", time.Second},
    35  		{"fourmiddle", "stdout", time.Second - time.Nanosecond},
    36  		{"fivesix", "stderr", time.Nanosecond},
    37  		{"seventail", "stdout", time.Second},
    38  	}
    39  
    40  	got, err := r.Events()
    41  	if err != nil {
    42  		t.Fatalf("Decode: %v", err)
    43  	}
    44  	if !reflect.DeepEqual(got, want) {
    45  		t.Errorf("got: \n%v,\nwant \n%v", got, want)
    46  	}
    47  }
    48  
    49  func pbWrite(offset time.Duration, s string) []byte {
    50  	out := make([]byte, 16)
    51  	out[2] = 'P'
    52  	out[3] = 'B'
    53  	binary.BigEndian.PutUint64(out[4:], uint64(epoch.Add(offset).UnixNano()))
    54  	binary.BigEndian.PutUint32(out[12:], uint32(len(s)))
    55  	return append(out, s...)
    56  }