Skip to content

Commit

Permalink
Merge pull request adobe#29 from PravinPK/finalTests
Browse files Browse the repository at this point in the history
[Tests]- Remaining unit tests
  • Loading branch information
PravinPK authored Jun 24, 2021
2 parents 6230ebb + 90d7911 commit 63f77fc
Show file tree
Hide file tree
Showing 15 changed files with 677 additions and 129 deletions.
8 changes: 8 additions & 0 deletions AEPAssurance.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@
B6407206262C90FA00C43183 /* Assurance+PublicAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = B6407205262C90FA00C43183 /* Assurance+PublicAPI.swift */; };
B6407223262CEBC600C43183 /* URL+Parser.swift in Sources */ = {isa = PBXBuildFile; fileRef = B6407222262CEBC600C43183 /* URL+Parser.swift */; };
B640722B262CF06100C43183 /* AssuranceEnvironment.swift in Sources */ = {isa = PBXBuildFile; fileRef = B640722A262CF06100C43183 /* AssuranceEnvironment.swift */; };
B64212B326849021007343B6 /* MockPinPad.swift in Sources */ = {isa = PBXBuildFile; fileRef = B64212B226849021007343B6 /* MockPinPad.swift */; };
B64212B52684A655007343B6 /* AssuranceConnectionError.swift in Sources */ = {isa = PBXBuildFile; fileRef = B64212B42684A655007343B6 /* AssuranceConnectionError.swift */; };
B64FDF6E264F33EF00D33192 /* AssurancePlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = B64FDF6D264F33EF00D33192 /* AssurancePlugin.swift */; };
B64FDF70264F341600D33192 /* PluginFakeEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = B64FDF6F264F341600D33192 /* PluginFakeEvent.swift */; };
B64FDF73264F384700D33192 /* PluginFakeEventTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B64FDF71264F384400D33192 /* PluginFakeEventTests.swift */; };
Expand Down Expand Up @@ -219,6 +221,8 @@
B6407205262C90FA00C43183 /* Assurance+PublicAPI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Assurance+PublicAPI.swift"; sourceTree = "<group>"; };
B6407222262CEBC600C43183 /* URL+Parser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "URL+Parser.swift"; sourceTree = "<group>"; };
B640722A262CF06100C43183 /* AssuranceEnvironment.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssuranceEnvironment.swift; sourceTree = "<group>"; };
B64212B226849021007343B6 /* MockPinPad.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockPinPad.swift; sourceTree = "<group>"; };
B64212B42684A655007343B6 /* AssuranceConnectionError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssuranceConnectionError.swift; sourceTree = "<group>"; };
B64FDF6D264F33EF00D33192 /* AssurancePlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssurancePlugin.swift; sourceTree = "<group>"; };
B64FDF6F264F341600D33192 /* PluginFakeEvent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PluginFakeEvent.swift; sourceTree = "<group>"; };
B64FDF71264F384400D33192 /* PluginFakeEventTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PluginFakeEventTests.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -453,6 +457,7 @@
B6D6A016265D8863005042BE /* AssuranceClientInfoTests.swift */,
B6D6A01F265F086A005042BE /* AssuranceBlobTests.swift */,
B63ADA8D266F718900A1281A /* ErrorViewTests.swift */,
B64212B42684A655007343B6 /* AssuranceConnectionError.swift */,
B63EB79C2668D524005BE2C5 /* AssuranceClientLogMessageTests.swift */,
B64071A9262C313E00C43183 /* Info.plist */,
);
Expand Down Expand Up @@ -598,6 +603,7 @@
B6D6A028265FA0EE005042BE /* MockAssuranceUIUtil.swift */,
B63ADABB26731A0400A1281A /* MockSocket.swift */,
B6DBD81F2678FB19009EB47E /* MockStatusUI.swift */,
B64212B226849021007343B6 /* MockPinPad.swift */,
);
path = Mocks;
sourceTree = "<group>";
Expand Down Expand Up @@ -1137,6 +1143,7 @@
B6CECC682655A94F000D517F /* ThreadSafeQueueTests.swift in Sources */,
B6AFD58E2634041E00C63608 /* AssuranceEventTests.swift in Sources */,
B6D6A01D265F05F8005042BE /* MockNetworkService.swift in Sources */,
B64212B326849021007343B6 /* MockPinPad.swift in Sources */,
B6DBD8202678FB19009EB47E /* MockStatusUI.swift in Sources */,
B6AB2DF326337BE700FE8AEA /* AssuranceStateTests.swift in Sources */,
B6D2A91026322D6D0062AC5E /* AssuranceEnvironmentTests.swift in Sources */,
Expand All @@ -1149,6 +1156,7 @@
B63EB79D2668D524005BE2C5 /* AssuranceClientLogMessageTests.swift in Sources */,
B6D6A02A265FAAA6005042BE /* MockUIService.swift in Sources */,
B6CECC5E26545834000D517F /* MockAssurance.swift in Sources */,
B64212B52684A655007343B6 /* AssuranceConnectionError.swift in Sources */,
B6AB2DEE26337BB700FE8AEA /* MockDataStore.swift in Sources */,
B6CECC6026545857000D517F /* PluginHubTests.swift in Sources */,
B6D6A017265D8863005042BE /* AssuranceClientInfoTests.swift in Sources */,
Expand Down
1 change: 1 addition & 0 deletions AEPAssurance/Source/AssuranceSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ class AssuranceSession {
// since we don't give retry option for these errors and UI will be dismissed anyway, hence notify plugins for onSessionTerminated
if !error.info.shouldRetry {
clearSessionData()
statusUI.remove()
pluginHub.notifyPluginsOnSessionTerminated()
}
}
Expand Down
240 changes: 121 additions & 119 deletions AEPAssurance/Source/Socket/Native/NativeSocket.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,122 +10,124 @@
governing permissions and limitations under the License.
*/

