github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/net/http/httptrace/trace_test.go (about)

     1  // Copyright 2016 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 httptrace
     6  
     7  import (
     8  	"bytes"
     9  	"context"
    10  	"testing"
    11  )
    12  
    13  func TestWithClientTrace(t *testing.T) {
    14  	var buf bytes.Buffer
    15  	connectStart := func(b byte) func(network, addr string) {
    16  		return func(network, addr string) {
    17  			buf.WriteByte(b)
    18  		}
    19  	}
    20  
    21  	ctx := context.Background()
    22  	oldtrace := &ClientTrace{
    23  		ConnectStart: connectStart('O'),
    24  	}
    25  	ctx = WithClientTrace(ctx, oldtrace)
    26  	newtrace := &ClientTrace{
    27  		ConnectStart: connectStart('N'),
    28  	}
    29  	ctx = WithClientTrace(ctx, newtrace)
    30  	trace := ContextClientTrace(ctx)
    31  
    32  	buf.Reset()
    33  	trace.ConnectStart("net", "addr")
    34  	if got, want := buf.String(), "NO"; got != want {
    35  		t.Errorf("got %q; want %q", got, want)
    36  	}
    37  }
    38  
    39  func TestCompose(t *testing.T) {
    40  	var buf bytes.Buffer
    41  	var testNum int
    42  
    43  	connectStart := func(b byte) func(network, addr string) {
    44  		return func(network, addr string) {
    45  			if addr != "addr" {
    46  				t.Errorf(`%d. args for %q case = %q, %q; want addr of "addr"`, testNum, b, network, addr)
    47  			}
    48  			buf.WriteByte(b)
    49  		}
    50  	}
    51  
    52  	tests := [...]struct {
    53  		trace, old *ClientTrace
    54  		want       string
    55  	}{
    56  		0: {
    57  			want: "T",
    58  			trace: &ClientTrace{
    59  				ConnectStart: connectStart('T'),
    60  			},
    61  		},
    62  		1: {
    63  			want: "TO",
    64  			trace: &ClientTrace{
    65  				ConnectStart: connectStart('T'),
    66  			},
    67  			old: &ClientTrace{ConnectStart: connectStart('O')},
    68  		},
    69  		2: {
    70  			want:  "O",
    71  			trace: &ClientTrace{},
    72  			old:   &ClientTrace{ConnectStart: connectStart('O')},
    73  		},
    74  	}
    75  	for i, tt := range tests {
    76  		testNum = i
    77  		buf.Reset()
    78  
    79  		tr := *tt.trace
    80  		tr.compose(tt.old)
    81  		if tr.ConnectStart != nil {
    82  			tr.ConnectStart("net", "addr")
    83  		}
    84  		if got := buf.String(); got != tt.want {
    85  			t.Errorf("%d. got = %q; want %q", i, got, tt.want)
    86  		}
    87  	}
    88  
    89  }