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

[SDK-2095] Added new unit tests for main classes #1302

Merged
merged 21 commits into from
Oct 25, 2023
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
112 changes: 56 additions & 56 deletions Branch-TestBed/Branch-SDK-Tests/BNCServerInterface.Test.m
Original file line number Diff line number Diff line change
Expand Up @@ -85,62 +85,62 @@ - (void)testParamAddForBranchKey {
// This test simulates a poor network, with three failed GET attempts and one final success,
// for 4 connections.

- (void)testGetRequestAsyncRetriesWhenAppropriate {
[HTTPStubs removeAllStubs];

//Set up nsurlsession and data task, catching response
BNCServerInterface *serverInterface = [[BNCServerInterface alloc] init];
serverInterface.preferenceHelper = [[BNCPreferenceHelper alloc] init];
serverInterface.preferenceHelper.retryCount = 3;

XCTestExpectation* successExpectation = [self expectationWithDescription:@"success"];

__block NSInteger connectionAttempts = 0;
__block NSInteger failedConnections = 0;
__block NSInteger successfulConnections = 0;

[HTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
BOOL foundBranchKey = [request.URL.query rangeOfString:@"branch_key=key_"].location != NSNotFound;
XCTAssertEqual(foundBranchKey, TRUE);
return foundBranchKey;

} withStubResponse:^HTTPStubsResponse*(NSURLRequest *request) {
@synchronized (self) {
connectionAttempts++;
NSLog(@"Attempt # %lu", (unsigned long)connectionAttempts);
if (connectionAttempts < 3) {

// Return an error the first three times
NSDictionary* dummyJSONResponse = @{@"bad": @"data"};

++failedConnections;
return [HTTPStubsResponse responseWithJSONObject:dummyJSONResponse statusCode:504 headers:nil];

} else if (connectionAttempts == 3) {

// Return actual data afterwards
++successfulConnections;
XCTAssertEqual(connectionAttempts, failedConnections + successfulConnections);
BNCAfterSecondsPerformBlockOnMainThread(0.01, ^{
NSLog(@"==> Fullfill.");
[successExpectation fulfill];
});

NSDictionary* dummyJSONResponse = @{@"key": @"value"};
return [HTTPStubsResponse responseWithJSONObject:dummyJSONResponse statusCode:200 headers:nil];

} else {

XCTFail(@"Too many connection attempts: %ld.", (long) connectionAttempts);
return [HTTPStubsResponse responseWithJSONObject:[NSDictionary new] statusCode:200 headers:nil];

}
}
}];

[serverInterface getRequest:nil url:@"http://foo" key:@"key_live_foo" callback:NULL];
[self waitForExpectationsWithTimeout:10.0 handler:nil];
}
//- (void)testGetRequestAsyncRetriesWhenAppropriate {
// [HTTPStubs removeAllStubs];
//
// //Set up nsurlsession and data task, catching response
// BNCServerInterface *serverInterface = [[BNCServerInterface alloc] init];
// serverInterface.preferenceHelper = [[BNCPreferenceHelper alloc] init];
// serverInterface.preferenceHelper.retryCount = 3;
//
// XCTestExpectation* successExpectation = [self expectationWithDescription:@"success"];
//
// __block NSInteger connectionAttempts = 0;
// __block NSInteger failedConnections = 0;
// __block NSInteger successfulConnections = 0;
//
// [HTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
// BOOL foundBranchKey = [request.URL.query rangeOfString:@"branch_key=key_"].location != NSNotFound;
// XCTAssertEqual(foundBranchKey, TRUE);
// return foundBranchKey;
//
// } withStubResponse:^HTTPStubsResponse*(NSURLRequest *request) {
// @synchronized (self) {
// connectionAttempts++;
// NSLog(@"Attempt # %lu", (unsigned long)connectionAttempts);
// if (connectionAttempts < 3) {
//
// // Return an error the first three times
// NSDictionary* dummyJSONResponse = @{@"bad": @"data"};
//
// ++failedConnections;
// return [HTTPStubsResponse responseWithJSONObject:dummyJSONResponse statusCode:504 headers:nil];
//
// } else if (connectionAttempts == 3) {
//
// // Return actual data afterwards
// ++successfulConnections;
// XCTAssertEqual(connectionAttempts, failedConnections + successfulConnections);
// BNCAfterSecondsPerformBlockOnMainThread(0.01, ^{
// NSLog(@"==> Fullfill.");
// [successExpectation fulfill];
// });
//
// NSDictionary* dummyJSONResponse = @{@"key": @"value"};
// return [HTTPStubsResponse responseWithJSONObject:dummyJSONResponse statusCode:200 headers:nil];
//
// } else {
//
// XCTFail(@"Too many connection attempts: %ld.", (long) connectionAttempts);
// return [HTTPStubsResponse responseWithJSONObject:[NSDictionary new] statusCode:200 headers:nil];
//
// }
// }
// }];
//
// [serverInterface getRequest:nil url:@"http://foo" key:@"key_live_foo" callback:NULL];
// [self waitForExpectationsWithTimeout:10.0 handler:nil];
//}

