Esempio n. 1
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)
}
Esempio n. 2
0
// Send a burst of GET messages to the server.
func TestHttpFlooding(t *testing.T) {
	serveProcess := NewServeScumbag()
	errSS := serveProcess.Start()
	assert.NoError(t, errSS, "Scumbag-ed!")
	t.Logf("Flooding http requests.")
	for i := 0; i < 3; i++ {
		err := runHttp()
		assert.NoError(t, err)
		time.Sleep(200 * time.Millisecond)
	}
	stopC := serveProcess.StopEventChannel()
	errStop := serveProcess.Stop(0)
	<-stopC
	assert.NoError(t, errStop, "Scumbag-ed!")
}
Esempio n. 3
0
func assertFilter(t *testing.T, filter, field, op, val string) {
	arr, err := _parseSearchQuery(filter)
	assert.NoError(t, err)
	assert.NotNil(t, arr)
	assert.Len(t, arr, 1)
	assert.Equal(t, arr[0], &ep.FilterData{field, op, val})
}
Esempio n. 4
0
func TestUnixSocket(t *testing.T) {
	buffer := new(bytes.Buffer)
	router := New()

	go func() {
		router.Use(LoggerWithWriter(buffer))
		router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") })
		router.RunUnix("/tmp/unix_unit_test")
	}()
	// have to wait for the goroutine to start and run the server
	// otherwise the main thread will complete
	time.Sleep(5 * time.Millisecond)

	c, err := net.Dial("unix", "/tmp/unix_unit_test")
	assert.NoError(t, err)

	fmt.Fprintf(c, "GET /example HTTP/1.0\r\n\r\n")
	scanner := bufio.NewScanner(c)
	var response string
	for scanner.Scan() {
		response += scanner.Text()
	}
	assert.Contains(t, response, "HTTP/1.0 200", "should get a 200")
	assert.Contains(t, response, "it worked", "resp body should match")
}
Esempio n. 5
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})
}
Esempio n. 6
0
func TestEncodeOnlyData(t *testing.T) {
	w := new(bytes.Buffer)
	err := Encode(w, Event{
		Data: "junk\n\njk\nid:fake",
	})
	assert.NoError(t, err)
	assert.Equal(t, w.String(), "data: junk\\n\\njk\\nid:fake\n\n")
}
Esempio n. 7
0
func TestEncodeWithRetry(t *testing.T) {
	w := new(bytes.Buffer)
	err := Encode(w, Event{
		Retry: 11,
		Data:  "junk\n\njk\nid:fake\n",
	})
	assert.NoError(t, err)
	assert.Equal(t, w.String(), "retry: 11\ndata: junk\\n\\njk\\nid:fake\\n\n\n")
}
Esempio n. 8
0
func TestEncodeWithId(t *testing.T) {
	w := new(bytes.Buffer)
	err := Encode(w, Event{
		Id:   "t\n:<>\r\test",
		Data: "junk\n\njk\nid:fa\rke",
	})
	assert.NoError(t, err)
	assert.Equal(t, w.String(), "id: t\\n:<>\\r\test\ndata: junk\\n\\njk\\nid:fa\\rke\n\n")
}
Esempio n. 9
0
func TestEncodeSlice(t *testing.T) {
	w := new(bytes.Buffer)
	err := Encode(w, Event{
		Event: "a slice",
		Data:  []interface{}{1, "text", map[string]interface{}{"foo": "bar"}},
	})
	assert.NoError(t, err)
	assert.Equal(t, w.String(), "event: a slice\ndata: [1,\"text\",{\"foo\":\"bar\"}]\n\n")
}
Esempio n. 10
0
func TestEncodeFloat(t *testing.T) {
	w := new(bytes.Buffer)
	err := Encode(w, Event{
		Event: "Float",
		Data:  1.5,
	})
	assert.NoError(t, err)
	assert.Equal(t, w.String(), "event: Float\ndata: 1.5\n\n")
}
Esempio n. 11
0
func TestEncodeInteger(t *testing.T) {
	w := new(bytes.Buffer)
	err := Encode(w, Event{
		Event: "an integer",
		Data:  1,
	})
	assert.NoError(t, err)
	assert.Equal(t, w.String(), "event: an integer\ndata: 1\n\n")
}
Esempio n. 12
0
func TestValidationDisabled(t *testing.T) {
	backup := Validator
	Validator = nil
	defer func() { Validator = backup }()

	var obj FooStruct
	req := requestWithBody("POST", "/", `{"bar": "foo"}`)
	err := JSON.Bind(req, &obj)
	assert.NoError(t, err)
}
Esempio n. 13
0
func TestEncodeWithEverything(t *testing.T) {
	w := new(bytes.Buffer)
	err := Encode(w, Event{
		Event: "abc",
		Id:    "12345",
		Retry: 10,
		Data:  "some data",
	})
	assert.NoError(t, err)
	assert.Equal(t, w.String(), "id: 12345\nevent: abc\nretry: 10\ndata: some data\n\n")
}
Esempio n. 14
0
func TestResponseWriterWrite(t *testing.T) {
	testWritter := httptest.NewRecorder()
	writer := &responseWriter{}
	writer.reset(testWritter)
	w := ResponseWriter(writer)

	n, err := w.Write([]byte("hola"))
	assert.Equal(t, n, 4)
	assert.Equal(t, w.Size(), 4)
	assert.Equal(t, w.Status(), 200)
	assert.Equal(t, testWritter.Code, 200)
	assert.Equal(t, testWritter.Body.String(), "hola")
	assert.NoError(t, err)

	n, err = w.Write([]byte(" adios"))
	assert.Equal(t, n, 6)
	assert.Equal(t, w.Size(), 10)
	assert.Equal(t, testWritter.Body.String(), "hola adios")
	assert.NoError(t, err)
}
Esempio n. 15
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")
}
Esempio n. 16
0
func TestEncodeMap(t *testing.T) {
	w := new(bytes.Buffer)
	err := Encode(w, Event{
		Event: "a map",
		Data: map[string]interface{}{
			"foo": "b\n\rar",
			"bar": "id: 2",
		},
	})
	assert.NoError(t, err)
	assert.Equal(t, w.String(), "event: a map\ndata: {\"bar\":\"id: 2\",\"foo\":\"b\\n\\rar\"}\n\n")
}
Esempio n. 17
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")
}
Esempio n. 18
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")
}
Esempio n. 19
0
func TestRenderData(t *testing.T) {
	w := httptest.NewRecorder()
	data := []byte("#!PNG some raw data")

	err := (Data{
		ContentType: "image/png",
		Data:        data,
	}).Render(w)

	assert.NoError(t, err)
	assert.Equal(t, w.Body.String(), "#!PNG some raw data")
	assert.Equal(t, w.Header().Get("Content-Type"), "image/png")
}
Esempio n. 20
0
func TestRenderSSE(t *testing.T) {
	w := httptest.NewRecorder()

	err := (Event{
		Event: "msg",
		Data:  "hi! how are you?",
	}).Render(w)

	assert.NoError(t, err)
	assert.Equal(t, w.Body.String(), "event: msg\ndata: hi! how are you?\n\n")
	assert.Equal(t, w.Header().Get("Content-Type"), "text/event-stream")
	assert.Equal(t, w.Header().Get("Cache-Control"), "no-cache")
}
Esempio n. 21
0
func TestEncodeStruct(t *testing.T) {
	myStruct := struct {
		A int
		B string `json:"value"`
	}{1, "number"}

	w := new(bytes.Buffer)
	err := Encode(w, Event{
		Event: "a struct",
		Data:  myStruct,
	})
	assert.NoError(t, err)
	assert.Equal(t, w.String(), "event: a struct\ndata: {\"A\":1,\"value\":\"number\"}\n\n")

	w.Reset()
	err = Encode(w, Event{
		Event: "a struct",
		Data:  &myStruct,
	})
	assert.NoError(t, err)
	assert.Equal(t, w.String(), "event: a struct\ndata: {\"A\":1,\"value\":\"number\"}\n\n")
}
Esempio n. 22
0
func testBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
	assert.Equal(t, b.Name(), name)

	obj := FooStruct{}
	req := requestWithBody("POST", path, body)
	err := b.Bind(req, &obj)
	assert.NoError(t, err)
	assert.Equal(t, obj.Foo, "bar")

	obj = FooStruct{}
	req = requestWithBody("POST", badPath, badBody)
	err = JSON.Bind(req, &obj)
	assert.Error(t, err)
}
Esempio n. 23
0
func TestRun(t *testing.T) {
	buffer := new(bytes.Buffer)
	router := New()
	go func() {
		router.Use(LoggerWithWriter(buffer))
		router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") })
		router.Run(":5150")
	}()
	// have to wait for the goroutine to start and run the server
	// otherwise the main thread will complete
	time.Sleep(5 * time.Millisecond)

	assert.Error(t, router.Run(":5150"))

	resp, err := http.Get("http://localhost:5150/example")
	defer resp.Body.Close()
	assert.NoError(t, err)

	body, ioerr := ioutil.ReadAll(resp.Body)
	assert.NoError(t, ioerr)
	assert.Equal(t, "it worked", string(body[:]), "resp body should match")
	assert.Equal(t, "200 OK", resp.Status, "should get a 200")
}
Esempio n. 24
0
func TestContextBindWithJSON(t *testing.T) {
	c, w, _ := createTestContext()
	c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
	c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type

	var obj struct {
		Foo string `json:"foo"`
		Bar string `json:"bar"`
	}
	assert.NoError(t, c.BindJSON(&obj))
	assert.Equal(t, obj.Bar, "foo")
	assert.Equal(t, obj.Foo, "bar")
	assert.Equal(t, w.Body.Len(), 0)
}
Esempio n. 25
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)
}
Esempio n. 26
0
func TestCombined(t *testing.T) {
	q := "balance:>=5 sequence:<8"
	arr, err := _parseSearchQuery(q)
	assert.NoError(t, err)
	assert.Len(t, arr, 2)
	f0 := arr[0]
	assert.Equal(t, f0.Field, "balance")
	assert.Equal(t, f0.Op, ">=")
	assert.Equal(t, f0.Value, "5")
	f1 := arr[1]
	assert.Equal(t, f1.Field, "sequence")
	assert.Equal(t, f1.Op, "<")
	assert.Equal(t, f1.Value, "8")

}
Esempio n. 27
0
func TestRenderHTMLTemplate(t *testing.T) {
	w := httptest.NewRecorder()
	templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))

	htmlRender := HTMLProduction{Template: templ}
	instance := htmlRender.Instance("t", map[string]interface{}{
		"name": "alexandernyquist",
	})

	err := instance.Render(w)

	assert.NoError(t, err)
	assert.Equal(t, w.Body.String(), "Hello alexandernyquist")
	assert.Equal(t, w.Header().Get("Content-Type"), "text/html; charset=utf-8")
}
Esempio n. 28
0
func TestContextGolangContext(t *testing.T) {
	c, _, _ := createTestContext()
	c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
	assert.NoError(t, c.Err())
	assert.Nil(t, c.Done())
	ti, ok := c.Deadline()
	assert.Equal(t, ti, time.Time{})
	assert.False(t, ok)
	assert.Equal(t, c.Value(0), c.Request)
	assert.Nil(t, c.Value("foo"))

	c.Set("foo", "bar")
	assert.Equal(t, c.Value("foo"), "bar")
	assert.Nil(t, c.Value(1))
}
Esempio n. 29
0
// Test that the system doesn't fail under high pressure.
func TestSubFlooding(t *testing.T) {
	NUM_SUBS := 100
	// Keep the reaper out of this.
	reaperThreshold = 10000 * time.Millisecond
	reaperTimeout = 10000 * time.Millisecond
	// Crank it up. Now pressure is 10 times higher on each sub.
	mockInterval = 1 * time.Millisecond
	mee := newMockEventEmitter()
	eSubs := NewEventSubscriptions(mee)
	doneChan := make(chan error)
	go func() {
		for i := 0; i < NUM_SUBS; i++ {
			time.Sleep(1 * time.Millisecond)
			go func() {
				id, err := eSubs.add("WeirdEvent")
				if err != nil {
					doneChan <- err
					return
				}
				if len(id) != 64 {
					doneChan <- fmt.Errorf("Id not of length 64")
					return
				}
				_, err2 := hex.DecodeString(id)
				if err2 != nil {
					doneChan <- err2
				}
				time.Sleep(1000 * time.Millisecond)
				err3 := eSubs.remove(id)
				if err3 != nil {
					doneChan <- err3
				}
				doneChan <- nil
			}()
		}
	}()
	k := 0
	for k < NUM_SUBS {
		err := <-doneChan
		assert.NoError(t, err)
		k++
	}

	assert.Len(t, mee.subs, 0)
	assert.Len(t, eSubs.subs, 0)
	t.Logf("Added %d subs that all received 1000 events each. They were all closed down by unsubscribing.", NUM_SUBS)
}
Esempio n. 30
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")
}