-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathRestClientTests.swift
2171 lines (1840 loc) · 98.2 KB
/
RestClientTests.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Ably
import Nimble
import XCTest
private var testHTTPExecutor: TestProxyHTTPExecutor!
private func testOptionsGiveBasicAuthFalse(_ caseSetter: (ARTAuthOptions) -> Void) {
let options = ARTClientOptions()
caseSetter(options)
let client = ARTRest(options: options)
XCTAssertFalse(client.auth.internal.options.isBasicAuth())
}
private let expectedHostOrder = [4, 3, 0, 2, 1]
private let shuffleArrayInExpectedHostOrder = { (array: NSMutableArray) in
let arranged = expectedHostOrder.reversed().map { array[$0] }
for (i, element) in arranged.enumerated() {
array[i] = element
}
}
private let _fallbackHosts = ["f.ably-realtime.com", "g.ably-realtime.com", "h.ably-realtime.com", "i.ably-realtime.com", "j.ably-realtime.com"]
private func testUsesAlternativeHost(_ caseTest: FakeNetworkResponse, channelName: String) {
let options = ARTClientOptions(key: "xxxx:xxxx")
let client = ARTRest(options: options)
let internalLog = InternalLog(clientOptions: options)
let mockHTTP = MockHTTP(logger: internalLog)
testHTTPExecutor = TestProxyHTTPExecutor(http: mockHTTP, logger: internalLog)
client.internal.httpExecutor = testHTTPExecutor
mockHTTP.setNetworkState(network: caseTest, resetAfter: 1)
let channel = client.channels.get(channelName)
waitUntil(timeout: testTimeout) { done in
channel.publish(nil, data: "nil") { _ in
done()
}
}
XCTAssertEqual(testHTTPExecutor.requests.count, 2)
if testHTTPExecutor.requests.count != 2 {
return
}
XCTAssertTrue(NSRegularExpression.match(testHTTPExecutor.requests[0].url!.absoluteString, pattern: "//rest.ably.io"))
XCTAssertTrue(NSRegularExpression.match(testHTTPExecutor.requests[1].url!.absoluteString, pattern: "//[a-e].ably-realtime.com"))
}
private func testStoresSuccessfulFallbackHostAsDefaultHost(_ caseTest: FakeNetworkResponse, channelName: String) {
let options = ARTClientOptions(key: "xxxx:xxxx")
let client = ARTRest(options: options)
let internalLog = InternalLog(clientOptions: options)
let mockHTTP = MockHTTP(logger: internalLog)
testHTTPExecutor = TestProxyHTTPExecutor(http: mockHTTP, logger: internalLog)
client.internal.httpExecutor = testHTTPExecutor
mockHTTP.setNetworkState(network: caseTest, resetAfter: 1)
let channel = client.channels.get(channelName)
waitUntil(timeout: testTimeout) { done in
channel.publish(nil, data: "nil") { _ in
done()
}
}
XCTAssertEqual(testHTTPExecutor.requests.count, 2)
XCTAssertTrue(NSRegularExpression.match(testHTTPExecutor.requests[0].url!.host, pattern: "rest.ably.io"))
XCTAssertTrue(NSRegularExpression.match(testHTTPExecutor.requests[1].url!.host, pattern: "[a-e].ably-realtime.com"))
// #1 Store fallback used to request
let usedFallbackURL = testHTTPExecutor.requests[1].url!
waitUntil(timeout: testTimeout) { done in
channel.publish(nil, data: "nil") { _ in
done()
}
}
let reusedURL = testHTTPExecutor.requests[2].url!
// Reuse host has to be equal previous (stored #1) fallback host
XCTAssertEqual(testHTTPExecutor.requests.count, 3)
XCTAssertEqual(usedFallbackURL.host, reusedURL.host)
}
private func testRestoresDefaultPrimaryHostAfterTimeoutExpires(_ caseTest: FakeNetworkResponse, channelName: String) {
let options = ARTClientOptions(key: "xxxx:xxxx")
options.logLevel = .debug
options.fallbackRetryTimeout = 1
let client = ARTRest(options: options)
let internalLog = InternalLog(clientOptions: options)
let mockHTTP = MockHTTP(logger: internalLog)
testHTTPExecutor = TestProxyHTTPExecutor(http: mockHTTP, logger: internalLog)
client.internal.httpExecutor = testHTTPExecutor
mockHTTP.setNetworkState(network: caseTest, resetAfter: 1)
let channel = client.channels.get(channelName)
waitUntil(timeout: testTimeout) { done in
channel.publish(nil, data: "nil") { _ in
done()
}
}
waitUntil(timeout: testTimeout) { done in
delay(1.1) {
channel.publish(nil, data: "nil") { _ in
done()
}
}
}
XCTAssertEqual(testHTTPExecutor.requests.count, 3)
XCTAssertEqual(testHTTPExecutor.requests[2].url!.host, "rest.ably.io")
}
private func testUsesAnotherFallbackHost(_ caseTest: FakeNetworkResponse, channelName: String) {
let options = ARTClientOptions(key: "xxxx:xxxx")
options.fallbackRetryTimeout = 10
options.logLevel = .debug
let client = ARTRest(options: options)
let internalLog = InternalLog(clientOptions: options)
let mockHTTP = MockHTTP(logger: internalLog)
testHTTPExecutor = TestProxyHTTPExecutor(http: mockHTTP, logger: internalLog)
client.internal.httpExecutor = testHTTPExecutor
mockHTTP.setNetworkState(network: caseTest, resetAfter: 2)
let channel = client.channels.get(channelName)
waitUntil(timeout: testTimeout) { done in
channel.publish(nil, data: "nil") { _ in
done()
}
}
XCTAssertEqual(testHTTPExecutor.requests.count, 3)
XCTAssertTrue(NSRegularExpression.match(testHTTPExecutor.requests[1].url!.host, pattern: "[a-e].ably-realtime.com"))
XCTAssertTrue(NSRegularExpression.match(testHTTPExecutor.requests[2].url!.host, pattern: "[a-e].ably-realtime.com"))
XCTAssertNotEqual(testHTTPExecutor.requests[1].url!.host, testHTTPExecutor.requests[2].url!.host)
}
class RestClientTests: XCTestCase {
// XCTest invokes this method before executing the first test in the test suite. We use it to ensure that the global variables are initialized at the same moment, and in the same order, as they would have been when we used the Quick testing framework.
override class var defaultTestSuite: XCTestSuite {
_ = testHTTPExecutor
_ = expectedHostOrder
_ = _fallbackHosts
return super.defaultTestSuite
}
// G4
func test__001__RestClient__All_REST_requests_should_include_the_current_API_version() throws {
let test = Test()
let options = try AblyTests.commonAppSetup(for: test)
let client = ARTRest(options: options)
testHTTPExecutor = TestProxyHTTPExecutor(logger: .init(clientOptions: options))
client.internal.httpExecutor = testHTTPExecutor
let channel = client.channels.get(test.uniqueChannelName())
waitUntil(timeout: testTimeout) { done in
channel.publish(nil, data: "message") { error in
XCTAssertNil(error)
let version = testHTTPExecutor.requests.first!.allHTTPHeaderFields?["X-Ably-Version"]
// This test should not directly validate version against ARTDefault.version(), as
// ultimately the version header has been derived from that value.
XCTAssertEqual(version, "1.2")
done()
}
}
}
// RSC1
func test__015__RestClient__initializer__should_accept_an_API_key() throws {
let test = Test()
let options = try AblyTests.commonAppSetup(for: test)
let client = ARTRest(key: options.key!)
client.internal.prioritizedHost = options.restHost
let publishTask = publishTestMessage(client, channelName: test.uniqueChannelName())
expect(publishTask.error).toEventually(beNil(), timeout: testTimeout)
}
func test__016__RestClient__initializer__should_throw_when_provided_an_invalid_key() {
expect { ARTRest(key: "invalid_key") }.to(raiseException())
}
func test__017__RestClient__initializer__should_result_in_error_status_when_provided_a_bad_key() {
let test = Test()
let client = ARTRest(key: "fake:key")
let publishTask = publishTestMessage(client, channelName: test.uniqueChannelName(), failOnError: false)
expect(publishTask.error?.code).toEventually(equal(ARTErrorCode.invalidCredential.intValue), timeout: testTimeout)
}
func test__018__RestClient__initializer__should_accept_a_token() throws {
let test = Test()
ARTClientOptions.setDefaultEnvironment(getEnvironment())
defer { ARTClientOptions.setDefaultEnvironment(nil) }
let client = ARTRest(token: try getTestToken(for: test))
let publishTask = publishTestMessage(client, channelName: test.uniqueChannelName())
expect(publishTask.error).toEventually(beNil(), timeout: testTimeout)
}
func test__019__RestClient__initializer__should_accept_an_options_object() throws {
let test = Test()
let options = try AblyTests.commonAppSetup(for: test)
let client = ARTRest(options: options)
let publishTask = publishTestMessage(client, channelName: test.uniqueChannelName())
expect(publishTask.error).toEventually(beNil(), timeout: testTimeout)
}
func test__020__RestClient__initializer__should_accept_an_options_object_with_token_authentication() throws {
let test = Test()
let options = try AblyTests.clientOptions(for: test, requestToken: true)
let client = ARTRest(options: options)
let publishTask = publishTestMessage(client, channelName: test.uniqueChannelName())
expect(publishTask.error).toEventually(beNil(), timeout: testTimeout)
}
func test__021__RestClient__initializer__should_result_in_error_status_when_provided_a_bad_token() throws {
let test = Test()
let options = try AblyTests.clientOptions(for: test)
options.token = "invalid_token"
let client = ARTRest(options: options)
let publishTask = publishTestMessage(client, channelName: test.uniqueChannelName(), failOnError: false)
expect(publishTask.error?.code).toEventually(equal(ARTErrorCode.invalidCredential.intValue), timeout: testTimeout)
}
// RSC2
func test__022__RestClient__logging__should_output_to_the_system_log_and_the_log_level_should_be_Warn() {
ARTClientOptions.setDefaultEnvironment(getEnvironment())
defer {
ARTClientOptions.setDefaultEnvironment(nil)
}
let options = ARTClientOptions(key: "xxxx:xxxx")
options.logHandler = ARTLog(capturingOutput: true)
let client = ARTRest(options: options)
client.internal.logger_onlyForUseInClassMethodsAndTests.log("This is a warning", with: .warn, file: "foo.m", line: 10)
XCTAssertEqual(client.internal.logger_onlyForUseInClassMethodsAndTests.logLevel, ARTLogLevel.warn)
guard let line = options.logHandler.captured.last else {
fail("didn't log line.")
return
}
XCTAssertEqual(line.level, ARTLogLevel.warn)
XCTAssertEqual(line.toString(), "WARN: (foo.m:10) This is a warning")
}
// RSC3
func test__023__RestClient__logging__should_have_a_mutable_log_level() throws {
let test = Test()
let options = try AblyTests.commonAppSetup(for: test)
options.logHandler = ARTLog(capturingOutput: true)
let client = ARTRest(options: options)
client.internal.logger_onlyForUseInClassMethodsAndTests.logLevel = .error
let logTime = NSDate()
client.internal.logger_onlyForUseInClassMethodsAndTests.log("This is a warning", with: .warn, file: "foo.m", line: 10)
let logs = options.logHandler.captured.filter { !$0.date.isBefore(logTime as Date) }
expect(logs).to(beEmpty())
}
// RSC4
func test__024__RestClient__logging__should_accept_a_custom_logger() throws {
let test = Test()
enum Log {
static var interceptedLog: (String, ARTLogLevel) = ("", .none)
}
class MyLogger: ARTLog {
override func log(_ message: String, with level: ARTLogLevel) {
Log.interceptedLog = (message, level)
}
}
let options = try AblyTests.commonAppSetup(for: test)
let customLogger = MyLogger()
options.logHandler = customLogger
options.logLevel = .verbose
let client = ARTRest(options: options)
client.internal.logger_onlyForUseInClassMethodsAndTests.log("This is a warning", with: .warn, file: "foo.m", line: 10)
XCTAssertEqual(Log.interceptedLog.0, "(foo.m:10) This is a warning")
XCTAssertEqual(Log.interceptedLog.1, ARTLogLevel.warn)
XCTAssertEqual(client.internal.logger_onlyForUseInClassMethodsAndTests.logLevel, customLogger.logLevel)
}
// RSC11
// RSC11a
func test__025__RestClient__endpoint__should_accept_a_custom_host_and_send_requests_to_the_specified_host() {
let test = Test()
let options = ARTClientOptions(key: "fake:key")
options.restHost = "fake.ably.io"
let client = ARTRest(options: options)
testHTTPExecutor = TestProxyHTTPExecutor(logger: .init(clientOptions: options))
client.internal.httpExecutor = testHTTPExecutor
publishTestMessage(client, channelName: test.uniqueChannelName(), failOnError: false)
expect(testHTTPExecutor.requests.first?.url?.host).toEventually(equal("fake.ably.io"), timeout: testTimeout)
}
func test__026__RestClient__endpoint__should_ignore_an_environment_when_restHost_is_customized() {
let test = Test()
let options = ARTClientOptions(key: "fake:key")
options.environment = "test"
options.restHost = "fake.ably.io"
let client = ARTRest(options: options)
testHTTPExecutor = TestProxyHTTPExecutor(logger: .init(clientOptions: options))
client.internal.httpExecutor = testHTTPExecutor
publishTestMessage(client, channelName: test.uniqueChannelName(), failOnError: false)
expect(testHTTPExecutor.requests.first?.url?.host).toEventually(equal("fake.ably.io"), timeout: testTimeout)
}
// RSC11b
func test__027__RestClient__endpoint__should_accept_an_environment_when_restHost_is_left_unchanged() {
let test = Test()
let options = ARTClientOptions(key: "fake:key")
options.environment = "myEnvironment"
let client = ARTRest(options: options)
testHTTPExecutor = TestProxyHTTPExecutor(logger: .init(clientOptions: options))
client.internal.httpExecutor = testHTTPExecutor
publishTestMessage(client, channelName: test.uniqueChannelName(), failOnError: false)
expect(testHTTPExecutor.requests.first?.url?.host).toEventually(equal("myEnvironment-rest.ably.io"), timeout: testTimeout)
}
func test__028__RestClient__endpoint__should_default_to_https___rest_ably_io() {
let test = Test()
let options = ARTClientOptions(key: "fake:key")
let client = ARTRest(options: options)
testHTTPExecutor = TestProxyHTTPExecutor(logger: .init(clientOptions: options))
client.internal.httpExecutor = testHTTPExecutor
publishTestMessage(client, channelName: test.uniqueChannelName(), failOnError: false)
expect(testHTTPExecutor.requests.first?.url?.absoluteString).toEventually(beginWith("https://rest.ably.io"), timeout: testTimeout)
}
func test__029__RestClient__endpoint__should_connect_over_plain_http____when_tls_is_off() throws {
let test = Test()
let options = try AblyTests.clientOptions(for: test, requestToken: true)
options.tls = false
let client = ARTRest(options: options)
testHTTPExecutor = TestProxyHTTPExecutor(logger: .init(clientOptions: options))
client.internal.httpExecutor = testHTTPExecutor
publishTestMessage(client, channelName: test.uniqueChannelName(), failOnError: false)
expect(testHTTPExecutor.requests.first?.url?.scheme).toEventually(equal("http"), timeout: testTimeout)
}
// RSC11b
func test__030__RestClient__endpoint__should_not_prepend_the_environment_if_environment_is_configured_as__production_() {
let options = ARTClientOptions(key: "xxxx:xxxx")
options.environment = "production"
let client = ARTRest(options: options)
XCTAssertEqual(client.internal.options.restHost, ARTDefault.restHost())
XCTAssertEqual(client.internal.options.realtimeHost, ARTDefault.realtimeHost())
}
// RSC13
func test__031__RestClient__should_use_the_the_connection_and_request_timeouts_specified__timeout_for_any_single_HTTP_request_and_response() {
let test = Test()
let options = ARTClientOptions(key: "xxxx:xxxx")
options.restHost = "10.255.255.1" // non-routable IP address
XCTAssertEqual(options.httpRequestTimeout, 10.0) // Seconds
options.httpRequestTimeout = 1.0
let client = ARTRest(options: options)
let channel = client.channels.get(test.uniqueChannelName())
waitUntil(timeout: testTimeout) { done in
let start = NSDate()
channel.publish(nil, data: "message") { error in
let end = NSDate()
expect(end.timeIntervalSince(start as Date)).to(beCloseTo(options.httpRequestTimeout, within: 0.5))
XCTAssertNotNil(error)
if let error = error {
expect(error.code).to(satisfyAnyOf(equal(-1001 /* Timed Out */ ), equal(-1004 /* Cannot Connect To Host */ )))
}
done()
}
}
}
func test__032__RestClient__should_use_the_the_connection_and_request_timeouts_specified__max_number_of_fallback_hosts() {
let test = Test()
let options = ARTClientOptions(key: "xxxx:xxxx")
XCTAssertEqual(options.httpMaxRetryCount, 3)
options.httpMaxRetryCount = 1
let client = ARTRest(options: options)
let internalLog = InternalLog(clientOptions: options)
let mockHTTP = MockHTTP(logger: internalLog)
testHTTPExecutor = TestProxyHTTPExecutor(http: mockHTTP, logger: internalLog)
client.internal.httpExecutor = testHTTPExecutor
mockHTTP.setNetworkState(network: .hostUnreachable)
var totalRetry: UInt = 0
testHTTPExecutor.setListenerAfterRequest { request in
if NSRegularExpression.match(request.url!.absoluteString, pattern: "//[a-e].ably-realtime.com") {
totalRetry += 1
}
}
let channel = client.channels.get(test.uniqueChannelName())
waitUntil(timeout: testTimeout) { done in
channel.publish(nil, data: "nil") { _ in
done()
}
}
XCTAssertEqual(totalRetry, options.httpMaxRetryCount)
}
func test__033__RestClient__should_use_the_the_connection_and_request_timeouts_specified__max_elapsed_time_in_which_fallback_host_retries_for_HTTP_requests_will_be_attempted() {
let test = Test()
let options = ARTClientOptions(key: "xxxx:xxxx")
XCTAssertEqual(options.httpMaxRetryDuration, 15.0) // Seconds
options.httpMaxRetryDuration = 1.0
let client = ARTRest(options: options)
let internalLog = InternalLog(clientOptions: options)
let mockHTTP = MockHTTP(logger: internalLog)
testHTTPExecutor = TestProxyHTTPExecutor(http: mockHTTP, logger: internalLog)
client.internal.httpExecutor = testHTTPExecutor
mockHTTP.setNetworkState(network: .requestTimeout(timeout: 0.1))
let channel = client.channels.get(test.uniqueChannelName())
waitUntil(timeout: testTimeout) { done in
let start = Date()
channel.publish(nil, data: "nil") { _ in
let end = Date()
expect(end.timeIntervalSince(start)).to(beCloseTo(options.httpMaxRetryDuration, within: 0.9))
done()
}
}
}
// RSC5
func test__002__RestClient__should_provide_access_to_the_AuthOptions_object_passed_in_ClientOptions() throws {
let test = Test()
let options = try AblyTests.commonAppSetup(for: test)
let client = ARTRest(options: options)
let authOptions = client.auth.internal.options
XCTAssertTrue(authOptions == options)
}
// RSC12
func test__003__RestClient__REST_endpoint_host_should_be_configurable_in_the_Client_constructor_with_the_option_restHost() throws {
let test = Test()
let options = ARTClientOptions(key: "xxxx:xxxx")
XCTAssertEqual(options.restHost, "rest.ably.io")
options.restHost = "rest.ably.test"
XCTAssertEqual(options.restHost, "rest.ably.test")
let client = ARTRest(options: options)
testHTTPExecutor = TestProxyHTTPExecutor(logger: .init(clientOptions: options))
client.internal.httpExecutor = testHTTPExecutor
waitUntil(timeout: testTimeout) { done in
client.channels.get(test.uniqueChannelName()).publish(nil, data: "message") { error in
XCTAssertNotNil(error)
done()
}
}
let url = try XCTUnwrap(testHTTPExecutor.requests.first?.url, "No request url found")
expect(url.absoluteString).to(contain("//rest.ably.test"))
}
// RSC16
func test__034__RestClient__time__should_return_server_time() throws {
let test = Test()
let options = try AblyTests.commonAppSetup(for: test)
let client = ARTRest(options: options)
var time: NSDate?
client.time { date, _ in
time = date as NSDate? as NSDate?
}
expect(time?.timeIntervalSince1970).toEventually(beCloseTo(NSDate().timeIntervalSince1970, within: 60), timeout: testTimeout)
}
// RSC7, RSC18
func test__004__RestClient__should_send_requests_over_http_and_https() throws {
let test = Test()
let options = try AblyTests.commonAppSetup(for: test)
let clientHttps = ARTRest(options: options)
testHTTPExecutor = TestProxyHTTPExecutor(logger: .init(clientOptions: options))
clientHttps.internal.httpExecutor = testHTTPExecutor
let channelName = test.uniqueChannelName()
waitUntil(timeout: testTimeout) { done in
publishTestMessage(clientHttps, channelName: channelName) { _ in
done()
}
}
let requestUrlA = try XCTUnwrap(testHTTPExecutor.requests.first?.url, "No request url found")
XCTAssertEqual(requestUrlA.scheme, "https")
options.clientId = "client_http"
options.useTokenAuth = true
options.tls = false
let clientHttp = ARTRest(options: options)
testHTTPExecutor = TestProxyHTTPExecutor(logger: .init(clientOptions: options))
clientHttp.internal.httpExecutor = testHTTPExecutor
waitUntil(timeout: testTimeout) { done in
publishTestMessage(clientHttp, channelName: channelName) { _ in
done()
}
}
let requestUrlB = try XCTUnwrap(testHTTPExecutor.requests.last?.url, "No request url found")
XCTAssertEqual(requestUrlB.scheme, "http")
}
// RSC9
func test__005__RestClient__should_use_Auth_to_manage_authentication() throws {
let test = Test()
let options = try AblyTests.clientOptions(for: test)
let testTokenDetails = try getTestTokenDetails(for: test)
options.tokenDetails = testTokenDetails
options.authCallback = { _, completion in
completion(testTokenDetails, nil)
}
let client = ARTRest(options: options)
expect(client.auth).to(beAnInstanceOf(ARTAuth.self))
waitUntil(timeout: testTimeout) { done in
client.auth.authorize(nil, options: nil) { tokenDetails, error in
if let e = error {
XCTFail(e.localizedDescription)
done()
return
}
guard let tokenDetails = tokenDetails else {
XCTFail("expected tokenDetails to not be nil when error is nil")
done()
return
}
XCTAssertEqual(tokenDetails.token, testTokenDetails.token)
done()
}
}
}
// RSC10
func test__006__RestClient__should_request_another_token_after_current_one_is_no_longer_valid() throws {
let test = Test()
let options = try AblyTests.commonAppSetup(for: test)
options.token = try getTestToken(for: test, ttl: 0.5)
let client = ARTRest(options: options)
testHTTPExecutor = TestProxyHTTPExecutor(logger: .init(clientOptions: options))
client.internal.httpExecutor = testHTTPExecutor
let auth = client.auth
waitUntil(timeout: testTimeout) { done in
delay(1.0) {
client.channels.get(test.uniqueChannelName()).history { result, error in
XCTAssertNil(error)
XCTAssertNotNil(result)
guard let headerErrorCode = testHTTPExecutor.responses.first?.value(forHTTPHeaderField: "X-Ably-Errorcode") else {
fail("X-Ably-Errorcode not found"); done()
return
}
XCTAssertEqual(Int(headerErrorCode), ARTErrorCode.tokenExpired.intValue)
// Different token
XCTAssertNotEqual(auth.tokenDetails!.token, options.token)
done()
}
}
}
}
// RSC10
func test__007__RestClient__should_result_in_an_error_when_user_does_not_have_sufficient_permissions() throws {
let test = Test()
let options = try AblyTests.clientOptions(for: test)
options.token = try getTestToken(for: test, capability: "{ \"main\":[\"subscribe\"] }")
let client = ARTRest(options: options)
testHTTPExecutor = TestProxyHTTPExecutor(logger: .init(clientOptions: options))
client.internal.httpExecutor = testHTTPExecutor
waitUntil(timeout: testTimeout) { done in
client.channels.get(test.uniqueChannelName()).history { result, error in
guard let errorCode = error?.code else {
fail("Error is empty"); done()
return
}
XCTAssertEqual(errorCode, ARTErrorCode.operationNotPermittedWithProvidedCapability.intValue)
XCTAssertNil(result)
guard let headerErrorCode = testHTTPExecutor.responses.first?.value(forHTTPHeaderField: "X-Ably-Errorcode") else {
fail("X-Ably-Errorcode not found"); done()
return
}
XCTAssertEqual(Int(headerErrorCode), ARTErrorCode.operationNotPermittedWithProvidedCapability.intValue)
done()
}
}
}
// RSC14
// RSC14a
func test__035__RestClient__Authentication__should_support_basic_authentication_when_an_API_key_is_provided_with_the_key_option() throws {
let test = Test()
let options = try AblyTests.commonAppSetup(for: test)
guard let components = options.key?.components(separatedBy: ":"), let keyName = components.first, let keySecret = components.last else {
fail("Invalid API key: \(options.key ?? "nil")"); return
}
ARTClientOptions.setDefaultEnvironment(getEnvironment())
defer {
ARTClientOptions.setDefaultEnvironment(nil)
}
let rest = ARTRest(key: "\(keyName):\(keySecret)")
waitUntil(timeout: testTimeout) { done in
rest.channels.get(test.uniqueChannelName()).publish(nil, data: "testing") { error in
XCTAssertNil(error)
done()
}
}
}
// RSC14b
func test__038__RestClient__Authentication__basic_authentication_flag__should_be_true_when_initialized_with_a_key() {
let client = ARTRest(key: "key:secret")
XCTAssertTrue(client.auth.internal.options.isBasicAuth())
}
func test__039__RestClient__Authentication__basic_authentication_flag__should_be_false_when_options__useTokenAuth_is_set() {
testOptionsGiveBasicAuthFalse { $0.useTokenAuth = true; $0.key = "fake:key" }
}
func test__040__RestClient__Authentication__basic_authentication_flag__should_be_false_when_options__authUrl_is_set() {
testOptionsGiveBasicAuthFalse { $0.authUrl = URL(string: "http://test.com") }
}
func test__041__RestClient__Authentication__basic_authentication_flag__should_be_false_when_options__authCallback_is_set() {
testOptionsGiveBasicAuthFalse { $0.authCallback = { _, _ in } }
}
func test__042__RestClient__Authentication__basic_authentication_flag__should_be_false_when_options__tokenDetails_is_set() {
testOptionsGiveBasicAuthFalse { $0.tokenDetails = ARTTokenDetails(token: "token") }
}
func test__043__RestClient__Authentication__basic_authentication_flag__should_be_false_when_options__token_is_set() {
testOptionsGiveBasicAuthFalse { $0.token = "token" }
}
func test__044__RestClient__Authentication__basic_authentication_flag__should_be_false_when_options__key_is_set() {
testOptionsGiveBasicAuthFalse { $0.tokenDetails = ARTTokenDetails(token: "token"); $0.key = "fake:key" }
}
// RSC14c
func test__036__RestClient__Authentication__should_error_when_expired_token_and_no_means_to_renew() throws {
let test = Test()
let client = ARTRest(options: try AblyTests.commonAppSetup(for: test))
let auth = client.auth
let tokenParams = ARTTokenParams()
let tokenTtl = 3.0
tokenParams.ttl = NSNumber(value: tokenTtl) // Seconds
let options: ARTClientOptions = try AblyTests.waitFor(timeout: testTimeout) { value in
auth.requestToken(tokenParams, with: nil) { tokenDetails, error in
if let e = error {
XCTFail(e.localizedDescription)
value(nil)
return
}
guard let currentTokenDetails = tokenDetails else {
XCTFail("expected tokenDetails not to be nil when error is nil")
value(nil)
return
}
let options: ARTClientOptions
do {
options = try AblyTests.clientOptions(for: test)
} catch {
XCTFail(error.localizedDescription)
value(nil)
return
}
options.key = client.internal.options.key
// Expired token
options.tokenDetails = ARTTokenDetails(
token: currentTokenDetails.token,
expires: currentTokenDetails.expires!.addingTimeInterval(testTimeout.toTimeInterval()),
issued: currentTokenDetails.issued,
capability: currentTokenDetails.capability,
clientId: currentTokenDetails.clientId
)
options.authUrl = URL(string: "http://test-auth.ably.io")
value(options)
}
}
let rest = ARTRest(options: options)
testHTTPExecutor = TestProxyHTTPExecutor(logger: .init(clientOptions: options))
rest.internal.httpExecutor = testHTTPExecutor
waitUntil(timeout: testTimeout) { done in
// Delay for token expiration
delay(tokenTtl + AblyTests.tokenExpiryTolerance) {
// [40140, 40150) - token expired and will not recover because authUrl is invalid
publishTestMessage(rest, channelName: test.uniqueChannelName()) { error in
guard let errorCode = testHTTPExecutor.responses.first?.value(forHTTPHeaderField: "X-Ably-Errorcode") else {
fail("expected X-Ably-Errorcode header in response")
return
}
expect(Int(errorCode)).to(beGreaterThanOrEqualTo(ARTErrorCode.tokenErrorUnspecified.intValue))
expect(Int(errorCode)).to(beLessThan(ARTErrorCode.connectionLimitsExceeded.intValue))
XCTAssertNotNil(error)
done()
}
}
}
}
// RSC14d
func test__037__RestClient__Authentication__should_renew_the_token_when_it_has_expired() throws {
let test = Test()
let client = ARTRest(options: try AblyTests.commonAppSetup(for: test))
let auth = client.auth
let tokenParams = ARTTokenParams()
let tokenTtl = 3.0
tokenParams.ttl = NSNumber(value: tokenTtl) // Seconds
waitUntil(timeout: testTimeout) { done in
auth.requestToken(tokenParams, with: nil) { tokenDetails, error in
if let e = error {
XCTFail(e.localizedDescription)
done()
return
}
guard let currentTokenDetails = tokenDetails else {
XCTFail("expected tokenDetails not to be nil when error is nil")
done()
return
}
let options: ARTClientOptions
do {
options = try AblyTests.clientOptions(for: test)
} catch {
XCTFail(error.localizedDescription)
done()
return
}
options.key = client.internal.options.key
// Expired token
options.tokenDetails = ARTTokenDetails(
token: currentTokenDetails.token,
expires: currentTokenDetails.expires!.addingTimeInterval(testTimeout.toTimeInterval()),
issued: currentTokenDetails.issued,
capability: currentTokenDetails.capability,
clientId: currentTokenDetails.clientId
)
let rest = ARTRest(options: options)
testHTTPExecutor = TestProxyHTTPExecutor(logger: .init(clientOptions: options))
rest.internal.httpExecutor = testHTTPExecutor
// Delay for token expiration
delay(tokenTtl + AblyTests.tokenExpiryTolerance) {
// [40140, 40150) - token expired and will not recover because authUrl is invalid
publishTestMessage(rest, channelName: test.uniqueChannelName()) { error in
guard let errorCode = testHTTPExecutor.responses.first?.value(forHTTPHeaderField: "X-Ably-Errorcode") else {
fail("expected X-Ably-Errorcode header in response")
return
}
expect(Int(errorCode)).to(beGreaterThanOrEqualTo(ARTErrorCode.tokenErrorUnspecified.intValue))
expect(Int(errorCode)).to(beLessThan(ARTErrorCode.connectionLimitsExceeded.intValue))
XCTAssertNil(error)
XCTAssertNotEqual(rest.auth.tokenDetails!.token, currentTokenDetails.token)
done()
}
}
}
}
}
// RSC15
// TO3k7
@available(*, deprecated, message: "This test is marked as deprecated so as to not trigger a compiler warning for using the -ARTClientOptions.fallbackHostsUseDefault property. Remove this deprecation when removing the property.")
func test__051__RestClient__Host_Fallback__fallbackHostsUseDefault_option__allows_the_default_fallback_hosts_to_be_used_when__environment__is_not_production() {
let options = ARTClientOptions(key: "xxxx:xxxx")
options.environment = "not-production"
options.fallbackHostsUseDefault = true
let client = ARTRest(options: options)
XCTAssertTrue(client.internal.options.fallbackHostsUseDefault)
// Not production
XCTAssertNotNil(client.internal.options.environment)
XCTAssertNotEqual(client.internal.options.environment, "production")
let hosts = ARTFallbackHosts.hosts(from: client.internal.options)
let fallback = ARTFallback(fallbackHosts: hosts, shuffleArray: ARTFallback_shuffleArray)
XCTAssertEqual(fallback.hosts.count, ARTDefault.fallbackHosts().count)
ARTDefault.fallbackHosts().forEach {
expect(fallback.hosts).to(contain($0))
}
}
@available(*, deprecated, message: "This test is marked as deprecated so as to not trigger a compiler warning for using the -ARTClientOptions.fallbackHostsUseDefault property. Remove this deprecation when removing the property.")
func test__052__RestClient__Host_Fallback__fallbackHostsUseDefault_option__allows_the_default_fallback_hosts_to_be_used_when_a_custom_Realtime_or_REST_host_endpoint_is_being_used() {
let options = ARTClientOptions(key: "xxxx:xxxx")
options.restHost = "fake1.ably.io"
options.realtimeHost = "fake2.ably.io"
options.fallbackHostsUseDefault = true
let client = ARTRest(options: options)
XCTAssertTrue(client.internal.options.fallbackHostsUseDefault)
// Custom
XCTAssertNotEqual(client.internal.options.restHost, ARTDefault.restHost())
XCTAssertNotEqual(client.internal.options.realtimeHost, ARTDefault.realtimeHost())
let hosts = ARTFallbackHosts.hosts(from: client.internal.options)
let fallback = ARTFallback(fallbackHosts: hosts, shuffleArray: ARTFallback_shuffleArray)
XCTAssertEqual(fallback.hosts.count, ARTDefault.fallbackHosts().count)
ARTDefault.fallbackHosts().forEach {
expect(fallback.hosts).to(contain($0))
}
}
@available(*, deprecated, message: "This test is marked as deprecated so as to not trigger a compiler warning for using the -ARTClientOptions.fallbackHostsUseDefault property. Remove this deprecation when removing the property.")
func test__053__RestClient__Host_Fallback__fallbackHostsUseDefault_option__should_be_inactive_by_default() {
let options = ARTClientOptions(key: "xxxx:xxxx")
XCTAssertFalse(options.fallbackHostsUseDefault)
}
@available(*, deprecated, message: "This test is marked as deprecated so as to not trigger a compiler warning for using the -ARTClientOptions.fallbackHostsUseDefault property. Remove this deprecation when removing the property.")
func test__054__RestClient__Host_Fallback__fallbackHostsUseDefault_option__should_never_accept_to_configure__fallbackHost__and_set__fallbackHostsUseDefault__to__true_() {
let options = ARTClientOptions(key: "xxxx:xxxx")
XCTAssertNil(options.fallbackHosts)
XCTAssertFalse(options.fallbackHostsUseDefault)
expect { options.fallbackHosts = [] }.toNot(raiseException())
expect { options.fallbackHostsUseDefault = true }.to(raiseException(named: ARTFallbackIncompatibleOptionsException))
options.fallbackHosts = nil
expect { options.fallbackHostsUseDefault = true }.toNot(raiseException())
expect { options.fallbackHosts = ["fake.ably.io"] }.to(raiseException(named: ARTFallbackIncompatibleOptionsException))
}
// RSC15b
// RSC15b1
func test__055__RestClient__Host_Fallback__Fallback_behavior__should_be_applied_when_restHost__port_and_tlsPort_has_not_been_set_to_an_explicit_value() {
let test = Test()
let options = ARTClientOptions(key: "xxxx:xxxx")
let client = ARTRest(options: options)
let internalLog = InternalLog(clientOptions: options)
let mockHTTP = MockHTTP(logger: internalLog)
testHTTPExecutor = TestProxyHTTPExecutor(http: mockHTTP, logger: internalLog)
client.internal.httpExecutor = testHTTPExecutor
mockHTTP.setNetworkState(network: .hostUnreachable, resetAfter: 2)
let channel = client.channels.get(test.uniqueChannelName())
waitUntil(timeout: testTimeout) { done in
channel.publish(nil, data: "") { error in
XCTAssertNil(error)
done()
}
}
let requests = testHTTPExecutor.requests
XCTAssertEqual(requests.count, 3)
let capturedURLs = requests.map { $0.url!.absoluteString }
XCTAssertTrue(NSRegularExpression.match(capturedURLs.at(0), pattern: "//rest.ably.io"))
XCTAssertTrue(NSRegularExpression.match(capturedURLs.at(1), pattern: "//[a-e].ably-realtime.com"))
XCTAssertTrue(NSRegularExpression.match(capturedURLs.at(2), pattern: "//[a-e].ably-realtime.com"))
}
// RSC15b1
func test__056__RestClient__Host_Fallback__Fallback_behavior__should_NOT_be_applied_when_ClientOptions_restHost_has_been_set() {
let test = Test()
let options = ARTClientOptions(key: "xxxx:xxxx")
options.restHost = "fake.ably.io"
let client = ARTRest(options: options)
let internalLog = InternalLog(clientOptions: options)
let mockHTTP = MockHTTP(logger: internalLog)
testHTTPExecutor = TestProxyHTTPExecutor(http: mockHTTP, logger: internalLog)
client.internal.httpExecutor = testHTTPExecutor
mockHTTP.setNetworkState(network: .hostUnreachable)
let channel = client.channels.get(test.uniqueChannelName())
waitUntil(timeout: testTimeout) { done in
channel.publish(nil, data: "") { error in
expect(error?.message).to(contain("hostname could not be found"))
done()
}
}
let requests = testHTTPExecutor.requests
XCTAssertEqual(requests.count, 1)
let capturedURLs = requests.map { $0.url!.absoluteString }
XCTAssertTrue(NSRegularExpression.match(capturedURLs.at(0), pattern: "//fake.ably.io"))
}
// RSC15b1
func test__057__RestClient__Host_Fallback__Fallback_behavior__should_NOT_be_applied_when_ClientOptions_port_has_been_set() {
let test = Test()
let options = ARTClientOptions(token: "xxxx")
options.tls = false
options.port = 999
let client = ARTRest(options: options)
let internalLog = InternalLog(clientOptions: options)
let mockHTTP = MockHTTP(logger: internalLog)
testHTTPExecutor = TestProxyHTTPExecutor(http: mockHTTP, logger: internalLog)
client.internal.httpExecutor = testHTTPExecutor
mockHTTP.setNetworkState(network: .hostUnreachable)
let channel = client.channels.get(test.uniqueChannelName())
waitUntil(timeout: testTimeout) { done in
channel.publish(nil, data: "") { error in
expect(error?.message).to(contain("hostname could not be found"))
done()
}
}
let requests = testHTTPExecutor.requests
XCTAssertEqual(requests.count, 1)
let capturedURLs = requests.map { $0.url!.absoluteString }
expect(capturedURLs.at(0)).to(beginWith("http://rest.ably.io:999"))
}
// RSC15b1
func test__058__RestClient__Host_Fallback__Fallback_behavior__should_NOT_be_applied_when_ClientOptions_tlsPort_has_been_set() {
let test = Test()
let options = ARTClientOptions(key: "xxxx:xxxx")
options.tlsPort = 999
let client = ARTRest(options: options)
let internalLog = InternalLog(clientOptions: options)
let mockHTTP = MockHTTP(logger: internalLog)
testHTTPExecutor = TestProxyHTTPExecutor(http: mockHTTP, logger: internalLog)
client.internal.httpExecutor = testHTTPExecutor
mockHTTP.setNetworkState(network: .hostUnreachable)
let channel = client.channels.get(test.uniqueChannelName())
waitUntil(timeout: testTimeout) { done in
channel.publish(nil, data: "") { error in
expect(error?.message).to(contain("hostname could not be found"))
done()
}
}
let requests = testHTTPExecutor.requests
XCTAssertEqual(requests.count, 1)
let capturedURLs = requests.map { $0.url!.absoluteString }
expect(capturedURLs.at(0)).to(beginWith("https://rest.ably.io:999"))
}
// RSC15b2
func test__059__RestClient__Host_Fallback__Fallback_behavior__should_be_applied_when_ClientOptions_fallbackHosts_is_provided() {