Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test suite: keep channel name prefix for current ClientOptions while calling 'setupOptions' and other improvements #1009

Merged
merged 6 commits into from
Apr 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Source/ARTChannelOptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ NS_ASSUME_NONNULL_BEGIN

@property (nonatomic, strong, nullable) ARTCipherParams *cipher;


- (instancetype)initWithCipher:(id<ARTCipherParamsCompatible> _Nullable)cipherParams;
- (instancetype)initWithCipherKey:(id<ARTCipherKeyCompatible>)key;

Expand Down
7 changes: 3 additions & 4 deletions Source/ARTChannels+Private.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@

NS_ASSUME_NONNULL_BEGIN

extern NSString* (^_Nullable ARTChannels_getChannelNamePrefix)(void);

@protocol ARTChannelsDelegate <NSObject>

- (id)makeChannel:(NSString *)channel options:(nullable ARTChannelOptions *)options;
Expand All @@ -25,15 +23,16 @@ extern NSString* (^_Nullable ARTChannels_getChannelNamePrefix)(void);

@property (nonatomic, readonly) NSMutableDictionary<NSString *, ChannelType> *channels;
@property (readonly, getter=getNosyncIterable) id<NSFastEnumeration> nosyncIterable;
@property (nonatomic, readonly) NSString *prefix;

+ (NSString *)addPrefix:(NSString *)name;
- (NSString *)addPrefix:(NSString *)name;

- (BOOL)_exists:(NSString *)name;
- (ChannelType)_get:(NSString *)name;
- (ChannelType)_getChannel:(NSString *)name options:(ARTChannelOptions * _Nullable)options addPrefix:(BOOL)addPrefix;
- (void)_release:(NSString *)name;

- (instancetype)initWithDelegate:(id<ARTChannelsDelegate>)delegate dispatchQueue:(dispatch_queue_t)queue;
- (instancetype)initWithDelegate:(id<ARTChannelsDelegate>)delegate dispatchQueue:(dispatch_queue_t)queue prefix:(nullable NSString *)prefix;

@end

Expand Down
25 changes: 11 additions & 14 deletions Source/ARTChannels.m
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@
#import "ARTChannelOptions.h"
#import "ARTRestChannel.h"

NSString* (^_Nullable ARTChannels_getChannelNamePrefix)(void);

