Exemplo n.º 1
0
func Test_Context_RedirectWithAbort(t *testing.T) {
	recorder := httptest.NewRecorder()
	request, _ := http.NewRequest("GET", "/path/to/resource?key=url_value&test=url_true", nil)
	location := "https://www.example.com"
	assertion := assert.New(t)

	ctx := NewContext(newMockServer())
	ctx.Request = request
	ctx.Response = &Response{
		ResponseWriter: recorder,
	}
	ctx.handlers = []Middleware{
		func(ctx *Context) {
			ctx.Redirect(location)

			ctx.Next()
		},
		func(ctx *Context) {
			ctx.Render(NewDefaultRender(ctx.Response), "next render")
		},
	}
	ctx.Next()

	assertion.Equal(location, recorder.Header().Get("Location"))
	assertion.NotContains(recorder.Body.String(), "next render")
}
Exemplo n.º 2
0
func Test_RouteMockHandle(t *testing.T) {
	server := newMockServer()
	route := NewAppRoute("/", server)
	response := httptest.NewRecorder()
	assertion := assert.New(t)

	// mock handler
	route.MockHandle("GET", "/mock", response, func(ctx *Context) {
		ctx.Text("MOCK")
	})

	// start server
	ts := httptest.NewServer(server)
	defer ts.Close()

	// testing by http request
	request, _ := http.NewRequest("GET", ts.URL+"/mock", nil)

	res, err := http.DefaultClient.Do(request)
	assertion.Nil(err)

	body, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
	assertion.Nil(err)
	assertion.Empty(body)

	assertion.Equal(http.StatusOK, response.Code)
	assertion.Equal("MOCK", response.Body.String())
}
Exemplo n.º 3
0
func Test_MultipartRequest(t *testing.T) {
	assertion := assert.New(t)
	method := "put"
	uri := "/put/multipart"
	filename := "gopher.png"
	file := filepath.Clean("./fixtures/gopher.png")
	params := map[string]string{"form_key": "form_value"}
	server := newMockServer(method, uri, func(w http.ResponseWriter, r *http.Request) {
		assertion.Equal(method, r.Method)
		assertion.Equal("/put/multipart", r.RequestURI)
		assertion.Equal("form_value", r.FormValue("form_key"))

		freader, fheader, ferr := r.FormFile("filename")
		assertion.Nil(ferr)
		assertion.Equal(filename, fheader.Filename)

		fb, _ := ioutil.ReadAll(freader)
		b, _ := ioutil.ReadFile(file)
		assertion.Equal(b, fb)

		w.Header().Set("x-request-method", r.Method)
		w.WriteHeader(http.StatusNoContent)
		w.Write([]byte(""))
	})

	ts := httptest.NewServer(server)
	defer ts.Close()

	client := New(ts.URL, false)
	client.NewMultipartRequest(t, method, uri, "gopher.png", file, params)
	client.AssertStatus(http.StatusNoContent)
	client.AssertHeader("x-request-method", method)
	client.AssertEmpty()
}
Exemplo n.º 4
0
func Test_NewJsonResponder(t *testing.T) {
	assertion := assert.New(t)
	code := 200
	header := http.Header{
		"Content-Type": []string{"text/plain"},
		"X-Testing":    []string{"testing"},
	}
	body := struct {
		Name string `json:"name"`
	}{"testing"}
	rawurl := "https://example.com"
	rawbody := `{"name":"testing"}`

	responder := NewJsonResponder(code, header, body)

	request, _ := http.NewRequest("GET", rawurl, nil)
	response, err := responder.RoundTrip(request)
	assertion.Nil(err)
	assertion.Equal(code, response.StatusCode)
	assertion.Equal("application/json", response.Header.Get("Content-Type"))
	assertion.Equal(strconv.Itoa(len(rawbody)), response.Header.Get("Content-Length"))

	b, _ := ioutil.ReadAll(response.Body)
	response.Body.Close()
	assertion.Equal(rawbody, string(b))
}
Exemplo n.º 5
0
func Test_PutForm(t *testing.T) {
	assertion := assert.New(t)
	method := "PUT"
	uri := "/put?key"
	params := url.Values{"form_key": []string{"form_value"}}
	server := newMockServer(method, uri, func(w http.ResponseWriter, r *http.Request) {
		assertion.Equal(method, r.Method)
		assertion.Equal(uri, r.RequestURI)
		assertion.Equal("application/x-www-form-urlencoded", r.Header.Get("Content-Type"))
		assertion.Equal("form_value", r.FormValue("form_key"))

		_, ok := r.URL.Query()["key"]
		assertion.True(ok)
		assertion.Empty(r.FormValue("key"))

		w.Header().Set("x-request-method", r.Method)
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(method + " " + uri + " OK!"))
	})

	ts := httptest.NewServer(server)
	defer ts.Close()

	client := New(ts.URL, false)
	client.PutForm(t, uri, params)
	client.AssertOK()
	client.AssertHeader("x-request-method", method)
	client.AssertContains("PUT /put?key OK!")
}
Exemplo n.º 6
0
func Test_NewXmlResponderWithError(t *testing.T) {
	assertion := assert.New(t)
	code := 200
	header := http.Header{
		"Content-Type": []string{"text/plain"},
		"X-Testing":    []string{"testing"},
	}
	body := struct {
		XMLName xml.Name
		Ch      chan<- bool `xml:"Channel"`
	}{
		XMLName: xml.Name{
			Space: "http://xmlns.example.com",
			Local: "Responder",
		},
		Ch: make(chan<- bool, 1),
	}
	rawurl := "https://exmaple.com"

	responder := NewXmlResponder(code, header, body)

	request, _ := http.NewRequest("GET", rawurl, nil)
	response, err := responder.RoundTrip(request)
	assertion.NotNil(err)
	assertion.Nil(response)
}
Exemplo n.º 7
0
func Test_NewResponder(t *testing.T) {
	assertion := assert.New(t)
	code := 200
	header := http.Header{
		"Content-Type": []string{"text/plain"},
		"X-Testing":    []string{"testing"},
	}
	body := "Hello, world!"
	rawurl := "https://example.com"

	responder := NewResponder(code, header, body)
	assertion.Implements((*http.RoundTripper)(nil), responder)

	request, _ := http.NewRequest("GET", rawurl, nil)
	response, err := responder.RoundTrip(request)
	assertion.Nil(err)
	assertion.Equal(code, response.StatusCode)
	assertion.Equal(strconv.Itoa(len(body)), response.Header.Get("Content-Length"))
	assertion.NotNil(response.Request)

	b, err := ioutil.ReadAll(response.Body)
	response.Body.Close()
	assertion.Nil(err)
	assertion.Equal(body, string(b))
}
Exemplo n.º 8
0
func Test_NewXmlResponder(t *testing.T) {
	assertion := assert.New(t)
	code := 200
	header := http.Header{
		"Content-Type": []string{"text/plain"},
		"X-Testing":    []string{"testing"},
	}
	body := struct {
		XMLName xml.Name
		Name    string `xml:"Name"`
	}{
		XMLName: xml.Name{
			Space: "http://xmlns.example.com",
			Local: "Responder",
		},
		Name: "testing",
	}
	rawurl := "https://exmpale.com"
	rawbody := `<Responder xmlns="http://xmlns.example.com"><Name>testing</Name></Responder>`

	responder := NewXmlResponder(code, header, body)

	request, _ := http.NewRequest("GET", rawurl, nil)
	response, err := responder.RoundTrip(request)
	assertion.Nil(err)
	assertion.Equal(code, response.StatusCode)
	assertion.Equal("text/xml", response.Header.Get("Content-Type"))
	assertion.Equal(strconv.Itoa(len(rawbody)), response.Header.Get("Content-Length"))

	b, _ := ioutil.ReadAll(response.Body)
	response.Body.Close()
	assertion.Equal(rawbody, string(b))
}
Exemplo n.º 9
0
func Test_FilterRequest(t *testing.T) {
	assertion := assert.New(t)
	method := "GET"
	uri := "/request/filter"
	server := newMockServer(method, uri, func(w http.ResponseWriter, r *http.Request) {
		assertion.Equal(method, r.Method)
		assertion.Equal("/request/filter", r.RequestURI)
		assertion.Equal("request filter", r.Header.Get("X-Filtered-Header"))

		w.WriteHeader(http.StatusOK)
		w.Write([]byte(""))
	})

	ts := httptest.NewServer(server)
	defer ts.Close()

	request, _ := http.NewRequest(method, ts.URL+"/request/filter", nil)

	client := New(ts.URL, false)
	client.NewFilterRequest(t, request, func(r *http.Request) error {
		r.Header.Add("X-Filtered-Header", "request filter")

		return nil
	})
	client.AssertOK()
	client.AssertEmpty()
}
Exemplo n.º 10
0
func Test_NewAppServer(t *testing.T) {
	assertion := assert.New(t)

	server := newMockServer()
	assertion.Implements((*http.Handler)(nil), server)
	assertion.IsType(&Context{}, server.pool.Get())
}
Exemplo n.º 11
0
func Test_Context_RequestHeader(t *testing.T) {
	recorder := httptest.NewRecorder()
	request, _ := http.NewRequest("GET", "https://www.example.com/resource?key=url_value&test=url_true", nil)
	request.Header.Add("X-Canonical-Key", "Canonical-Value")
	request.Header["x-normal-key"] = []string{"normal value"}
	params := NewAppParams(request, httprouter.Params{})
	assertion := assert.New(t)

	server := newMockServer()
	ctx := server.new(recorder, request, params, nil)
	assertion.True(ctx.HasRawHeader("X-Canonical-Key"))
	assertion.False(ctx.HasRawHeader("x-canonical-key"))
	assertion.True(ctx.HasHeader("X-Canonical-Key"))
	assertion.True(ctx.HasHeader("x-canonical-key"))
	assertion.True(ctx.HasRawHeader("x-normal-key"))
	assertion.False(ctx.HasRawHeader("X-Normal-Key"))
	assertion.False(ctx.HasHeader("x-normal-key"))
	assertion.False(ctx.HasHeader("X-Normal-Key"))
	assertion.Equal("Canonical-Value", ctx.RawHeader("X-Canonical-Key"))
	assertion.Empty(ctx.RawHeader("x-canonical-key"))
	assertion.Equal("Canonical-Value", ctx.Header("X-Canonical-Key"))
	assertion.Equal("Canonical-Value", ctx.Header("x-canonical-key"))
	assertion.Equal("normal value", ctx.RawHeader("x-normal-key"))
	assertion.Empty(ctx.RawHeader("X-Normal-Key"))
	assertion.Empty(ctx.Header("x-normal-key"))
	assertion.Empty(ctx.Header("X-Normal-Key"))
}
Exemplo n.º 12
0
func Test_MitmTransportPauseAndResume(t *testing.T) {
	assertion := assert.New(t)

	mt := NewMitmTransport()
	mt.StubDefaultTransport(t)
	defer mt.UnstubDefaultTransport()

	// mocks
	mt.MockRequest("GET", "https://example.com/").WithResponse(101, nil, "GET OK").AnyTimes()

	// response with mocked
	response, err := http.Get("mitm://example.com")
	assertion.Nil(err)
	assertion.Equal(101, response.StatusCode)

	// paused and response with real github server
	mt.Pause()

	response, err = http.Get("mitm://example.com")
	assertion.Nil(err)
	assertion.Equal(200, response.StatusCode)

	// resume and response with mock again
	mt.Resume()

	response, err = http.Get("mitm://example.com")
	assertion.Nil(err)
	assertion.Equal(101, response.StatusCode)
}
Exemplo n.º 13
0
func Test_AppParamsXml(t *testing.T) {
	str := `<Params>
    <Key>xml_value</Key>
    <Test>true</Test>
</Params>`

	request, _ := http.NewRequest("POST", "/path/to/resource?key=url_value&test=url_true", strings.NewReader(str))
	request.Header.Set("Content-Type", "application/json")
	routeParams := httprouter.Params{
		httprouter.Param{"test", "route_true"},
	}
	assertion := assert.New(t)

	p := NewAppParams(request, routeParams)

	var params struct {
		XMLName xml.Name `xml:"Params"`
		Key     string   `xml:"Key"`
		Test    bool     `xml:"Test"`
	}
	err := p.Xml(&params)
	assertion.Nil(err)
	assertion.Equal("xml_value", params.Key)
	assertion.True(params.Test)
}
Exemplo n.º 14
0
func Test_MitmTransportWithTimesError(t *testing.T) {
	mt := NewMitmTransport().StubDefaultTransport(t)
	defer mt.UnstubDefaultTransport()

	assertion := assert.New(t)

	type result struct {
		Code int    `json:"code"`
		Name string `json:"name"`
	}

	// mocks
	mt.MockRequest("GET", "http://example.com").WithJsonResponse(200, nil, result{
		Code: 200,
		Name: "OK",
	}).Times(3)

	// GET mitm://example.com
	for i := 0; i < 3; i++ {
		response, err := http.Get("mitm://example.com")
		assertion.Nil(err)
		assertion.Equal(200, response.StatusCode)

		b, err := ioutil.ReadAll(response.Body)
		response.Body.Close()

		assertion.Nil(err)
		assertion.Equal(`{"code":200,"name":"OK"}`, string(b))
	}
}
Exemplo n.º 15
0
func Test_AppParamsGob(t *testing.T) {
	type data struct {
		Key  string `bson:"key"`
		Test bool   `bson:"test"`
	}

	var buf bytes.Buffer

	assertion := assert.New(t)
	params := data{
		Key:  "gob_value",
		Test: true,
	}

	err := gob.NewEncoder(&buf).Encode(params)
	assertion.Nil(err)

	request, _ := http.NewRequest("POST", "/path/to/resource?key=url_value&test=url_true", strings.NewReader(buf.String()))
	request.Header.Set("Content-Type", "application/gob")

	p := NewAppParams(request, httprouter.Params{})

	var temp data
	err = p.Gob(&temp)
	assertion.Nil(err)
	assertion.Equal("gob_value", temp.Key)
	assertion.True(temp.Test)
}
Exemplo n.º 16
0
func Test_NewObjectId(t *testing.T) {
	assertion := assert.New(t)

	// Generate 10 ids
	ids := make([]ObjectId, 10)
	for i := 0; i < 10; i++ {
		ids[i] = NewObjectId()
	}

	for i := 1; i < 10; i++ {
		id := ids[i]
		prevId := ids[i-1]

		// Test for uniqueness among all other 9 generated ids
		for j, tid := range ids {
			if j != i {
				assertion.NotEqual(id, tid)
			}
		}

		// Check that timestamp was incremented and is within 30 seconds of the previous one
		assertion.InDelta(prevId.Time().Second(), id.Time().Second(), 0.1)

		// Check that machine ids are the same
		assertion.Equal(prevId.Machine(), id.Machine())

		// Check that pids are the same
		assertion.Equal(prevId.Pid(), id.Pid())

		// Test for proper increment
		assertion.Equal(1, int(id.Counter()-prevId.Counter()))
	}
}
Exemplo n.º 17
0
func Test_ConfigSection(t *testing.T) {
	assertion := assert.New(t)
	config, _ := newMockConfig("application.json")

	section := config.Section()
	assertion.NotNil(section.Server)
	assertion.NotNil(section.Logger)
}
Exemplo n.º 18
0
func Test_NewConfigWithoutName(t *testing.T) {
	assertion := assert.New(t)
	config, _ := NewStringAppConfig(`{
    "mode": "test"
}`)

	assertion.Equal("GOGO", config.Name)
}
Exemplo n.º 19
0
func Test_NewConfigWithoutMode(t *testing.T) {
	assertion := assert.New(t)
	config, _ := NewStringAppConfig(`{
    "name": "testing"
}`)

	assertion.Equal(Development, config.Mode)
}
Exemplo n.º 20
0
func Test_NewResponse(t *testing.T) {
	recorder := httptest.NewRecorder()
	assertion := assert.New(t)

	response := NewResponse(recorder)
	assertion.Implements((*Responser)(nil), response)
	assertion.Equal(http.StatusOK, response.Status())
	assertion.Equal(noneHeaderFlushed, response.Size())
}
Exemplo n.º 21
0
func Test_ConfigSetMode(t *testing.T) {
	assertion := assert.New(t)

	config, _ := newMockConfig("application.json")
	assertion.Equal(Test, config.Mode)

	config.SetMode(Production)
	assertion.Equal(Production, config.Mode)
}
Exemplo n.º 22
0
func Test_NewConfig(t *testing.T) {
	assertion := assert.New(t)

	config, err := newMockConfig("application.json")
	assertion.Nil(err)
	assertion.Equal(Test, config.Mode)
	assertion.Equal("gogo", config.Name)
	assertion.NotEmpty(config.Sections)
}
Exemplo n.º 23
0
func Test_ResponseWriteHeader(t *testing.T) {
	recorder := httptest.NewRecorder()
	assertion := assert.New(t)

	response := NewResponse(recorder)
	response.WriteHeader(http.StatusRequestTimeout)
	assertion.Equal(http.StatusRequestTimeout, response.Status())
	assertion.Equal(noneHeaderFlushed, response.Size())
}
Exemplo n.º 24
0
func Test_NewObjectIdWithTime(t *testing.T) {
	ts := time.Unix(12345678, 0)
	id := NewObjectIdWithTime(ts)
	assertion := assert.New(t)
	assertion.Equal(ts, id.Time())
	assertion.Equal([]byte{0x00, 0x00, 0x00}, id.Machine())
	assertion.EqualValues(0, id.Pid())
	assertion.EqualValues(0, id.Counter())
}
Exemplo n.º 25
0
func Test_Level_ResolveLevelByName(t *testing.T) {
	assertion := assert.New(t)

	for level, name := range levels {
		assertion.Equal(level, ResolveLevelByName(name))
	}

	assertion.Equal(lmin, ResolveLevelByName("UNKNOWN"))
}
Exemplo n.º 26
0
func Test_MitmTransportStubDefaultTransport(t *testing.T) {
	assertion := assert.New(t)

	mt := NewMitmTransport()
	defer mt.UnstubDefaultTransport()

	mt.StubDefaultTransport(t)
	assertion.Equal(mt, http.DefaultTransport)
}
Exemplo n.º 27
0
func Test_AppParamsHasQuery(t *testing.T) {
	request, _ := http.NewRequest("GET", "/path/to/resource?test&key=url_value", nil)
	assertion := assert.New(t)

	p := NewAppParams(request, httprouter.Params{})
	assertion.True(p.HasQuery("test"))
	assertion.True(p.HasQuery("key"))
	assertion.False(p.HasQuery("un-existed-key"))
}
Exemplo n.º 28
0
func Test_NewContext(t *testing.T) {
	assertion := assert.New(t)

	server := newMockServer()
	ctx := NewContext(server)
	assertion.Equal(server, ctx.Server)
	assertion.EqualValues(-1, ctx.index)

	// settings
	assertion.Empty(ctx.settings)
	value, ok := ctx.Get("unknownSetting")
	assertion.False(ok)
	assertion.Empty(value)

	ctx.Set("middlewareKey", "middlewareValue")
	assertion.Equal(1, len(ctx.settings))
	value, ok = ctx.Get("middlewareKey")
	assertion.True(ok)
	assertion.Equal("middlewareValue", value)

	// MustGet
	assertion.Equal("middlewareValue", ctx.MustGet("middlewareKey"))
	assertion.Panics(func() {
		ctx.MustGet("unknownSetting")
	})

	// final settings
	assertion.Empty(ctx.frozenSettings)
	value, ok = ctx.GetFinal("unknownFinalSetting")
	assertion.False(ok)
	assertion.Empty(value)

	err := ctx.SetFinal("middlewareFinalKey", "middlewareFinalValue")
	assertion.Nil(err)
	assertion.Equal(1, len(ctx.frozenSettings))
	value, ok = ctx.GetFinal("middlewareFinalKey")
	assertion.True(ok)
	assertion.Equal("middlewareFinalValue", value)

	err = ctx.SetFinal("middlewareFinalKey", "newMiddlewareFinalValue")
	assertion.EqualError(err, ErrSettingsKey.Error())
	assertion.Equal(1, len(ctx.frozenSettings))
	value, ok = ctx.GetFinal("middlewareFinalKey")
	assertion.True(ok)
	assertion.Equal("middlewareFinalValue", value)

	// MustSetFinal
	assertion.Panics(func() {
		ctx.MustSetFinal("middlewareFinalKey", "newMiddlewareFinalValue")
	})

	// MusetGetFinal
	assertion.Panics(func() {
		ctx.MustGetFinal("unknownMiddlewareFinalKey")
	})
}
Exemplo n.º 29
0
func Test_NewAppRoute(t *testing.T) {
	prefix := "/prefix"
	server := newMockServer()
	assertion := assert.New(t)

	route := NewAppRoute(prefix, server)
	assertion.Empty(route.handlers)
	assertion.Equal(prefix, route.prefix)
	assertion.Equal(server, route.server)
}
Exemplo n.º 30
0
func Test_TimeoutResponser(t *testing.T) {
	assertion := assert.New(t)

	assertion.Implements((*http.RoundTripper)(nil), RefusedResponser)

	request, _ := http.NewRequest("GET", "https://example.com", nil)
	response, err := TimeoutResponser.RoundTrip(request)
	assertion.EqualError(err, ErrTimeout.Error())
	assertion.Nil(response)
}