Skip to content

Commit

Permalink
Merge pull request #13 from deskpro/feat/write-unit-tests
Browse files Browse the repository at this point in the history
Unit tests
  • Loading branch information
qsd-faris authored Feb 16, 2024
2 parents 34f0103 + 1f7642b commit 7057c87
Show file tree
Hide file tree
Showing 11 changed files with 218 additions and 27 deletions.
6 changes: 5 additions & 1 deletion Sources/Data/User.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import Foundation

/// - Tag: User
public class User: Codable {
public class User: Codable, Equatable {

public var name: String? = nil
public var firstName: String? = nil
Expand All @@ -20,4 +20,8 @@ public class User: Codable {
self.lastName = lastName
self.email = email
}

public static func == (lhs: User, rhs: User) -> Bool {
return lhs.name == rhs.name && lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName && lhs.email == rhs.email
}
}
34 changes: 27 additions & 7 deletions Sources/Deskpro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public final class DeskPro: Messenger {
private var coordinator: PresentCoordinator

/// User defaults manager for storing user-related information.
private var appUserDefaults: AppUserDefaults?
var appUserDefaults: AppUserDefaults

/// Each Deskpro instance is having its own eventRouter to handle events in chat.
public var eventRouter: EventRouter
Expand All @@ -42,7 +42,7 @@ public final class DeskPro: Messenger {
/// The method is intended to simulate a test scenario and provide a String result based on the outcome of the test.
///
/// - Returns: A String representing the result of the test operation.
public final func test() -> String {
public static func test() -> String {
return "Hello world from Messenger!"
}

Expand All @@ -54,7 +54,17 @@ public final class DeskPro: Messenger {
/// - Parameter user: The [User](x-source-tag://User) object containing the user information.
///
public final func setUserInfo(user: User) {
appUserDefaults?.setUserInfo(user)
appUserDefaults.setUserInfo(user)
}

/// Getter method for user info, should only be used for testing.
final func getUserInfo() -> User? {
return appUserDefaults.getUserInfo()
}

/// Getter method for user info in JSON format, should only be used for testing.
final func getUserInfoJson() -> String? {
return appUserDefaults.getUserInfoJson()
}

/// Sets a user JWT token that enables Messenger to treat this user as a logged-in user.
Expand All @@ -64,18 +74,23 @@ public final class DeskPro: Messenger {
/// - Returns: `true` if the token is successfully saved, `false` otherwise.
@discardableResult
public final func authorizeUser(userJwt: String) -> Bool {
appUserDefaults?.setJwtToken(userJwt)
appUserDefaults.setJwtToken(userJwt)
return true
}

/// Getter method for JWT token, should only be used for testing.
func getJwtToken() -> String? {
return appUserDefaults.getJwtToken()
}

/// Logs out the current user from the SDK session.
///
/// This method performs a logout operation, ending the current user's session with the SDK. After calling this method, the user will need to log in again to use the SDK features.
///
/// - Returns: `true` if the logout operation is successful; `false` otherwise.
@discardableResult
public final func forgetUser() -> Bool {
appUserDefaults?.clear()
appUserDefaults.clear()
return true
}

Expand All @@ -88,10 +103,15 @@ public final class DeskPro: Messenger {
/// - Returns: `true` if the push registration token is successfully set; `false` otherwise.
@discardableResult
public final func setPushRegistrationToken(token: String) -> Bool {
appUserDefaults?.setDeviceToken(token)
appUserDefaults.setDeviceToken(token)
return true
}

/// Getter method for device token, should only be used for testing.
func getPushRegistrationToken() -> String? {
return appUserDefaults.getDeviceToken()
}

/// Checks whether a push notification is related to the DeskPro SDK.
///
/// This method examines the provided push notification data to determine whether it is intended for the DeskPro SDK.
Expand All @@ -101,7 +121,7 @@ public final class DeskPro: Messenger {
/// - Returns: `true` if the push notification is related to DeskPro; `false` otherwise.
///
/// - Tag: isDeskProPushNotification
public final func isDeskProPushNotification(data: [AnyHashable: Any]) -> Bool {
public static func isDeskProPushNotification(data: [AnyHashable: Any]) -> Bool {
if let issuer = data["issuer"] as? String {
return issuer == "deskpro-messenger"
} else {
Expand Down
File renamed without changes.
4 changes: 2 additions & 2 deletions Sources/Messenger.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ protocol Messenger {
/// The method is intended to simulate a test scenario and provide a String result based on the outcome of the test.
///
/// - Returns: A String representing the result of the test operation.
func test() -> String
static func test() -> String

/// Sets user information for the application.
///
Expand Down Expand Up @@ -57,7 +57,7 @@ protocol Messenger {
/// - Returns: `true` if the push notification is related to DeskPro; `false` otherwise.
///
/// - Tag: isDeskProPushNotification
func isDeskProPushNotification(data: [AnyHashable: Any]) -> Bool
static func isDeskProPushNotification(data: [AnyHashable: Any]) -> Bool

/// Handles the incoming push notification data if it is related to DeskPro.
///
Expand Down
4 changes: 4 additions & 0 deletions Sources/PresentBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ public final class PresentBuilder {

/// Represents the constructed path for the URL.
private var path = ""

func getPath() -> String {
return path
}

/// This method is a constructor for creating Deskpro objects
///
Expand Down
6 changes: 0 additions & 6 deletions Sources/messenger-sdk-ios/messenger_sdk_ios.swift

This file was deleted.

110 changes: 110 additions & 0 deletions Tests/messenger-sdk-iosTests/DeskProSetup/DeskProSetupTest.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
//
// DeskproSetupTest.swift
//
//
// Created by QSD BiH on 14. 2. 2024..
//

import XCTest
@testable import messenger_sdk_ios

final class DeskproSetupTest: XCTestCase {

var messenger: DeskPro!
let appUrl = "test/url/data"
let appId = "1"
let vc = UIViewController()

let user = User(name: "John Doe", firstName: "John", lastName: "Doe", email: "[email protected]")
let jwtToken = "some-jwt-token"
let deviceToken = "some-device-token"

override func setUp() {
let messengerConfig = MessengerConfig(appUrl: appUrl, appId: appId)
messenger = DeskPro(messengerConfig: messengerConfig, containingViewController: vc)
}

override func tearDown() {
messenger = nil
}

func testSetAndGetUserInfo() {
messenger.setUserInfo(user: user)

XCTAssertEqual(user, messenger.getUserInfo(), ErrorMessages.usersNotMatching)
}

func testSetAndGetUserInfoJson() {
messenger.setUserInfo(user: user)

if let jsonString = messenger.getUserInfoJson(),
let jsonData = jsonString.data(using: .utf8) {
let savedUser = try? JSONDecoder().decode(User.self, from: jsonData)
XCTAssertEqual(user, savedUser, ErrorMessages.usersNotMatching)
}
}

func testSetAndGetJwtToken() {
messenger.authorizeUser(userJwt: jwtToken)

XCTAssertEqual(jwtToken, messenger.getJwtToken(), ErrorMessages.tokensNotMatching)
}

func testSetAndGetPushRegistrationToken() {
messenger.setPushRegistrationToken(token: deviceToken)

XCTAssertEqual(deviceToken, messenger.getPushRegistrationToken(), ErrorMessages.tokensNotMatching)
}

func testClearData() {
messenger.setUserInfo(user: user)
messenger.authorizeUser(userJwt: jwtToken)
messenger.setPushRegistrationToken(token: deviceToken)

messenger.forgetUser()

XCTAssertNil(messenger.getUserInfo(), ErrorMessages.userInfoNotNil)
XCTAssertNil(messenger.getUserInfoJson(), ErrorMessages.userInfoJsonNotNil)
XCTAssertNil(messenger.getJwtToken(), ErrorMessages.jwtTokenNotNil)
XCTAssertNil(messenger.getPushRegistrationToken(), ErrorMessages.deviceTokenNotNil)
}

func testSetAndGetMultipleDeskProInstances() {
let messengerConfig2 = MessengerConfig(appUrl: "some_url", appId: "2")
let messenger2 = DeskPro(messengerConfig: messengerConfig2, containingViewController: vc)
let user2 = User(name: "John Doe 2", firstName: "John 2", lastName: "Doe 2", email: "[email protected]")
let jwtToken2 = "another-jwt-token"
let deviceToken2 = "another-device-token"

messenger.setUserInfo(user: user)
messenger.authorizeUser(userJwt: jwtToken)
messenger.setPushRegistrationToken(token: deviceToken)

messenger2.setUserInfo(user: user2)
messenger2.authorizeUser(userJwt: jwtToken2)
messenger2.setPushRegistrationToken(token: deviceToken2)

XCTAssertEqual(user2, messenger2.getUserInfo(), ErrorMessages.usersNotMatching)
if let jsonString = messenger2.getUserInfoJson(),
let jsonData = jsonString.data(using: .utf8) {
let savedUser = try? JSONDecoder().decode(User.self, from: jsonData)
XCTAssertEqual(user2, savedUser, ErrorMessages.usersNotMatching)
}
XCTAssertEqual(jwtToken2, messenger2.getJwtToken(), ErrorMessages.tokensNotMatching)
XCTAssertEqual(deviceToken2, messenger2.getPushRegistrationToken(), ErrorMessages.tokensNotMatching)
}

func testPresentBuilder() {
let presentBuilder = PresentBuilder(url: appUrl, appId: appId, coordinator: PresentCoordinator(containingViewController: vc, eventRouter: EventRouter()))
XCTAssertEqual(appUrl, presentBuilder.getPath(), ErrorMessages.pathsNotMatching)

_ = presentBuilder.chatHistory(1)
XCTAssertEqual("\(appUrl)/chat_history/1", presentBuilder.getPath(), ErrorMessages.pathsNotMatching)

_ = presentBuilder.article(1)
XCTAssertEqual("\(appUrl)/chat_history/1/article/1", presentBuilder.getPath(), ErrorMessages.pathsNotMatching)

_ = presentBuilder.comments()
XCTAssertEqual("\(appUrl)/chat_history/1/article/1/comments", presentBuilder.getPath(), ErrorMessages.pathsNotMatching)
}
}
26 changes: 26 additions & 0 deletions Tests/messenger-sdk-iosTests/ErrorMessages.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//
// ErrorMessages.swift
//
//
// Created by QSD BiH on 16. 2. 2024..
//

import Foundation

struct ErrorMessages {

static var usersNotMatching = formatMessage("The users do not match.")
static var tokensNotMatching = formatMessage("The tokens do not match.")
static var pathsNotMatching = formatMessage("The paths do not match.")
static var stringsNotMatching = formatMessage("The strings do not match.")
static var userInfoNotNil = formatMessage("The user info is not nil.")
static var userInfoJsonNotNil = formatMessage("The user info Json is not nil.")
static var jwtTokenNotNil = formatMessage("The jwt token is not nil.")
static var deviceTokenNotNil = formatMessage("The device token is not nil.")
static var validNotificationData = formatMessage("The notification is valid.")
static var invalidNotificationData = formatMessage("The notification is not valid.")

private static func formatMessage(_ message: String) -> String {
return "\(message)"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//
// PushNotificationTests.swift
//
//
// Created by QSD BiH on 14. 2. 2024..
//

import XCTest
@testable import messenger_sdk_ios

final class PushNotificationTests: XCTestCase {

func testValidPushNotification() {
let content = UNMutableNotificationContent()
let userInfo = ["issuer" : "deskpro-messenger"]
content.userInfo = userInfo as [AnyHashable : Any]

XCTAssertTrue(DeskPro.isDeskProPushNotification(data: content.userInfo), ErrorMessages.invalidNotificationData)
}

func testInvalidPushNotification() {
let content = UNMutableNotificationContent()
let userInfo = ["issuer" : "some-messenger"]
content.userInfo = userInfo as [AnyHashable : Any]

XCTAssertFalse(DeskPro.isDeskProPushNotification(data: content.userInfo), ErrorMessages.validNotificationData)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//
// SDKConnectionTests.swift
//
//
// Created by QSD BiH on 14. 2. 2024..
//

import XCTest
@testable import messenger_sdk_ios

final class SDKConnectionTests: XCTestCase {

func testConnectionWithSDK() {
XCTAssertEqual(DeskPro.test(), "Hello world from Messenger!", ErrorMessages.stringsNotMatching)
}
}
11 changes: 0 additions & 11 deletions Tests/messenger-sdk-iosTests/messenger_sdk_iosTests.swift

This file was deleted.

0 comments on commit 7057c87

Please sign in to comment.