SenTest+FWaiter.m 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "SenTest+FWaiter.h"
  17. #import "FTestContants.h"
  18. @implementation XCTestCase (FWaiter)
  19. - (NSTimeInterval) waitUntil:(BOOL (^)())predicate {
  20. return [self waitUntil:predicate timeout:kFirebaseTestWaitUntilTimeout description:nil];
  21. }
  22. - (NSTimeInterval) waitUntil:(BOOL (^)())predicate description:(NSString*)desc {
  23. return [self waitUntil:predicate timeout:kFirebaseTestWaitUntilTimeout description:desc];
  24. }
  25. - (NSTimeInterval) waitUntil:(BOOL (^)())predicate timeout:(NSTimeInterval)seconds {
  26. return [self waitUntil:predicate timeout:seconds description:nil];
  27. }
  28. - (NSTimeInterval) waitUntil:(BOOL (^)())predicate timeout:(NSTimeInterval)seconds description:(NSString*)desc {
  29. NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
  30. NSDate *timeoutDate = [NSDate dateWithTimeIntervalSinceNow:seconds];
  31. NSTimeInterval timeoutTime = [timeoutDate timeIntervalSinceReferenceDate];
  32. NSTimeInterval currentTime;
  33. for (currentTime = [NSDate timeIntervalSinceReferenceDate];
  34. !predicate() && currentTime < timeoutTime;
  35. currentTime = [NSDate timeIntervalSinceReferenceDate]) {
  36. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.25]];
  37. }
  38. NSTimeInterval finish = [NSDate timeIntervalSinceReferenceDate];
  39. if (currentTime > timeoutTime) {
  40. if (desc != nil) {
  41. XCTFail("Timed out on: %@", desc);
  42. } else {
  43. XCTFail("Timed out");
  44. }
  45. }
  46. return (finish - start);
  47. }
  48. @end