Skip to content

Commit f0f892d

Browse files
Merge pull request #359 from pusher/tech/reduce-string-literals-in-tests
Tests improvements
2 parents 0a5f6c4 + 16def43 commit f0f892d

17 files changed

+579
-930
lines changed

.swiftlint.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,4 @@ identifier_name:
2727

2828
# This generates a compiler error if more than this many SwiftLint warnings are present
2929
# (This threshold can become more restrictive as remaining warnings are resolved via refactoring)
30-
warning_threshold: 13
30+
warning_threshold: 10

PusherSwift.xcodeproj/project.pbxproj

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@
6060
53F08C4825ECEFFD00BDFFB3 /* PusherChannel+EncryptionHelpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53F08C4725ECEFFD00BDFFB3 /* PusherChannel+EncryptionHelpers.swift */; };
6161
57A44493264942B700984790 /* NWWebSocket.xcframework in Frameworks */ = {isa = PBXBuildFile; fileRef = 57A44492264942B700984790 /* NWWebSocket.xcframework */; };
6262
57A44495264942BB00984790 /* TweetNacl.xcframework in Frameworks */ = {isa = PBXBuildFile; fileRef = 57A44494264942BB00984790 /* TweetNacl.xcframework */; };
63+
57F6E444269C5A2E00ECFAD4 /* TestObjects.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57F6E443269C5A2E00ECFAD4 /* TestObjects.swift */; };
6364
736E53F5242A378B0052CC1B /* String+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 736E53F3242A35D90052CC1B /* String+Extensions.swift */; };
6465
736E53F7242A45AC0052CC1B /* XCTest+Assertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 736E53F6242A45AC0052CC1B /* XCTest+Assertions.swift */; };
6566
E2498293231E612700CFBBD6 /* PusherError.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2498292231E612700CFBBD6 /* PusherError.swift */; };
@@ -140,6 +141,7 @@
140141
53F08C4725ECEFFD00BDFFB3 /* PusherChannel+EncryptionHelpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PusherChannel+EncryptionHelpers.swift"; sourceTree = "<group>"; };
141142
57A44492264942B700984790 /* NWWebSocket.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = NWWebSocket.xcframework; path = Carthage/Build/NWWebSocket.xcframework; sourceTree = "<group>"; };
142143
57A44494264942BB00984790 /* TweetNacl.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = TweetNacl.xcframework; path = Carthage/Build/TweetNacl.xcframework; sourceTree = "<group>"; };
144+
57F6E443269C5A2E00ECFAD4 /* TestObjects.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestObjects.swift; sourceTree = "<group>"; };
143145
736E53F3242A35D90052CC1B /* String+Extensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "String+Extensions.swift"; sourceTree = "<group>"; };
144146
736E53F6242A45AC0052CC1B /* XCTest+Assertions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "XCTest+Assertions.swift"; sourceTree = "<group>"; };
145147
73D8A22C2435F381001FDE05 /* ChannelEventFactory+DecryptionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ChannelEventFactory+DecryptionTests.swift"; sourceTree = "<group>"; };
@@ -332,6 +334,7 @@
332334
children = (
333335
33BB995F1D21226C00B25C2A /* Helpers.swift */,
334336
33BB99601D21226C00B25C2A /* Mocks.swift */,
337+
57F6E443269C5A2E00ECFAD4 /* TestObjects.swift */,
335338
);
336339
path = Helpers;
337340
sourceTree = "<group>";
@@ -626,6 +629,7 @@
626629
33BB99771D21230100B25C2A /* PresenceChannelTests.swift in Sources */,
627630
33BB997C1D21230100B25C2A /* PusherTopLevelAPITests.swift in Sources */,
628631
736E53F7242A45AC0052CC1B /* XCTest+Assertions.swift in Sources */,
632+
57F6E444269C5A2E00ECFAD4 /* TestObjects.swift in Sources */,
629633
E2594CE42447753200E36300 /* ChannelEventQueueTests.swift in Sources */,
630634
33BB997B1D21230100B25C2A /* PusherIncomingEventHandlingTests.swift in Sources */,
631635
3342F3BD1D808AC900C0296E /* ClientEventTests.swift in Sources */,

