Skip to content

Commit

Permalink
Added integration tests.
Browse files Browse the repository at this point in the history
Extracted strings to constants.
  • Loading branch information
marcin-cebo committed Sep 28, 2024
1 parent 2aaada8 commit c3aa3b0
Show file tree
Hide file tree
Showing 12 changed files with 81 additions and 44 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ interface Channel {
* The result of this future can be processed using the `async` method of `PNFuture`.
*
*/
fun whoIsPresent(): PNFuture<Collection<String>> // todo do we have an integTest for this ?
fun whoIsPresent(): PNFuture<Collection<String>>

/**
* Returns information if the user is present on the [Channel]
Expand All @@ -189,7 +189,7 @@ interface Channel {
*
* @return [PNFuture] with Boolean value informing if a given user is present on a specified [Channel]
*/
fun isPresent(userId: String): PNFuture<Boolean> // todo do we have an integTest for this ?
fun isPresent(userId: String): PNFuture<Boolean>

/**
* Returns historical messages for the [Channel]
Expand Down
6 changes: 3 additions & 3 deletions pubnub-chat-api/src/commonMain/kotlin/com/pubnub/chat/Chat.kt
Original file line number Diff line number Diff line change
Expand Up @@ -204,9 +204,9 @@ interface Chat {
* @param name Display name for the channel.
* @param custom Any custom properties or metadata associated with the channel in the form of a `Map`.
* Values must be scalar only; arrays or objects are not supported.
* @param description
* @param status
* @param type
* @param description Additional details about the channel.
* @param status Tag that categorizes a channel by its state, like archived.
* @param type Tag that categorizes a channel by its function, like offtopic.
*
* @return
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@ interface Membership {
*/
val lastReadMessageTimetoken: Long?

// todo do we want to have test for this?

/**
* Setting the last read message for users lets you implement the Read Receipts feature and monitor which channel member read which message.
*
Expand All @@ -61,8 +59,6 @@ interface Membership {
*/
fun update(custom: CustomObject): PNFuture<Membership>

// todo do we have test for this?

/**
* Setting the last read message for users lets you implement the Read Receipts feature and monitor which channel member read which message.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -644,8 +644,8 @@ class ChatImpl(
val eventContent: EventContent = try {
PNDataEncoder.decode<EventContent>(message)
} catch (e: Exception) {
if (message.asMap()?.get("type")?.asString() == "custom") {
EventContent.Custom((message.decode() as Map<String, Any?>) - "type")
if (message.asMap()?.get(TYPE_OF_MESSAGE)?.asString() == TYPE_OF_MESSAGE_IS_CUSTOM) {
EventContent.Custom((message.decode() as Map<String, Any?>) - TYPE_OF_MESSAGE)
} else {
throw e
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.pubnub.chat.internal

import com.pubnub.api.JsonElement
import com.pubnub.api.asString
import com.pubnub.chat.internal.error.PubNubErrorMessage.ERROR_CALLING_DEFAULT_GET_MESSAGE_RESPONSE_BODY
import com.pubnub.chat.internal.serialization.PNDataEncoder
import com.pubnub.chat.types.EventContent
import org.lighthousegames.logging.logging
Expand Down Expand Up @@ -30,7 +31,7 @@ fun defaultGetMessageResponseBody(message: JsonElement): EventContent.TextMessag
?: try {
PNDataEncoder.decode<EventContent.TextMessageContent>(message)
} catch (e: Exception) {
log.e { "Error calling defaultGetMessageResponseBody: ${e.message}" } // todo move message to PubNubErrorMessage
log.e { "$ERROR_CALLING_DEFAULT_GET_MESSAGE_RESPONSE_BODY ${e.message}" }
null
}
}
Expand All @@ -40,3 +41,8 @@ internal const val METADATA_REFERENCED_CHANNELS = "referencedChannels"
internal const val METADATA_QUOTED_MESSAGE = "quotedMessage"
internal const val METADATA_TEXT_LINKS = "textLinks"
internal const val METADATA_LAST_READ_MESSAGE_TIMETOKEN = "lastReadMessageTimetoken"
internal const val TYPE_OF_MESSAGE = "type"
internal const val TYPE_OF_MESSAGE_IS_CUSTOM = "custom"
internal const val RESTRICTION_BAN = "ban"
internal const val RESTRICTION_MUTE = "mute"
internal const val RESTRICTION_REASON = "reason"
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ class EventImpl<T : EventContent>(
val eventContent: EventContent = try {
PNDataEncoder.decode<EventContent>(pnFetchMessageItem.message)
} catch (e: Exception) {
if (pnFetchMessageItem.message.asMap()?.get("type")?.asString() == "custom") {
EventContent.Custom((pnFetchMessageItem.message.decode() as Map<String, Any?>) - "type")
if (pnFetchMessageItem.message.asMap()?.get(TYPE_OF_MESSAGE)?.asString() == TYPE_OF_MESSAGE_IS_CUSTOM) {
EventContent.Custom((pnFetchMessageItem.message.decode() as Map<String, Any?>) - TYPE_OF_MESSAGE)
} else {
throw e
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import com.pubnub.chat.internal.MembershipImpl
import com.pubnub.chat.internal.PINNED_MESSAGE_CHANNEL_ID
import com.pubnub.chat.internal.PINNED_MESSAGE_TIMETOKEN
import com.pubnub.chat.internal.defaultGetMessageResponseBody
import com.pubnub.chat.internal.error.PubNubErrorMessage.CANNOT_QUOTE_MESSAGE_FROM_OTHER_CHANNELS
import com.pubnub.chat.internal.error.PubNubErrorMessage.CAN_NOT_STREAM_CHANNEL_UPDATES_ON_EMPTY_LIST
import com.pubnub.chat.internal.error.PubNubErrorMessage.CHANNEL_INVITES_ARE_NOT_SUPPORTED_IN_PUBLIC_CHATS
import com.pubnub.chat.internal.error.PubNubErrorMessage.ERROR_HANDLING_ONMESSAGE_EVENT
Expand Down Expand Up @@ -99,8 +100,6 @@ import tryLong
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds

private const val CANNOT_QUOTE_MESSAGE_FROM_OTHER_CHANNELS = "You cannot quote messages from other channels"

abstract class BaseChannel<C : Channel, M : Message>(
override val chat: ChatInternal,
private val clock: Clock = Clock.System,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,27 +10,17 @@ internal object PubNubErrorMessage {
internal const val FAILED_TO_CREATE_UPDATE_CHANNEL_DATA = "Failed to create/update channel data."
internal const val FAILED_TO_CREATE_UPDATE_USER_DATA = "Failed to create/update user data."
internal const val FAILED_TO_RETRIEVE_CHANNEL_DATA = "Failed to retrieve channel data."
internal const val FAILED_TO_RETRIEVE_USER_DATA = "Failed to retrieve user data."
internal const val FAILED_TO_RETRIEVE_GET_MEMBERSHIP_DATA = "Failed to retrieve getMembership data."
internal const val FAILED_TO_GET_USERS = "Failed to get users."
internal const val FAILED_TO_GET_CHANNELS = "Failed to get channels."
internal const val FAILED_TO_FORWARD_MESSAGE = "Failed to forward message."
internal const val CHANNEL_META_DATA_IS_EMPTY = "Channel metadata is empty."
internal const val CANNOT_FORWARD_MESSAGE_TO_THE_SAME_CHANNEL =
"You cannot forward the message to the same channel."
internal const val FOR_PUBLISH_PAYLOAD_SHOULD_BE_OF_TYPE_TEXT_MESSAGE_CONTENT =
"When emitEvent method is PUBLISH payload should be of type EventContent.TextMessageContent"
internal const val CHANNEL_ID_ALREADY_EXIST = "Channel with this ID already exists"
internal const val USER_ID_ALREADY_EXIST = "User with this ID already exists"
internal const val CHANNEL_NOT_EXIST = "Channel does not exist"
internal const val CHANNEL_ID_MUST_BE_DEFINED = "Channel id must be defined"
internal const val USER_ID_MUST_BE_DEFINED = "User id must be defined"
internal const val USER_NOT_EXIST = "User does not exist"
internal const val FAILED_TO_SOFT_DELETE_CHANNEL = "Failed to soft delete the channel"
internal const val FAILED_TO_DELETE_USER = "Failed to delete the user"
internal const val FAILED_TO_UPDATE_USER_METADATA = "Failed to update user metadata."
internal const val FAILED_TO_REMOVE_CHANNEL_MEMBERS = "Failed to remove channel members."
internal const val FAILED_TO_SET_CHANNEL_MEMBERS = "Failed to set channel members."
internal const val CHANNEL_INVITES_ARE_NOT_SUPPORTED_IN_PUBLIC_CHATS =
"Channel invites are not supported in Public chats."
internal const val MODERATION_CAN_BE_SET_ONLY_BY_CLIENT_HAVING_SECRET_KEY =
Expand All @@ -42,22 +32,16 @@ internal object PubNubErrorMessage {
internal const val APNS_TOPIC_SHOULD_BE_DEFINED_WHEN_DEVICE_GATEWAY_IS_SET_TO_APNS2 =
"apnsTopic has to be defined when deviceGateway is set to apns2"
internal const val NO_SUCH_MEMBERSHIP_EXISTS = "No such membership exists"
internal const val UNKNOWN_EVENT_TYPE = "Unknown event type: "
internal const val ID_IS_REQUIRED = "Id is required"
internal const val CHANNEL_ID_IS_REQUIRED = "Channel Id is required"
internal const val COUNT_SHOULD_NOT_EXCEED_100 = "Count should not exceed 100"
internal const val PNUUID_METADATA_RESULT_IS_NULL = "PNUUIDMetadataResult is null"
internal const val PNUUID_METADATA_IS_NULL = "PNUUIDMetadata is null"
internal const val PNCHANNEL_METADATA_IS_NULL = "PNChannelMetadata is null"
internal const val CHANNEL_NOT_FOUND = "Channel not found"
internal const val DEVICE_TOKEN_HAS_TO_BE_DEFINED_IN_CHAT_PUSHNOTIFICATIONS_CONFIG = "Device Token has to be defined in Chat pushNotifications config."
internal const val NO_DATA_AVAILABLE_TO_CREATE_OR_UPDATE_CHANNEL = "No data available to create or update Channel."
internal const val THERE_IS_NO_THREAD_TO_BE_DELETED = "There is no thread to be deleted."
internal const val THERE_IS_NO_ACTION_TIMETOKEN_CORRESPONDING_TO_THE_THREAD = "There is no action timetoken corresponding to the thread."
internal const val THERE_IS_NO_THREAD_WITH_ID = "There is no thread with id: "
internal const val CAN_NOT_FIND_CHANNEL_WITH_ID = "Cannot find channel with id: "
internal const val THIS_MESSAGE_IS_NOT_A_THREAD = "This message is not a thread."
internal const val UNABLE_TO_READ_MESSAGES = "Unable to read messages."
internal const val THREAD_CHANNEL_DOES_NOT_EXISTS = "The thread channel does not exist."
internal const val PARENT_CHANNEL_DOES_NOT_EXISTS = "Parent channel doesn't exist."
internal const val CAN_NOT_STREAM_CHANNEL_UPDATES_ON_EMPTY_LIST = "Cannot stream channel updates on an empty list."
Expand All @@ -73,4 +57,6 @@ internal object PubNubErrorMessage {
internal const val THIS_MESSAGE_HAS_NOT_BEEN_DELETED = "This message has not been deleted"
internal const val THIS_THREAD_ID_ALREADY_RESTORED = "This thread is already restored"
internal const val KEY_IS_NOT_VALID_INTEGER = "Key is not a valid integer"
internal const val ERROR_CALLING_DEFAULT_GET_MESSAGE_RESPONSE_BODY = "Error calling defaultGetMessageResponseBody:"
internal const val CANNOT_QUOTE_MESSAGE_FROM_OTHER_CHANNELS = "You cannot quote messages from other channels"
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,20 @@ package com.pubnub.chat.internal.restrictions
import com.pubnub.api.models.consumer.objects.member.PNMember
import com.pubnub.api.models.consumer.objects.membership.PNChannelMembership
import com.pubnub.chat.internal.INTERNAL_MODERATION_PREFIX
import com.pubnub.chat.internal.RESTRICTION_BAN
import com.pubnub.chat.internal.RESTRICTION_MUTE
import com.pubnub.chat.internal.RESTRICTION_REASON
import com.pubnub.chat.restrictions.Restriction
import org.lighthousegames.logging.logging

class RestrictionImpl {
companion object {
private val log = logging()

fun fromChannelMembershipDTO(userId: String, pnChannelMembership: PNChannelMembership): Restriction {
val channelId =
pnChannelMembership.channel.id.substringAfter(INTERNAL_MODERATION_PREFIX)
val customData: Map<String, Any?>? = pnChannelMembership.custom?.value
val ban: Boolean = (customData?.get("ban") as? Boolean) == true
val mute: Boolean = (customData?.get("mute") as? Boolean) == true
val reason: String? = customData?.get("reason")?.toString()
val ban: Boolean = (customData?.get(RESTRICTION_BAN) as? Boolean) == true
val mute: Boolean = (customData?.get(RESTRICTION_MUTE) as? Boolean) == true
val reason: String? = customData?.get(RESTRICTION_REASON)?.toString()

return Restriction(
userId = userId,
Expand All @@ -30,9 +30,9 @@ class RestrictionImpl {
fun fromMemberDTO(channelId: String, pnMember: PNMember): Restriction {
val userId = pnMember.uuid.id
val customData: Map<String, Any?>? = pnMember.custom?.value
val ban: Boolean = (customData?.get("ban") as? Boolean) == true
val mute: Boolean = (customData?.get("mute") as? Boolean) == true
val reason: String? = customData?.get("reason")?.toString()
val ban: Boolean = (customData?.get(RESTRICTION_BAN) as? Boolean) == true
val mute: Boolean = (customData?.get(RESTRICTION_MUTE) as? Boolean) == true
val reason: String? = customData?.get(RESTRICTION_REASON)?.toString()
return Restriction(
userId = userId,
channelId = channelId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,23 +26,38 @@ internal const val THREAD_CHANNEL_ID_PREFIX = "threadChannel_id_"

abstract class BaseChatIntegrationTest : BaseIntegrationTest() {
lateinit var chat: ChatImpl
lateinit var chat02: ChatImpl
lateinit var chatPam: ChatImpl
lateinit var channel01: Channel
lateinit var channel01: Channel // this simulates first user in channel01
lateinit var channel01Chat02: Channel // this simulates second user in channel01
lateinit var channel02: Channel
lateinit var threadChannel: ThreadChannel
lateinit var channelPam: Channel
lateinit var someUser: User
lateinit var someUser02: User
lateinit var userPam: User
var cleanup: MutableList<suspend () -> Unit> = mutableListOf() // todo is this used?

@BeforeTest
override fun before() {
super.before()
chat = ChatImpl(ChatConfiguration(), pubnub)
chat02 = ChatImpl(ChatConfiguration(), pubnub02)
chatPam = ChatImpl(ChatConfiguration(), pubnubPam)
val channel01Id = randomString() + "!_=-@"
channel01 = ChannelImpl(
chat = chat,
id = randomString() + "!_=-@",
id = channel01Id,
name = randomString(),
custom = mapOf(randomString() to randomString()),
description = randomString(),
updated = randomString(),
status = randomString(),
type = ChannelType.DIRECT
)
channel01Chat02 = ChannelImpl(
chat = chat02,
id = channel01Id,
name = randomString(),
custom = mapOf(randomString() to randomString()),
description = randomString(),
Expand Down Expand Up @@ -92,6 +107,7 @@ abstract class BaseChatIntegrationTest : BaseIntegrationTest() {
)
// user has chat and chat has user they should be the same?
someUser = chat.currentUser
someUser02 = chat02.currentUser
userPam = chatPam.currentUser
}

Expand All @@ -100,6 +116,7 @@ abstract class BaseChatIntegrationTest : BaseIntegrationTest() {
pubnub.removeUUIDMetadata(someUser.id).await()
pubnub.removeUUIDMetadata(userPam.id).await()
pubnub.removeChannelMetadata(channel01.id).await()
pubnub.removeChannelMetadata(channel01Chat02.id).await()
pubnub.removeChannelMetadata(channel02.id).await()
pubnub.removeChannelMetadata(threadChannel.id).await()
pubnub.removeChannelMetadata(channelPam.id).await()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,39 @@ class ChannelIntegrationTest : BaseChatIntegrationTest() {
assertEquals(expectedStatus, completableStatus.await())
}
}

@Test
fun canCheck_whoIsPresent() = runTest {
val channel01withChat = channel01
val join01 = channel01withChat.join { }.await()
val join02 = channel01Chat02.join { }.await()
delayInMillis(1000)
val whoIsPresent01: Collection<String> = channel01withChat.whoIsPresent().await()
val whoIsPresent02: Collection<String> = channel01Chat02.whoIsPresent().await()

join01.disconnect?.close()
join02.disconnect?.close()

assertEquals(whoIsPresent01.size, whoIsPresent02.size)
assertTrue(whoIsPresent01.contains(someUser.id))
assertTrue(whoIsPresent01.contains(someUser02.id))
assertTrue(whoIsPresent02.contains(someUser.id))
assertTrue(whoIsPresent02.contains(someUser02.id))
}

@Test
fun canCheck_isPresent() = runTest {
val channel01withChat = channel01
val join01 = channel01withChat.join { }.await()
val join02 = channel01Chat02.join { }.await()
delayInMillis(1000)

assertTrue(channel01withChat.isPresent(channel01Chat02.chat.currentUser.id).await())
assertTrue(channel01Chat02.isPresent(channel01withChat.chat.currentUser.id).await())

join01.disconnect?.close()
join02.disconnect?.close()
}
}

private fun Channel.asImpl(): ChannelImpl {
Expand Down

0 comments on commit c3aa3b0

Please sign in to comment.