Skip to content

Commit

Permalink
Test suites: reuse test app. (#420)
Browse files Browse the repository at this point in the history
For this, we isolate tests by prepending a prefix to channel names in
different tests (ie. that use different calls to 
TestUtilties.setupOptions.)

This should make #397 unnecessary.
  • Loading branch information
tcard committed Apr 21, 2016
1 parent b44861e commit 98c99da
Show file tree
Hide file tree
Showing 16 changed files with 129 additions and 89 deletions.
2 changes: 2 additions & 0 deletions Source/ARTChannels+Private.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

ART_ASSUME_NONNULL_BEGIN

extern NSString* (^__art_nullable ARTChannels_getChannelNamePrefix)();

@protocol ARTChannelsDelegate <NSObject>

- (id)makeChannel:(NSString *)channel options:(ARTChannelOptions *)options;
Expand Down
21 changes: 17 additions & 4 deletions Source/ARTChannels.m
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
#import "ARTChannelOptions.h"
#import "ARTRestChannel.h"

NSString* (^__art_nullable ARTChannels_getChannelNamePrefix)();

@interface ARTChannels() {
__weak ARTRest *_rest;
__weak id<ARTChannelsDelegate> _delegate;
Expand All @@ -39,22 +41,23 @@ - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state object
}

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

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

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

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

- (ARTRestChannel *)_getChannel:(NSString *)name options:(ARTChannelOptions *)options {
name = [self addPrefix:name];
ARTRestChannel *channel = self->_channels[name];
if (!channel) {
channel = [_delegate makeChannel:name options:options];
Expand All @@ -65,4 +68,14 @@ - (ARTRestChannel *)_getChannel:(NSString *)name options:(ARTChannelOptions *)op
return channel;
}

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

@end
5 changes: 4 additions & 1 deletion Source/ARTRealtimeChannels.m
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,10 @@ - (BOOL)exists:(NSString *)name {
}

- (void)release:(NSString *)name callback:(void (^)(ARTErrorInfo * _Nullable))cb {
ARTRealtimeChannel *channel = _channels.channels[name];
ARTRealtimeChannel *channel;
if ([self exists:name]) {
channel = [self get:name];
}
if (channel) {
[channel detach:^(ARTErrorInfo *errorInfo) {
[channel off];
Expand Down
1 change: 0 additions & 1 deletion Source/ARTRest+Private.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ ART_ASSUME_NONNULL_BEGIN
@property (readonly, strong, nonatomic) NSDictionary *encoders;

@property (nonatomic, strong) id<ARTHTTPExecutor> httpExecutor;
@property (readonly, nonatomic, assign) Class channelClass;

@property (nonatomic, strong) NSURL *baseUrl;

Expand Down
1 change: 0 additions & 1 deletion Source/ARTRest.m
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ - (instancetype)initWithOptions:(ARTClientOptions *)options {
[_logger debug:__FILE__ line:__LINE__ message:@"%p alloc HTTP", _http];
_httpExecutor = _http;
_httpExecutor.logger = _logger;
_channelClass = [ARTRestChannel class];

id<ARTEncoder> defaultEncoder = [[ARTJsonEncoder alloc] initWithLogger:self.logger];
_encoders = @{ [defaultEncoder mimeType]: defaultEncoder };
Expand Down
8 changes: 4 additions & 4 deletions Spec/RealtimeClientChannel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -775,8 +775,8 @@ class RealtimeClientChannel: QuickSpec {
}

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

Expand Down Expand Up @@ -814,8 +814,8 @@ class RealtimeClientChannel: QuickSpec {
}

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

Expand Down
2 changes: 1 addition & 1 deletion Spec/RealtimeClientChannels.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class RealtimeClientChannels: QuickSpec {

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

expect(client.channels.collection).to(haveCount(1))
expect(client.channels.get("test")).to(beIdenticalTo(channel))
Expand Down
4 changes: 2 additions & 2 deletions Spec/RealtimeClientConnection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -544,8 +544,8 @@ class RealtimeClientConnection: QuickSpec {
}

it("message failure") {
let options = AblyTests.clientOptions()
options.token = getTestToken(capability: "{ \"test\":[\"subscribe\"] }")
let options = AblyTests.commonAppSetup()
options.token = getTestToken(key: options.key, capability: "{ \"\(ARTChannels_getChannelNamePrefix!())-test\":[\"subscribe\"] }")
options.autoConnect = false
let client = ARTRealtime(options: options)
client.setTransportClass(TestProxyTransport.self)
Expand Down
4 changes: 4 additions & 0 deletions Spec/RestClientChannel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,10 @@ class RestClientChannel: QuickSpec {
// RSP3
context("get") {
it("should return presence fixture data") {
let originalARTChannels_getChannelNamePrefix = ARTChannels_getChannelNamePrefix
defer { ARTChannels_getChannelNamePrefix = originalARTChannels_getChannelNamePrefix }
ARTChannels_getChannelNamePrefix = nil // Force that channel name is not changed.

let key = appSetupJson["cipher"]["key"].string!
let cipherParams = ARTCipherParams.init(
algorithm: appSetupJson["cipher"]["algorithm"].string!,
Expand Down
6 changes: 3 additions & 3 deletions Spec/RestClientChannels.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class RestClientChannels: QuickSpec {
// RSN3a
it("should return a channel") {
let channel = client.channels.get(channelName)
expect(channel).to(beAChannel(named: channelName))
expect(channel).to(beAChannel(named: "\(ARTChannels_getChannelNamePrefix!())-\(channelName)"))

let sameChannel = client.channels.get(channelName)
expect(sameChannel).to(beIdenticalTo(channel))
Expand All @@ -62,7 +62,7 @@ class RestClientChannels: QuickSpec {
let options = ARTChannelOptions(cipher: cipherParams)
let channel = client.channels.get(channelName, options: options)

expect(channel).to(beAChannel(named: channelName))
expect(channel).to(beAChannel(named: "\(ARTChannels_getChannelNamePrefix!())-\(channelName)"))
expect(channel.options).to(beIdenticalTo(options))
}

Expand Down Expand Up @@ -110,7 +110,7 @@ class RestClientChannels: QuickSpec {
autoreleasepool {
channel = client.channels.get(channelName)

expect(channel).to(beAChannel(named: channelName))
expect(channel).to(beAChannel(named: "\(ARTChannels_getChannelNamePrefix!())-\(channelName)"))
client.channels.release(channel.name)
}

Expand Down
2 changes: 1 addition & 1 deletion Spec/RestClientStats.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import SwiftyJSON
import Foundation

private func postTestStats(stats: JSON) -> ARTClientOptions {
let options = AblyTests.setupOptions(AblyTests.jsonRestOptions);
let options = AblyTests.setupOptions(AblyTests.jsonRestOptions, forceNewApp: true);

let keyBase64 = encodeBase64(options.key ?? "")

Expand Down
56 changes: 33 additions & 23 deletions Spec/TestUtilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,35 +78,46 @@ class AblyTests {
}
}

class func setupOptions(options: ARTClientOptions, debug: Bool = false) -> ARTClientOptions {
let request = NSMutableURLRequest(URL: NSURL(string: "https://\(options.restHost):\(options.tlsPort)/apps")!)
request.HTTPMethod = "POST"
request.HTTPBody = try? appSetupJson["post_apps"].rawData()

request.allHTTPHeaderFields = [
"Accept" : "application/json",
"Content-Type" : "application/json"
]

let (responseData, responseError, _) = NSURLSessionServerTrustSync().get(request)

if let error = responseError {
XCTFail(error.localizedDescription)
} else if let data = responseData {
let response = JSON(data: data)
static var testApplication: JSON?
static private var setupOptionsCounter = 0

class func setupOptions(options: ARTClientOptions, forceNewApp: Bool = false, debug: Bool = false) -> ARTClientOptions {
ARTChannels_getChannelNamePrefix = { "test-\(setupOptionsCounter)" }
setupOptionsCounter += 1

if forceNewApp {
testApplication = nil
}

guard let app = testApplication else {
let request = NSMutableURLRequest(URL: NSURL(string: "https://\(options.restHost):\(options.tlsPort)/apps")!)
request.HTTPMethod = "POST"
request.HTTPBody = try? appSetupJson["post_apps"].rawData()

request.allHTTPHeaderFields = [
"Accept" : "application/json",
"Content-Type" : "application/json"
]

let (responseData, responseError, _) = NSURLSessionServerTrustSync().get(request)

if let error = responseError {
XCTFail(error.localizedDescription)
return options
}

testApplication = JSON(data: responseData!)

if debug {
options.logLevel = .Verbose
print(response)
print(testApplication!)
}

let key = response["keys"][0]

options.key = key["keyStr"].stringValue

return options
return setupOptions(options, debug: debug)
}

let key = app["keys"][0]
options.key = key["keyStr"].stringValue
return options
}

Expand Down Expand Up @@ -816,7 +827,6 @@ extension ARTWebSocketTransport {
}
}


// MARK: - Custom Nimble Matchers

/// A Nimble matcher that succeeds when two dates are quite the same.
Expand Down
17 changes: 12 additions & 5 deletions Tests/ARTRealtimeChannelTest.m
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#import "ARTTestUtil.h"
#import "ARTCrypto+Private.h"
#import "ARTChannelOptions.h"
#import "ARTChannels+Private.h"

@interface ARTRealtimeChannelTest : XCTestCase

Expand Down Expand Up @@ -207,18 +208,24 @@ - (void)testGetChannels {
[d setValue:channel forKey:channel.name];
}
XCTAssertEqual([[d allKeys] count], 3);
XCTAssertEqualObjects([d valueForKey:@"channel"], c1);
XCTAssertEqualObjects([d valueForKey:@"channel2"], c2);
XCTAssertEqualObjects([d valueForKey:@"channel3"], c3);
NSString *prefix = ARTChannels_getChannelNamePrefix();
__block NSString *expectedName = [NSString stringWithFormat:@"%@-channel", prefix];
XCTAssertEqualObjects([d valueForKey:expectedName], c1);
expectedName = [NSString stringWithFormat:@"%@-channel2", prefix];
XCTAssertEqualObjects([d valueForKey:expectedName], c2);
expectedName = [NSString stringWithFormat:@"%@-channel3", prefix];
XCTAssertEqualObjects([d valueForKey:expectedName], c3);

[realtime.channels release:c3.name callback:^(ARTErrorInfo *errorInfo) {
NSMutableDictionary *d = [[NSMutableDictionary alloc] init];
for (ARTRealtimeChannel *channel in realtime.channels) {
[d setValue:channel forKey:channel.name];
}
XCTAssertEqual([[d allKeys] count], 2);
XCTAssertEqualObjects([d valueForKey:@"channel"], c1);
XCTAssertEqualObjects([d valueForKey:@"channel2"], c2);
expectedName = [NSString stringWithFormat:@"%@-channel", prefix];
XCTAssertEqualObjects([d valueForKey:expectedName], c1);
expectedName = [NSString stringWithFormat:@"%@-channel2", prefix];
XCTAssertEqualObjects([d valueForKey:expectedName], c2);
}];

[expectation fulfill];
Expand Down
17 changes: 2 additions & 15 deletions Tests/ARTRestCapabilityTest.m
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#import "ARTAuth.h"
#import "ARTTokenParams.h"
#import "ARTTokenDetails.h"
#import "ARTChannels+Private.h"

@interface ARTRestCapabilityTest : XCTestCase {
ARTRest *_rest;
Expand All @@ -34,23 +35,9 @@ - (void)tearDown {
[super tearDown];
}

- (void)withRestRestrictCap:(void (^)(ARTRest *rest))cb {
if (!_rest) {
ARTClientOptions *theOptions = [ARTTestUtil clientOptions];
[ARTTestUtil setupApp:theOptions withAlteration:TestAlterationRestrictCapability callback:^(ARTClientOptions *options) {
if (options) {

}
}];
return;
}
else {
cb(_rest);
}
}

- (void)testPublishRestricted {
ARTClientOptions *options = [ARTTestUtil newSandboxApp:self withDescription:__FUNCTION__];
ARTChannels_getChannelNamePrefix = nil; // Force that channel name is not changed.

__weak XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"%s", __FUNCTION__]];
options.clientId = @"client_string";
Expand Down
6 changes: 6 additions & 0 deletions Tests/ARTRestPresenceTest.m
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#import "ARTChannels.h"
#import "ARTDataQuery.h"
#import "ARTPaginatedResult.h"
#import "ARTChannels+Private.h"

@interface ARTRestPresenceTest : XCTestCase

Expand All @@ -32,6 +33,7 @@ - (void)tearDown {

- (void)testPresence {
ARTClientOptions *options = [ARTTestUtil newSandboxApp:self withDescription:__FUNCTION__];
ARTChannels_getChannelNamePrefix = nil; // Force that channel name is not changed.

__weak XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"%s", __FUNCTION__]];
ARTRest *rest = [[ARTRest alloc] initWithOptions:options];
Expand Down Expand Up @@ -75,6 +77,7 @@ - (void)testPresence {

- (void)testHistory {
ARTClientOptions *options = [ARTTestUtil newSandboxApp:self withDescription:__FUNCTION__];
ARTChannels_getChannelNamePrefix = nil; // Force that channel name is not changed.
__weak XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"%s", __FUNCTION__]];
ARTRest *rest = [[ARTRest alloc] initWithOptions:options];
ARTRestChannel *channel = [rest.channels get:@"persisted:presence_fixtures"];
Expand All @@ -89,6 +92,7 @@ - (void)testHistory {

- (void)testHistoryDefaultBackwards {
ARTClientOptions *options = [ARTTestUtil newSandboxApp:self withDescription:__FUNCTION__];
ARTChannels_getChannelNamePrefix = nil; // Force that channel name is not changed.
__weak XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"%s", __FUNCTION__]];
ARTRest *rest = [[ARTRest alloc] initWithOptions:options];
ARTRestChannel *channel = [rest.channels get:@"persisted:presence_fixtures"];
Expand All @@ -100,11 +104,13 @@ - (void)testHistoryDefaultBackwards {
XCTAssertEqualObjects(@"true", [m data]);
[expectation fulfill];
} error:nil];

[self waitForExpectationsWithTimeout:[ARTTestUtil timeout] handler:nil];
}

- (void)testHistoryDirection {
ARTClientOptions *options = [ARTTestUtil newSandboxApp:self withDescription:__FUNCTION__];
ARTChannels_getChannelNamePrefix = nil; // Force that channel name is not changed.
__weak XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"%s", __FUNCTION__]];
ARTRest *rest = [[ARTRest alloc] initWithOptions:options];
ARTRestChannel *channel = [rest.channels get:@"persisted:presence_fixtures"];
Expand Down
Loading

0 comments on commit 98c99da

Please sign in to comment.