Skip to content

Commit

Permalink
Merge pull request #19 from particle-iot/feature/get_10percent_test_c…
Browse files Browse the repository at this point in the history
…overage

Feature/get 10percent test coverage
  • Loading branch information
RaimundasSakalauskas authored Jan 10, 2020
2 parents 1c33b12 + 966b033 commit 01a5886
Show file tree
Hide file tree
Showing 13 changed files with 478 additions and 140 deletions.
92 changes: 83 additions & 9 deletions ParticleSDK.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions ParticleSDK/SDK/ParticleCloud.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
#import "ParticleNetwork.h"
#import "ParticlePricingInfo.h"
#import "ParticleSimInfo.h"
#import "ParticleSession.h"

NS_ASSUME_NONNULL_BEGIN

Expand Down
1 change: 1 addition & 0 deletions ParticleSDK/SDK/ParticleSession.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
// limitations under the License.

#import <Foundation/Foundation.h>
#import "KeychainHelper.h"

NS_ASSUME_NONNULL_BEGIN

Expand Down
1 change: 0 additions & 1 deletion ParticleSDK/SDK/ParticleSession.m
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

#import "ParticleSession.h"
#import "ParticleCloud.h"
#import "KeychainHelper.h"

NS_ASSUME_NONNULL_BEGIN

Expand Down
69 changes: 69 additions & 0 deletions ParticleSDKTests/Cases/Helpers/KeychainHelperTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
//
// KeychainHelperTests.swift
// ParticleSDKTests
//
// Created by Raimundas Sakalauskas on 13/12/2019.
// Copyright © 2019 Particle Inc. All rights reserved.
//

import XCTest
@testable import ParticleSDK


class KeychainHelperTests: XCTestCase {

var key:String!
var expectedValue:String!
var expectedValue2:String!

override func setUp() {
key = self.randomString(withLength: 20)
expectedValue = self.randomString(withLength: 20)
expectedValue2 = self.randomString(withLength: 20)
}

override func tearDown() {
KeychainHelper.resetKeychainValue(forKey: key)
}

func test_keychainValueNotSet_valueIsNil(){
XCTAssertNil(KeychainHelper.keychainValue(forKey: key))
}

func test_keychainValueSet_valueNotNil() {
KeychainHelper.setKeychainValue(expectedValue, forKey: key)
XCTAssertNotNil(KeychainHelper.keychainValue(forKey: key))
}

func test_keychainValueSet_valueIsSet() {
KeychainHelper.setKeychainValue(expectedValue, forKey: key)
XCTAssertEqual(KeychainHelper.keychainValue(forKey: key)!, expectedValue)
}

func test_keychainValueOverwritten_valueIsSet() {
KeychainHelper.setKeychainValue(expectedValue, forKey: key)

KeychainHelper.setKeychainValue(expectedValue2, forKey: key)
XCTAssertEqual(KeychainHelper.keychainValue(forKey: key)!, expectedValue2)
}

func test_keychainValueReset_valueIsNil() {
KeychainHelper.setKeychainValue(expectedValue, forKey: key)
XCTAssertNotNil(KeychainHelper.keychainValue(forKey: key))

KeychainHelper.resetKeychainValue(forKey: key)
XCTAssertNil(KeychainHelper.keychainValue(forKey: key))
}

let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

func randomString(withLength len: Int) -> String {
var randomString = ""

for _ in 0 ..< len {
randomString.append(letters.randomElement()!)
}

return randomString
}
}
83 changes: 83 additions & 0 deletions ParticleSDKTests/Cases/Helpers/ParticleErrorHelperTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
//
// ParticleErrorHelperTests.swift
// ParticleSDKTests
//
// Created by Raimundas Sakalauskas on 13/12/2019.
// Copyright © 2019 Particle Inc. All rights reserved.
//

import XCTest
@testable import ParticleSDK