import AEPServices
import Foundation
import WebKit

@available(iOS 13.0, *)
class NativeSocket: NSObject, SocketConnectable, URLSessionDelegate, URLSessionWebSocketDelegate {
var socketURL: URL?

var delegate: SocketDelegate
var socketState: SocketState = .unknown {
didSet {
delegate.webSocket(self, didChangeState: self.socketState)
}
}

// MARK: - Private properties

private var session: URLSession?
private var socketTask: URLSessionWebSocketTask?

// MARK: - SocketConnectable Interfaces

/// Initialization of native socket connection.
/// - Parameters:
/// - delegate: the delegate instance to get notified on essential socket events
required init(withDelegate delegate: SocketDelegate) {
self.delegate = delegate
}

/// Makes a socket connection with the provided URL
/// Sets the socket state to `CONNECTING` and attempts to make a connection.
/// On successful connection the socketDelegate's `webSocketDidConnect` method is invoked. And the socket state is set to `OPEN`.
/// On any error, the socketDelegate `webSocketOnError` method is invoked.
/// - Parameters :
/// - url : the socket `URL`
func connect(withUrl url: URL) {
session = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue())
socketTask = session?.webSocketTask(with: url)
socketTask?.resume()
registerCallbacks()
socketState = .connecting
}

/// Disconnect the ongoing socket connection.
/// Sets the socket state to `CLOSING` and attempts for disconnection
/// On successful disconnection the socketDelegate's `webSocketDidDisconnect`method is invoked. And the socket state is set to`CLOSED`.
/// On any error, the socketDelegate's `webSocketOnError`method is invoked.
func disconnect() {
socketState = .closing
socketTask?.cancel(with: .normalClosure, reason: nil)
}

func sendEvent(_ event: AssuranceEvent) {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .millisecondsSince1970
let jsonData = (try? encoder.encode(event)) ?? Data()
let dataString = jsonData.base64EncodedString(options: .endLineWithLineFeed)
socketTask?.send(URLSessionWebSocketTask.Message.string(dataString), completionHandler: { [weak self] error in
if let error = error {
self?.didReceiveError(error)
}
})
}

// MARK: - URLSessionWebSocketDelegate methods

func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {
socketState = .open
self.delegate.webSocketDidConnect(self)
}

func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
socketState = .closed
self.delegate.webSocketDidDisconnect(self, closeCode.rawValue, reason?.base64EncodedString() ?? "", true)
}

// MARK: - Private methods

private func registerCallbacks() {
socketTask?.receive {[weak self] result in
switch result {
case .success(let response):
switch response {
case .string(let message):
self?.didReceiveMessage(message)
case .data(let data):
self?.didReceiveBinaryData(data)
@unknown default:
Log.debug(label: AssuranceConstants.LOG_TAG, "Unknown format data received from socket. Ignoring incoming event")
}
case .failure(let error):
self?.didReceiveError(error)
}
}
}

