go.etcd.io/etcd@v3.3.27+incompatible/etcdserver/api/etcdhttp/version_test.go (about)

     1  // Copyright 2017 The etcd Authors
     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 etcdhttp
    16  
    17  import (
    18  	"encoding/json"
    19  	"net/http"
    20  	"net/http/httptest"
    21  	"testing"
    22  
    23  	"github.com/coreos/etcd/version"
    24  )
    25  
    26  func TestServeVersion(t *testing.T) {
    27  	req, err := http.NewRequest("GET", "", nil)
    28  	if err != nil {
    29  		t.Fatalf("error creating request: %v", err)
    30  	}
    31  	rw := httptest.NewRecorder()
    32  	serveVersion(rw, req, "2.1.0")
    33  	if rw.Code != http.StatusOK {
    34  		t.Errorf("code=%d, want %d", rw.Code, http.StatusOK)
    35  	}
    36  	vs := version.Versions{
    37  		Server:  version.Version,
    38  		Cluster: "2.1.0",
    39  	}
    40  	w, err := json.Marshal(&vs)
    41  	if err != nil {
    42  		t.Fatal(err)
    43  	}
    44  	if g := rw.Body.String(); g != string(w) {
    45  		t.Fatalf("body = %q, want %q", g, string(w))
    46  	}
    47  	if ct := rw.HeaderMap.Get("Content-Type"); ct != "application/json" {
    48  		t.Errorf("contet-type header = %s, want %s", ct, "application/json")
    49  	}
    50  }
    51  
    52  func TestServeVersionFails(t *testing.T) {
    53  	for _, m := range []string{
    54  		"CONNECT", "TRACE", "PUT", "POST", "HEAD",
    55  	} {
    56  		req, err := http.NewRequest(m, "", nil)
    57  		if err != nil {
    58  			t.Fatalf("error creating request: %v", err)
    59  		}
    60  		rw := httptest.NewRecorder()
    61  		serveVersion(rw, req, "2.1.0")
    62  		if rw.Code != http.StatusMethodNotAllowed {
    63  			t.Errorf("method %s: code=%d, want %d", m, rw.Code, http.StatusMethodNotAllowed)
    64  		}
    65  	}
    66  }