class ParticleErrorHelperTests: XCTestCase {

func test_errorDescriptionSet_PrioritizedOverError() {
let json = "{ \"error\" : \"error1\", \"error_description\": \"error2\" }"
let expectedMessage = "error2"

let message = ParticleErrorHelper.getErrorMessage(getJSONDict(withJSONString: json))
XCTAssertEqual(message, expectedMessage)
}

func test_errorSet_parsedCorrectly() {
let json = "{ \"error\" : \"error1\" }"
let expectedMessage = "error1"

let message = ParticleErrorHelper.getErrorMessage(getJSONDict(withJSONString: json))
XCTAssertEqual(message, expectedMessage)
}

func test_errSet_parsedCorrectly() {
let json = "{ \"err\" : \"error1\" }"
let expectedMessage = "error1"

let message = ParticleErrorHelper.getErrorMessage(getJSONDict(withJSONString: json))
XCTAssertEqual(message, expectedMessage)
}

func test_infoSet_parsedCorrectly() {
let json = "{ \"info\" : \"error1\" }"
let expectedMessage = "error1"

let message = ParticleErrorHelper.getErrorMessage(getJSONDict(withJSONString: json))
XCTAssertEqual(message, expectedMessage)
}

func test_multipleErrorsSet_parsedCorrectly() {
let json = "{ \"errors\" : [ \"error1\", \"error2\" ] }"
let expectedMessage = "error1\r\nerror2"

let message = ParticleErrorHelper.getErrorMessage(getJSONDict(withJSONString: json))
XCTAssertEqual(message, expectedMessage)
}

func test_errorDictionarySet_parsedCorrectly() {
let json = "{ \"errors\" : [ {\"error\" : \"error1\"}, {\"error\" : \"error2\"} ] }"
let expectedMessage = "error1\r\nerror2"

let message = ParticleErrorHelper.getErrorMessage(getJSONDict(withJSONString: json))
XCTAssertEqual(message, expectedMessage)
}

func test_errorAndStatusDictionarySet_parsedCorrectly() {
let json = "{ \"errors\" : [ {\"error\" : { \"status\" : \"error1\"} }, {\"error\" : { \"status\" : \"error2\"} } ] }"
let expectedMessage = "error1\r\nerror2"

let message = ParticleErrorHelper.getErrorMessage(getJSONDict(withJSONString: json))
XCTAssertEqual(message, expectedMessage)
}

func test_noErrorSet_templateErrorReturned() {
let json = "{ }"
let expectedMessage = "Unknown error occurred."

let message = ParticleErrorHelper.getErrorMessage(getJSONDict(withJSONString: json))
XCTAssertEqual(message, expectedMessage)
}


func getJSONDict(withJSONString inputString: String) -> [AnyHashable: Any] {
let data = inputString.data(using: .utf8)!
return try! JSONSerialization.jsonObject(with: data, options: []) as! [AnyHashable: Any]
}
}
127 changes: 127 additions & 0 deletions ParticleSDKTests/Cases/SDK/ParticleCloudTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
//
// ParticleCloudTests.swift
// ParticleSDKTests
//
// Created by Raimundas Sakalauskas on 10/12/2019.
// Copyright © 2019 Particle Inc. All rights reserved.
//

import XCTest
@testable import ParticleSDK
import OHHTTPStubs