/// Handle the error from socket connection
private func didReceiveError(_ error: Error) {
self.delegate.webSocketOnError(self)
}

/// Handle the incoming string message from socket
private func didReceiveMessage(_ message: String) {
guard let data = message.data(using: .utf8) else {
Log.debug(label: AssuranceConstants.LOG_TAG, "Unable to convert the received socket message to data. Ignoring the incoming event.")
return
}
guard let receivedEvent = AssuranceEvent.from(jsonData: data) else {
return
}
self.delegate.webSocket(self, didReceiveEvent: receivedEvent)
}

/// Handle the incoming binary data from socket
private func didReceiveBinaryData(_ data: Data) {
Log.debug(label: AssuranceConstants.LOG_TAG, "Assurance SDK cannot to handle binary data received from socket.")
}

}
// NativeSocket will be uncommented and included during Assurance support for TVOS.

//import AEPServices
//import Foundation
//import WebKit
//
//@available(iOS 13.0, *)
//class NativeSocket: NSObject, SocketConnectable, URLSessionDelegate, URLSessionWebSocketDelegate {
// var socketURL: URL?
//
// var delegate: SocketDelegate
// var socketState: SocketState = .unknown {
// didSet {
// delegate.webSocket(self, didChangeState: self.socketState)
// }
// }
//
// // MARK: - Private properties
//
// private var session: URLSession?
// private var socketTask: URLSessionWebSocketTask?
//
// // MARK: - SocketConnectable Interfaces
//
// /// Initialization of native socket connection.
// /// - Parameters:
// /// - delegate: the delegate instance to get notified on essential socket events
// required init(withDelegate delegate: SocketDelegate) {
// self.delegate = delegate
// }
//
// /// Makes a socket connection with the provided URL
// /// Sets the socket state to `CONNECTING` and attempts to make a connection.
// /// On successful connection the socketDelegate's `webSocketDidConnect` method is invoked. And the socket state is set to `OPEN`.
// /// On any error, the socketDelegate `webSocketOnError` method is invoked.
// /// - Parameters :
// /// - url : the socket `URL`
// func connect(withUrl url: URL) {
// session = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue())
// socketTask = session?.webSocketTask(with: url)
// socketTask?.resume()
// registerCallbacks()
// socketState = .connecting
// }
//
// /// Disconnect the ongoing socket connection.
// /// Sets the socket state to `CLOSING` and attempts for disconnection
// /// On successful disconnection the socketDelegate's `webSocketDidDisconnect`method is invoked. And the socket state is set to`CLOSED`.
// /// On any error, the socketDelegate's `webSocketOnError`method is invoked.
// func disconnect() {
// socketState = .closing
// socketTask?.cancel(with: .normalClosure, reason: nil)
// }
//
// func sendEvent(_ event: AssuranceEvent) {
// let encoder = JSONEncoder()
// encoder.dateEncodingStrategy = .millisecondsSince1970
// let jsonData = (try? encoder.encode(event)) ?? Data()
// let dataString = jsonData.base64EncodedString(options: .endLineWithLineFeed)
// socketTask?.send(URLSessionWebSocketTask.Message.string(dataString), completionHandler: { [weak self] error in
// if let error = error {
// self?.didReceiveError(error)
// }
// })
// }
//
// // MARK: - URLSessionWebSocketDelegate methods
//
// func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {
// socketState = .open
// self.delegate.webSocketDidConnect(self)
// }
//
// func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
// socketState = .closed
// self.delegate.webSocketDidDisconnect(self, closeCode.rawValue, reason?.base64EncodedString() ?? "", true)
// }
//
// // MARK: - Private methods
//
// private func registerCallbacks() {
// socketTask?.receive {[weak self] result in
// switch result {
// case .success(let response):
// switch response {
// case .string(let message):
// self?.didReceiveMessage(message)
// case .data(let data):
// self?.didReceiveBinaryData(data)
// @unknown default:
// Log.debug(label: AssuranceConstants.LOG_TAG, "Unknown format data received from socket. Ignoring incoming event")
// }
// case .failure(let error):
// self?.didReceiveError(error)
// }
// }
// }
//
// /// Handle the error from socket connection
// private func didReceiveError(_ error: Error) {
// self.delegate.webSocketOnError(self)
// }
//
// /// Handle the incoming string message from socket
// private func didReceiveMessage(_ message: String) {
// guard let data = message.data(using: .utf8) else {
// Log.debug(label: AssuranceConstants.LOG_TAG, "Unable to convert the received socket message to data. Ignoring the incoming event.")
// return
// }
// guard let receivedEvent = AssuranceEvent.from(jsonData: data) else {
// return
// }
// self.delegate.webSocket(self, didReceiveEvent: receivedEvent)
// }
//
// /// Handle the incoming binary data from socket
// private func didReceiveBinaryData(_ data: Data) {
// Log.debug(label: AssuranceConstants.LOG_TAG, "Assurance SDK cannot to handle binary data received from socket.")
// }
//
//}
2 changes: 1 addition & 1 deletion AEPAssurance/Source/Socket/WebView/WebViewSocket.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import WebKit

