-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChannelAsyncIntegrationTests.swift
More file actions
644 lines (523 loc) · 21 KB
/
ChannelAsyncIntegrationTests.swift
File metadata and controls
644 lines (523 loc) · 21 KB
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
//
// ChannelAsyncIntegrationTests.swift
//
// Copyright (c) PubNub Inc.
// All rights reserved.
//
// This source code is licensed under the license found in the
// LICENSE file in the root directory of this source tree.
//
import Foundation
import PubNubSDK
import XCTest
@testable import PubNubSwiftChatSDK
class ChannelAsyncIntegrationTests: BaseAsyncIntegrationTestCase {
var channel: ChannelImpl!
override func customSetup() async throws {
channel = try await chat.createChannel(id: randomString())
}
override func customTearDown() async throws {
_ = try? await channel.delete()
channel = nil
}
func testChannelAsync_Update() async throws {
let newCustom: [String: JSONCodableScalar] = [
"a": 123,
"b": "xyz"
]
let updatedChannel = try await channel.update(
name: "NewName",
custom: newCustom,
status: "NewStatus",
type: .public
)
XCTAssertEqual(updatedChannel.id, channel.id)
XCTAssertEqual(updatedChannel.name, "NewName")
XCTAssertEqual(updatedChannel.custom?.mapValues { $0.scalarValue }, newCustom.mapValues { $0.scalarValue })
XCTAssertEqual(updatedChannel.status, "NewStatus")
XCTAssertEqual(updatedChannel.type, .public)
}
func testChannelAsync_Delete() async throws {
let someChannel = try await chat.createChannel(id: randomString())
let removalResult = try await someChannel.delete(soft: false)
let retrievedChannel = try await chat.getChannel(channelId: someChannel.id)
XCTAssertNil(removalResult)
XCTAssertNil(retrievedChannel)
addTeardownBlock { [unowned self] in
_ = try? await chat.deleteChannel(id: someChannel.id)
}
}
func testChannelAsync_SoftDelete() async throws {
let someChannel = try await chat.createChannel(id: randomString())
let removalResult = try await someChannel.delete(soft: true)
let retrievedChannel = try await chat.getChannel(channelId: someChannel.id)
XCTAssertNotNil(removalResult)
XCTAssertEqual(retrievedChannel?.id, someChannel.id)
addTeardownBlock { [unowned self] in
_ = try? await chat.deleteChannel(id: someChannel.id)
}
}
func testChannelAsync_Forward() async throws {
let anotherChannel = try await chat.createChannel(id: randomString())
let tt = try await anotherChannel.sendText(text: "Some text to send")
try await Task.sleep(nanoseconds: 3_000_000_000)
let message = try await anotherChannel.getMessage(timetoken: tt)
let unwrappedMessage = try XCTUnwrap(message)
try await channel.forward(message: unwrappedMessage)
try await Task.sleep(nanoseconds: 3_000_000_000)
let retrievedMssgsFromForwardedChannel = try await channel.getHistory()
XCTAssertEqual(retrievedMssgsFromForwardedChannel.messages.count, 1)
XCTAssertEqual(retrievedMssgsFromForwardedChannel.messages.first?.channelId, channel.id)
addTeardownBlock { [unowned self] in
_ = try await chat.deleteChannel(id: anotherChannel.id)
}
}
func testChannelAsync_StartTyping() async throws {
let expectation = expectation(description: "GetTyping")
expectation.assertForOverFulfill = true
expectation.expectedFulfillmentCount = 1
let task = Task {
for await userIdentifiers in channel.getTyping() {
XCTAssertEqual(userIdentifiers.first, chat.currentUser.id)
expectation.fulfill()
}
}
try await Task.sleep(nanoseconds: 2_000_000_000)
try await channel.startTyping()
await fulfillment(of: [expectation], timeout: 3)
addTeardownBlock { task.cancel() }
}
func testChannelAsync_StopTyping() async throws {
try await channel.stopTyping()
}
func testChannelAsync_WhoIsPresent() async throws {
// Keeps a strong reference to the returned AsyncStream to prevent it from being deallocated. If this object is not retained,
// the AsyncStream will be deallocated, which would cause the behavior being tested to fail.
let joinResult = try await channel.join()
debugPrint(joinResult)
try await Task.sleep(nanoseconds: 4_000_000_000)
let whoIsPresent = try await channel.whoIsPresent()
XCTAssertEqual(whoIsPresent.count, 1)
XCTAssertEqual(whoIsPresent.first, chat.currentUser.id)
}
func testChannelAsync_WhoIsPresentWithLimitAndOffset() async throws {
// Keeps a strong reference to the returned AsyncStream to prevent it from being deallocated. If this object is not retained,
// the AsyncStream will be deallocated, which would cause the behavior being tested to fail.
let joinResult = try await channel.join()
debugPrint(joinResult)
try await Task.sleep(nanoseconds: 4_000_000_000)
let whoIsPresentWithLimit = try await channel.whoIsPresent(limit: 10)
XCTAssertEqual(whoIsPresentWithLimit.count, 1)
XCTAssertEqual(whoIsPresentWithLimit.first, chat.currentUser.id)
let whoIsPresentWithOffset = try await channel.whoIsPresent(limit: 10, offset: 1)
XCTAssertTrue(whoIsPresentWithOffset.isEmpty)
let whoIsPresentWithZeroOffset = try await channel.whoIsPresent(limit: 10, offset: 0)
XCTAssertEqual(whoIsPresentWithZeroOffset.count, 1)
XCTAssertEqual(whoIsPresentWithZeroOffset.first, chat.currentUser.id)
}
func testChannelAsync_IsPresent() async throws {
// Keeps a strong reference to the returned AsyncStream to prevent it from being deallocated. If this object is not retained,
// the AsyncStream will be deallocated, which would cause the behavior being tested to fail.
let joinResult = try await channel.join()
debugPrint(joinResult)
try await Task.sleep(nanoseconds: 4_000_000_000)
let isPresent = try await channel.isPresent(userId: chat.currentUser.id)
XCTAssertTrue(isPresent)
}
func testChannelAsync_GetHistory() async throws {
for counter in 1 ... 3 {
try await channel.sendText(text: "Text \(counter)")
}
try await Task.sleep(nanoseconds: 2_000_000_000)
let messages = try await channel.getHistory()
XCTAssertEqual(messages.messages.count, 3)
XCTAssertEqual(messages.messages[0].text, "Text 1")
XCTAssertEqual(messages.messages[1].text, "Text 2")
XCTAssertEqual(messages.messages[2].text, "Text 3")
}
func testChannelAsync_SendText() async throws {
let tt = try await channel.sendText(
text: "Some text to send",
meta: ["a": 123, "b": "someString"],
shouldStore: true,
usersToMention: nil
)
try await Task.sleep(nanoseconds: 2_000_000_000)
let retrievedMessage = try await channel.getMessage(timetoken: tt)
XCTAssertEqual(retrievedMessage?.text, "Some text to send")
XCTAssertEqual(retrievedMessage?.meta?["a"]?.codableValue.rawValue as? Int, 123)
XCTAssertEqual(retrievedMessage?.meta?["b"]?.codableValue.rawValue as? String, "someString")
}
func testChannelAsync_SendTextWithFiles() async throws {
let downloadExpect = expectation(description: "Download File Expect")
downloadExpect.expectedFulfillmentCount = 1
downloadExpect.assertForOverFulfill = true
let fileUrlSession = URLSession(
configuration: URLSessionConfiguration.default,
delegate: FileSessionManager(),
delegateQueue: .main
)
let newPubNub = PubNub(
configuration: chat.pubNub.configuration,
fileSession: fileUrlSession
)
let newChat = ChatImpl(
pubNub: newPubNub,
configuration: chat.config
)
let data = Data("Lorem ipsum".utf8)
let newChannel = try await newChat.createChannel(id: randomString())
let inputFile = InputFile(name: "TxtFile", type: "text/plain", source: .data(data, contentType: "text/plain"))
try await newChannel.sendText(text: "Text", files: [inputFile])
try await Task.sleep(nanoseconds: 3_000_000_000)
let getFilesResult = try await newChannel.getFiles()
let file = try XCTUnwrap(getFilesResult.files.first)
let temporaryDirectory = URL(fileURLWithPath: NSTemporaryDirectory())
let outputPath = temporaryDirectory.appendingPathComponent(UUID().uuidString + ".txt")
let fileToDownload = PubNubFileBase(
channel: newChannel.id,
fileId: file.id,
filename: file.name,
size: Int64(data.count),
contentType: "text/plain"
)
newPubNub.download(file: fileToDownload, toFileURL: outputPath) { downloadResult in
switch downloadResult {
case let .success(downloadResponse):
XCTAssertEqual(try? Data(contentsOf: downloadResponse.file.fileURL), data)
case let .failure(error):
XCTFail("Unexpected error: \(error)")
}
downloadExpect.fulfill()
}
await fulfillment(
of: [downloadExpect],
timeout: 20
)
addTeardownBlock {
newPubNub.remove(
fileId: file.id,
filename: file.name,
channel: newChannel.id,
completion: nil
)
newChat.deleteChannel(
id: newChannel.id,
completion: nil
)
try FileManager.default.removeItem(
at: outputPath
)
}
}
func testChannelAsync_Invite() async throws {
try await channel.invite(user: chat.currentUser)
let member = try await channel.getMembers().memberships.first
XCTAssertEqual(member?.user.id, chat.currentUser.id)
}
func testChannelAsync_InviteMultiple() async throws {
let someUser = try await chat.createUser(user: UserImpl(chat: chat, id: randomString()))
let invitationResult = try await channel.inviteMultiple(users: [chat.currentUser, someUser])
let firstMatch = try XCTUnwrap(
invitationResult.first {
$0.user.id == chat.currentUser.id && $0.channel.id == channel.id
}
)
let secondMatch = try XCTUnwrap(
invitationResult.first {
$0.user.id == someUser.id && $0.channel.id == channel.id
}
)
XCTAssertEqual(invitationResult.count, 2)
XCTAssertNotNil(firstMatch)
XCTAssertNotNil(secondMatch)
addTeardownBlock { [unowned self] in
_ = try? await chat.deleteUser(id: someUser.id)
}
}
func testChannelAsync_GetMembers() async throws {
let someUser = try await chat.createUser(user: UserImpl(chat: chat, id: randomString()))
try await channel.inviteMultiple(users: [chat.currentUser, someUser])
let memberships = try await channel.getMembers().memberships
let firstMatch = try XCTUnwrap(
memberships.first {
$0.user.id == chat.currentUser.id && $0.channel.id == channel.id
}
)
let secondMatch = try XCTUnwrap(
memberships.first {
$0.user.id == someUser.id && $0.channel.id == channel.id
}
)
XCTAssertEqual(memberships.count, 2)
XCTAssertNotNil(firstMatch)
XCTAssertNotNil(secondMatch)
addTeardownBlock { [unowned self] in
_ = try? await chat.deleteUser(id: someUser.id)
}
}
func testChannelAsync_Connect() async throws {
let expectation = XCTestExpectation(description: "Connect")
expectation.assertForOverFulfill = true
expectation.expectedFulfillmentCount = 1
let task = Task {
for await message in channel.connect() {
XCTAssertEqual(message.text, "This is a text")
XCTAssertEqual(message.channelId, channel.id)
expectation.fulfill()
}
}
try await Task.sleep(nanoseconds: 2_000_000_000)
try await channel.sendText(text: "This is a text")
await fulfillment(of: [expectation], timeout: 6)
addTeardownBlock { task.cancel() }
}
func testChannelAsync_Join() async throws {
let expectation = XCTestExpectation(description: "Connect")
expectation.assertForOverFulfill = true
expectation.expectedFulfillmentCount = 1
let joinResult = try await channel.join()
XCTAssertEqual(joinResult.membership.channel.id, channel.id)
XCTAssertEqual(joinResult.membership.user.id, chat.currentUser.id)
let task = Task {
for await message in joinResult.messagesStream {
XCTAssertEqual(message.text, "This is a text")
XCTAssertEqual(message.channelId, channel.id)
expectation.fulfill()
}
}
try await Task.sleep(nanoseconds: 2_000_000_000)
try await channel.sendText(text: "This is a text")
await fulfillment(of: [expectation], timeout: 7)
addTeardownBlock { task.cancel() }
}
func testChannelAsync_Leave() async throws {
try await channel.join()
try await Task.sleep(nanoseconds: 3_000_000_000)
try await channel.leave()
try await Task.sleep(nanoseconds: 3_000_000_000)
let membershipsResult = try await channel.getMembers()
XCTAssertTrue(membershipsResult.memberships.isEmpty)
}
func testChannelAsync_PinMessageGetPinnedMessage() async throws {
let tt = try await channel.sendText(text: "Pinned message")
try await Task.sleep(nanoseconds: 2_000_000_000)
let message = try await channel.getMessage(timetoken: tt)
let unwrappedMessage = try XCTUnwrap(message)
let updatedChannel = try await channel.pinMessage(message: unwrappedMessage)
try await Task.sleep(nanoseconds: 2_000_000_000)
let pinnedMessage = try await updatedChannel.getPinnedMessage()
XCTAssertNotNil(pinnedMessage)
XCTAssertEqual(pinnedMessage?.channelId, channel.id)
}
func testChannelAsync_GetMessage() async throws {
let tt = try await channel.sendText(text: "Message text")
try await Task.sleep(nanoseconds: 2_000_000_000)
let message = try await channel.getMessage(timetoken: tt)
XCTAssertEqual(message?.channelId, channel.id)
XCTAssertEqual(message?.userId, chat.currentUser.id)
}
func testChannelAsync_RegisterUnregisterFromPush() async throws {
let pushNotificationsConfig = PushNotificationsConfig(
sendPushes: false,
deviceToken: "4d3f92b6d7a9348e5f2b8c6d1e4f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f",
deviceGateway: .fcm,
apnsEnvironment: .development
)
let anotherChat = ChatImpl(
chatConfiguration: ChatConfiguration(pushNotificationsConfig: pushNotificationsConfig),
pubNubConfiguration: chat.pubNub.configuration
)
let anotherChannel = try await anotherChat.createChannel(id: randomString())
try await anotherChannel.registerForPush()
try await anotherChannel.unregisterFromPush()
addTeardownBlock {
_ = try? await anotherChat.deleteChannel(id: anotherChannel.id)
}
}
func testChannelAsync_StreamUpdates() async throws {
let expectation = expectation(description: "StreamUpdates")
expectation.assertForOverFulfill = true
expectation.expectedFulfillmentCount = 1
let task = Task {
for await receivedChannel in channel.streamUpdates() {
XCTAssertEqual(receivedChannel?.name, "NewName")
XCTAssertEqual(receivedChannel?.status, "NewStatus")
expectation.fulfill()
}
}
try await Task.sleep(nanoseconds: 3_000_000_000)
_ = try await channel.update(name: "NewName", status: "NewStatus")
await fulfillment(of: [expectation], timeout: 6)
addTeardownBlock { task.cancel() }
}
func testChannelAsync_StreamReadReceipts() async throws {
let expectation = expectation(description: "StreamReadReceipts")
expectation.assertForOverFulfill = true
expectation.expectedFulfillmentCount = 1
let anotherUser = try await chat.createUser(user: UserImpl(chat: chat, id: randomString()))
try await Task.sleep(nanoseconds: 3_000_000_000)
let membership = try await channel.invite(user: chat.currentUser)
try await Task.sleep(nanoseconds: 1_000_000_000)
let anotherMembership = try await channel.invite(user: anotherUser)
let timetoken = try XCTUnwrap(membership.lastReadMessageTimetoken)
let secondTimetoken = try XCTUnwrap(anotherMembership.lastReadMessageTimetoken)
let currentUserId = chat.currentUser.id
let anotherUserId = anotherUser.id
let task = Task {
for await readReceipt in channel.streamReadReceipts() {
XCTAssertEqual(readReceipt[timetoken]?.count, 1)
XCTAssertEqual(readReceipt[timetoken]?.first, currentUserId)
XCTAssertEqual(readReceipt[secondTimetoken]?.count, 1)
XCTAssertEqual(readReceipt[secondTimetoken]?.first, anotherUserId)
expectation.fulfill()
}
}
await fulfillment(of: [expectation], timeout: 6)
addTeardownBlock { [unowned self] in
task.cancel()
_ = try? await chat.deleteUser(id: anotherUserId)
}
}
func testChannelAsync_GetFiles() async throws {
let fileUrlSession = URLSession(
configuration: URLSessionConfiguration.default,
delegate: FileSessionManager(),
delegateQueue: .main
)
let newPubNub = PubNub(
configuration: chat.pubNub.configuration,
fileSession: fileUrlSession
)
let newChat = ChatImpl(
pubNub: newPubNub,
configuration: chat.config
)
let newChannel = try await newChat.createChannel(
id: randomString()
)
let inputFile = InputFile(
name: "TxtFile",
type: "text/plain",
source: .data(Data("Lorem ipsum".utf8), contentType: "text/plain")
)
try await newChannel.sendText(text: "Text", files: [inputFile])
try await Task.sleep(nanoseconds: 3_000_000_000)
let getFilesResult = try await newChannel.getFiles()
let file = try XCTUnwrap(getFilesResult.files.first)
XCTAssertEqual(getFilesResult.files.count, 1)
XCTAssertEqual(file.name, "TxtFile")
addTeardownBlock {
newPubNub.remove(
fileId: file.id,
filename: file.name,
channel: newChannel.id,
completion: nil
)
newChat.deleteChannel(
id: newChannel.id,
completion: nil
)
}
}
func testChannelAsync_DeleteFile() async throws {
let fileUrlSession = URLSession(
configuration: URLSessionConfiguration.default,
delegate: FileSessionManager(),
delegateQueue: .main
)
let newPubNub = PubNub(
configuration: chat.pubNub.configuration,
fileSession: fileUrlSession
)
let newChat = ChatImpl(
pubNub: newPubNub,
configuration: chat.config
)
let newChannel = try await newChat.createChannel(
id: randomString()
)
let inputFile = InputFile(
name: "TxtFile",
type: "text/plain",
source: .data(Data("Lorem ipsum".utf8), contentType: "text/plain")
)
try await newChannel.sendText(text: "Text", files: [inputFile])
try await Task.sleep(nanoseconds: 3_000_000_000)
let getFilesResult = try await newChannel.getFiles()
let file = try XCTUnwrap(getFilesResult.files.first)
try await channel.deleteFile(id: file.id, name: file.name)
let getFilesResultAfterRemoval = try await channel.getFiles()
XCTAssertTrue(getFilesResultAfterRemoval.files.isEmpty)
addTeardownBlock {
_ = try? await newChat.deleteChannel(id: newChannel.id)
}
}
func testChannelAsync_StreamPresence() async throws {
let expectation = expectation(description: "StreamPresence")
expectation.assertForOverFulfill = true
expectation.expectedFulfillmentCount = 1
let task = Task {
for await message in channel.connect() {
debugPrint("Did receive message: \(message)")
}
}
let presenceStreamTask = Task {
for await userIdentifiers in channel.streamPresence() where !userIdentifiers.isEmpty {
XCTAssertEqual(userIdentifiers.count, 1)
XCTAssertEqual(userIdentifiers.first, chat.currentUser.id)
expectation.fulfill()
}
}
await fulfillment(of: [expectation], timeout: 5)
addTeardownBlock {
presenceStreamTask.cancel()
task.cancel()
}
}
func testChannelAsync_GetUserSuggestions() async throws {
let usersToCreate = [
UserImpl(chat: chat, id: randomString(), name: "user_\(randomString())"),
UserImpl(chat: chat, id: randomString(), name: "user_\(randomString())"),
UserImpl(chat: chat, id: randomString(), name: "user_\(randomString())")
]
for user in usersToCreate {
_ = try await chat.createUser(user: user)
}
try await channel.inviteMultiple(users: usersToCreate)
let users = try await channel.getUserSuggestions(text: "user_")
XCTAssertEqual(
users.compactMap(\.user.name).sorted(by: <),
usersToCreate.compactMap(\.name).sorted(by: <)
)
addTeardownBlock { [unowned self] in
for user in usersToCreate {
_ = try? await chat.deleteUser(id: user.id)
}
}
}
func testChannelAsync_StreamMessageReports() async throws {
let expectation = expectation(description: "StreamMessageReports")
expectation.assertForOverFulfill = true
expectation.expectedFulfillmentCount = 1
let tt = try await channel.sendText(text: "Some text")
try await Task.sleep(nanoseconds: 2_000_000_000)
let message = try await channel.getMessage(timetoken: tt)
let task = Task {
for await report in channel.streamMessageReports() {
XCTAssertEqual(report.event.payload.reason, "reportReason")
XCTAssertEqual(report.event.payload.text, "Some text")
XCTAssertEqual(report.event.payload.reportedUserId, chat.currentUser.id)
expectation.fulfill()
}
}
try await Task.sleep(nanoseconds: 4_000_000_000)
try await message?.report(reason: "reportReason")
await fulfillment(of: [expectation], timeout: 10)
addTeardownBlock {
task.cancel()
_ = try? await message?.delete()
}
}
// swiftlint:disable:next file_length
}