示例#1
0
// TestServerTime calls the GetTime method of the messaging to test the time
func TestServerTime(t *testing.T) {
	stop, _ := NewVCRNonSubscribe("fixtures/time", []string{})
	defer stop()

	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "", false, "testTime")

	assert := assert.New(t)
	successChannel := make(chan []byte)
	errorChannel := make(chan []byte)

	go pubnubInstance.GetTime(successChannel, errorChannel)
	select {
	case value := <-successChannel:
		response := string(value)
		timestamp, err := strconv.Atoi(strings.Trim(response, "[]\n"))
		if err != nil {
			assert.Fail(err.Error())
		}

		assert.NotZero(timestamp)
	case err := <-errorChannel:
		assert.Fail(string(err))
	case <-timeouts(10):
		assert.Fail("Getting server timestamp timeout")
	}
}
示例#2
0
func TestSubscribeGrantPositive(t *testing.T) {
	pubnubInstance := messaging.NewPubnub(PamPubKey, PamSubKey, PamSecKey, "", false, "")
	channel := "testChannelSubscribeGrantPositive"
	ttl := 1
	message := fmt.Sprintf(`{"status":200,"service":"Access Manager","message":"Success","payload":{"channels":{"%s":{"r":1,"m":0,"w":1}},"subscribe_key":"%s","ttl":%d,"level":"channel"}}`, channel, PamSubKey, ttl)
	message2 := fmt.Sprintf(`{"status":200,"service":"Access Manager","message":"Success","payload":{"channels":{"%s":{"r":0,"m":0,"w":0}},"subscribe_key":"%s","ttl":%d,"level":"channel"}}`, channel, PamSubKey, ttl)

	time.Sleep(time.Duration(5) * time.Second)

	returnPamChannel := make(chan []byte)
	errorChannel := make(chan []byte)
	responseChannel := make(chan string)
	waitChannel := make(chan string)

	go pubnubInstance.GrantSubscribe(channel, true, true, ttl, returnPamChannel, errorChannel)
	go ParsePamResponse(returnPamChannel, pubnubInstance, message, channel, "SubscribeGrantPositiveGrant", responseChannel)
	go ParseErrorResponse(errorChannel, responseChannel)
	go WaitForCompletion(responseChannel, waitChannel)
	ParseWaitResponse(waitChannel, t, "SubscribeGrantPositiveGrant")

	returnPamChannel2 := make(chan []byte)
	errorChannel2 := make(chan []byte)
	responseChannel2 := make(chan string)
	waitChannel2 := make(chan string)

	go pubnubInstance.GrantSubscribe(channel, false, false, -1, returnPamChannel2, errorChannel2)
	go ParsePamResponse(returnPamChannel2, pubnubInstance, message2, channel, "SubscribeGrantPositiveRevoke", responseChannel2)
	go ParseErrorResponse(errorChannel2, responseChannel2)
	go WaitForCompletion(responseChannel2, waitChannel2)
	ParseWaitResponse(waitChannel2, t, "SubscribeGrantPositiveRevoke")

}
示例#3
0
// ResumeOnReconnect contains the actual impementation of both TestResumeOnReconnectFalse and TestResumeOnReconnectTrue
// the parameter b determines of resume on reconnect setting is true or false.
//
// The test contains a data race
func ResumeOnReconnect(t *testing.T, b bool) {
	testName := "ResumeOnReconnectFalse"
	if b {
		messaging.SetResumeOnReconnect(true)
		testName = "ResumeOnReconnectTrue"
	} else {
		messaging.SetResumeOnReconnect(false)
	}
	r := GenRandom()
	pubnubChannel := fmt.Sprintf("testChannel_subror_%d", r.Intn(20))

	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "", false, "")
	returnSubscribeChannel := make(chan []byte)
	errorChannelSub := make(chan []byte)
	responseChannelSub := make(chan string)
	waitChannelSub := make(chan string)

	messaging.SetSubscribeTimeout(12)
	go pubnubInstance.Subscribe(pubnubChannel, "", returnSubscribeChannel, false, errorChannelSub)
	go ParseSubscribeForTimetoken(pubnubInstance, pubnubChannel, returnSubscribeChannel, errorChannelSub, testName, responseChannelSub)
	go WaitForCompletion(responseChannelSub, waitChannelSub)
	ParseWaitResponse(waitChannelSub, t, testName)
	messaging.SetSubscribeTimeout(310)
	go pubnubInstance.Unsubscribe(pubnubChannel, returnSubscribeChannel, errorChannelSub)
	pubnubInstance.CloseExistingConnection()
}
示例#4
0
文件: main.go 项目: pubnub/go
func handler(w http.ResponseWriter, r *http.Request) {
	log.Print("Info: IN handler")
	uuid := ""
	pubInstance := messaging.NewPubnub(publishKey, subscribeKey, secretKey, "", true, uuid)
	if pubInstance == nil {
		log.Print("Error: Couldn't create pubnub instance")
		http.Error(w, "Couldn't create pubnub instance", http.StatusInternalServerError)
		return
	}
	nuuid := pubInstance.GetUUID()
	log.Print("UUID: %s", nuuid)
	tok := "s"

	err1 := mainTemplate.Execute(w, map[string]string{
		"token":        tok,
		"uuid":         nuuid,
		"subscribeKey": subscribeKey,
		"publishKey":   publishKey,
		"secretKey":    secretKey,
		"hostname":     fmt.Sprintf("%s%s", hostname, port),
	})
	if err1 != nil {
		log.Print("Error: mainTemplate: %v", err1)
	}
}
示例#5
0
func NewPubNubClient(cs *ClientSettings) *PubNubClient {
	pub := messaging.NewPubnub(cs.PublishKey, cs.SubscribeKey, cs.SecretKey, cs.Cipher, cs.SSL, cs.ID)
	return &PubNubClient{
		pub:      pub,
		channels: make(map[string]*Channel),
	}
}
示例#6
0
// SendMultiplexingRequest is the common method to test TestMultiplexing,
// TestMultiplexingSSL, TestEncryptedMultiplexing, TestEncryptedMultiplexingWithSSL.
//
// It subscribes to 2 channels in the same request and then calls the ParseSubscribeMultiplexedResponse
// for further processing.
//
// Parameters:
// t: *testing.T instance.
// testName: testname for display.
// ssl: ssl setting.
// encrypted: encryption setting.
func SendMultiplexingRequest(t *testing.T, testName string, ssl bool, encrypted bool) {
	cipher := ""
	if encrypted {
		cipher = "enigma"
	}
	message1 := "message1"
	message2 := "message2"
	r := GenRandom()

	pubnubChannel1 := fmt.Sprintf("testChannel_sub_%d", r.Intn(20))
	pubnubChannel2 := fmt.Sprintf("testChannel_sub_%d", r.Intn(20))

	pubnubChannel := pubnubChannel1 + "," + pubnubChannel2

	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", cipher, ssl, "")
	returnSubscribeChannel := make(chan []byte)
	errorChannelSub := make(chan []byte)
	responseChannelSub := make(chan string)
	waitChannelSub := make(chan string)

	go pubnubInstance.Subscribe(pubnubChannel, "", returnSubscribeChannel, false, errorChannelSub)
	go ParseSubscribeMultiplexedResponse(pubnubInstance, returnSubscribeChannel, message1, message2, pubnubChannel1, pubnubChannel2, testName, responseChannelSub)
	//go ParseErrorResponse(errorChannelSub, responseChannelSub)
	go ParseResponseDummyMessage(errorChannelSub, "aborted", responseChannelSub)
	go WaitForCompletion(responseChannelSub, waitChannelSub)
	ParseWaitResponse(waitChannelSub, t, testName)
	go pubnubInstance.Unsubscribe(pubnubChannel, returnSubscribeChannel, errorChannelSub)
	pubnubInstance.CloseExistingConnection()
}
示例#7
0
// TestSubscriptionConnectStatus sends out a subscribe request to a pubnub channel
// and validates the response for the connect status.
func TestSubscriptionConnectStatus(t *testing.T) {
	assert := assert.New(t)

	stop, _ := NewVCRBoth(
		"fixtures/subscribe/connectStatus", []string{"uuid"})
	defer stop()

	channel := "Channel_ConnectStatus"
	uuid := "UUID_ConnectStatus"
	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "", false, uuid)

	successChannel := make(chan []byte)
	errorChannel := make(chan []byte)
	unsubscribeSuccessChannel := make(chan []byte)
	unsubscribeErrorChannel := make(chan []byte)

	go pubnubInstance.Subscribe(channel, "", successChannel, false, errorChannel)
	select {
	case resp := <-successChannel:
		response := fmt.Sprintf("%s", resp)
		if response != "[]" {
			message := "'" + channel + "' connected"
			assert.Contains(response, message)
		}
	case err := <-errorChannel:
		if !IsConnectionRefusedError(err) {
			assert.Fail(string(err))
		}
	case <-timeouts(3):
		assert.Fail("Subscribe timeout 3s")
	}

	go pubnubInstance.Unsubscribe(channel, unsubscribeSuccessChannel, unsubscribeErrorChannel)
	ExpectUnsubscribedEvent(t, channel, "", unsubscribeSuccessChannel, unsubscribeErrorChannel)
}
示例#8
0
// DetailedHistoryFor10Messages is a common method used by both TestDetailedHistoryFor10EncryptedMessages
// and TestDetailedHistoryFor10Messages to publish's 10 messages to a pubnub channel, and after that
// call the history method of the messaging package to fetch last 10 messages. These received
// messages are compared to the messages sent and if all match test is successful.
func DetailedHistoryFor10Messages(t *testing.T, cipherKey string, testName string) {
	numberOfMessages := 10
	startMessagesFrom := 0
	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, SecKey, cipherKey, false, "")

	message := "Test Message "
	r := GenRandom()
	channel := fmt.Sprintf("testChannel_dh_%d", r.Intn(20))

	messagesSent := PublishMessages(pubnubInstance, channel, t, startMessagesFrom, numberOfMessages, message)
	if messagesSent {
		returnHistoryChannel := make(chan []byte)
		errorChannel := make(chan []byte)
		responseChannel := make(chan string)
		waitChannel := make(chan string)

		go pubnubInstance.History(channel, numberOfMessages, 0, 0, false, returnHistoryChannel, errorChannel)
		go ParseHistoryResponseForMultipleMessages(returnHistoryChannel, channel, message, testName, startMessagesFrom, numberOfMessages, cipherKey, responseChannel)
		go ParseErrorResponse(errorChannel, responseChannel)
		go WaitForCompletion(responseChannel, waitChannel)
		ParseWaitResponse(waitChannel, t, testName)
	} else {
		t.Error("Test '" + testName + "': failed.")
	}
}
示例#9
0
// TestSuccessCodeAndInfoForComplexMessage sends out a complex message to the pubnub channel
func TestSuccessCodeAndInfoForComplexMessage(t *testing.T) {
	assert := assert.New(t)

	stop, _ := NewVCRNonSubscribe(
		"fixtures/publish/successCodeAndInfoForComplexMessage", []string{"uuid"})
	defer stop()

	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "", false, "")
	channel := "successCodeAndInfoForComplexMessage"

	customStruct := CustomStruct{
		Foo: "hi!",
		Bar: []int{1, 2, 3, 4, 5},
	}

	successChannel := make(chan []byte)
	errorChannel := make(chan []byte)

	go pubnubInstance.Publish(channel, customStruct, successChannel, errorChannel)
	select {
	case msg := <-successChannel:
		assert.Contains(string(msg), "1,")
		assert.Contains(string(msg), "\"Sent\",")
	case err := <-errorChannel:
		assert.Fail(string(err))
	case <-timeout():
		assert.Fail("Publish timeout")
	}
}
示例#10
0
// TestSuccessCodeAndInfoWithEncryption sends out an encrypted
// message to the pubnub channel
func TestSuccessCodeAndInfoWithEncryption(t *testing.T) {
	assert := assert.New(t)

	stop, _ := NewVCRNonSubscribe(
		"fixtures/publish/successCodeAndInfoWithEncryption", []string{"uuid"})
	defer stop()

	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "enigma", false, "")
	channel := "successCodeAndInfo"
	message := "Pubnub API Usage Example"

	successChannel := make(chan []byte)
	errorChannel := make(chan []byte)

	go pubnubInstance.Publish(channel, message, successChannel, errorChannel)
	select {
	case msg := <-successChannel:
		assert.Contains(string(msg), "1,")
		assert.Contains(string(msg), "\"Sent\",")
	case err := <-errorChannel:
		assert.Fail(string(err))
	case <-timeout():
		assert.Fail("Publish timeout")
	}
}
func TestWildcardSubscriptionConnectedAndUnsubscribedSingle(t *testing.T) {
	assert := assert.New(t)

	stop, _ := NewVCRBoth("fixtures/wildcard/connAndUns", []string{"uuid"})
	defer stop()

	major := "Channel_ConnAndUns"
	wildcard := fmt.Sprintf("%s.*", major)
	uuid := "UUID_ConnAndUns"
	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "", false, uuid)

	subscribeSuccessChannel := make(chan []byte)
	subscribeErrorChannel := make(chan []byte)
	successChannel := make(chan []byte)
	errorChannel := make(chan []byte)

	go pubnubInstance.Subscribe(wildcard, "",
		subscribeSuccessChannel, false, subscribeErrorChannel)
	select {
	case msg := <-subscribeSuccessChannel:
		val := string(msg)
		assert.Equal(fmt.Sprintf(
			"[1, \"Subscription to channel '%s' connected\", \"%s\"]",
			wildcard, wildcard), val)
	case err := <-subscribeErrorChannel:
		assert.Fail(string(err))
	}

	go pubnubInstance.Unsubscribe(wildcard, successChannel, errorChannel)
	ExpectUnsubscribedEvent(t, wildcard, "", successChannel, errorChannel)

	// pubnubInstance.CloseExistingConnection()
}
示例#12
0
func TestGroupSubscriptionToNotExistingChannelGroup(t *testing.T) {
	assert := assert.New(t)

	stop, sleep := NewVCRBoth(
		"fixtures/groups/notExistingCG", []string{"uuid"})
	defer stop()

	group := "Group_NotExistingCG"
	uuid := "UUID_NotExistingCG"
	pubnub := messaging.NewPubnub(PubKey, SubKey, "", "", false, uuid)

	successChannel := make(chan []byte)
	errorChannel := make(chan []byte)
	unsubscribeSuccessChannel := make(chan []byte)
	unsubscribeErrorChannel := make(chan []byte)

	removeChannelGroups(pubnub, []string{group})

	sleep(2)

	go pubnub.ChannelGroupSubscribe(group, successChannel, errorChannel)
	select {
	case response := <-successChannel:
		assert.Fail("Received success message while expecting error", string(response))
	case err := <-errorChannel:
		assert.Contains(string(err), "Channel group or groups result in empty subscription set")
		assert.Contains(string(err), group)
	}

	go pubnub.ChannelGroupUnsubscribe(group, unsubscribeSuccessChannel, unsubscribeErrorChannel)
	ExpectUnsubscribedEvent(t, "", group, unsubscribeSuccessChannel,
		unsubscribeErrorChannel)
}
示例#13
0
func TestGroupSubscriptionNotSubscribed(t *testing.T) {
	assert := assert.New(t)

	stop, sleep := NewVCRNonSubscribe(
		"fixtures/groups/notSubscribed", []string{"uuid"})
	defer stop()

	group := "Group_NotSubscribed"
	uuid := "UUID_NotSubscribed"
	pubnub := messaging.NewPubnub(PubKey, SubKey, "", "", false, uuid)

	createChannelGroups(pubnub, []string{group})
	defer removeChannelGroups(pubnub, []string{group})

	sleep(2)

	successChannel := make(chan []byte)
	errorChannel := make(chan []byte)

	go pubnub.ChannelGroupUnsubscribe(group, successChannel, errorChannel)
	select {
	case response := <-successChannel:
		assert.Fail("Received success message while expecting error", string(response))
	case err := <-errorChannel:
		assert.Contains(string(err), "Subscription to channel group")
		assert.Contains(string(err), "not subscribed")
	}

	pubnub.CloseExistingConnection()
}
示例#14
0
func SetUpChannelGroup() {
	errorChannel := make(chan []byte)
	successChannel := make(chan []byte)
	done := make(chan bool)

	pubnub := messaging.NewPubnub(config.Keys.Pub, config.Keys.Sub, "", "",
		false, "")

	pubnub.SetAuthenticationKey(bootstrapAuth)

	// Remove Group
	go pubnub.ChannelGroupRemoveGroup(config.StocksChannelGroup,
		successChannel, errorChannel)
	go handleResponse(successChannel, errorChannel,
		messaging.GetNonSubscribeTimeout(), done)

	<-done

	// Create it from the scratch
	go pubnub.ChannelGroupAddChannel(config.StocksChannelGroup, stockNames,
		successChannel, errorChannel)
	go handleResponse(successChannel, errorChannel,
		messaging.GetNonSubscribeTimeout(), done)

	<-done
}
示例#15
0
文件: main.go 项目: pubnub/go
func grantSubscribe(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	ch := q.Get("ch")
	read := q.Get("r")
	write := q.Get("w")
	ttl := q.Get("ttl")
	bRead := false
	if read == "1" {
		bRead = true
	}
	bWrite := false
	if write == "1" {
		bWrite = true
	}
	iTTL := 1440
	if ival, err := strconv.Atoi(ttl); err == nil {
		iTTL = ival
	}

	uuid := q.Get("uuid")
	pubInstance := messaging.NewPubnub(publishKey, subscribeKey, secretKey, "", true, uuid)
	errorChannel := make(chan []byte)
	successChannel := make(chan []byte)
	go pubInstance.GrantSubscribe(ch, bRead, bWrite, iTTL, "", successChannel, errorChannel)
	handleResult(w, r, uuid, successChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Revoke Subscribe")
}
示例#16
0
// TestUnsubscribe will subscribe to a pubnub channel and then send an unsubscribe request
// The response should contain 'unsubscribed'
func TestUnsubscribeChannel(t *testing.T) {
	assert := assert.New(t)

	stop, sleep := NewVCRBoth(
		"fixtures/unsubscribe/channel", []string{"uuid"})
	defer stop()

	channel := "Channel_UnsubscribeChannel"
	uuid := "UUID_UnsubscribeChannel"
	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "", false, uuid)

	subscribeSuccessChannel := make(chan []byte)
	subscribeErrorChannel := make(chan []byte)
	unSubscribeSuccessChannel := make(chan []byte)
	unSubscribeErrorChannel := make(chan []byte)

	go pubnubInstance.Subscribe(channel, "", subscribeSuccessChannel,
		false, subscribeErrorChannel)
	select {
	case msg := <-subscribeSuccessChannel:
		val := string(msg)
		assert.Equal(val, fmt.Sprintf(
			"[1, \"Subscription to channel '%s' connected\", \"%s\"]",
			channel, channel))
	case err := <-subscribeErrorChannel:
		assert.Fail(string(err))
	}

	sleep(2)

	go pubnubInstance.Unsubscribe(channel, unSubscribeSuccessChannel,
		unSubscribeErrorChannel)
	select {
	case msg := <-unSubscribeSuccessChannel:
		val := string(msg)
		assert.Equal(val, fmt.Sprintf(
			"[1, \"Subscription to channel '%s' unsubscribed\", \"%s\"]",
			channel, channel))
	case err := <-unSubscribeErrorChannel:
		assert.Fail(string(err))
	}

	select {
	case ev := <-unSubscribeSuccessChannel:
		var event messaging.PresenceResonse

		err := json.Unmarshal(ev, &event)
		if err != nil {
			assert.Fail(err.Error())
		}

		assert.Equal("leave", event.Action)
		assert.Equal(200, event.Status)
	case err := <-unSubscribeErrorChannel:
		assert.Fail(string(err))
	}

	// pubnubInstance.CloseExistingConnection()
}
示例#17
0
func TestSetUserStateGlobalHereNow(t *testing.T) {
	assert := assert.New(t)

	stop, sleep := NewVCRBoth(
		"fixtures/presence/setUserStateGlobalHereNow", []string{"uuid"})
	defer stop()

	channel := "Channel_SetUserStateGlobalHereNow"
	uuid := "UUID_SetUserStateGlobalHereNow"
	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, SecKey, "", false, uuid)

	key := "testkey"
	val := "testval"

	successChannel := make(chan []byte)
	errorChannel := make(chan []byte)
	successSet := make(chan []byte)
	errorSet := make(chan []byte)
	successGet := make(chan []byte)
	errorGet := make(chan []byte)
	unsubscribeSuccessChannel := make(chan []byte)
	unsubscribeErrorChannel := make(chan []byte)

	go pubnubInstance.Subscribe(channel, "", successChannel, false, errorChannel)
	ExpectConnectedEvent(t, channel, "", successChannel, errorChannel)

	go pubnubInstance.SetUserStateKeyVal(channel, key, val, successSet, errorSet)
	select {
	case value := <-successSet:
		actual := string(value)
		expectedSubstring := fmt.Sprintf("{\"%s\": \"%s\"}", key, val)

		assert.Contains(actual, expectedSubstring)
	case err := <-errorSet:
		assert.Fail("Failed to set state", string(err))
	case <-messaging.Timeout():
		assert.Fail("Set state timeout")
	}

	sleep(PresenceServerTimeoutLower)

	go pubnubInstance.GlobalHereNow(true, true, successGet, errorGet)
	select {
	case value := <-successGet:
		actual := string(value)
		expectedSubstring := fmt.Sprintf("{\"%s\": \"%s\"}", key, val)

		assert.Contains(actual, expectedSubstring)
		assert.Contains(actual, pubnubInstance.GetUUID())
	case err := <-errorSet:
		assert.Fail("Failed to get state", string(err))
	case <-messaging.Timeout():
		assert.Fail("Get state timeout")
	}

	go pubnubInstance.Unsubscribe(channel, unsubscribeSuccessChannel, unsubscribeErrorChannel)
	ExpectUnsubscribedEvent(t, channel, "", unsubscribeSuccessChannel, unsubscribeErrorChannel)
}
示例#18
0
文件: main.go 项目: pubnub/go
func setAuthKey(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	authKey := q.Get("authkey")
	uuid := q.Get("uuid")

	pubInstance := messaging.NewPubnub(publishKey, subscribeKey, secretKey, "", true, uuid)
	pubInstance.SetAuthenticationKey(authKey)
	sendResponseToChannel(w, "Auth key set", r, uuid)
}
示例#19
0
文件: main.go 项目: pubnub/go
func revokeSubscribe(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	ch := q.Get("ch")
	uuid := q.Get("uuid")
	pubInstance := messaging.NewPubnub(publishKey, subscribeKey, secretKey, "", true, uuid)
	errorChannel := make(chan []byte)
	successChannel := make(chan []byte)
	go pubInstance.GrantSubscribe(ch, false, false, 0, "", successChannel, errorChannel)
	handleResult(w, r, uuid, successChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Revoke Subscribe")
}
示例#20
0
文件: main.go 项目: pubnub/go
func subscribe(w http.ResponseWriter, r *http.Request) {
	var errorChannel = make(chan []byte)
	var subscribeChannel = make(chan []byte)
	messaging.LoggingEnabled(true)
	messaging.SetLogOutput(os.Stdout)
	pubInstance := messaging.NewPubnub(publishKey, subscribeKey, secretKey, "", true, "")

	go pubInstance.Subscribe("test2", "", subscribeChannel, false, errorChannel)
	go handleSubscribeResult(subscribeChannel, errorChannel, "Subscribe")
}
示例#21
0
// TestCustomUuid subscribes to a pubnub channel using a custom uuid and then
// makes a call to the herenow method of the pubnub api. The custom id should
// be present in the response else the test fails.
func TestCustomUuid(t *testing.T) {
	assert := assert.New(t)

	stop, sleep := NewVCRBoth(
		"fixtures/presence/customUuid", []string{"uuid"})
	defer stop()

	uuid := "customuuid"
	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "", false, uuid)
	channel := "customUuid"

	successChannel := make(chan []byte)
	errorChannel := make(chan []byte)
	unsubscribeSuccessChannel := make(chan []byte)
	unsubscribeErrorChannel := make(chan []byte)
	successGet := make(chan []byte)
	errorGet := make(chan []byte)

	go pubnubInstance.Subscribe(channel, "", successChannel, false, errorChannel)
	ExpectConnectedEvent(t, channel, "", successChannel, errorChannel)

	sleep(PresenceServerTimeoutHighter)

	go pubnubInstance.HereNow(channel, "", true, true, successGet, errorGet)
	select {
	case value := <-successGet:
		assert.Contains(string(value), uuid)
		var occupants struct {
			Uuids     []map[string]string
			Occupancy int
		}

		err := json.Unmarshal(value, &occupants)
		if err != nil {
			assert.Fail(err.Error())
		}

		found := false
		for _, v := range occupants.Uuids {
			if v["uuid"] == uuid {
				found = true
			}
		}

		assert.True(found)
	case err := <-errorGet:
		assert.Fail("Failed to get online users", string(err))
	case <-messaging.Timeout():
		assert.Fail("HereNow timeout")
	}

	go pubnubInstance.Unsubscribe(channel, unsubscribeSuccessChannel, unsubscribeErrorChannel)
	ExpectUnsubscribedEvent(t, channel, "", unsubscribeSuccessChannel, unsubscribeErrorChannel)
}
示例#22
0
文件: main.go 项目: pubnub/go
func getTime(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	uuid := q.Get("uuid")

	errorChannel := make(chan []byte)
	successChannel := make(chan []byte)

	pubInstance := messaging.NewPubnub(publishKey, subscribeKey, secretKey, "", true, uuid)
	go pubInstance.GetTime(successChannel, errorChannel)
	handleResult(w, r, uuid, successChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Time")
}
示例#23
0
func GrantPermissions() {
	errorChannel := make(chan []byte)
	successChannel := make(chan []byte)

	done := make(chan bool)

	pubnub := messaging.NewPubnub(config.Keys.Pub, config.Keys.Sub,
		config.Keys.Secret, "", false, "")

	pubnub.SetAuthenticationKey(bootstrapAuth)

	// Allow current Pubnub instance to managet the channel group
	go pubnub.GrantChannelGroup(config.StocksChannelGroup,
		false, true, config.GrantTTL,
		bootstrapAuth, successChannel, errorChannel)
	go handleResponse(successChannel, errorChannel,
		messaging.GetNonSubscribeTimeout(), done)

	<-done

	// Allow unauthorized users to subscribe to stockblast channel group
	go pubnub.GrantChannelGroup(config.StocksChannelGroup,
		true, false, config.GrantTTL,
		"", successChannel, errorChannel)
	go handleResponse(successChannel, errorChannel,
		messaging.GetNonSubscribeTimeout(), done)

	<-done

	// Unauthorized users can both read and write on chat channel
	go pubnub.GrantSubscribe(config.ChatChannel, true, true, config.GrantTTL, "",
		successChannel, errorChannel)
	go handleResponse(successChannel, errorChannel,
		messaging.GetNonSubscribeTimeout(), done)

	<-done

	// Unauthorized users can only read history
	go pubnub.GrantSubscribe(config.HistoryChannel,
		true, false, config.GrantTTL, "", successChannel, errorChannel)
	go handleResponse(successChannel, errorChannel,
		messaging.GetNonSubscribeTimeout(), done)

	<-done

	// Allow stock tickers authorized by auths.Auth key to publish to stock
	// channels
	go pubnub.GrantSubscribe(stockNames, false, true, config.GrantTTL,
		config.Keys.Auth, successChannel, errorChannel)
	go handleResponse(successChannel, errorChannel,
		messaging.GetNonSubscribeTimeout(), done)

	<-done
}
示例#24
0
文件: main.go 项目: pubnub/go
func setUserStateJSON(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	ch := q.Get("ch")
	j := q.Get("j")
	uuid := q.Get("uuid")
	pubInstance := messaging.NewPubnub(publishKey, subscribeKey, secretKey, "", true, uuid)
	errorChannel := make(chan []byte)
	successChannel := make(chan []byte)

	go pubInstance.SetUserStateJSON(ch, j, successChannel, errorChannel)
	handleResult(w, r, uuid, successChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Set User State JSON")
}
示例#25
0
// DetailedHistoryFor10Messages is a common method used by both TestDetailedHistoryFor10EncryptedMessages
// and TestDetailedHistoryFor10Messages to publish's 10 messages to a pubnub channel, and after that
// call the history method of the messaging package to fetch last 10 messages. These received
// messages are compared to the messages sent and if all match test is successful.
func DetailedHistoryFor10Messages(t *testing.T, cipherKey string, testName string) {
	assert := assert.New(t)

	numberOfMessages := 10
	startMessagesFrom := 0

	stop, sleep := NewVCRNonSubscribe(fmt.Sprintf("fixtures/history/%s", testName),
		[]string{"uuid"})
	defer stop()

	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", cipherKey, false, "")

	message := "Test Message "
	channel := testName

	messagesSent := PublishMessages(pubnubInstance, channel, t, startMessagesFrom,
		numberOfMessages, message, sleep)

	assert.True(messagesSent)

	successChannel := make(chan []byte)
	errorChannel := make(chan []byte)

	go pubnubInstance.History(channel, numberOfMessages, 0, 0, false, false,
		successChannel, errorChannel)
	select {
	case value := <-successChannel:
		data, _, _, err := pubnubInstance.ParseJSON(value, cipherKey)
		if err != nil {
			assert.Fail(err.Error())
		}

		var arr []string
		err = json.Unmarshal([]byte(data), &arr)
		if err != nil {
			assert.Fail(err.Error())
		}

		messagesReceived := 0

		assert.Len(arr, numberOfMessages)

		for i := 0; i < len(arr); i++ {
			if arr[i] == message+strconv.Itoa(startMessagesFrom+i) {
				messagesReceived++
			}
		}

		assert.Equal(numberOfMessages, messagesReceived)
	case err := <-errorChannel:
		assert.Fail(string(err))
	}
}
示例#26
0
// TestSetGetUserState subscribes to a pubnub channel and then
// makes a call to the herenow method of the pubnub api. The occupancy should
// be greater than one.
func TestSetGetUserState(t *testing.T) {
	cipherKey := ""
	testName := "SetGetUserState"

	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, SecKey, cipherKey, false, "")

	r := GenRandom()
	channel := fmt.Sprintf("testChannel_us_%d", r.Intn(100))
	key := "testkey"
	val := "testval"
	CommonUserState(pubnubInstance, t, channel, key, val, testName)
}
示例#27
0
// TestPublishWithReplicate sends out a complex message to the pubnub channel
func TestPublishWithReplicate(t *testing.T) {
	assert := assert.New(t)

	stop, _ := NewVCRNonSubscribe(
		"fixtures/publish/publishWithReplicate", []string{"uuid"})
	defer stop()
	//messaging.SetLogOutput(os.Stdout)
	//messaging.LoggingEnabled(true)

	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "", false, "")
	channel := "publishWithReplicate"

	message := "publishWithReplicate"
	await := make(chan bool)

	successChannel := make(chan []byte)
	errorChannel := make(chan []byte)

	go pubnubInstance.PublishExtendedWithMetaAndReplicate(channel, message, nil, true, false, false, successChannel, errorChannel)
	go func() {
		select {
		case msg := <-successChannel:
			assert.Contains(string(msg), "1,")
			assert.Contains(string(msg), "\"Sent\",")
			await <- true
		case err := <-errorChannel:
			assert.Fail(string(err))
			await <- false
		case <-timeout():
			assert.Fail("Publish timeout")
			await <- false
		}
	}()

	<-await

	successChannelHis := make(chan []byte)
	errorChannelHis := make(chan []byte)

	go pubnubInstance.History(channel, 1, 0, 0, false, false,
		successChannelHis, errorChannelHis)
	select {
	case value := <-successChannelHis:
		data, _, _, err := pubnubInstance.ParseJSON(value, "")
		if err != nil {
			assert.Fail(err.Error())
		}

		assert.Contains(data, message)
	case err := <-errorChannelHis:
		assert.Fail(string(err))
	}
}
示例#28
0
func (stock *Stock) RunCycle() {
	cycle := make(chan bool)
	i := 0
	pubnub := messaging.NewPubnub(config.Keys.Pub, config.Keys.Sub, "", "",
		false, "")
	pubnub.SetAuthenticationKey(config.Keys.Auth)

	for {
		go stock.UpdateValuesAndPublish(pubnub, cycle)
		<-cycle
		i++
	}
}
示例#29
0
// SendMultipleResponse is the common implementation for TestMultipleResponsed and
// TestMultipleResponseEncrypted
func SendMultipleResponse(t *testing.T, encrypted bool) {
	cipher := ""
	testName := "TestMultipleResponse"
	if encrypted {
		cipher = "enigma"
		testName = "TestMultipleResponseEncrypted"
	}
	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", cipher, false, "")
	//pubnubChannel := "testChannel"
	r := GenRandom()
	pubnubChannel := fmt.Sprintf("testChannel_sub_%d", r.Intn(20))

	returnTimeChannel := make(chan []byte)
	errorChannelTime := make(chan []byte)

	go pubnubInstance.GetTime(returnTimeChannel, errorChannelTime)

	retTime, errTime := ParseTimeFromServer(returnTimeChannel, errorChannelTime)
	if errTime == nil {
		message1 := "message1"
		message2 := "message2"
		returnPublishChannel := make(chan []byte)
		errorChannelPub := make(chan []byte)

		go pubnubInstance.Publish(pubnubChannel, message1, returnPublishChannel, errorChannelPub)
		b1, _ := ParsePublishResponseFromServer(returnPublishChannel, errorChannelPub)

		returnPublishChannel2 := make(chan []byte)
		errorChannelPub2 := make(chan []byte)
		time.Sleep(time.Duration(2) * time.Second)

		go pubnubInstance.Publish(pubnubChannel, message2, returnPublishChannel2, errorChannelPub2)
		b2, _ := ParsePublishResponseFromServer(returnPublishChannel2, errorChannelPub2)

		if b1 && b2 {

			returnSubscribeChannel := make(chan []byte)
			errorChannelSub := make(chan []byte)
			responseChannelSub := make(chan string)
			waitChannelSub := make(chan string)

			go pubnubInstance.Subscribe(pubnubChannel, retTime, returnSubscribeChannel, false, errorChannelSub)
			go ParseSubscribeMultiResponse(pubnubChannel, returnSubscribeChannel, message1, message2, cipher, testName, responseChannelSub)
			go ParseErrorResponse(errorChannelSub, responseChannelSub)
			go WaitForCompletion(responseChannelSub, waitChannelSub)
			ParseWaitResponse(waitChannelSub, t, testName)
			go pubnubInstance.Unsubscribe(pubnubChannel, returnSubscribeChannel, errorChannelSub)
			pubnubInstance.CloseExistingConnection()
		}
	}
}
示例#30
0
// TestServerTime calls the GetTime method of the messaging to test the time
func TestServerTime(t *testing.T) {
	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "", false, "")

	returnTimeChannel := make(chan []byte)
	errorChannel := make(chan []byte)
	responseChannel := make(chan string)
	waitChannel := make(chan string)

	go pubnubInstance.GetTime(returnTimeChannel, errorChannel)
	go ParseTimeResponse(returnTimeChannel, responseChannel)
	go ParseErrorResponse(errorChannel, responseChannel)
	go WaitForCompletion(responseChannel, waitChannel)
	ParseWaitResponse(waitChannel, t, "Time")
}