Ejemplo n.º 1
0
func TestBasicAuthSearchCredential(t *testing.T) {
	pairs := processAccounts(Accounts{
		"admin": "password",
		"foo":   "bar",
		"bar":   "foo",
	})

	user, found := pairs.searchCredential(authorizationHeader("admin", "password"))
	assert.Equal(t, user, "admin")
	assert.True(t, found)

	user, found = pairs.searchCredential(authorizationHeader("foo", "bar"))
	assert.Equal(t, user, "foo")
	assert.True(t, found)

	user, found = pairs.searchCredential(authorizationHeader("bar", "foo"))
	assert.Equal(t, user, "bar")
	assert.True(t, found)

	user, found = pairs.searchCredential(authorizationHeader("admins", "password"))
	assert.Empty(t, user)
	assert.False(t, found)

	user, found = pairs.searchCredential(authorizationHeader("foo", "bar "))
	assert.Empty(t, user)
	assert.False(t, found)

	user, found = pairs.searchCredential("")
	assert.Empty(t, user)
	assert.False(t, found)
}
Ejemplo n.º 2
0
// TestContextParamsGet tests that a parameter can be parsed from the URL.
func TestRouteParamsByName(t *testing.T) {
	name := ""
	lastName := ""
	wild := ""
	router := New()
	router.GET("/test/:name/:last_name/*wild", func(c *Context) {
		name = c.Params.ByName("name")
		lastName = c.Params.ByName("last_name")
		var ok bool
		wild, ok = c.Params.Get("wild")

		assert.True(t, ok)
		assert.Equal(t, name, c.Param("name"))
		assert.Equal(t, name, c.Param("name"))
		assert.Equal(t, lastName, c.Param("last_name"))

		assert.Empty(t, c.Param("wtf"))
		assert.Empty(t, c.Params.ByName("wtf"))

		wtf, ok := c.Params.Get("wtf")
		assert.Empty(t, wtf)
		assert.False(t, ok)
	})

	w := performRequest(router, "GET", "/test/john/smith/is/super/great")

	assert.Equal(t, w.Code, 200)
	assert.Equal(t, name, "john")
	assert.Equal(t, lastName, "smith")
	assert.Equal(t, wild, "/is/super/great")
}
Ejemplo n.º 3
0
func TestContextError(t *testing.T) {
	c, _, _ := createTestContext()
	assert.Empty(t, c.Errors)

	c.Error(errors.New("first error"))
	assert.Len(t, c.Errors, 1)
	assert.Equal(t, c.Errors.String(), "Error #01: first error\n")

	c.Error(&Error{
		Err:  errors.New("second error"),
		Meta: "some data 2",
		Type: ErrorTypePublic,
	})
	assert.Len(t, c.Errors, 2)

	assert.Equal(t, c.Errors[0].Err, errors.New("first error"))
	assert.Nil(t, c.Errors[0].Meta)
	assert.Equal(t, c.Errors[0].Type, ErrorTypePrivate)

	assert.Equal(t, c.Errors[1].Err, errors.New("second error"))
	assert.Equal(t, c.Errors[1].Meta, "some data 2")
	assert.Equal(t, c.Errors[1].Type, ErrorTypePublic)

	assert.Equal(t, c.Errors.Last(), c.Errors[1])
}
Ejemplo n.º 4
0
func TestContextQuery(t *testing.T) {
	c, _, _ := createTestContext()
	c.Request, _ = http.NewRequest("GET", "http://example.com/?foo=bar&page=10", nil)

	assert.Equal(t, c.DefaultQuery("foo", "none"), "bar")
	assert.Equal(t, c.Query("foo"), "bar")
	assert.Empty(t, c.PostForm("foo"))

	assert.Equal(t, c.DefaultQuery("page", "0"), "10")
	assert.Equal(t, c.Query("page"), "10")
	assert.Empty(t, c.PostForm("page"))

	assert.Equal(t, c.DefaultQuery("NoKey", "nada"), "nada")
	assert.Empty(t, c.Query("NoKey"))
	assert.Empty(t, c.PostForm("NoKey"))
}
Ejemplo n.º 5
0
func TestContextPostFormMultipart(t *testing.T) {
	c, _, _ := createTestContext()
	c.Request = createMultipartRequest()

	var obj struct {
		Foo string `form:"foo"`
		Bar string `form:"bar"`
	}
	assert.NoError(t, c.Bind(&obj))
	assert.Equal(t, obj.Bar, "foo")
	assert.Equal(t, obj.Foo, "bar")

	assert.Empty(t, c.Query("foo"))
	assert.Empty(t, c.Query("bar"))
	assert.Equal(t, c.PostForm("foo"), "bar")
	assert.Equal(t, c.PostForm("bar"), "foo")
}
Ejemplo n.º 6
0
func TestContextBadAutoBind(t *testing.T) {
	c, w, _ := createTestContext()
	c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
	c.Request.Header.Add("Content-Type", MIMEJSON)
	var obj struct {
		Foo string `json:"foo"`
		Bar string `json:"bar"`
	}

	assert.False(t, c.IsAborted())
	assert.Error(t, c.Bind(&obj))
	c.Writer.WriteHeaderNow()

	assert.Empty(t, obj.Bar)
	assert.Empty(t, obj.Foo)
	assert.Equal(t, w.Code, 400)
	assert.True(t, c.IsAborted())
}
Ejemplo n.º 7
0
func TestDebugPrintError(t *testing.T) {
	var w bytes.Buffer
	setup(&w)
	defer teardown()

	SetMode(DebugMode)
	debugPrintError(nil)
	assert.Empty(t, w.String())

	debugPrintError(errors.New("this is an error"))
	assert.Equal(t, w.String(), "[GIN-debug] [ERROR] this is an error\n")
}
Ejemplo n.º 8
0
func TestErrorSlice(t *testing.T) {
	errs := errorMsgs{
		{Err: errors.New("first"), Type: ErrorTypePrivate},
		{Err: errors.New("second"), Type: ErrorTypePrivate, Meta: "some data"},
		{Err: errors.New("third"), Type: ErrorTypePublic, Meta: H{"status": "400"}},
	}

	assert.Equal(t, errs.Last().Error(), "third")
	assert.Equal(t, errs.Errors(), []string{"first", "second", "third"})
	assert.Equal(t, errs.ByType(ErrorTypePublic).Errors(), []string{"third"})
	assert.Equal(t, errs.ByType(ErrorTypePrivate).Errors(), []string{"first", "second"})
	assert.Equal(t, errs.ByType(ErrorTypePublic|ErrorTypePrivate).Errors(), []string{"first", "second", "third"})
	assert.Empty(t, errs.ByType(ErrorTypeBind))
	assert.Empty(t, errs.ByType(ErrorTypeBind).String())

	assert.Equal(t, errs.String(), `Error #01: first
Error #02: second
     Meta: some data
Error #03: third
     Meta: map[status:400]
`)
	assert.Equal(t, errs.JSON(), []interface{}{
		H{"error": "first"},
		H{"error": "second", "meta": "some data"},
		H{"error": "third", "status": "400"},
	})
	jsonBytes, _ := json.Marshal(errs)
	assert.Equal(t, string(jsonBytes), "[{\"error\":\"first\"},{\"error\":\"second\",\"meta\":\"some data\"},{\"error\":\"third\",\"status\":\"400\"}]")
	errs = errorMsgs{
		{Err: errors.New("first"), Type: ErrorTypePrivate},
	}
	assert.Equal(t, errs.JSON(), H{"error": "first"})
	jsonBytes, _ = json.Marshal(errs)
	assert.Equal(t, string(jsonBytes), "{\"error\":\"first\"}")

	errs = errorMsgs{}
	assert.Nil(t, errs.Last())
	assert.Nil(t, errs.JSON())
	assert.Empty(t, errs.String())
}
Ejemplo n.º 9
0
func TestContextReset(t *testing.T) {
	router := New()
	c := router.allocateContext()
	assert.Equal(t, c.engine, router)

	c.index = 2
	c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()}
	c.Params = Params{Param{}}
	c.Error(errors.New("test"))
	c.Set("foo", "bar")
	c.reset()

	assert.False(t, c.IsAborted())
	assert.Nil(t, c.Keys)
	assert.Nil(t, c.Accepted)
	assert.Len(t, c.Errors, 0)
	assert.Empty(t, c.Errors.Errors())
	assert.Empty(t, c.Errors.ByType(ErrorTypeAny))
	assert.Len(t, c.Params, 0)
	assert.EqualValues(t, c.index, -1)
	assert.Equal(t, c.Writer.(*responseWriter), &c.writermem)
}
Ejemplo n.º 10
0
func TestContextAutoBindJSON(t *testing.T) {
	c, _, _ := createTestContext()
	c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
	c.Request.Header.Add("Content-Type", MIMEJSON)

	var obj struct {
		Foo string `json:"foo"`
		Bar string `json:"bar"`
	}
	assert.NoError(t, c.Bind(&obj))
	assert.Equal(t, obj.Bar, "foo")
	assert.Equal(t, obj.Foo, "bar")
	assert.Empty(t, c.Errors)
}
Ejemplo n.º 11
0
func TestContextQueryAndPostForm(t *testing.T) {
	c, _, _ := createTestContext()
	body := bytes.NewBufferString("foo=bar&page=11&both=POST")
	c.Request, _ = http.NewRequest("POST", "/?both=GET&id=main", body)
	c.Request.Header.Add("Content-Type", MIMEPOSTForm)

	assert.Equal(t, c.DefaultPostForm("foo", "none"), "bar")
	assert.Equal(t, c.PostForm("foo"), "bar")
	assert.Empty(t, c.Query("foo"))

	assert.Equal(t, c.DefaultPostForm("page", "0"), "11")
	assert.Equal(t, c.PostForm("page"), "11")
	assert.Equal(t, c.Query("page"), "")

	assert.Equal(t, c.PostForm("both"), "POST")
	assert.Equal(t, c.Query("both"), "GET")

	assert.Equal(t, c.DefaultPostForm("id", "000"), "000")
	assert.Equal(t, c.Query("id"), "main")
	assert.Empty(t, c.PostForm("id"))

	assert.Equal(t, c.DefaultPostForm("NoKey", "nada"), "nada")
	assert.Empty(t, c.PostForm("NoKey"))
	assert.Empty(t, c.Query("NoKey"))

	var obj struct {
		Foo  string `form:"foo"`
		Id   string `form:"id"`
		Page string `form:"page"`
		Both string `form:"both"`
	}
	assert.NoError(t, c.Bind(&obj))
	assert.Equal(t, obj.Foo, "bar")
	assert.Equal(t, obj.Id, "main")
	assert.Equal(t, obj.Page, "11")
	assert.Equal(t, obj.Both, "POST")
}
Ejemplo n.º 12
0
func TestDebugPrint(t *testing.T) {
	var w bytes.Buffer
	setup(&w)
	defer teardown()

	SetMode(ReleaseMode)
	debugPrint("DEBUG this!")
	SetMode(TestMode)
	debugPrint("DEBUG this!")
	assert.Empty(t, w.String())

	SetMode(DebugMode)
	debugPrint("these are %d %s\n", 2, "error messages")
	assert.Equal(t, w.String(), "[GIN-debug] these are 2 error messages\n")
}
Ejemplo n.º 13
0
func TestNoMethodWithoutGlobalHandlers(t *testing.T) {
	var middleware0 HandlerFunc = func(c *Context) {}
	var middleware1 HandlerFunc = func(c *Context) {}

	router := New()

	router.NoMethod(middleware0)
	assert.Empty(t, router.Handlers)
	assert.Len(t, router.noMethod, 1)
	assert.Len(t, router.allNoMethod, 1)
	compareFunc(t, router.noMethod[0], middleware0)
	compareFunc(t, router.allNoMethod[0], middleware0)

	router.NoMethod(middleware1, middleware0)
	assert.Len(t, router.noMethod, 2)
	assert.Len(t, router.allNoMethod, 2)
	compareFunc(t, router.noMethod[0], middleware1)
	compareFunc(t, router.allNoMethod[0], middleware1)
	compareFunc(t, router.noMethod[1], middleware0)
	compareFunc(t, router.allNoMethod[1], middleware0)
}
Ejemplo n.º 14
0
// Empty asserts that the specified object is empty.  I.e. nil, "", false, 0 or either
// a slice or a channel with len == 0.
//
// require.Empty(t, obj)
func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) {
	if !assert.Empty(t, object, msgAndArgs...) {
		t.FailNow()
	}
}
Ejemplo n.º 15
0
func TestCreateEngine(t *testing.T) {
	router := New()
	assert.Equal(t, "/", router.BasePath)
	assert.Equal(t, router.engine, router)
	assert.Empty(t, router.Handlers)
}