@interface ARTChannels() {
__weak id<ARTChannelsDelegate> _delegate; // weak because delegates outlive their counterpart
dispatch_queue_t _queue;
Expand All @@ -24,11 +22,12 @@ @interface ARTChannels() {

@implementation ARTChannels

- (instancetype)initWithDelegate:(id)delegate dispatchQueue:(dispatch_queue_t)queue {
- (instancetype)initWithDelegate:(id)delegate dispatchQueue:(dispatch_queue_t)queue prefix:(NSString *)prefix {
if (self = [super init]) {
_queue = queue;
_channels = [[NSMutableDictionary alloc] init];
_delegate = delegate;
_prefix = prefix;
}
return self;
}
Expand Down Expand Up @@ -58,15 +57,15 @@ - (BOOL)exists:(NSString *)name {
}

- (BOOL)_exists:(NSString *)name {
return self->_channels[[ARTChannels addPrefix:name]] != nil;
return self->_channels[[self addPrefix:name]] != nil;
}

- (id)get:(NSString *)name {
return [self getChannel:[ARTChannels addPrefix:name] options:nil];
return [self getChannel:[self addPrefix:name] options:nil];
}

- (id)get:(NSString *)name options:(ARTChannelOptions *)options {
return [self getChannel:[ARTChannels addPrefix:name] options:options];
return [self getChannel:[self addPrefix:name] options:options];
}

- (void)release:(NSString *)name {
Expand All @@ -76,7 +75,7 @@ - (void)release:(NSString *)name {
}

- (void)_release:(NSString *)name {
[self->_channels removeObjectForKey:[ARTChannels addPrefix:name]];
[self->_channels removeObjectForKey:[self addPrefix:name]];
}

- (ARTRestChannel *)getChannel:(NSString *)name options:(ARTChannelOptions *)options {
Expand All @@ -89,7 +88,7 @@ - (ARTRestChannel *)getChannel:(NSString *)name options:(ARTChannelOptions *)opt

- (ARTChannel *)_getChannel:(NSString *)name options:(ARTChannelOptions *)options addPrefix:(BOOL)addPrefix {
if (addPrefix) {
name = [ARTChannels addPrefix:name];
name = [self addPrefix:name];
}
ARTChannel *channel = [self _get:name];
if (!channel) {
Expand All @@ -105,15 +104,13 @@ - (id)_get:(NSString *)name {
return self->_channels[name];
}

+ (NSString *)addPrefix:(NSString *)name {
if (ARTChannels_getChannelNamePrefix) {
NSString *prefix = [NSString stringWithFormat:@"%@-", ARTChannels_getChannelNamePrefix()];
if (![name hasPrefix:prefix]) {
return [NSString stringWithFormat:@"%@-%@", ARTChannels_getChannelNamePrefix(), name];
- (NSString *)addPrefix:(NSString *)name {
if (_prefix) {
if (![name hasPrefix:_prefix]) {
return [NSString stringWithFormat:@"%@-%@", _prefix, name];
}
}
return name;
}

@end

2 changes: 2 additions & 0 deletions Source/ARTClientOptions+Private.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

@interface ARTClientOptions ()

@property (nullable, strong, nonatomic) NSString *channelNamePrefix;

+ (void)setDefaultEnvironment:(NSString *_Nullable)environment;
+ (BOOL)getDefaultIdempotentRestPublishingForVersion:(NSString *_Nonnull)version;
- (NSURLComponents *_Nonnull)restUrlComponents;
Expand Down
11 changes: 6 additions & 5 deletions Source/ARTClientOptions.m
Original file line number Diff line number Diff line change
Expand Up @@ -128,17 +128,18 @@ - (id)copyWithZone:(NSZone *)zone {
options.internalDispatchQueue = self.internalDispatchQueue;
options.pushFullWait = self.pushFullWait;
options.idempotentRestPublishing = self.idempotentRestPublishing;
options.channelNamePrefix = self.channelNamePrefix;

return options;
}

- (BOOL)isBasicAuth {
return self.useTokenAuth == false &&
self.key != nil &&
self.token == nil &&
self.tokenDetails == nil &&
self.authUrl == nil &&
self.authCallback == nil;
self.key != nil &&
self.token == nil &&
self.tokenDetails == nil &&
self.authUrl == nil &&
self.authCallback == nil;
}

- (BOOL)hasCustomRestHost {
Expand Down
1 change: 1 addition & 0 deletions Source/ARTPushActivationStateMachine+Private.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ extern NSString *const ARTPushActivationPendingEventsKey;

@property (weak, nonatomic) id delegate; // weak because delegates outlive their counterpart
@property (nonatomic, copy, nullable) void (^transitions)(ARTPushActivationEvent *event, ARTPushActivationState *from, ARTPushActivationState *to);
@property (nonatomic, copy, nullable) void (^onEvent)(ARTPushActivationEvent *event, ARTPushActivationState *state);
@property (readonly, nonatomic) ARTPushActivationEvent *lastEvent_nosync;
@property (readonly, nonatomic) ARTPushActivationState *current_nosync;

Expand Down
1 change: 1 addition & 0 deletions Source/ARTPushActivationStateMachine.m
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ - (void)handleEvent:(nonnull ARTPushActivationEvent *)event {
[_rest.logger debug:@"%@: handling event %@ from %@", NSStringFromClass(self.class), NSStringFromClass(event.class), NSStringFromClass(_current.class)];
_lastHandledEvent = event;

if (self.onEvent) self.onEvent(event, _current);
ARTPushActivationState *maybeNext = [_current transition:event];

if (maybeNext == nil) {
Expand Down
5 changes: 3 additions & 2 deletions Source/ARTRealtimeChannels.m
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#import "ARTRealtimeChannel+Private.h"
#import "ARTRealtime+Private.h"
#import "ARTRealtimePresence+Private.h"
#import "ARTClientOptions+Private.h"

@implementation ARTRealtimeChannels {
ARTQueuedDealloc *_dealloc;
Expand Down Expand Up @@ -74,7 +75,7 @@ - (instancetype)initWithRealtime:(ARTRealtimeInternal *)realtime {
_realtime = realtime;
_userQueue = _realtime.rest.userQueue;
_queue = _realtime.rest.queue;
_channels = [[ARTChannels alloc] initWithDelegate:self dispatchQueue:_queue];
_channels = [[ARTChannels alloc] initWithDelegate:self dispatchQueue:_queue prefix:_realtime.options.channelNamePrefix];
}
return self;
} ART_TRY_OR_MOVE_TO_FAILED_END
Expand All @@ -101,7 +102,7 @@ - (BOOL)exists:(NSString *)name {
}

- (void)release:(NSString *)name callback:(void (^)(ARTErrorInfo * _Nullable))cb {
name = [ARTChannels addPrefix:name];
name = [_channels addPrefix:name];

if (cb) {
void (^userCallback)(ARTErrorInfo *error) = cb;
Expand Down
3 changes: 2 additions & 1 deletion Source/ARTRestChannels.m
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#import "ARTChannels+Private.h"
#import "ARTRestChannel+Private.h"
#import "ARTRest+Private.h"
#import "ARTClientOptions+Private.h"

@implementation ARTRestChannels {
ARTQueuedDealloc *_dealloc;
Expand Down Expand Up @@ -66,7 +67,7 @@ - (instancetype)initWithRest:(ARTRestInternal *)rest {
ART_TRY_OR_REPORT_CRASH_START(rest) {
if (self = [super init]) {
_rest = rest;
_channels = [[ARTChannels alloc] initWithDelegate:self dispatchQueue:_rest.queue];
_channels = [[ARTChannels alloc] initWithDelegate:self dispatchQueue:_rest.queue prefix:rest.options.channelNamePrefix];
}
return self;
} ART_TRY_OR_REPORT_CRASH_END
Expand Down
2 changes: 1 addition & 1 deletion Source/ARTTypes.m
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ -(void)invokeWithResult:(const id)result error:(NSError *const)error {
}

if (callback) {
_callback(result, error);
callback(result, error);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small but important fix.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😬 .... 😌

}
}

Expand Down
14 changes: 6 additions & 8 deletions Spec/Auth.swift
Original file line number Diff line number Diff line change
Expand Up @@ -983,8 +983,8 @@ class Auth : QuickSpec {

waitUntil(timeout: testTimeout) { done in
realtime.connection.once(.failed) { stateChange in
expect(stateChange!.reason?.code).to(equal(40102))
expect(stateChange!.reason?.description).to(contain("incompatible credentials"))
expect(stateChange!.reason?.code).to(equal(40101))
expect(stateChange!.reason?.description.lowercased()).to(contain("invalid clientid for credentials"))
done()
}
realtime.connect()
Expand Down Expand Up @@ -3458,7 +3458,7 @@ class Auth : QuickSpec {
expect(timeOffset).toNot(equal(0))
expect(rest.auth.internal.timeOffset).toNot(beNil())
let calculatedServerDate = currentDate.addingTimeInterval(timeOffset)
expect(calculatedServerDate).to(beCloseTo(mockServerDate, within: 0.5))
expect(calculatedServerDate).to(beCloseTo(mockServerDate, within: 0.9))
expect(serverTimeRequestCount) == 1
done()
})
Expand All @@ -3477,7 +3477,7 @@ class Auth : QuickSpec {
}
expect(timeOffset).toNot(equal(0))
let calculatedServerDate = currentDate.addingTimeInterval(timeOffset)
expect(calculatedServerDate).to(beCloseTo(mockServerDate, within: 0.5))
expect(calculatedServerDate).to(beCloseTo(mockServerDate, within: 0.9))
expect(serverTimeRequestCount) == 1
done()
}
Expand Down Expand Up @@ -4318,13 +4318,11 @@ class Auth : QuickSpec {
let capability = "{\"\(channelName)\":[\"subscribe\"]}"
let options = AblyTests.clientOptions()
options.tokenDetails = ARTTokenDetails(token: getJWTToken(capability: capability)!)
// Prevent channel name to be prefixed by test-*
options.channelNamePrefix = nil
let client = ARTRealtime(options: options)
defer { client.dispose(); client.close() }

let originalARTChannels_getChannelNamePrefix = ARTChannels_getChannelNamePrefix
defer { ARTChannels_getChannelNamePrefix = originalARTChannels_getChannelNamePrefix }
ARTChannels_getChannelNamePrefix = nil // Force that channel name is not changed.

waitUntil(timeout: testTimeout) { done in
client.channels.get(channelName).publish(messageName, data: nil, callback: { error in
expect(error?.code).to(equal(40160))
Expand Down
12 changes: 10 additions & 2 deletions Spec/Push.swift
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,16 @@ class Push : QuickSpec {
let deviceTokenBase64 = "HYRXxPSQdt1pnxqtDAvc6PTTLH7N6okiBhYyLClJdmQ="
let deviceTokenData = Data(base64Encoded: deviceTokenBase64, options: [])!
let expectedDeviceToken = "1d8457c4f49076dd699f1aad0c0bdce8f4d32c7ecdea89220616322c29497664"
ARTPush.didRegisterForRemoteNotifications(withDeviceToken: deviceTokenData, rest: rest)
expect(storage.keysWritten.keys).toEventually(contain(["ARTDeviceToken"]), timeout: testTimeout)
defer { rest.push.internal.activationMachine().transitions = nil }
waitUntil(timeout: testTimeout) { done in
rest.push.internal.activationMachine().onEvent = { event, _ in
if event is ARTPushActivationEventGotPushDeviceDetails {
done()
}
}
ARTPush.didRegisterForRemoteNotifications(withDeviceToken: deviceTokenData, rest: rest)
}
expect(storage.keysWritten.keys).to(contain(["ARTDeviceToken"]))
expect(storage.keysWritten.at("ARTDeviceToken")?.value as? String).to(equal(expectedDeviceToken))
}

Expand Down
6 changes: 2 additions & 4 deletions Spec/PushChannel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -347,12 +347,10 @@ class PushChannel : QuickSpec {
it("should return a paginated result with PushChannelSubscription") {
let options = AblyTests.commonAppSetup()
options.clientId = "tester"
// Prevent channel name to be prefixed by test-*
options.channelNamePrefix = nil
let rest = ARTRest(options: options)
rest.internal.storage = MockDeviceStorage()
// Prevent channel name to be prefixed by test-*
let originalChannelNamePrefix = ARTChannels_getChannelNamePrefix
defer { ARTChannels_getChannelNamePrefix = originalChannelNamePrefix }
ARTChannels_getChannelNamePrefix = nil

// Activate device
let testIdentityTokenDetails = ARTDeviceIdentityTokenDetails(token: "xxxx-xxxx-xxx", issued: Date(), expires: Date.distantFuture, capability: "", clientId: "")
Expand Down
28 changes: 16 additions & 12 deletions Spec/RealtimeClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -698,43 +698,43 @@ class RealtimeClient: QuickSpec {

it("authorize call should complete with an error if the request fails") {
let options = AblyTests.clientOptions()
options.autoConnect = false
let testToken = getTestToken()
options.token = testToken
let client = ARTRealtime(options: options)
defer { client.dispose(); client.close() }
client.internal.setTransport(TestProxyTransport.self)

waitUntil(timeout: testTimeout) { done in
client.connection.once(.connected) { stateChange in
expect(stateChange?.reason).to(beNil())
done()
}
client.connect()
}

waitUntil(timeout: testTimeout) { done in
let tokenParams = ARTTokenParams()
tokenParams.clientId = "john"

let simulatedError = NSError(domain: ARTAblyErrorDomain, code: 1234, userInfo: nil)

let authOptions = ARTAuthOptions()
authOptions.authCallback = { tokenParams, completion in
getTestTokenDetails(clientId: "tester", completion: completion)
DispatchQueue.main.async {
completion(nil, simulatedError)
}
}

client.auth.authorize(tokenParams, options: authOptions) { tokenDetails, error in
guard let error = error as? ARTErrorInfo else {
fail("ErrorInfo is nil"); done(); return
guard let error = error else {
fail("Error is nil"); done(); return
}
expect((error ).code).to(equal(40102))
expect(error.localizedDescription).to(contain("incompatible credentials"))
expect(error as NSError).to(equal(simulatedError))
expect(tokenDetails).to(beNil())
done()
}
}

expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected))
expect(client.auth.tokenDetails!.token).to(equal(testToken))
expect(client.auth.tokenDetails?.token).to(equal(testToken))
}

// RTC8a3
Expand Down Expand Up @@ -1331,9 +1331,13 @@ class RealtimeClient: QuickSpec {
}

it ("subscriber should receive messages in the same order in which they have been sent") {
let realtime1 = ARTRealtime(options: AblyTests.commonAppSetup())
let realtime2 = ARTRealtime(options: AblyTests.commonAppSetup())
defer { realtime1.dispose(); realtime1.close(); realtime2.dispose(); realtime2.close(); }
let options = AblyTests.commonAppSetup()
let realtime1 = ARTRealtime(options: options)
let realtime2 = ARTRealtime(options: options)
defer {
realtime1.dispose(); realtime1.close();
realtime2.dispose(); realtime2.close();
}
waitUntil(timeout: testTimeout) { done in
realtime1.connection.on(.connected) { _ in
done()
Expand Down
4 changes: 2 additions & 2 deletions Spec/RealtimeClientChannel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1766,7 +1766,7 @@ class RealtimeClientChannel: QuickSpec {

it("upon failure") {
let options = AblyTests.commonAppSetup()
options.token = getTestToken(key: options.key, capability: "{ \"\(ARTChannels_getChannelNamePrefix!())-test\":[\"subscribe\"] }")
options.token = getTestToken(key: options.key, capability: "{ \"\(options.channelNamePrefix!)-test\":[\"subscribe\"] }")
let client = ARTRealtime(options: options)
defer { client.dispose(); client.close() }

Expand Down Expand Up @@ -1808,7 +1808,7 @@ class RealtimeClientChannel: QuickSpec {

it("for all messages published") {
let options = AblyTests.commonAppSetup()
options.token = getTestToken(key: options.key, capability: "{ \"\(ARTChannels_getChannelNamePrefix!())-channelToSucceed\":[\"subscribe\", \"publish\"], \"\(ARTChannels_getChannelNamePrefix!())-channelToFail\":[\"subscribe\"] }")
options.token = getTestToken(key: options.key, capability: "{ \"\(options.channelNamePrefix!)-channelToSucceed\":[\"subscribe\", \"publish\"], \"\(options.channelNamePrefix!)-channelToFail\":[\"subscribe\"] }")
let client = ARTRealtime(options: options)
defer { client.dispose(); client.close() }

Expand Down
5 changes: 3 additions & 2 deletions Spec/RealtimeClientChannels.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,13 @@ class RealtimeClientChannels: QuickSpec {

// RTS3a
it("should create a new Channel if none exists or return the existing one") {
let client = ARTRealtime(options: AblyTests.commonAppSetup())
let options = AblyTests.commonAppSetup()
let client = ARTRealtime(options: options)
defer { client.dispose(); client.close() }

expect(client.channels.internal.collection).to(haveCount(0))
let channel = client.channels.get("test")
expect(channel.name).to(equal("\(ARTChannels_getChannelNamePrefix!())-test"))
expect(channel.name).to(equal("\(options.channelNamePrefix!)-test"))

expect(client.channels.internal.collection).to(haveCount(1))
expect(client.channels.get("test").internal).to(beIdenticalTo(channel.internal))
Expand Down
Loading