// 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, successChannel, errorChannel)
	select {
	case value := <-successChannel:
		data, _, _, err := messaging.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))
	}
}
// ParseHistoryResponseForMultipleMessages unmarshalls the response of the history call to the
// pubnub api and compares the received messages to the sent messages. If the response match the
// test is successful.
//
// Parameters:
// returnChannel: channel to read the response from,
// t: a reference to *testing.T,
// channel: the pubnub channel to publish the messages,
// message: message to compare,
// testname: the test name form where this method is called,
// startMessagesFrom: the message identifer,
// numberOfMessages: number of messages to send,
// cipherKey: the cipher key if used. Can be empty.
func ParseHistoryResponseForMultipleMessages(returnChannel chan []byte, channel string, message string, testName string, startMessagesFrom int, numberOfMessages int, cipherKey string, responseChannel chan string) {
	for {
		value, ok := <-returnChannel
		if !ok {
			break
		}
		if string(value) != "[]" {
			data, _, _, err := messaging.ParseJSON(value, cipherKey)
			if err != nil {
				//t.Error("Test '" + testName + "': failed.")
				responseChannel <- "Test '" + testName + "': failed. Message: " + err.Error()
			} else {
				var arr []string
				err2 := json.Unmarshal([]byte(data), &arr)
				if err2 != nil {
					//t.Error("Test '" + testName + "': failed.");
					responseChannel <- "Test '" + testName + "': failed. Message: " + err2.Error()
				} else {
					messagesReceived := 0

					if len(arr) != numberOfMessages {
						responseChannel <- "Test '" + testName + "': failed."
						//t.Error("Test '" + testName + "': failed.");
						break
					}
					for i := 0; i < numberOfMessages; i++ {
						if arr[i] == message+strconv.Itoa(startMessagesFrom+i) {
							//fmt.Println("data:",arr[i])
							messagesReceived++
						}
					}
					if messagesReceived == numberOfMessages {
						fmt.Println("Test '" + testName + "': passed.")
						responseChannel <- "Test '" + testName + "': passed."
					} else {
						responseChannel <- "Test '" + testName + "': failed. Returned message mismatch"
						//t.Error("Test '" + testName + "': failed.");
					}
					break
				}
			}
		}
	}
}
Exemple #3
0
// TestGermanDecryption tests the German decryption.
// Assumes that the input message is deserialized
// Decrypted string should match ÜÖ
func TestGermanDecryption(t *testing.T) {
	message := "stpgsG1DZZxb44J7mFNSzg=="
	//decrypt
	decrypted, decErr := messaging.DecryptString("enigma", message)
	if decErr != nil {
		t.Error("German decryption: failed.")
	} else {
		data, _, _, err := messaging.ParseJSON([]byte(decrypted.(string)), "")
		if err != nil {
			t.Error("German decryption: failed.", err)
		} else {
			if "ÜÖ" == data {
				fmt.Println("German decryption: passed.")
			} else {
				t.Error("German decryption: failed.")
			}
		}
	}
}
Exemple #4
0
// TestUnicodeDecryption tests the Unicode decryption.
// Assumes that the input message is deserialized
// Decrypted string should match 漢語
func TestUnicodeDecryption(t *testing.T) {
	message := "+BY5/miAA8aeuhVl4d13Kg=="
	//decrypt
	decrypted, decErr := messaging.DecryptString("enigma", message)
	if decErr != nil {
		t.Error("Unicode decryption: failed.")
	} else {
		data, _, _, err := messaging.ParseJSON([]byte(decrypted.(string)), "")
		if err != nil {
			t.Error("Unicode decryption: failed.", err)
		} else {
			if "漢語" == data {
				fmt.Println("Unicode decryption: passed.")
			} else {
				t.Error("Unicode decryption: failed.")
			}
		}
	}
}
// 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 with time parameters
// between which the messages were sent. These received message is compared to the messages sent and
// if all match test is successful.
func DetailedHistoryParamsFor10Messages(t *testing.T, cipherKey string, secretKey string, testName string) {
	assert := assert.New(t)
	numberOfMessages := 5

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

	sleep(5)

	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", cipherKey, false,
		fmt.Sprintf("uuid_%s", testName))

	message := "Test Message "
	channel := testName

	startTime := GetServerTime("start")
	startMessagesFrom := 0
	messagesSent := PublishMessages(pubnubInstance, channel, t,
		startMessagesFrom, numberOfMessages, message, sleep)
	midTime := GetServerTime("mid")
	startMessagesFrom = 5
	messagesSent2 := PublishMessages(pubnubInstance, channel, t,
		startMessagesFrom, numberOfMessages, message, sleep)
	endTime := GetServerTime("end")
	startMessagesFrom = 0

	assert.True(messagesSent, "Error while sending a first bunch of messages")
	successChannel := make(chan []byte)
	errorChannel := make(chan []byte)

	go pubnubInstance.History(channel, numberOfMessages, startTime, midTime,
		false, successChannel, errorChannel)
	select {
	case value := <-successChannel:
		data, _, _, err := messaging.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))
	}

	startMessagesFrom = 5

	assert.True(messagesSent2, "Error while sending a second bunch of messages")

	go pubnubInstance.History(channel, numberOfMessages, midTime, endTime, false,
		successChannel, errorChannel)
	select {
	case value := <-successChannel:
		data, _, _, err := messaging.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))
	}
}
Exemple #6
0
// ParseSubscribeResponseForPresence will look for the connection status in the response
// received on the go channel.
func ParseSubscribeResponseForPresence(pubnubInstance *messaging.Pubnub, customUuid string, returnChannel chan []byte, channel string, testName string, responseChannel chan string) {
	for {
		value, ok := <-returnChannel
		if !ok {
			break
		}
		//response := fmt.Sprintf("%s", value)
		//fmt.Println(response);

		if string(value) != "[]" {
			if (testName == "CustomUuid") || (testName == "HereNow") || (testName == "HereNowWithCipher") {
				response := fmt.Sprintf("%s", value)
				message := "'" + channel + "' connected"
				messageReconn := "'" + channel + "' reconnected"
				if (strings.Contains(response, message)) || (strings.Contains(response, messageReconn)) {
					errorChannel := make(chan []byte)
					returnChannel := make(chan []byte)
					time.Sleep(3 * time.Second)
					go pubnubInstance.HereNow(channel, true, true, returnChannel, errorChannel)
					go ParseHereNowResponse(returnChannel, channel, customUuid, testName, responseChannel)
					go ParseErrorResponse(errorChannel, responseChannel)
					break
				}
			} else if testName == "WhereNow" {
				response := fmt.Sprintf("%s", value)
				message := "'" + channel + "' connected"
				messageReconn := "'" + channel + "' reconnected"
				if (strings.Contains(response, message)) || (strings.Contains(response, messageReconn)) {
					errorChannel := make(chan []byte)
					returnChannel := make(chan []byte)
					time.Sleep(3 * time.Second)
					go pubnubInstance.WhereNow(customUuid, returnChannel, errorChannel)
					go ParseHereNowResponse(returnChannel, channel, customUuid, testName, responseChannel)
					go ParseErrorResponse(errorChannel, responseChannel)
					break
				}
			} else if testName == "GlobalHereNow" {
				response := fmt.Sprintf("%s", value)
				message := "'" + channel + "' connected"
				messageReconn := "'" + channel + "' reconnected"
				if (strings.Contains(response, message)) || (strings.Contains(response, messageReconn)) {
					errorChannel := make(chan []byte)
					returnChannel := make(chan []byte)
					time.Sleep(3 * time.Second)
					go pubnubInstance.GlobalHereNow(true, false, returnChannel, errorChannel)
					go ParseHereNowResponse(returnChannel, channel, customUuid, testName, responseChannel)
					go ParseErrorResponse(errorChannel, responseChannel)
					break
				}
			} else {
				response := fmt.Sprintf("%s", value)
				message := "'" + channel + "' connected"
				messageReconn := "'" + channel + "' reconnected"
				//fmt.Println("Test3 '" + testName + "':" +response)
				if (strings.Contains(response, message)) || (strings.Contains(response, messageReconn)) {

					errorChannel2 := make(chan []byte)
					returnSubscribeChannel := make(chan []byte)
					time.Sleep(1 * time.Second)
					go pubnubInstance.Subscribe(channel, "", returnSubscribeChannel, false, errorChannel2)
					go ParseResponseDummy(returnSubscribeChannel)
					go ParseResponseDummy(errorChannel2)
				} else {
					if testName == "Presence" {
						data, _, returnedChannel, err2 := messaging.ParseJSON(value, "")

						var occupants []struct {
							Action    string
							Uuid      string
							Timestamp float64
							Occupancy int
						}

						if err2 != nil {
							responseChannel <- "Test '" + testName + "': failed. Message: 1 :" + err2.Error()
							break
						}
						//fmt.Println("Test3 '" + testName + "':" +data)
						err := json.Unmarshal([]byte(data), &occupants)
						if err != nil {
							//fmt.Println("err '" + testName + "':",err)
							responseChannel <- "Test '" + testName + "': failed. Message: 2 :" + err.Error()
							break
						} else {
							channelSubRepsonseReceived := false
							for i := 0; i < len(occupants); i++ {
								if (occupants[i].Action == "join") && occupants[i].Uuid == customUuid {
									channelSubRepsonseReceived = true
									break
								}
							}
							if !channelSubRepsonseReceived {
								responseChannel <- "Test '" + testName + "': failed. Message: err3"
								break
							}
							if channel == returnedChannel {
								responseChannel <- "Test '" + testName + "': passed."
								break
							} else {
								responseChannel <- "Test '" + testName + "': failed. Message: err4"
								break
							}
						}
					}
				}
			}
		}
	}
}
// TestPresence subscribes to the presence notifications on a pubnub channel and
// then subscribes to a pubnub channel. The test waits till we get a response from
// the subscribe call. The method that parses the presence response sets the global
// variable _endPresenceTestAsSuccess to true if the presence contains a join info
// on the channel and _endPresenceTestAsFailure is otherwise.
func Test0Presence(t *testing.T) {
	assert := assert.New(t)

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

	customUuid := "UUID_zeroPresence"
	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, SecKey, "", false, customUuid)
	channel := "Channel_ZeroPresence"

	successSubscribe := make(chan []byte)
	errorSubscribe := make(chan []byte)
	successPresence := make(chan []byte)
	errorPresence := make(chan []byte)
	unsubscribeSuccessChannel := make(chan []byte)
	unsubscribeErrorChannel := make(chan []byte)
	unsubscribeSuccessPresence := make(chan []byte)
	unsubscribeErrorPresence := make(chan []byte)

	await := make(chan bool)

	go pubnubInstance.Subscribe(channel, "", successPresence, true, errorPresence)
	ExpectConnectedEvent(t, channel, "", successPresence, errorPresence)

	go func() {
		for {
			select {
			case value := <-successPresence:
				data, _, returnedChannel, err := messaging.ParseJSON(value, "")
				if err != nil {
					assert.Fail(err.Error())
				}

				var occupants []struct {
					Action    string
					Uuid      string
					Timestamp float64
					Occupancy int
				}

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

				channelSubRepsonseReceived := false
				for i := 0; i < len(occupants); i++ {
					if (occupants[i].Action == "join") && occupants[i].Uuid == customUuid {
						channelSubRepsonseReceived = true
						break
					}
				}

				assert.True(channelSubRepsonseReceived, "Sub-response not received")
				assert.Equal(channel, returnedChannel)

				await <- true
				return
			case err := <-errorPresence:
				if !strings.Contains(string(err), "aborted") {
					await <- false
					assert.Fail("Failed to subscribe to presence", string(err))
					return
				}
			case <-timeouts(15):
				await <- false
				return
			}
		}
	}()

	go pubnubInstance.Subscribe(channel, "", successSubscribe, false, errorSubscribe)
	ExpectConnectedEvent(t, channel, "", successSubscribe, errorSubscribe)
	go func() {
		select {
		case <-successSubscribe:
		case err := <-errorSubscribe:
			if !strings.Contains(string(err), "aborted") {
				assert.Fail("Error in subscribe dummy loop", string(err))
			}
		}
	}()

	<-await

	go func() {
		select {
		case <-successPresence:
		case err := <-errorPresence:
			if !strings.Contains(string(err), "aborted") {
				assert.Fail("Error in presence dummy loop", string(err))
			}
		}
	}()

	go pubnubInstance.Unsubscribe(channel,
		unsubscribeSuccessChannel, unsubscribeErrorChannel)
	ExpectUnsubscribedEvent(t, channel, "", unsubscribeSuccessChannel, unsubscribeErrorChannel)

	go pubnubInstance.Unsubscribe(fmt.Sprintf("%s-pnpres", channel),
		unsubscribeSuccessPresence, unsubscribeErrorPresence)
	ExpectUnsubscribedEvent(t, channel, "", unsubscribeSuccessPresence, unsubscribeErrorPresence)
}