Example #1
0
func TestMiddlewareGeneralCase(t *testing.T) {
	signature := ""
	router := New()
	router.Use(func(c *Context) {
		signature += "A"
		c.Next()
		signature += "B"
	})
	router.Use(func(c *Context) {
		signature += "C"
	})
	router.GET("/", func(c *Context) {
		signature += "D"
	})
	router.NoRoute(func(c *Context) {
		signature += " X "
	})
	router.NoMethod(func(c *Context) {
		signature += " XX "
	})
	// RUN
	w := performRequest(router, "GET", "/")

	// TEST
	assert.Equal(t, w.Code, 200)
	assert.Equal(t, signature, "ACDB")
}
Example #2
0
func TestChooseData(t *testing.T) {
	A := "a"
	B := "b"
	assert.Equal(t, chooseData(A, B), A)
	assert.Equal(t, chooseData(nil, B), B)
	assert.Panics(t, func() { chooseData(nil, nil) })
}
Example #3
0
func TestFilterFlags(t *testing.T) {
	result := filterFlags("text/html ")
	assert.Equal(t, result, "text/html")

	result = filterFlags("text/html;")
	assert.Equal(t, result, "text/html")
}
Example #4
0
func TestMiddlewareNoRoute(t *testing.T) {
	signature := ""
	router := New()
	router.Use(func(c *Context) {
		signature += "A"
		c.Next()
		signature += "B"
	})
	router.Use(func(c *Context) {
		signature += "C"
		c.Next()
		c.Next()
		c.Next()
		c.Next()
		signature += "D"
	})
	router.NoRoute(func(c *Context) {
		signature += "E"
		c.Next()
		signature += "F"
	}, func(c *Context) {
		signature += "G"
		c.Next()
		signature += "H"
	})
	router.NoMethod(func(c *Context) {
		signature += " X "
	})
	// RUN
	w := performRequest(router, "GET", "/")

	// TEST
	assert.Equal(t, w.Code, 404)
	assert.Equal(t, signature, "ACEGHFDB")
}
Example #5
0
func TestMiddlewareWrite(t *testing.T) {
	router := New()
	router.Use(func(c *Context) {
		c.String(400, "hola\n")
	})
	router.Use(func(c *Context) {
		c.XML(400, H{"foo": "bar"})
	})
	router.Use(func(c *Context) {
		c.JSON(400, H{"foo": "bar"})
	})
	router.GET("/", func(c *Context) {
		c.JSON(400, H{"foo": "bar"})
	}, func(c *Context) {
		c.Render(400, sse.Event{
			Event: "test",
			Data:  "message",
		})
	})

	w := performRequest(router, "GET", "/")

	assert.Equal(t, w.Code, 400)
	assert.Equal(t, w.Body.String(), `hola
<map><foo>bar</foo></map>{"foo":"bar"}
{"foo":"bar"}
event: test
data: message

`)
}
Example #6
0
func TestMiddlewareAbort(t *testing.T) {
	signature := ""
	router := New()
	router.Use(func(c *Context) {
		signature += "A"
	})
	router.Use(func(c *Context) {
		signature += "C"
		c.AbortWithStatus(401)
		c.Next()
		signature += "D"
	})
	router.GET("/", func(c *Context) {
		signature += " X "
		c.Next()
		signature += " XX "
	})

	// RUN
	w := performRequest(router, "GET", "/")

	// TEST
	assert.Equal(t, w.Code, 401)
	assert.Equal(t, signature, "ACD")
}
Example #7
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)
}
Example #8
0
// Testing to ensure that websocket server does not crash, and that it
// cleans up after itself.
func TestWsFlooding(t *testing.T) {

	// New websocket server.
	wsServer := NewScumsocketServer(CONNS)

	// Keep track of sessions.
	sc := &SessionCounter{}

	// Register the observer.
	oChan := wsServer.SessionManager().SessionOpenEventChannel()
	cChan := wsServer.SessionManager().SessionCloseEventChannel()

	sc.Run(oChan, cChan)

	serveProcess := NewServeScumSocket(wsServer)
	errServe := serveProcess.Start()
	assert.NoError(t, errServe, "ScumSocketed!")
	t.Logf("Flooding...")
	// Run. Blocks.
	errRun := runWs()
	stopC := serveProcess.StopEventChannel()
	errStop := serveProcess.Stop(0)
	<-stopC
	assert.NoError(t, errRun, "ScumSocketed!")
	assert.NoError(t, errStop, "ScumSocketed!")
	o, c, a := sc.Report()
	assert.Equal(t, o, CONNS, "Server registered '%d' opened conns out of '%d'", o, CONNS)
	assert.Equal(t, c, CONNS, "Server registered '%d' closed conns out of '%d'", c, CONNS)
	assert.Equal(t, a, 0, "Server registered '%d' conns still active after shutting down.", a)
}
Example #9
0
func TestParseAccept(t *testing.T) {
	parts := parseAccept("text/html , application/xhtml+xml,application/xml;q=0.9,  */* ;q=0.8")
	assert.Len(t, parts, 4)
	assert.Equal(t, parts[0], "text/html")
	assert.Equal(t, parts[1], "application/xhtml+xml")
	assert.Equal(t, parts[2], "application/xml")
	assert.Equal(t, parts[3], "*/*")
}
Example #10
0
func assertRangeFilter(t *testing.T, min, max, res0, res1 string) {
	arr, err := _parseSearchQuery("test:" + min + ".." + max)
	assert.NoError(t, err)
	assert.NotNil(t, arr)
	assert.Len(t, arr, 2)
	assert.Equal(t, arr[0], &ep.FilterData{"test", ">=", res0})
	assert.Equal(t, arr[1], &ep.FilterData{"test", "<=", res1})
}
Example #11
0
// Tests that the response is serialized as JSON
// and Content-Type is set to application/json
func TestContextRenderIndentedJSON(t *testing.T) {
	c, w, _ := createTestContext()
	c.IndentedJSON(201, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})

	assert.Equal(t, w.Code, 201)
	assert.Equal(t, w.Body.String(), "{\n    \"bar\": \"foo\",\n    \"foo\": \"bar\",\n    \"nested\": {\n        \"foo\": \"bar\"\n    }\n}")
	assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
}
Example #12
0
// TestContextData tests that the response can be written from `bytesting`
// with specified MIME type
func TestContextRenderData(t *testing.T) {
	c, w, _ := createTestContext()
	c.Data(201, "text/csv", []byte(`foo,bar`))

	assert.Equal(t, w.Code, 201)
	assert.Equal(t, w.Body.String(), "foo,bar")
	assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv")
}
Example #13
0
func TestSuiteGetters(t *testing.T) {
	suite := new(SuiteTester)
	suite.SetT(t)
	assert.NotNil(t, suite.Assert())
	assert.Equal(t, suite.Assertions, suite.Assert())
	assert.NotNil(t, suite.Require())
	assert.Equal(t, suite.require, suite.Require())
}
Example #14
0
func TestContextNegotiationFormat(t *testing.T) {
	c, _, _ := createTestContext()
	c.Request, _ = http.NewRequest("POST", "", nil)

	assert.Panics(t, func() { c.NegotiateFormat() })
	assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
	assert.Equal(t, c.NegotiateFormat(MIMEHTML, MIMEJSON), MIMEHTML)
}
Example #15
0
// TestContextString tests that the response is returned
// with Content-Type set to text/plain
func TestContextRenderString(t *testing.T) {
	c, w, _ := createTestContext()
	c.String(201, "test %s %d", "string", 2)

	assert.Equal(t, w.Code, 201)
	assert.Equal(t, w.Body.String(), "test string 2")
	assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
}
Example #16
0
// Tests that the response is serialized as JSON
// and Content-Type is set to application/json
func TestContextRenderJSON(t *testing.T) {
	c, w, _ := createTestContext()
	c.JSON(201, H{"foo": "bar"})

	assert.Equal(t, w.Code, 201)
	assert.Equal(t, w.Body.String(), "{\"foo\":\"bar\"}\n")
	assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
}
Example #17
0
// TestContextXML tests that the response is serialized as XML
// and Content-Type is set to application/xml
func TestContextRenderXML(t *testing.T) {
	c, w, _ := createTestContext()
	c.XML(201, H{"foo": "bar"})

	assert.Equal(t, w.Code, 201)
	assert.Equal(t, w.Body.String(), "<map><foo>bar</foo></map>")
	assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8")
}
Example #18
0
func TestContextAbortWithError(t *testing.T) {
	c, w, _ := createTestContext()
	c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")
	c.Writer.WriteHeaderNow()

	assert.Equal(t, w.Code, 401)
	assert.Equal(t, c.index, AbortIndex)
	assert.True(t, c.IsAborted())
}
Example #19
0
func TestContextNegotiationFormatWithAccept(t *testing.T) {
	c, _, _ := createTestContext()
	c.Request, _ = http.NewRequest("POST", "/", nil)
	c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")

	assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEXML)
	assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEHTML)
	assert.Equal(t, c.NegotiateFormat(MIMEJSON), "")
}
Example #20
0
func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
	c, w, _ := createTestContext()
	c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
	c.Redirect(302, "http://google.com")
	c.Writer.WriteHeaderNow()

	assert.Equal(t, w.Code, 302)
	assert.Equal(t, w.Header().Get("Location"), "http://google.com")
}
Example #21
0
// TestContextString tests that the response is returned
// with Content-Type set to text/html
func TestContextRenderHTMLString(t *testing.T) {
	c, w, _ := createTestContext()
	c.Header("Content-Type", "text/html; charset=utf-8")
	c.String(201, "<html>%s %d</html>", "string", 3)

	assert.Equal(t, w.Code, 201)
	assert.Equal(t, w.Body.String(), "<html>string 3</html>")
	assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
}
Example #22
0
func TestContextRenderFile(t *testing.T) {
	c, w, _ := createTestContext()
	c.Request, _ = http.NewRequest("GET", "/", nil)
	c.File("./gin.go")

	assert.Equal(t, w.Code, 200)
	assert.Contains(t, w.Body.String(), "func New() *Engine {")
	assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
}
Example #23
0
// TestHandleStaticDir - ensure the root/sub dir handles properly
func TestRouteStaticListingDir(t *testing.T) {
	router := New()
	router.StaticFS("/", Dir("./", true))

	w := performRequest(router, "GET", "/")

	assert.Equal(t, w.Code, 200)
	assert.Contains(t, w.Body.String(), "gin.go")
	assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
}
Example #24
0
// TestContextData tests that the response can be written from `bytesting`
// with specified MIME type
func TestContextAbortWithStatus(t *testing.T) {
	c, w, _ := createTestContext()
	c.index = 4
	c.AbortWithStatus(401)
	c.Writer.WriteHeaderNow()

	assert.Equal(t, c.index, AbortIndex)
	assert.Equal(t, c.Writer.Status(), 401)
	assert.Equal(t, w.Code, 401)
	assert.True(t, c.IsAborted())
}
Example #25
0
// TODO
func TestContextRenderRedirectWithRelativePath(t *testing.T) {
	c, w, _ := createTestContext()
	c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
	assert.Panics(t, func() { c.Redirect(299, "/new_path") })
	assert.Panics(t, func() { c.Redirect(309, "/new_path") })

	c.Redirect(302, "/path")
	c.Writer.WriteHeaderNow()
	assert.Equal(t, w.Code, 302)
	assert.Equal(t, w.Header().Get("Location"), "/path")
}
Example #26
0
// Tests that the response executes the templates
// and responds with Content-Type set to text/html
func TestContextRenderHTML(t *testing.T) {
	c, w, router := createTestContext()
	templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
	router.SetHTMLTemplate(templ)

	c.HTML(201, "t", H{"name": "alexandernyquist"})

	assert.Equal(t, w.Code, 201)
	assert.Equal(t, w.Body.String(), "Hello alexandernyquist")
	assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
}
Example #27
0
func TestRenderJSON(t *testing.T) {
	w := httptest.NewRecorder()
	data := map[string]interface{}{
		"foo": "bar",
	}

	err := (JSON{data}).Render(w)

	assert.NoError(t, err)
	assert.Equal(t, w.Body.String(), "{\"foo\":\"bar\"}\n")
	assert.Equal(t, w.Header().Get("Content-Type"), "application/json; charset=utf-8")
}
Example #28
0
func TestJoinPaths(t *testing.T) {
	assert.Equal(t, joinPaths("", ""), "")
	assert.Equal(t, joinPaths("", "/"), "/")
	assert.Equal(t, joinPaths("/a", ""), "/a")
	assert.Equal(t, joinPaths("/a/", ""), "/a/")
	assert.Equal(t, joinPaths("/a/", "/"), "/a/")
	assert.Equal(t, joinPaths("/a", "/"), "/a/")
	assert.Equal(t, joinPaths("/a", "/hola"), "/a/hola")
	assert.Equal(t, joinPaths("/a/", "/hola"), "/a/hola")
	assert.Equal(t, joinPaths("/a/", "/hola/"), "/a/hola/")
	assert.Equal(t, joinPaths("/a/", "/hola//"), "/a/hola/")
}
Example #29
0
func TestRenderString(t *testing.T) {
	w := httptest.NewRecorder()

	err := (String{
		Format: "hola %s %d",
		Data:   []interface{}{"manu", 2},
	}).Render(w)

	assert.NoError(t, err)
	assert.Equal(t, w.Body.String(), "hola manu 2")
	assert.Equal(t, w.Header().Get("Content-Type"), "text/plain; charset=utf-8")
}
Example #30
0
func TestRenderXML(t *testing.T) {
	w := httptest.NewRecorder()
	data := xmlmap{
		"foo": "bar",
	}

	err := (XML{data}).Render(w)

	assert.NoError(t, err)
	assert.Equal(t, w.Body.String(), "<map><foo>bar</foo></map>")
	assert.Equal(t, w.Header().Get("Content-Type"), "application/xml; charset=utf-8")
}