SenTest+FWaiter.m 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 "FTestContants.h"
  17. #import "SenTest+FWaiter.h"
  18. @implementation XCTestCase (FWaiter)
  19. - (NSTimeInterval)waitUntil:(BOOL (^)(void))predicate {
  20. return [self waitUntil:predicate timeout:kFirebaseTestWaitUntilTimeout description:nil];
  21. }
  22. - (NSTimeInterval)waitUntil:(BOOL (^)(void))predicate description:(NSString *)desc {
  23. return [self waitUntil:predicate timeout:kFirebaseTestWaitUntilTimeout description:desc];
  24. }
  25. - (NSTimeInterval)waitUntil:(BOOL (^)(void))predicate timeout:(NSTimeInterval)seconds {
  26. return [self waitUntil:predicate timeout:seconds description:nil];
  27. }
  28. - (NSTimeInterval)waitUntil:(BOOL (^)(void))predicate
  29. timeout:(NSTimeInterval)seconds
  30. description:(NSString *)desc {
  31. NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
  32. NSDate *timeoutDate = [NSDate dateWithTimeIntervalSinceNow:seconds];
  33. NSTimeInterval timeoutTime = [timeoutDate timeIntervalSinceReferenceDate];
  34. NSTimeInterval currentTime;
  35. for (currentTime = [NSDate timeIntervalSinceReferenceDate];
  36. !predicate() && currentTime < timeoutTime;
  37. currentTime = [NSDate timeIntervalSinceReferenceDate]) {
  38. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
  39. beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.25]];
  40. }
  41. NSTimeInterval finish = [NSDate timeIntervalSinceReferenceDate];
  42. if (currentTime > timeoutTime) {
  43. if (desc != nil) {
  44. XCTFail("Timed out on: %@", desc);
  45. } else {
  46. XCTFail("Timed out");
  47. }
  48. }
  49. return (finish - start);
  50. }
  51. @end