KWContainMatcher.m 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. //
  2. // Licensed under the terms in License.txt
  3. //
  4. // Copyright 2010 Allen Ding. All rights reserved.
  5. //
  6. #import "KWContainMatcher.h"
  7. #import "KWFormatter.h"
  8. #import "KWGenericMatchingAdditions.h"
  9. @interface KWContainMatcher()
  10. @property (nonatomic, readwrite, strong) id objects;
  11. @end
  12. @implementation KWContainMatcher
  13. #pragma mark - Getting Matcher Strings
  14. + (NSArray *)matcherStrings {
  15. return @[@"contain:", @"containObjectsInArray:"];
  16. }
  17. #pragma mark - Matching
  18. - (BOOL)evaluate {
  19. if (![self.subject respondsToSelector:@selector(containsObjectEqualToOrMatching:)])
  20. [NSException raise:@"KWMatcherException" format:@"subject does not respond to -containsObjectEqualToOrMatching:"];
  21. for (id object in self.objects) {
  22. if (![self.subject containsObjectEqualToOrMatching:object])
  23. return NO;
  24. }
  25. return YES;
  26. }
  27. #pragma mark - Getting Failure Messages
  28. - (NSString *)objectsPhrase {
  29. if ([self.objects count] == 1)
  30. return [KWFormatter formatObject:(self.objects)[0]];
  31. return [NSString stringWithFormat:@"all of %@", [KWFormatter formatObject:self.objects]];
  32. }
  33. - (NSString *)failureMessageForShould {
  34. return [NSString stringWithFormat:@"expected subject to contain %@", [self objectsPhrase]];
  35. }
  36. - (NSString *)description {
  37. return [NSString stringWithFormat:@"contain %@", [self objectsPhrase]];
  38. }
  39. #pragma mark - Configuring Matchers
  40. - (void)contain:(id)anObject {
  41. self.objects = @[anObject];
  42. }
  43. - (void)containObjectsInArray:(NSArray *)anArray {
  44. self.objects = anArray;
  45. }
  46. @end
  47. @implementation KWMatchVerifier(KWContainMatcherAdditions)
  48. #pragma mark - Verifying
  49. - (void)containObjects:(id)firstObject, ... {
  50. NSMutableArray *objects = [NSMutableArray array];
  51. va_list argumentList;
  52. va_start(argumentList, firstObject);
  53. id object = firstObject;
  54. while (object != nil) {
  55. [objects addObject:object];
  56. object = va_arg(argumentList, id);
  57. }
  58. va_end(argumentList);
  59. [(id)self containObjectsInArray:objects];
  60. }
  61. @end