github.com/XiaoMi/Gaea@v1.2.5/util/requests/api_test.go (about)

     1  // Copyright 2019 The Gaea Authors. 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 requests
    16  
    17  import (
    18  	"encoding/json"
    19  	"net/http/httputil"
    20  	"testing"
    21  )
    22  
    23  func TestAddParameters(t *testing.T) {
    24  	url := "http://127.0.0.1:8080"
    25  	expect := "http://127.0.0.1:8080?a=test1&b=test2"
    26  	params := make(map[string]string, 2)
    27  	params["a"] = "test1"
    28  	params["b"] = "test2"
    29  	r := AddParameters(url, params)
    30  	if r != expect {
    31  		t.Errorf("test AddParameters failed, expect: %s, result: %s", expect, r)
    32  	}
    33  }
    34  
    35  func TestBuildHTTPRequest(t *testing.T) {
    36  	url := "http://127.0.0.1:8080"
    37  	method := Put
    38  
    39  	header := make(map[string]string, 2)
    40  	header["Content-Type"] = "application/json"
    41  
    42  	params := make(map[string]string, 2)
    43  	params["a"] = "test1"
    44  	params["b"] = "test2"
    45  
    46  	type ReqBody struct {
    47  		Field1 string `json:"field_1"`
    48  		Field2 int    `json:"field_2"`
    49  	}
    50  	rb := ReqBody{Field1: "contest1", Field2: 99}
    51  	body, _ := json.Marshal(rb)
    52  
    53  	req := NewRequest(url, method, header, params, body)
    54  	req.SetBasicAuth("test", "test")
    55  	httpReq, err := BuildHTTPRequest(req)
    56  	if err != nil {
    57  		t.Errorf("test BuildHTTPRequest failed, %v", err)
    58  	}
    59  
    60  	httpReqDump, err := httputil.DumpRequest(httpReq, true)
    61  	if err != nil {
    62  		t.Errorf("test BuildHTTPRequest failed, %v", err)
    63  	}
    64  	t.Logf("dumped http request: %s\n", string(httpReqDump))
    65  }
    66  
    67  func TestEncodeURL(t *testing.T) {
    68  	url := EncodeURL("127.0.0.1:8080", "/test/test/:%d", 1)
    69  	if url != "http://127.0.0.1:8080/test/test/:1" {
    70  		t.Fatalf("test EncodeURL failed, %s", url)
    71  	}
    72  }