Example #1
0
func TestRemotePrecedence(t *testing.T) {
	initJSON()

	remote := bytes.NewReader(remoteExample)
	assert.Equal(t, "0001", Get("id"))
	marshalReader(remote, v.kvstore)
	assert.Equal(t, "0001", Get("id"))
	assert.NotEqual(t, "cronut", Get("type"))
	assert.Equal(t, "remote", Get("newkey"))
	Set("newkey", "newvalue")
	assert.NotEqual(t, "remote", Get("newkey"))
	assert.Equal(t, "newvalue", Get("newkey"))
	Set("newkey", "remote")
}
Example #2
0
func TestClientUpdatePresence(t *testing.T) {
	app := testApp()
	c, err := newClient(app, &testSession{})
	assert.Equal(t, nil, err)

	timestamp := strconv.FormatInt(time.Now().Unix(), 10)
	cmds := []clientCommand{testConnectCmd(timestamp), testSubscribeCmd("test1"), testSubscribeCmd("test2")}
	err = c.handleCommands(cmds)
	assert.Equal(t, nil, err)
	assert.Equal(t, 2, len(c.channels()))

	assert.NotEqual(t, nil, c.presenceTimer)
	timer := c.presenceTimer
	c.updatePresence()
	assert.NotEqual(t, timer, c.presenceTimer)
}
Example #3
0
func TestClientMessage(t *testing.T) {
	app := testApp()
	c, err := newClient(app, &testSession{})
	assert.Equal(t, nil, err)

	// empty message
	err = c.message([]byte{})
	assert.Equal(t, ErrInvalidMessage, err)

	// malformed message
	err = c.message([]byte("wroooong"))
	assert.NotEqual(t, nil, err)

	var cmds []clientCommand

	nonConnectFirstCmd := clientCommand{
		Method: "subscribe",
		Params: []byte("{}"),
	}

	cmds = append(cmds, nonConnectFirstCmd)
	cmdBytes, err := json.Marshal(cmds)
	assert.Equal(t, nil, err)
	err = c.message(cmdBytes)
	assert.Equal(t, ErrUnauthorized, err)
}
Example #4
0
func TestAdminClient(t *testing.T) {
	c, err := newTestAdminClient()
	go c.writer()
	assert.Equal(t, nil, err)
	assert.NotEqual(t, c.uid(), "")
	err = c.send([]byte("message"))
	assert.Equal(t, nil, err)
}
Example #5
0
func TestMemoryEngine(t *testing.T) {
	e := testMemoryEngine()
	assert.NotEqual(t, nil, e.historyHub)
	assert.NotEqual(t, nil, e.presenceHub)
	assert.NotEqual(t, e.name(), "")
	assert.Equal(t, nil, e.publish(ChannelID("channel"), []byte("{}")))
	assert.Equal(t, nil, e.subscribe(ChannelID("channel")))
	assert.Equal(t, nil, e.unsubscribe(ChannelID("channel")))
	assert.Equal(t, nil, e.addPresence(ChannelID("channel"), "uid", ClientInfo{}))
	p, err := e.presence(ChannelID("channel"))
	assert.Equal(t, nil, err)
	assert.Equal(t, 1, len(p))
	assert.Equal(t, nil, e.addHistory(ChannelID("channel"), Message{}, 1, 1))
	h, err := e.history(ChannelID("channel"))
	assert.Equal(t, nil, err)
	assert.Equal(t, 1, len(h))
}
Example #6
0
func TestLevels(t *testing.T) {
	SetStdoutThreshold(LevelError)
	assert.Equal(t, outputThreshold, LevelError)
	SetLogThreshold(LevelCritical)
	assert.Equal(t, logThreshold, LevelCritical)
	assert.NotEqual(t, outputThreshold, LevelCritical)
	SetStdoutThreshold(LevelWarn)
	assert.Equal(t, outputThreshold, LevelWarn)
}
Example #7
0
func TestClientConnect(t *testing.T) {
	app := testApp()
	c, err := newClient(app, &testSession{})
	assert.Equal(t, nil, err)

	var cmd clientCommand
	var cmds []clientCommand

	cmd = clientCommand{
		Method: "connect",
		Params: []byte(`{"project": "test1"}`),
	}
	cmds = []clientCommand{cmd}
	err = c.handleCommands(cmds)
	assert.Equal(t, ErrInvalidToken, err)

	timestamp := strconv.FormatInt(time.Now().Unix(), 10)
	cmds = []clientCommand{testConnectCmd(timestamp)}
	err = c.handleCommands(cmds)
	assert.Equal(t, nil, err)
	assert.Equal(t, true, c.authenticated)
	ts, err := strconv.Atoi(timestamp)
	assert.Equal(t, int64(ts), c.timestamp)

	clientInfo := c.info(Channel(""))
	assert.Equal(t, UserID("user1"), clientInfo.User)

	assert.Equal(t, 1, len(app.clients.conns))

	assert.NotEqual(t, "", c.uid(), "uid must be already set")
	assert.NotEqual(t, "", c.user(), "user must be already set")

	err = c.clean()
	assert.Equal(t, nil, err)

	assert.Equal(t, 0, len(app.clients.conns))
}
Example #8
0
func TestAdminClientMessageHandling(t *testing.T) {
	c, err := newTestAdminClient()
	assert.Equal(t, nil, err)
	emptyMsg := ""
	_, err = c.handleMessage([]byte(emptyMsg))
	assert.NotEqual(t, nil, err)
	malformedMsg := "ooops"
	_, err = c.handleMessage([]byte(malformedMsg))
	assert.NotEqual(t, nil, err)
	unknownMsg := "{\"method\":\"unknown\", \"params\": {}}"
	_, err = c.handleMessage([]byte(unknownMsg))
	assert.Equal(t, ErrInvalidMessage, err)
	emptyAuthMethod := "{\"method\":\"auth\", \"params\": {}}"
	_, err = c.handleMessage([]byte(emptyAuthMethod))
	assert.Equal(t, ErrUnauthorized, err)
	s := securecookie.New([]byte(c.app.config.WebSecret), nil)
	token, _ := s.Encode(AuthTokenKey, AuthTokenValue)
	correctAuthMethod := "{\"method\":\"auth\", \"params\": {\"token\":\"" + token + "\"}}"
	_, err = c.handleMessage([]byte(correctAuthMethod))
	assert.Equal(t, nil, err)
	pingCommand := "{\"method\":\"ping\", \"params\": {}}"
	_, err = c.handleMessage([]byte(pingCommand))
	assert.Equal(t, nil, err)
}
Example #9
0
func TestRawWsHandler(t *testing.T) {
	app := testApp()
	mux := DefaultMux(app, DefaultMuxOptions)
	server := httptest.NewServer(mux)
	defer server.Close()
	url := "ws" + server.URL[4:]
	conn, resp, err := websocket.DefaultDialer.Dial(url+"/connection/websocket", nil)
	conn.Close()
	assert.Equal(t, nil, err)
	assert.NotEqual(t, nil, conn)
	assert.Equal(t, http.StatusSwitchingProtocols, resp.StatusCode)

	app.Shutdown()
	_, resp, err = websocket.DefaultDialer.Dial(url+"/connection/websocket", nil)
	assert.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
}
Example #10
0
func TestUnauthenticatedClient(t *testing.T) {
	app := testApp()
	c, err := newClient(app, &testSession{})
	assert.Equal(t, nil, err)
	assert.NotEqual(t, "", c.uid())

	// user not set before connect command success
	assert.Equal(t, UserID(""), c.user())

	assert.Equal(t, false, c.authenticated)
	assert.Equal(t, []Channel{}, c.channels())

	// check that unauthenticated client can be cleaned correctly
	err = c.clean()
	assert.Equal(t, nil, err)
}
Example #11
0
func TestAdminWebsocketHandler(t *testing.T) {
	app := testApp()
	mux := DefaultMux(app, "", "path/to/web", "sockjs url")
	server := httptest.NewServer(mux)
	defer server.Close()
	url := "ws" + server.URL[4:]
	conn, resp, err := websocket.DefaultDialer.Dial(url+"/socket", nil)
	data := map[string]interface{}{
		"method": "ping",
		"params": map[string]string{},
	}
	conn.WriteJSON(data)
	var response interface{}
	conn.ReadJSON(&response)
	conn.Close()
	assert.Equal(t, nil, err)
	assert.NotEqual(t, nil, conn)
	assert.Equal(t, http.StatusSwitchingProtocols, resp.StatusCode)
}
Example #12
0
func TestAdminWebsocketHandler(t *testing.T) {
	app := testApp()
	app.config.Web = true // admin websocket available only if web enabled at moment
	opts := DefaultMuxOptions
	opts.Web = true
	mux := DefaultMux(app, opts)
	server := httptest.NewServer(mux)
	defer server.Close()
	url := "ws" + server.URL[4:]
	conn, resp, err := websocket.DefaultDialer.Dial(url+"/socket", nil)
	data := map[string]interface{}{
		"method": "ping",
		"params": map[string]string{},
	}
	conn.WriteJSON(data)
	var response interface{}
	conn.ReadJSON(&response)
	conn.Close()
	assert.Equal(t, nil, err)
	assert.NotEqual(t, nil, conn)
	assert.Equal(t, http.StatusSwitchingProtocols, resp.StatusCode)

}
Example #13
0
func TestMemoryEngine(t *testing.T) {
	e := testMemoryEngine()
	err := e.run()
	assert.Equal(t, nil, err)
	assert.NotEqual(t, nil, e.historyHub)
	assert.NotEqual(t, nil, e.presenceHub)
	assert.NotEqual(t, e.name(), "")

	err = e.publish(ChannelID("channel"), []byte("{}"), nil)
	assert.Equal(t, nil, err)

	assert.Equal(t, nil, e.subscribe(ChannelID("channel")))

	// Memory engine is actually tightly coupled to application hubs in implementation
	// so calling subscribe on the engine alone is actually a no-op since Application already
	// knows about the subscription.
	// In order to test publish works after subscription is added, we actually need to inject a
	// fake subscription into the Application hub
	fakeConn := &TestConn{"test", "test", []Channel{"channel"}}
	e.app.clients.addSub(ChannelID("channel"), fakeConn)

	// Now we've subscribed...
	err = e.publish(ChannelID("channel"), []byte("{}"), nil)
	assert.Equal(t, nil, err)

	assert.Equal(t, nil, e.unsubscribe(ChannelID("channel")))

	// Same dance to manually remove sub from app hub
	e.app.clients.removeSub(ChannelID("channel"), fakeConn)

	assert.Equal(t, nil, e.addPresence(ChannelID("channel"), "uid", ClientInfo{}))
	p, err := e.presence(ChannelID("channel"))
	assert.Equal(t, nil, err)
	assert.Equal(t, 1, len(p))
	err = e.removePresence(ChannelID("channel"), "uid")
	assert.Equal(t, nil, err)

	msg := Message{UID: MessageID("test UID")}
	msgJSON, _ := json.Marshal(msg)

	// test adding history
	assert.Equal(t, nil, e.publish(ChannelID("channel"), msgJSON, &publishOpts{msg, 4, 1, false}))
	h, err := e.history(ChannelID("channel"), historyOpts{})
	assert.Equal(t, nil, err)
	assert.Equal(t, 1, len(h))
	assert.Equal(t, h[0].UID, MessageID("test UID"))

	// test history limit
	assert.Equal(t, nil, e.publish(ChannelID("channel"), msgJSON, &publishOpts{msg, 4, 1, false}))
	assert.Equal(t, nil, e.publish(ChannelID("channel"), msgJSON, &publishOpts{msg, 4, 1, false}))
	assert.Equal(t, nil, e.publish(ChannelID("channel"), msgJSON, &publishOpts{msg, 4, 1, false}))
	h, err = e.history(ChannelID("channel"), historyOpts{Limit: 2})
	assert.Equal(t, nil, err)
	assert.Equal(t, 2, len(h))

	// test history limit greater than history size
	assert.Equal(t, nil, e.publish(ChannelID("channel"), msgJSON, &publishOpts{msg, 1, 1, false}))
	assert.Equal(t, nil, e.publish(ChannelID("channel"), msgJSON, &publishOpts{msg, 1, 1, false}))
	assert.Equal(t, nil, e.publish(ChannelID("channel"), msgJSON, &publishOpts{msg, 1, 1, false}))
	h, err = e.history(ChannelID("channel"), historyOpts{Limit: 2})

	// HistoryDropInactive tests - new channel to avoid conflicts with test above
	// 1. add history with DropInactive = true should be a no-op if history is empty
	assert.Equal(t, nil, e.publish(ChannelID("channel-2"), msgJSON, &publishOpts{msg, 2, 5, true}))
	h, err = e.history(ChannelID("channel-2"), historyOpts{})
	assert.Equal(t, nil, err)
	assert.Equal(t, 0, len(h))

	// 2. add history with DropInactive = false should always work
	assert.Equal(t, nil, e.publish(ChannelID("channel-2"), msgJSON, &publishOpts{msg, 2, 5, false}))
	h, err = e.history(ChannelID("channel-2"), historyOpts{})
	assert.Equal(t, nil, err)
	assert.Equal(t, 1, len(h))

	// 3. add with DropInactive = true should work immediately since there should be something in history
	// for 5 seconds from above
	assert.Equal(t, nil, e.publish(ChannelID("channel-2"), msgJSON, &publishOpts{msg, 2, 5, true}))
	h, err = e.history(ChannelID("channel-2"), historyOpts{})
	assert.Equal(t, nil, err)
	assert.Equal(t, 2, len(h))
}
Example #14
0
func TestSetLogFile(t *testing.T) {
	err := SetLogFile("/tmp/testing")
	assert.Equal(t, nil, err)
	err = SetLogFile("/i_want_it_to_not_exist_so_error_return/testing")
	assert.NotEqual(t, nil, err)
}
Example #15
0
func TestMediator(t *testing.T) {
	app := testApp()
	m := &testMediator{}
	app.SetMediator(m)
	assert.NotEqual(t, nil, app.mediator)
}
Example #16
0
func TestSubscribeRecover(t *testing.T) {
	app := testMemoryApp()
	app.config.Recover = true
	app.config.HistoryLifetime = 30
	app.config.HistorySize = 5

	c, err := newClient(app, &testSession{})
	assert.Equal(t, nil, err)

	timestamp := strconv.FormatInt(time.Now().Unix(), 10)
	cmds := []clientCommand{testConnectCmd(timestamp), testSubscribeCmd("test")}
	err = c.handleCommands(cmds)
	assert.Equal(t, nil, err)

	data, _ := json.Marshal(map[string]string{"input": "test"})
	err = app.Publish(Channel("test"), data, ConnID(""), nil)
	assert.Equal(t, nil, err)
	assert.Equal(t, int64(1), app.metrics.numMsgPublished.Count())

	messages, _ := app.History(Channel("test"))
	assert.Equal(t, 1, len(messages))
	message := messages[0]
	last := message.UID

	// test setting last message uid when no uid provided
	c, _ = newClient(app, &testSession{})
	cmds = []clientCommand{testConnectCmd(timestamp)}
	err = c.handleCommands(cmds)
	assert.Equal(t, nil, err)
	subscribeCmd := testSubscribeCmd("test")
	resp, err := c.handleCmd(subscribeCmd)
	assert.Equal(t, nil, err)
	assert.Equal(t, last, resp.Body.(*SubscribeBody).Last)

	// publish 2 messages since last
	data, _ = json.Marshal(map[string]string{"input": "test1"})
	err = app.Publish(Channel("test"), data, ConnID(""), nil)
	assert.Equal(t, nil, err)
	data, _ = json.Marshal(map[string]string{"input": "test2"})
	err = app.Publish(Channel("test"), data, ConnID(""), nil)
	assert.Equal(t, nil, err)

	assert.Equal(t, int64(3), app.metrics.numMsgPublished.Count())

	// test no messages recovered when recover is false in subscribe cmd
	c, _ = newClient(app, &testSession{})
	cmds = []clientCommand{testConnectCmd(timestamp)}
	err = c.handleCommands(cmds)
	assert.Equal(t, nil, err)
	subscribeLastCmd := testSubscribeRecoverCmd("test", last, false)
	resp, err = c.handleCmd(subscribeLastCmd)
	assert.Equal(t, nil, err)
	assert.Equal(t, 0, len(resp.Body.(*SubscribeBody).Messages))
	assert.NotEqual(t, last, resp.Body.(*SubscribeBody).Last)

	// test normal recover
	c, _ = newClient(app, &testSession{})
	cmds = []clientCommand{testConnectCmd(timestamp)}
	err = c.handleCommands(cmds)
	assert.Equal(t, nil, err)
	subscribeLastCmd = testSubscribeRecoverCmd("test", last, true)
	resp, err = c.handleCmd(subscribeLastCmd)
	assert.Equal(t, nil, err)
	assert.Equal(t, 2, len(resp.Body.(*SubscribeBody).Messages))
	assert.Equal(t, true, resp.Body.(*SubscribeBody).Recovered)
	assert.Equal(t, MessageID(""), resp.Body.(*SubscribeBody).Last)
	messages = resp.Body.(*SubscribeBody).Messages
	m0, _ := messages[0].Data.MarshalJSON()
	m1, _ := messages[1].Data.MarshalJSON()
	// in reversed order in history
	assert.Equal(t, strings.Contains(string(m0), "test2"), true)
	assert.Equal(t, strings.Contains(string(m1), "test1"), true)

	// test part recover - when Centrifugo can not recover all missed messages
	for i := 0; i < 10; i++ {
		data, _ = json.Marshal(map[string]string{"input": "test1"})
		err = app.Publish(Channel("test"), data, ConnID(""), nil)
		assert.Equal(t, nil, err)
	}
	c, _ = newClient(app, &testSession{})
	cmds = []clientCommand{testConnectCmd(timestamp)}
	err = c.handleCommands(cmds)
	assert.Equal(t, nil, err)
	subscribeLastCmd = testSubscribeRecoverCmd("test", last, true)
	resp, err = c.handleCmd(subscribeLastCmd)
	assert.Equal(t, nil, err)
	assert.Equal(t, 5, len(resp.Body.(*SubscribeBody).Messages))
	assert.Equal(t, false, resp.Body.(*SubscribeBody).Recovered)
}
Example #17
0
func TestDefaultPost(t *testing.T) {
	assert.NotEqual(t, "NYC", Get("state"))
	SetDefault("state", "NYC")
	assert.Equal(t, "NYC", Get("state"))
}