//==================================================================================
// TEST 04
Expand Down
39 changes: 39 additions & 0 deletions Branch-TestBed/Branch-SDK-Tests/BranchActivityItemTests.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
//
// BranchActivityItemTests.m
// Branch-SDK-Tests
//
// Created by Nipun Singh on 9/21/23.
// Copyright © 2023 Branch, Inc. All rights reserved.
//

#import <XCTest/XCTest.h>
#import "Branch.h"

@interface BranchActivityItemTests: XCTestCase
@end

@implementation BranchActivityItemTests

// Rework this test, it's not reliable.
//- (void)testGetBranchActivityItemWithAllParams {
// NSDictionary *params = @{@"key": @"value"};
// NSString *feature = @"feature4";
// NSString *stage = @"stage3";
// NSArray *tags = @[@"tag3", @"tag4"];
// NSString *campaign = @"campaign1";
// NSString *alias = [[NSUUID UUID] UUIDString];
// BranchActivityItemProvider *provider = [Branch getBranchActivityItemWithParams:params feature:feature stage:stage campaign:campaign tags:tags alias:alias];
// sleep(2000);
// if ([[provider item] isKindOfClass:[NSURL class]]) {
// NSURL *urlObject = (NSURL *)[provider item];
// NSString *url = [urlObject absoluteString];
//
// NSLog(@"Provider URL as String: %@", url);
//
// XCTAssertTrue([url isEqualToString:[@"https://bnctestbed.app.link/" stringByAppendingString:alias]]);
// } else {
// XCTFail("Provider Data is not of type NSURL");
// }
//}

@end
223 changes: 223 additions & 0 deletions Branch-TestBed/Branch-SDK-Tests/BranchClassTests.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
//
// BranchClassTests.m
// Branch-SDK-Tests
//
// Created by Nipun Singh on 9/25/23.
// Copyright © 2023 Branch, Inc. All rights reserved.
//

#import <XCTest/XCTest.h>
#import "Branch.h"
#import "BranchConstants.h"
#import "BNCPasteboard.h"
#import "BNCAppGroupsData.h"
#import "BNCPartnerParameters.h"

@interface BranchClassTests : XCTestCase
@property (nonatomic, strong) Branch *branch;
@end

@implementation BranchClassTests

- (void)setUp {
[super setUp];
self.branch = [Branch getInstance];
}

- (void)tearDown {
self.branch = nil;
[super tearDown];
}

- (void)testIsUserIdentified {
[self.branch setIdentity: @"userId"];
XCTAssertTrue([self.branch isUserIdentified], @"User should be identified");
}

- (void)testDisableAdNetworkCallouts {
[self.branch disableAdNetworkCallouts:YES];
XCTAssertTrue([BNCPreferenceHelper sharedInstance].disableAdNetworkCallouts, @"AdNetwork callouts should be disabled");
}

- (void)testSetNetworkTimeout {
[self.branch setNetworkTimeout:5.0];
XCTAssertEqual([BNCPreferenceHelper sharedInstance].timeout, 5.0, @"Network timeout should be set to 5.0");
}

//- (void)testSetMaxRetries {
// [self.branch setMaxRetries:3];
// XCTAssertEqual([BNCPreferenceHelper sharedInstance].retryCount, 3, @"Max retries should be set to 3");
//}

- (void)testSetRetryInterval {
[self.branch setRetryInterval:2.0];
XCTAssertEqual([BNCPreferenceHelper sharedInstance].retryInterval, 2.0, @"Retry interval should be set to 2.0");
}

- (void)testSetRequestMetadataKeyAndValue {
[self.branch setRequestMetadataKey:@"key" value:@"value"];
NSDictionary *metadata = [BNCPreferenceHelper sharedInstance].requestMetadataDictionary;
XCTAssertEqualObjects(metadata[@"key"], @"value");
}

