KWExampleSuite.m 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. //
  2. // KWExampleSuite.m
  3. // Kiwi
  4. //
  5. // Created by Luke Redpath on 17/10/2011.
  6. // Copyright (c) 2011 Allen Ding. All rights reserved.
  7. //
  8. #import "KWExampleSuite.h"
  9. #import "KWAfterAllNode.h"
  10. #import "KWBeforeAllNode.h"
  11. #import "KWContextNode.h"
  12. #import "KWExample.h"
  13. #import "KWStringUtilities.h"
  14. #import "NSMethodSignature+KiwiAdditions.h"
  15. #import <objc/runtime.h>
  16. #define kKWINVOCATION_EXAMPLE_GROUP_KEY @"__KWExampleGroupKey"
  17. @interface KWExampleSuite()
  18. @property (nonatomic, strong) KWContextNode *rootNode;
  19. @property (nonatomic, strong) NSMutableArray *examples;
  20. @property (nonatomic, strong) NSMutableDictionary *selectorNameCache;
  21. @end
  22. @implementation KWExampleSuite
  23. - (id)initWithRootNode:(KWContextNode *)contextNode {
  24. self = [super init];
  25. if (self) {
  26. _rootNode = contextNode;
  27. _examples = [[NSMutableArray alloc] init];
  28. _selectorNameCache = [[NSMutableDictionary alloc] init];
  29. }
  30. return self;
  31. }
  32. - (void)addExample:(KWExample *)example {
  33. [self.examples addObject:example];
  34. example.suite = self;
  35. }
  36. - (void)markLastExampleAsLastInContext:(KWContextNode *)context
  37. {
  38. if ([self.examples count] > 0) {
  39. KWExample *lastExample = (KWExample *)[self.examples lastObject];
  40. [lastExample.lastInContexts addObject:context];
  41. }
  42. }
  43. #pragma mark - Example selector names
  44. - (NSString *)nextUniqueSelectorName:(NSString *)name {
  45. NSUInteger count = [(self.selectorNameCache[name] ?: @1) integerValue];
  46. NSString *uniqueName = name;
  47. if (count > 1) {
  48. NSString *format = [name hasSuffix:@"_"] ? @"%lu" : @"_%lu";
  49. uniqueName = [name stringByAppendingFormat:format, (unsigned long)count];
  50. }
  51. self.selectorNameCache[name] = @(++count);
  52. return uniqueName;
  53. }
  54. #pragma mark - NSFastEnumeration
  55. - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id [])buffer count:(NSUInteger)len {
  56. return [self.examples countByEnumeratingWithState:state objects:buffer count:len];
  57. }
  58. @end
  59. #pragma mark -
  60. // because XCTest will modify the invocation target, we'll have to store
  61. // another reference to the example group so we can retrieve it later
  62. @implementation NSInvocation (KWExampleGroup)
  63. - (void)kw_setExample:(KWExample *)exampleGroup {
  64. objc_setAssociatedObject(self, kKWINVOCATION_EXAMPLE_GROUP_KEY, exampleGroup, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  65. }
  66. - (KWExample *)kw_example {
  67. return objc_getAssociatedObject(self, kKWINVOCATION_EXAMPLE_GROUP_KEY);
  68. }
  69. @end