Sources/Models/Constants.swift

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,13 @@ enum Constants {
4343
static let auth = "auth"
4444
static let channel = "channel"
4545
static let channelData = "channel_data"
46+
static let ciphertext = "ciphertext"
4647
static let code = "code"
4748
static let data = "data"
4849
static let event = "event"
4950
static let hash = "hash"
5051
static let message = "message"
52+
static let nonce = "nonce"
5153
static let presence = "presence"
5254
static let socketId = "socket_id"
5355
static let sharedSecret = "shared_secret"

Tests/Helpers/TestObjects.swift

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
import Foundation
2+
@testable import PusherSwift
3+
4+
// swiftlint:disable nesting
5+
6+
struct TestObjects {
7+
8+
struct Event {
9+
10+
struct Data {
11+
12+
static let validDecryptionKey = "EOWC/ked3NtBDvEs9gFwk7x4oZEbH9I0Lz2qkopBxxs="
13+
14+
static let badDecryptionKey = "00000000000000000000000000000000000000000000"
15+
16+
// MARK: Valid payloads
17+
18+
/// Encrypted form of: `{ "message": "hello world" }`
19+
static let encryptedJSONOne = """
20+
{
21+
"\(Constants.JSONKeys.nonce)": "4sVYwy4j/8dCcjyxtPCWyk19GaaViaW9",
22+
"\(Constants.JSONKeys.ciphertext)": "/GMESnFGlbNn01BuBjp31XYa3i9vZsGKR8fgR9EDhXKx3lzGiUD501A="
23+
}
24+
"""
25+
26+
/// `{ "message": "hello world" }`
27+
static let decryptedJSONOne = "{\"message\":\"hello world\"}"
28+
29+
/// Encrypted form of: `{ "name": "freddy", "message": "hello" }`
30+
static let encryptedJSONTwo = """
31+
{
32+
"\(Constants.JSONKeys.nonce)": "Ew2lLeGzSefk8fyVPbwL1yV+8HMyIBrm",
33+
"\(Constants.JSONKeys.ciphertext)": "ig9HfL7OKJ9TL97WFRG0xpuk9w0DXUJhLQlQbGf+ID9S3h15vb/fgDfsnsGxQNQDxw+i"
34+
}
35+
"""
36+
37+
/// `{ "name": "freddy", "message": "hello" }`
38+
static let decryptedJSONTwo = """
39+
{
40+
"name": "freddy",
41+
"message": "hello"
42+
}
43+
"""
44+
45+
/// `{ "test": "test_string", "and": "another" }`
46+
static let unencryptedJSON = """
47+
{
48+
"test": "test_string",
49+
"and": "another"
50+
}
51+
"""
52+
53+
// MARK: Invalid payloads
54+
55+
static let undecryptableJSON = """
56+
{
57+
"\(Constants.JSONKeys.nonce)": "7w2hU5r5VMj3PGXXepgP6E/KgPob5o6t",
58+
"\(Constants.JSONKeys.ciphertext)": "FX0lJZu33f0dWPb89816ngn0l9NfJC5mFny6EQF6z25K+Ly5LFS9hP7XAC6s5pUoZqGXzC03FA=="
59+
}
60+
"""
61+
62+
static let missingNonceJSON = """
63+
{
64+
"\(Constants.JSONKeys.ciphertext)": "ig9HfL7OKJ9TL97WFRG0xpuk9w0DXUJhLQlQbGf+ID9S3h15vb/fgDfsnsGxQNQDxw+i"
65+
}
66+
"""
67+
68+
static let missingCiphertextJSON = """
69+
{
70+
"\(Constants.JSONKeys.nonce)": "Ew2lLeGzSefk8fyVPbwL1yV+8HMyIBrm"
71+
}
72+
"""
73+
74+
static let badNonceJSON = """
75+
{
76+
"\(Constants.JSONKeys.nonce)": "00000000000000000000000000000000",
77+
"\(Constants.JSONKeys.ciphertext)": "ig9HfL7OKJ9TL97WFRG0xpuk9w0DXUJhLQlQbGf+ID9S3h15vb/fgDfsnsGxQNQDxw+i"
78+
}
79+
"""
80+
81+
static let badCiphertextJSON = """
82+
{
83+
"\(Constants.JSONKeys.nonce)": "Ew2lLeGzSefk8fyVPbwL1yV+8HMyIBrm",
84+
"\(Constants.JSONKeys.ciphertext)": "00000000000000000000000000000000000000000000000000000000000000000000"
85+
}
86+
"""
87+
}
88+
89+
static let clientEventName = "client-test-event"
90+
static let encryptedChannelName = "private-encrypted-channel"
91+
static let presenceChannelName = "presence-channel"
92+
static let privateChannelName = "private-channel"
93+
static let testChannelName = "test-channel"
94+
static let testEventName = "test-event"
95+
static let userEventName = "user-event"
96+
97+
static func withJSON(name: String = testEventName,
98+
channel: String = testChannelName,
99+
data: String = Data.unencryptedJSON,
100+
customKeyValuePair: (key: String, value: Any)? = nil) -> String {
101+
102+
if let customKeyValuePair = customKeyValuePair {
103+
104+
var customValue: Any!
105+
if customKeyValuePair.value is String {
106+
customValue = (customKeyValuePair.value as! String).escaped
107+
} else if customKeyValuePair.value is NSNull {
108+
customValue = "null"
109+
} else if customKeyValuePair.value is [String: Any],
110+
let jsonStringData = try? JSONSerialization.data(withJSONObject: customKeyValuePair.value,
111+
options: []),
112+
let jsonString = String(data: jsonStringData, encoding: .utf8) {
113+
customValue = jsonString
114+
} else {
115+
customValue = customKeyValuePair.value
116+
}
117+
118+
return """
119+
{
120+
"\(Constants.JSONKeys.event)": "\(name)",
121+
"\(Constants.JSONKeys.channel)": "\(channel)",
122+
"\(Constants.JSONKeys.data)": \(data.removing(.whitespacesAndNewlines).escaped),
123+
\(customKeyValuePair.key.escaped): \(customValue!)
124+
}
125+
"""
126+
} else {
127+
128+
return """
129+
{
130+
"\(Constants.JSONKeys.event)": "\(name)",
131+
"\(Constants.JSONKeys.channel)": "\(channel)",
132+
"\(Constants.JSONKeys.data)": \(data.removing(.whitespacesAndNewlines).escaped)
133+
}
134+
"""
135+
}
136+
}
137+
138+
static let withoutChannelNameJSON = """
139+
{
140+
"\(Constants.JSONKeys.event)": "\(testEventName)",
141+
"\(Constants.JSONKeys.data)": \(Data.unencryptedJSON.removing(.whitespacesAndNewlines).escaped)
142+
}
143+
"""
144+
145+
static let withoutEventNameJSON = """
146+
{
147+
"\(Constants.JSONKeys.channel)": "\(testChannelName)",
148+
"\(Constants.JSONKeys.data)": \(Data.unencryptedJSON.removing(.whitespacesAndNewlines).escaped)
149+
}
150+
"""
151+
152+
static let withoutEventOrChannelNameJSON = """
153+
{
154+
"\(Constants.JSONKeys.data)": \(Data.unencryptedJSON.removing(.whitespacesAndNewlines).escaped)
155+
}
156+
"""
157+
}
158+
}

Tests/Integration/AuthenticationTests.swift

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ class AuthenticationTests: XCTestCase {
1919
private var pusher: Pusher!
2020
private var socket: MockWebSocket!
2121

22+
private let authJSONData = "{\"\(Constants.JSONKeys.auth)\":\"testKey123:12345678gfder78ikjbg\"}".data(using: .utf8)!
23+
2224
override func setUp() {
2325
super.setUp()
2426

@@ -42,9 +44,8 @@ class AuthenticationTests: XCTestCase {
4244
pusher.delegate = dummyDelegate
4345

4446
if case .endpoint(authEndpoint: let authEndpoint) = pusher.connection.options.authMethod {
45-
let jsonData = "{\"auth\":\"testKey123:12345678gfder78ikjbg\"}".data(using: String.Encoding.utf8, allowLossyConversion: false)!
4647
let urlResponse = HTTPURLResponse(url: URL(string: "\(authEndpoint)?channel_name=private-test-channel&socket_id=45481.3166671")!, statusCode: 200, httpVersion: nil, headerFields: nil)
47-
MockSession.mockResponse = (jsonData, urlResponse: urlResponse, error: nil)
48+
MockSession.mockResponse = (authJSONData, urlResponse: urlResponse, error: nil)
4849
pusher.connection.URLSession = MockSession.shared
4950
}
5051

@@ -65,9 +66,8 @@ class AuthenticationTests: XCTestCase {
6566
pusher.delegate = dummyDelegate
6667

6768
if case .endpoint(authEndpoint: let authEndpoint) = pusher.connection.options.authMethod {
68-
let jsonData = "{\"auth\":\"testKey123:12345678gfder78ikjbg\"}".data(using: String.Encoding.utf8, allowLossyConversion: false)!
6969
let urlResponse = HTTPURLResponse(url: URL(string: "\(authEndpoint)?channel_name=private-reservations-for-venue%40venue_id%3D399ccd2d-3f4a-43c9-803c-9e4b6bdf0f16%3Bdate%3D2017-01-13&socket_id=45481.3166671")!, statusCode: 200, httpVersion: nil, headerFields: nil)
70-
MockSession.mockResponse = (jsonData, urlResponse: urlResponse, error: nil)
70+
MockSession.mockResponse = (authJSONData, urlResponse: urlResponse, error: nil)
7171
pusher.connection.URLSession = MockSession.shared
7272
}
7373

@@ -91,7 +91,7 @@ class AuthenticationTests: XCTestCase {
9191
XCTAssertFalse(chan.subscribed, "the channel should not be subscribed")
9292

9393
let ex = expectation(description: "subscription succeed")
94-
chan.bind(eventName: "pusher:subscription_succeeded") { (_: PusherEvent) in
94+
chan.bind(eventName: Constants.Events.Pusher.subscriptionSucceeded) { (_: PusherEvent) in
9595
ex.fulfill()
9696
XCTAssertTrue(chan.subscribed, "the channel should be subscribed")
9797
}
@@ -126,7 +126,7 @@ class AuthenticationTests: XCTestCase {
126126
XCTAssertFalse(chan.subscribed, "the channel should not be subscribed")
127127

128128
pusher.bind { event in
129-
XCTAssertEqual(event.eventName, "pusher:subscription_error")
129+
XCTAssertEqual(event.eventName, Constants.Events.Pusher.subscriptionError)
130130
XCTAssertEqual(event.channelName, "private-test-channel")
131131
XCTAssertTrue(Thread.isMainThread)
132132
ex.fulfill()
@@ -143,7 +143,7 @@ class AuthenticationTests: XCTestCase {
143143
func requestFor(socketID: String, channelName: String) -> URLRequest? {
144144
var request = URLRequest(url: URL(string: "http://localhost:9292/builder")!)
145145
request.httpMethod = "POST"
146-
request.httpBody = "socket_id=\(socketID)&channel_name=\(channelName)".data(using: String.Encoding.utf8)
146+
request.httpBody = "socket_id=\(socketID)&channel_name=\(channelName)".data(using: .utf8)
147147
request.addValue("myToken", forHTTPHeaderField: "Authorization")
148148
return request
149149
}
@@ -165,9 +165,8 @@ class AuthenticationTests: XCTestCase {
165165
socket.delegate = pusher.connection
166166
pusher.connection.socket = socket
167167

168-
let jsonData = "{\"auth\":\"testKey123:12345678gfder78ikjbg\"}".data(using: String.Encoding.utf8, allowLossyConversion: false)!
169168
let urlResponse = HTTPURLResponse(url: URL(string: "http://localhost:9292/builder?channel_name=private-test-channel&socket_id=45481.3166671")!, statusCode: 200, httpVersion: nil, headerFields: nil)
170-
MockSession.mockResponse = (jsonData, urlResponse: urlResponse, error: nil)
169+
MockSession.mockResponse = (authJSONData, urlResponse: urlResponse, error: nil)
171170
pusher.connection.URLSession = MockSession.shared
172171

173172
let chan = pusher.subscribe("private-test-channel")
@@ -206,7 +205,7 @@ class AuthenticationTests: XCTestCase {
206205
channelName,
207206
auth: PusherAuth(
208207
auth: "testKey123:12345678gfder78ikjbgmanualauth",
209-
channelData: "{\"user_id\":16,\"user_info\":{\"time\":\"2017-02-20 14:54:36 +0000\"}}"
208+
channelData: "{\"\(Constants.JSONKeys.userId)\":16,\"\(Constants.JSONKeys.userInfo)\":{\"time\":\"2017-02-20 14:54:36 +0000\"}}"
210209
)
211210
)
212211
XCTAssertFalse(chan.subscribed, "the channel should not be subscribed")
@@ -252,7 +251,7 @@ class AuthenticationTests: XCTestCase {
252251
func fetchAuthValue(socketID: String, channelName: String, completionHandler: @escaping (PusherAuth?) -> Void) {
253252
completionHandler(PusherAuth(
254253
auth: "testKey123:authorizerblah1234",
255-
channelData: "{\"user_id\":\"777\", \"user_info\":{\"twitter\":\"hamchapman\"}}"
254+
channelData: "{\"\(Constants.JSONKeys.userId)\":\"777\", \"\(Constants.JSONKeys.userInfo)\":{\"twitter\":\"hamchapman\"}}"
256255
))
257256
}
258257
}

0 commit comments

Comments
 (0)