class WebViewSocket: NSObject, SocketConnectable, WKNavigationDelegate, WKScriptMessageHandler {

var delegate: SocketDelegate
weak var delegate: SocketDelegate
var socketURL: URL?

/// variable tracking the current socket status
Expand Down
71 changes: 71 additions & 0 deletions AEPAssurance/UnitTests/AssuranceConnectionError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/

@testable import AEPAssurance
import XCTest

class AssuranceConnectionErrorTests: XCTestCase {

func test_AssuranceConnectionErrorEnum() throws {

// Generic Error
XCTAssertNotNil(AssuranceConnectionError.genericError.info.name)
XCTAssertNotNil(AssuranceConnectionError.genericError.info.description)
XCTAssertTrue(AssuranceConnectionError.genericError.info.shouldRetry)

// NoSessionId Error
XCTAssertNotNil(AssuranceConnectionError.noSessionID.info.name)
XCTAssertNotNil(AssuranceConnectionError.noSessionID.info.description)
XCTAssertFalse(AssuranceConnectionError.noSessionID.info.shouldRetry)

// No PinCode Error
XCTAssertNotNil(AssuranceConnectionError.noPincode.info.name)
XCTAssertNotNil(AssuranceConnectionError.noPincode.info.description)
XCTAssertTrue(AssuranceConnectionError.noPincode.info.shouldRetry)

// NoURL Error
XCTAssertNotNil(AssuranceConnectionError.noURL.info.name)
XCTAssertNotNil(AssuranceConnectionError.noURL.info.description)
XCTAssertFalse(AssuranceConnectionError.noURL.info.shouldRetry)

// noOrgId Error
XCTAssertNotNil(AssuranceConnectionError.noOrgId.info.name)
XCTAssertNotNil(AssuranceConnectionError.noOrgId.info.description)
XCTAssertFalse(AssuranceConnectionError.noOrgId.info.shouldRetry)

// orgIDMismatch Error
XCTAssertNotNil(AssuranceConnectionError.orgIDMismatch.info.name)
XCTAssertNotNil(AssuranceConnectionError.orgIDMismatch.info.description)
XCTAssertFalse(AssuranceConnectionError.orgIDMismatch.info.shouldRetry)

// connectionLimit Error
XCTAssertNotNil(AssuranceConnectionError.connectionLimit.info.name)
XCTAssertNotNil(AssuranceConnectionError.connectionLimit.info.description)
XCTAssertFalse(AssuranceConnectionError.connectionLimit.info.shouldRetry)

// eventLimit Error
XCTAssertNotNil(AssuranceConnectionError.eventLimit.info.name)
XCTAssertNotNil(AssuranceConnectionError.eventLimit.info.description)
XCTAssertFalse(AssuranceConnectionError.eventLimit.info.shouldRetry)

// clientError Error
XCTAssertNotNil(AssuranceConnectionError.clientError.info.name)
XCTAssertNotNil(AssuranceConnectionError.clientError.info.description)
XCTAssertFalse(AssuranceConnectionError.clientError.info.shouldRetry)

// userCancelled Error
XCTAssertNotNil(AssuranceConnectionError.userCancelled.info.name)
XCTAssertNotNil(AssuranceConnectionError.userCancelled.info.description)
XCTAssertFalse(AssuranceConnectionError.userCancelled.info.shouldRetry)

}
}
Loading

0 comments on commit 63f77fc

Please sign in to comment.