github.com/cheng762/platon-go@v1.8.17-0.20190529111256-7deff2d7be26/swarm/api/http/roundtripper_test.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package http
    18  
    19  import (
    20  	"io/ioutil"
    21  	"net"
    22  	"net/http"
    23  	"net/http/httptest"
    24  	"strings"
    25  	"testing"
    26  	"time"
    27  )
    28  
    29  func TestRoundTripper(t *testing.T) {
    30  	serveMux := http.NewServeMux()
    31  	serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    32  		if r.Method == "GET" {
    33  			w.Header().Set("Content-Type", "text/plain")
    34  			http.ServeContent(w, r, "", time.Unix(0, 0), strings.NewReader(r.RequestURI))
    35  		} else {
    36  			http.Error(w, "Method "+r.Method+" is not supported.", http.StatusMethodNotAllowed)
    37  		}
    38  	})
    39  
    40  	srv := httptest.NewServer(serveMux)
    41  	defer srv.Close()
    42  
    43  	host, port, _ := net.SplitHostPort(srv.Listener.Addr().String())
    44  	rt := &RoundTripper{Host: host, Port: port}
    45  	trans := &http.Transport{}
    46  	trans.RegisterProtocol("bzz", rt)
    47  	client := &http.Client{Transport: trans}
    48  	resp, err := client.Get("bzz://test.com/path")
    49  	if err != nil {
    50  		t.Errorf("expected no error, got %v", err)
    51  		return
    52  	}
    53  
    54  	defer func() {
    55  		if resp != nil {
    56  			resp.Body.Close()
    57  		}
    58  	}()
    59  
    60  	content, err := ioutil.ReadAll(resp.Body)
    61  	if err != nil {
    62  		t.Errorf("expected no error, got %v", err)
    63  		return
    64  	}
    65  	if string(content) != "/HTTP/1.1:/test.com/path" {
    66  		t.Errorf("incorrect response from http server: expected '%v', got '%v'", "/HTTP/1.1:/test.com/path", string(content))
    67  	}
    68  
    69  }