class ParticleCloudTests: XCTestCase {

private var sut: ParticleCloud!

override func setUp() {
sut = ParticleCloud.sharedInstance()
}

override func tearDown() {
sut = nil
OHHTTPStubs.removeAllStubs()
}

func test_whenInitialized_baseURLNotNil() {
XCTAssertNotNil(sut.currentBaseURL)
}

let expectedAccessToken: String = "some+access+token"
let expectedTokenType: String = "bearer"
let expectedExpiresIn: String = "6000"
let expectedRefreshToken: String = "some+refresh+token"

let expectedClaimCode: String = "some+claim+code"
let expectedDevice1: String = "some+device+id1"
let expectedDevice2: String = "some+device+id2"

func setupAccessTokenDict() -> Dictionary<String,Any> {
let string = """
{
"token_type": "\(expectedTokenType)",
"access_token": "\(expectedAccessToken)",
"expires_in": \(expectedExpiresIn),
"refresh_token": "\(expectedRefreshToken)"
}
"""
let data = string.data(using: .utf8)!
return try! JSONSerialization.jsonObject(with: data, options : .allowFragments) as! Dictionary<String,Any>
}

func setupClaimCodeDict() -> Dictionary<String, Any> {
let string = """
{
"claim_code": "\(expectedClaimCode)",
"device_ids": [
"\(expectedDevice1)",
"\(expectedDevice2)"
]
}
"""
let data = string.data(using: .utf8)!
return try! JSONSerialization.jsonObject(with: data, options : .allowFragments) as! Dictionary<String,Any>
}

func test_generateAccessToken_notNil() {
let json = setupAccessTokenDict()
stub(condition: isPath("/oauth/token")) {
_ -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(jsonObject: json as Any, statusCode: 200, headers: nil)
}

let expected = expectation(description: "Login endpoint returns request")
sut.login(withUser: "user", password: "password") { (error) in
expected.fulfill()
}

wait(for: [expected], timeout: 1)
XCTAssertEqual(sut.accessToken, self.expectedAccessToken)
}


func test_generateClaimCode_notNil() {
let json = setupClaimCodeDict()
stub(condition: isPath("/v1/device_claims")) {
_ -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(jsonObject: json as Any, statusCode: 200, headers: nil)
}

let expected = expectation(description: "Generate claim code endpoint returns request")


var generatedClaimCode: String!
var receivedDevices: [String]!
sut.generateClaimCode { claimCode, devices, error in
generatedClaimCode = claimCode
receivedDevices = devices as? [String]
expected.fulfill()
}
wait(for: [expected], timeout: 1)
XCTAssertEqual(generatedClaimCode, self.expectedClaimCode)
}

func test_generateClaimCode_deviceIdsAreCorrect() {
let json = setupClaimCodeDict()
stub(condition: isPath("/v1/device_claims")) {
_ -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(jsonObject: json as Any, statusCode: 200, headers: nil)
}

let expected = expectation(description: "Generate claim code endpoint returns request")


var generatedClaimCode: String!
var receivedDevices: [String]!
sut.generateClaimCode { claimCode, devices, error in
generatedClaimCode = claimCode
receivedDevices = devices as? [String]
expected.fulfill()
}
wait(for: [expected], timeout: 1)
XCTAssertTrue(receivedDevices.contains(self.expectedDevice1))
XCTAssertTrue(receivedDevices.contains(self.expectedDevice2))
}


}
87 changes: 87 additions & 0 deletions ParticleSDKTests/Cases/SDK/ParticleSessionTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
//
// ParticleSessionTests.swift
// ParticleSDKTests
//
// Created by Raimundas Sakalauskas on 11/12/2019.
// Copyright © 2019 Particle Inc. All rights reserved.
//

import XCTest
@testable import ParticleSDK

class ParticleSessionTests: XCTestCase {

let expectedAccessToken: String = "some+access+token"
let expectedRefreshToken: String = "some+refresh+token"

func setupCorrectDict() -> Dictionary<String,Any> {
let string = """
{
"token_type": "bearer",
"expires_in": 6000,
"access_token": "\(expectedAccessToken)",
"refresh_token": "\(expectedRefreshToken)"
}
"""
let data = string.data(using: .utf8)!
return try! JSONSerialization.jsonObject(with: data, options : .allowFragments) as! Dictionary<String,Any>
}

func test_initWithDict_sessionNotNil(){
let dict = setupCorrectDict()
let sut = ParticleSession(newSession: dict)

XCTAssertNotNil(sut)
}

func test_initWithoutBearer_sessionNil() {
var dict = setupCorrectDict()
dict["token_type"] = nil

let sut = ParticleSession(newSession: dict)

XCTAssertNil(sut)
}

func test_initWithoutExpiresIn_sessionNil() {
var dict = setupCorrectDict()
dict["expires_in"] = nil

let sut = ParticleSession(newSession: dict)

XCTAssertNil(sut)
}

func test_initWithDict_allButUsernameValuesAreNotNil(){
let dict = setupCorrectDict()
let sut = ParticleSession(newSession: dict)

XCTAssertNotNil(sut?.accessToken)
XCTAssertNotNil(sut?.refreshToken)
XCTAssertNil(sut?.username)
}

func test_initWithDict_valuesAsExpected() {
let dict = setupCorrectDict()
let sut = ParticleSession(newSession: dict)

XCTAssertEqual(sut?.accessToken, expectedAccessToken)
XCTAssertEqual(sut?.refreshToken, expectedRefreshToken)
}


func test_initWithToken_sessionNotNil() {
let sut = ParticleSession(token: expectedAccessToken)

XCTAssertNotNil(sut)
}

func test_initWithToken_valuesAreSet(){
let sut = ParticleSession(token: expectedAccessToken)

XCTAssertEqual(sut?.accessToken, expectedAccessToken)
XCTAssertNil(sut?.refreshToken)
XCTAssertNil(sut?.username)
}

}
Loading

0 comments on commit 01a5886

Please sign in to comment.