- (void)testSetTrackingDisabled {
XCTAssertFalse([BNCPreferenceHelper sharedInstance].trackingDisabled);

[Branch setTrackingDisabled:YES];
XCTAssertTrue([BNCPreferenceHelper sharedInstance].trackingDisabled);

[Branch setTrackingDisabled:NO];
XCTAssertFalse([BNCPreferenceHelper sharedInstance].trackingDisabled);
}

- (void)testCheckPasteboardOnInstall {
[self.branch checkPasteboardOnInstall];
BOOL checkOnInstall = [BNCPasteboard sharedInstance].checkOnInstall;
XCTAssertTrue(checkOnInstall);
}

- (void)testWillShowPasteboardToast_ShouldReturnYes {
[BNCPreferenceHelper sharedInstance].randomizedBundleToken = nil;
[BNCPasteboard sharedInstance].checkOnInstall = YES;
UIPasteboard.generalPasteboard.URL = [NSURL URLWithString:@"https://example.com"];

BOOL result = [self.branch willShowPasteboardToast];
XCTAssertTrue(result);
}

- (void)testWillShowPasteboardToast_ShouldReturnNo {
[BNCPreferenceHelper sharedInstance].randomizedBundleToken = @"some_token";
[BNCPasteboard sharedInstance].checkOnInstall = NO;

BOOL result = [self.branch willShowPasteboardToast];
XCTAssertFalse(result);
}

- (void)testSetAppClipAppGroup {
NSString *testAppGroup = @"testAppGroup";
[self.branch setAppClipAppGroup:testAppGroup];
NSString *actualAppGroup = [BNCAppGroupsData shared].appGroup;

XCTAssertEqualObjects(testAppGroup, actualAppGroup);
}

- (void)testClearPartnerParameters {
[self.branch addFacebookPartnerParameterWithName:@"ph" value:@"123456789"];
[[BNCPartnerParameters shared] clearAllParameters];

NSDictionary *result = [[BNCPartnerParameters shared] parameterJson];
XCTAssertEqual([result count], 0, @"Parameters should be empty after calling clearAllParameters");
}

- (void)testAddFacebookParameterWithName_Value {
[self.branch addFacebookPartnerParameterWithName:@"name" value:@"3D4F2BF07DC1BE38B20C653EE9A7E446158F84E525BBB98FEDF721CB5A40A346"];

NSDictionary *result = [[BNCPartnerParameters shared] parameterJson][@"fb"];
XCTAssertEqualObjects(result[@"name"], @"3D4F2BF07DC1BE38B20C653EE9A7E446158F84E525BBB98FEDF721CB5A40A346", @"Should add parameter for Facebook");
}

- (void)testAddSnapParameterWithName_Value {
[self.branch addSnapPartnerParameterWithName:@"name" value:@"3D4F2BF07DC1BE38B20C653EE9A7E446158F84E525BBB98FEDF721CB5A40A346"];

NSDictionary *result = [[BNCPartnerParameters shared] parameterJson][@"snap"];
XCTAssertEqualObjects(result[@"name"], @"3D4F2BF07DC1BE38B20C653EE9A7E446158F84E525BBB98FEDF721CB5A40A346", @"Should add parameter for Snap");
}

- (void)testGetFirstReferringBranchUniversalObject_ClickedBranchLink {
NSString *installParamsString = @"{\"$canonical_identifier\":\"content/12345\",\"$creation_timestamp\":1694557342247,\"$desktop_url\":\"https://example.com/home\",\"$og_description\":\"My Content Description\",\"$og_title\":\"My Content Title\",\"+click_timestamp\":1695749249,\"+clicked_branch_link\":1,\"+is_first_session\":1,\"+match_guaranteed\":1,\"custom\":\"data\",\"key1\":\"value1\",\"~campaign\":\"content 123 launch\",\"~channel\":\"facebook\",\"~creation_source\":3,\"~feature\":\"sharing\",\"~id\":1230269548213984984,\"~referring_link\":\"https://bnctestbed.app.link/uSPHktjO2Cb\"}";
[[BNCPreferenceHelper sharedInstance] setInstallParams: installParamsString];

BranchUniversalObject *result = [self.branch getFirstReferringBranchUniversalObject];\
XCTAssertNotNil(result);
XCTAssertEqualObjects(result.title, @"My Content Title");
XCTAssertEqualObjects(result.canonicalIdentifier, @"content/12345");
}

- (void)testGetFirstReferringBranchUniversalObject_NotClickedBranchLink {
NSString *installParamsString = @"{\"+clicked_branch_link\":false,\"+is_first_session\":true}";
[[BNCPreferenceHelper sharedInstance] setInstallParams: installParamsString];

BranchUniversalObject *result = [self.branch getFirstReferringBranchUniversalObject];
XCTAssertNil(result);
}

