CompactionTests.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2017 Realm Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. ////////////////////////////////////////////////////////////////////////////
  18. #import "RLMTestCase.h"
  19. @interface RLMRealm ()
  20. - (BOOL)compact;
  21. @end
  22. @interface CompactionTests : RLMTestCase
  23. @end
  24. @implementation CompactionTests {
  25. uint64_t _expectedTotalBytesBefore;
  26. }
  27. static const NSUInteger expectedUsedBytesBeforeMin = 50000;
  28. static const NSUInteger count = 1000;
  29. #pragma mark - Helpers
  30. - (unsigned long long)fileSize:(NSURL *)fileURL {
  31. NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:fileURL.path error:nil];
  32. return [attributes[NSFileSize] unsignedLongLongValue];
  33. }
  34. - (void)setUp {
  35. [super setUp];
  36. @autoreleasepool {
  37. // Make compactable Realm
  38. RLMRealm *realm = self.realmWithTestPath;
  39. NSString *uuid = [[NSUUID UUID] UUIDString];
  40. [realm transactionWithBlock:^{
  41. [StringObject createInRealm:realm withValue:@[@"A"]];
  42. for (NSUInteger i = 0; i < count; ++i) {
  43. [StringObject createInRealm:realm withValue:@[uuid]];
  44. }
  45. [StringObject createInRealm:realm withValue:@[@"B"]];
  46. }];
  47. }
  48. _expectedTotalBytesBefore = [self fileSize:RLMTestRealmURL()];
  49. }
  50. #pragma mark - Tests
  51. - (void)testCompact {
  52. RLMRealm *realm = self.realmWithTestPath;
  53. unsigned long long fileSizeBefore = [self fileSize:realm.configuration.fileURL];
  54. StringObject *object = [StringObject allObjectsInRealm:realm].firstObject;
  55. XCTAssertTrue([realm compact]);
  56. XCTAssertTrue(object.isInvalidated);
  57. XCTAssertEqual([[StringObject allObjectsInRealm:realm] count], count + 2);
  58. XCTAssertEqualObjects(@"A", [[StringObject allObjectsInRealm:realm].firstObject stringCol]);
  59. XCTAssertEqualObjects(@"B", [[StringObject allObjectsInRealm:realm].lastObject stringCol]);
  60. unsigned long long fileSizeAfter = [self fileSize:realm.configuration.fileURL];
  61. XCTAssertGreaterThan(fileSizeBefore, fileSizeAfter);
  62. }
  63. - (void)testSuccessfulCompactOnLaunch {
  64. // Configure the Realm to compact on launch
  65. RLMRealmConfiguration *configuration = [RLMRealmConfiguration defaultConfiguration];
  66. configuration.fileURL = RLMTestRealmURL();
  67. configuration.shouldCompactOnLaunch = ^BOOL(NSUInteger totalBytes, NSUInteger usedBytes){
  68. // Confirm expected sizes
  69. XCTAssertEqual(totalBytes, _expectedTotalBytesBefore);
  70. XCTAssertTrue((usedBytes < totalBytes) && (usedBytes > expectedUsedBytesBeforeMin));
  71. return true;
  72. };
  73. // Confirm expected sizes before and after opening the Realm
  74. XCTAssertEqual([self fileSize:configuration.fileURL], _expectedTotalBytesBefore);
  75. RLMRealm *realm = [RLMRealm realmWithConfiguration:configuration error:nil];
  76. XCTAssertLessThan([self fileSize:configuration.fileURL], _expectedTotalBytesBefore);
  77. // Validate that the file still contains what it should
  78. XCTAssertEqual([[StringObject allObjectsInRealm:realm] count], count + 2);
  79. XCTAssertEqualObjects(@"A", [[StringObject allObjectsInRealm:realm].firstObject stringCol]);
  80. XCTAssertEqualObjects(@"B", [[StringObject allObjectsInRealm:realm].lastObject stringCol]);
  81. }
  82. - (void)testNoBlockCompactOnLaunch {
  83. // Configure the Realm to compact on launch
  84. RLMRealmConfiguration *configuration = [RLMRealmConfiguration defaultConfiguration];
  85. configuration.fileURL = RLMTestRealmURL();
  86. // Confirm expected sizes before and after opening the Realm
  87. XCTAssertEqual([self fileSize:configuration.fileURL], _expectedTotalBytesBefore);
  88. RLMRealm *realm = [RLMRealm realmWithConfiguration:configuration error:nil];
  89. XCTAssertEqual([self fileSize:configuration.fileURL], _expectedTotalBytesBefore);
  90. // Validate that the file still contains what it should
  91. XCTAssertEqual([[StringObject allObjectsInRealm:realm] count], count + 2);
  92. XCTAssertEqualObjects(@"A", [[StringObject allObjectsInRealm:realm].firstObject stringCol]);
  93. XCTAssertEqualObjects(@"B", [[StringObject allObjectsInRealm:realm].lastObject stringCol]);
  94. }
  95. - (void)testCachedRealmCompactOnLaunch {
  96. // Test that the compaction block never gets called if there are cached Realms
  97. // Access Realm before opening it with a compaction block
  98. RLMRealmConfiguration *configuration = [RLMRealmConfiguration defaultConfiguration];
  99. configuration.fileURL = RLMTestRealmURL();
  100. __unused RLMRealm *firstRealm = [RLMRealm realmWithConfiguration:configuration error:nil];
  101. // Configure the Realm to compact on launch
  102. RLMRealmConfiguration *configurationWithCompactBlock = [configuration copy];
  103. __block BOOL compactBlockInvoked = NO;
  104. configurationWithCompactBlock.shouldCompactOnLaunch = ^BOOL(__unused NSUInteger totalBytes, __unused NSUInteger usedBytes){
  105. compactBlockInvoked = YES;
  106. // Always attempt to compact
  107. return YES;
  108. };
  109. // Confirm expected sizes before and after opening the Realm
  110. XCTAssertEqual([self fileSize:configuration.fileURL], _expectedTotalBytesBefore);
  111. RLMRealm *realm = [RLMRealm realmWithConfiguration:configurationWithCompactBlock error:nil];
  112. XCTAssertFalse(compactBlockInvoked);
  113. XCTAssertEqual([self fileSize:configuration.fileURL], _expectedTotalBytesBefore);
  114. // Validate that the file still contains what it should
  115. XCTAssertEqual([[StringObject allObjectsInRealm:realm] count], count + 2);
  116. XCTAssertEqualObjects(@"A", [[StringObject allObjectsInRealm:realm].firstObject stringCol]);
  117. XCTAssertEqualObjects(@"B", [[StringObject allObjectsInRealm:realm].lastObject stringCol]);
  118. }
  119. - (void)testCachedRealmOtherThreadCompactOnLaunch {
  120. // Test that the compaction block never gets called if the Realm is open on a different thread
  121. // Access Realm before opening it with a compaction block
  122. RLMRealmConfiguration *configuration = [RLMRealmConfiguration defaultConfiguration];
  123. configuration.fileURL = RLMTestRealmURL();
  124. dispatch_semaphore_t failedCompactTestCompleteSema = dispatch_semaphore_create(0);
  125. dispatch_semaphore_t bgRealmClosedSema = dispatch_semaphore_create(0);
  126. XCTestExpectation *realmOpenedExpectation = [self expectationWithDescription:@"Realm was opened on background thread"];
  127. [self dispatchAsync:^{
  128. @autoreleasepool {
  129. __unused RLMRealm *firstRealm = [RLMRealm realmWithConfiguration:configuration error:nil];
  130. [realmOpenedExpectation fulfill];
  131. dispatch_semaphore_wait(failedCompactTestCompleteSema, DISPATCH_TIME_FOREVER);
  132. }
  133. dispatch_semaphore_signal(bgRealmClosedSema);
  134. }];
  135. [self waitForExpectationsWithTimeout:2 handler:nil];
  136. @autoreleasepool {
  137. // Configure the Realm to compact on launch
  138. RLMRealmConfiguration *configurationWithCompactBlock = [configuration copy];
  139. __block BOOL compactBlockInvoked = NO;
  140. configurationWithCompactBlock.shouldCompactOnLaunch = ^BOOL(__unused NSUInteger totalBytes, __unused NSUInteger usedBytes){
  141. compactBlockInvoked = YES;
  142. // Always attempt to compact
  143. return YES;
  144. };
  145. // Confirm expected sizes before and after opening the Realm
  146. XCTAssertEqual([self fileSize:configuration.fileURL], _expectedTotalBytesBefore);
  147. __unused RLMRealm *realm = [RLMRealm realmWithConfiguration:configurationWithCompactBlock error:nil];
  148. XCTAssertFalse(compactBlockInvoked);
  149. XCTAssertEqual([self fileSize:configuration.fileURL], _expectedTotalBytesBefore);
  150. dispatch_semaphore_signal(failedCompactTestCompleteSema);
  151. }
  152. dispatch_semaphore_wait(bgRealmClosedSema, DISPATCH_TIME_FOREVER);
  153. // Configure the Realm to compact on launch
  154. RLMRealmConfiguration *configurationWithCompactBlock = [configuration copy];
  155. __block BOOL compactBlockInvoked = NO;
  156. configurationWithCompactBlock.shouldCompactOnLaunch = ^BOOL(NSUInteger totalBytes, NSUInteger usedBytes){
  157. // Confirm expected sizes
  158. XCTAssertEqual(totalBytes, _expectedTotalBytesBefore);
  159. XCTAssertTrue((usedBytes < totalBytes) && (usedBytes > expectedUsedBytesBeforeMin));
  160. compactBlockInvoked = YES;
  161. return true;
  162. };
  163. // Confirm expected sizes before and after opening the Realm
  164. XCTAssertEqual([self fileSize:configuration.fileURL], _expectedTotalBytesBefore);
  165. RLMRealm *realm = [RLMRealm realmWithConfiguration:configurationWithCompactBlock error:nil];
  166. XCTAssertTrue(compactBlockInvoked);
  167. XCTAssertLessThan([self fileSize:configuration.fileURL], _expectedTotalBytesBefore);
  168. // Validate that the file still contains what it should
  169. XCTAssertEqual([[StringObject allObjectsInRealm:realm] count], count + 2);
  170. XCTAssertEqualObjects(@"A", [[StringObject allObjectsInRealm:realm].firstObject stringCol]);
  171. XCTAssertEqualObjects(@"B", [[StringObject allObjectsInRealm:realm].lastObject stringCol]);
  172. }
  173. - (void)testReturnNoCompactOnLaunch {
  174. // Configure the Realm to compact on launch
  175. RLMRealmConfiguration *configuration = [RLMRealmConfiguration defaultConfiguration];
  176. configuration.fileURL = RLMTestRealmURL();
  177. configuration.shouldCompactOnLaunch = ^BOOL(NSUInteger totalBytes, NSUInteger usedBytes){
  178. // Confirm expected sizes
  179. XCTAssertEqual(totalBytes, _expectedTotalBytesBefore);
  180. XCTAssertTrue((usedBytes < totalBytes) && (usedBytes > expectedUsedBytesBeforeMin));
  181. // Don't compact.
  182. return NO;
  183. };
  184. // Confirm expected sizes before and after opening the Realm
  185. XCTAssertEqual([self fileSize:configuration.fileURL], _expectedTotalBytesBefore);
  186. RLMRealm *realm = [RLMRealm realmWithConfiguration:configuration error:nil];
  187. XCTAssertEqual([self fileSize:configuration.fileURL], _expectedTotalBytesBefore);
  188. // Validate that the file still contains what it should
  189. XCTAssertEqual([[StringObject allObjectsInRealm:realm] count], count + 2);
  190. XCTAssertEqualObjects(@"A", [[StringObject allObjectsInRealm:realm].firstObject stringCol]);
  191. XCTAssertEqualObjects(@"B", [[StringObject allObjectsInRealm:realm].lastObject stringCol]);
  192. }
  193. - (void)testCompactOnLaunchValidation {
  194. RLMRealmConfiguration *configuration = [RLMRealmConfiguration defaultConfiguration];
  195. configuration.readOnly = YES;
  196. BOOL (^compactBlock)(NSUInteger, NSUInteger) = ^BOOL(__unused NSUInteger totalBytes, __unused NSUInteger usedBytes){
  197. return NO;
  198. };
  199. RLMAssertThrowsWithReasonMatching(configuration.shouldCompactOnLaunch = compactBlock,
  200. @"Cannot set `shouldCompactOnLaunch` when `readOnly` is set.");
  201. configuration.readOnly = NO;
  202. configuration.shouldCompactOnLaunch = compactBlock;
  203. RLMAssertThrowsWithReasonMatching(configuration.readOnly = YES,
  204. @"Cannot set `readOnly` when `shouldCompactOnLaunch` is set.");
  205. }
  206. - (void)testAccessDeniedOnTemporaryFile {
  207. RLMRealmConfiguration *configuration = [RLMRealmConfiguration defaultConfiguration];
  208. configuration.fileURL = RLMTestRealmURL();
  209. configuration.shouldCompactOnLaunch = ^(__unused NSUInteger totalBytes, __unused NSUInteger usedBytes){
  210. return YES;
  211. };
  212. NSURL *tmpURL = [configuration.fileURL URLByAppendingPathExtension:@"tmp_compaction_space"];
  213. [NSData.data writeToURL:tmpURL atomically:NO];
  214. [NSFileManager.defaultManager setAttributes:@{NSFileImmutable: @YES} ofItemAtPath:tmpURL.path error:nil];
  215. RLMAssertThrowsWithReason([RLMRealm realmWithConfiguration:configuration error:nil],
  216. @"unlink() failed: Operation not permitted");
  217. [NSFileManager.defaultManager setAttributes:@{NSFileImmutable: @NO} ofItemAtPath:tmpURL.path error:nil];
  218. XCTAssertNoThrow([RLMRealm realmWithConfiguration:configuration error:nil]);
  219. }
  220. @end