0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

httptestを試してみた

Posted at

goの勉強続き。
testをやってみる

なんとか動いてCoverage 75%になったけど、100%にならないのはなんでなんだろ。
httptestでやるのはなかなか手応えがあったので、
単純な数値計算関数などに戻って、試してみようとおもう。

http2.go
package main

import (
	"io"
	"net/http"
	"strconv"
	"strings"
)

// ResponseWriter is interface as
//	Header()  Header
//  Write([]byte)(int,error)
//  iWriteHeder(statuscoe int)

// WriteString is function as
// func WriteString(w Writer, s string) (n int, err error)

// Writer is interface as
// Write(p []byte) (n int, err error)

func ServeHoge(w http.ResponseWriter, req *http.Request) {
	agent := req.Header.Get("user-agent")
	check := strings.Contains(agent, "537")
	check_string := strconv.FormatBool(check)

	if check {
		io.WriteString(w, agent+"\n537 is error\n"+check_string+"\n")
	}
	io.WriteString(w, "Welcome! this is hoge server\n" + agent+"\n")
}

// testの方法はたぶん、
// requestを作ってuse-agentをセットしてなげる
// それを受けて、結果が書き込まれるのもの(Recorder?)を
// うまく記録して、
// その結果のBodyをチェックするのかな。

//参考:https://qiita.com/umisama/items/3d44560e1c06fa531069

func main() {
	http.HandleFunc("/hoge", ServeHoge)

	http.ListenAndServe(":12345", nil)
}

http2_test.go
package main

import (
	"net/http"
	"net/http/httptest"
	"testing"
	"strings"
	"io/ioutil"
)

func TestCheckAgent(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(ServeHoge))
	defer ts.Close()

	_, err := http.Get(ts.URL)

	var request1 *http.Request

	request1, err = http.NewRequest("GET", ts.URL, nil)

	request1.Header.Add("user-agent","537")

	c := http.DefaultClient
	reply, err := c.Do(request1)

	if err != nil {
		t.Error("unexpected")
		return
	}

	data, err := ioutil.ReadAll(reply.Body)
	if err != nil {
		t.Fatalf("Error:%v",err)
	}
	if reply.StatusCode == 200 && ! strings.Contains(string(data), "537") {
		t.Fatalf("agent is not included 537 in Body:%v",string(data))
 	}

	request1.Header.Add("user-agent","532")
	c = http.DefaultClient
	reply, err = c.Do(request1)
	data, err = ioutil.ReadAll(reply.Body)
	if reply.StatusCode == 200 && ! strings.Contains(string(data), "Welcome") {
		t.Fatalf("agent is not included Welcome in Body:%v",string(data))
 	}



}

テスト結果

(base) http2 $ go test -v -cover
=== RUN   TestCheckAgent
--- PASS: TestCheckAgent (0.00s)
PASS
coverage: 75.0% of statements
ok  	http2	0.330s
(base) http2 $ 

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?