github.com/google/martian/v3@v3.3.3/header/id_modifier_test.go (about)

     1  // Copyright 2015 Google Inc. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package header
    16  
    17  import (
    18  	"net/http"
    19  	"testing"
    20  
    21  	"github.com/google/martian/v3"
    22  	"github.com/google/martian/v3/parse"
    23  )
    24  
    25  func TestIdModifier(t *testing.T) {
    26  	mod := NewIDModifier()
    27  
    28  	req, err := http.NewRequest("GET", "/", nil)
    29  	if err != nil {
    30  		t.Fatalf("http.NewRequest(): got %v, want no error", err)
    31  	}
    32  
    33  	ctx, remove, err := martian.TestContext(req, nil, nil)
    34  	if err != nil {
    35  		t.Fatalf("TestContext(): got %v, want no error", err)
    36  	}
    37  	defer remove()
    38  
    39  	if err := mod.ModifyRequest(req); err != nil {
    40  		t.Fatalf("ModifyRequest(): got %v, want no error", err)
    41  	}
    42  
    43  	if got, want := req.Header.Get("X-Martian-ID"), ctx.ID(); got != want {
    44  		t.Errorf("req.Header.Get(%q): got %q, want %q", "X-Martian-ID", got, want)
    45  	}
    46  }
    47  
    48  func TestFromJSON(t *testing.T) {
    49  	msg := []byte(`{
    50  			"header.Id": {}
    51  	}`)
    52  
    53  	r, err := parse.FromJSON(msg)
    54  	if err != nil {
    55  		t.Fatalf("parse.FromJSON(): got %v, want no error", err)
    56  	}
    57  
    58  	reqmod := r.RequestModifier()
    59  	if _, ok := reqmod.(*idModifier); !ok {
    60  		t.Fatal("reqmod.(*idModifier): got !ok, want ok")
    61  	}
    62  
    63  	req, err := http.NewRequest("GET", "/", nil)
    64  	if err != nil {
    65  		t.Fatalf("http.NewRequest(): got %v, want no error", err)
    66  	}
    67  
    68  	ctx, remove, err := martian.TestContext(req, nil, nil)
    69  	if err != nil {
    70  		t.Fatalf("TestContext(): got %v, want no error", err)
    71  	}
    72  	defer remove()
    73  
    74  	if err := reqmod.ModifyRequest(req); err != nil {
    75  		t.Fatalf("ModifyRequest(): got %v, want no error", err)
    76  	}
    77  
    78  	if got, want := req.Header.Get("X-Martian-ID"), ctx.ID(); got != want {
    79  		t.Errorf("req.Header.Get(%q): got %q, want %q", "X-Martian-ID", got, want)
    80  	}
    81  }