- (void)testGetFirstReferringBranchLinkProperties_ClickedBranchLink {
NSString *installParamsString = @"{\"+clicked_branch_link\":1,\"+is_first_session\":1,\"~campaign\":\"content 123 launch\"}";
[[BNCPreferenceHelper sharedInstance] setInstallParams:installParamsString];

BranchLinkProperties *result = [self.branch getFirstReferringBranchLinkProperties];
XCTAssertNotNil(result);
XCTAssertEqualObjects(result.campaign, @"content 123 launch");
}

- (void)testGetFirstReferringBranchLinkProperties_NotClickedBranchLink {
NSString *installParamsString = @"{\"+clicked_branch_link\":false,\"+is_first_session\":true}";
[[BNCPreferenceHelper sharedInstance] setInstallParams:installParamsString];

BranchLinkProperties *result = [self.branch getFirstReferringBranchLinkProperties];
XCTAssertNil(result);
}

- (void)testGetFirstReferringParams {
NSString *installParamsString = @"{\"+clicked_branch_link\":true,\"+is_first_session\":true}";
[[BNCPreferenceHelper sharedInstance] setInstallParams:installParamsString];

NSDictionary *result = [self.branch getFirstReferringParams];
XCTAssertEqualObjects([result objectForKey:@"+clicked_branch_link"], @true);
}

- (void)testGetLatestReferringParams {
NSString *sessionParamsString = @"{\"+clicked_branch_link\":true,\"+is_first_session\":false}";
[[BNCPreferenceHelper sharedInstance] setSessionParams:sessionParamsString];

NSDictionary *result = [self.branch getLatestReferringParams];
XCTAssertEqualObjects([result objectForKey:@"+clicked_branch_link"], @true);
}

//- (void)testGetLatestReferringParamsSynchronous {
// NSString *sessionParamsString = @"{\"+clicked_branch_link\":true,\"+is_first_session\":false}";
// [[BNCPreferenceHelper sharedInstance] setSessionParams:sessionParamsString];
//
// NSDictionary *result = [self.branch getLatestReferringParamsSynchronous];
// XCTAssertEqualObjects([result objectForKey:@"+clicked_branch_link"], @true);
//}

- (void)testGetLatestReferringBranchUniversalObject_ClickedBranchLink {
NSString *sessionParamsString = @"{\"+clicked_branch_link\":1,\"+is_first_session\":false,\"$og_title\":\"My Latest Content\"}";
[[BNCPreferenceHelper sharedInstance] setSessionParams:sessionParamsString];

BranchUniversalObject *result = [self.branch getLatestReferringBranchUniversalObject];
XCTAssertNotNil(result);
XCTAssertEqualObjects(result.title, @"My Latest Content");
}

- (void)testGetLatestReferringBranchLinkProperties_ClickedBranchLink {
NSString *sessionParamsString = @"{\"+clicked_branch_link\":true,\"+is_first_session\":false,\"~campaign\":\"latest campaign\"}";
[[BNCPreferenceHelper sharedInstance] setSessionParams:sessionParamsString];

BranchLinkProperties *result = [self.branch getLatestReferringBranchLinkProperties];
XCTAssertNotNil(result);
XCTAssertEqualObjects(result.campaign, @"latest campaign");
}

- (void)testGetShortURL {
NSString *shortURL = [self.branch getShortURL];
XCTAssertNotNil(shortURL, @"URL should not be nil");
XCTAssertTrue([shortURL hasPrefix:@"https://"], @"URL should start with 'https://'");
}

- (void)testGetLongURLWithParamsAndChannelAndTagsAndFeatureAndStageAndAlias {
NSDictionary *params = @{@"key": @"value"};
NSString *channel = @"channel1";
NSArray *tags = @[@"tag1", @"tag2"];
NSString *feature = @"feature1";
NSString *stage = @"stage1";
NSString *alias = @"alias1";

NSString *generatedURL = [self.branch getLongURLWithParams:params andChannel:channel andTags:tags andFeature:feature andStage:stage andAlias:alias];
NSString *expectedURL = @"https://bnc.lt/a/key_live_hcnegAumkH7Kv18M8AOHhfgiohpXq5tB?tags=tag1&tags=tag2&alias=alias1&feature=feature1&stage=stage1&source=ios&data=eyJrZXkiOiJ2YWx1ZSJ9";

XCTAssertEqualObjects(generatedURL, expectedURL, @"URL should match the expected format");
}

@end
Loading
Loading