-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathMocktail.m
260 lines (217 loc) · 8.32 KB
/
Mocktail.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
//
// Mocktail.m
// Mocktail
//
// Created by Jim Puls on 2/7/13.
// Licensed to Square, Inc. under one or more contributor license agreements.
// See the LICENSE file distributed with this work for the terms under
// which Square, Inc. licenses this file to you.
//
#import "Mocktail.h"
#import "Mocktail_Private.h"
#import "MocktailResponse.h"
#import "MocktailURLProtocol.h"
#import <UIKit/UIKit.h>
static NSString *const MocktailFileExtension = @".tail";
static NSString *const MocktailPasteboardName = @"Mocktail Query String";
@interface Mocktail ()
@property (nonatomic, strong) NSURLSessionConfiguration *configuration;
@property (nonatomic, strong) NSMutableDictionary *mutablePlaceholderValues;
@property (nonatomic, strong) NSMutableSet *mutableMockResponses;
@end
@implementation Mocktail
static NSMutableSet *_allMocktails;
+ (NSMutableSet *)allMocktails;
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_allMocktails = [NSMutableSet new];
});
return _allMocktails;
}
+ (instancetype)startWithContentsOfDirectoryAtURL:(NSURL *)url
{
return [self startWithContentsOfDirectoryAtURL:url configuration:nil];
}
+ (instancetype)startWithContentsOfDirectoryAtURL:(NSURL *)url configuration:(NSURLSessionConfiguration *)configuration;
{
Mocktail *mocktail = [self new];
[mocktail registerContentsOfDirectoryAtURL:url];
mocktail.configuration = configuration;
[mocktail start];
return mocktail;
}
+ (instancetype)startWithFileAtURL:(NSURL *)url
{
return [self startWithFilesAtURLs:@[url]];
}
+ (instancetype)startWithFilesAtURLs:(NSArray *)urlArray
{
Mocktail *mocktail = [self new];
for (NSURL *url in urlArray) {
if ([url isKindOfClass:[NSURL class]]) {
[mocktail registerFileAtURL:url];
}
}
[mocktail start];
return mocktail;
}
- (id)init;
{
self = [super init];
if (!self) {
return nil;
}
_mutableMockResponses = [[NSMutableSet alloc] init];
_mutablePlaceholderValues = [[NSMutableDictionary alloc] init];
_networkDelay = 0.0;
return self;
}
#pragma mark - Accessors/Mutators
- (NSDictionary *)placeholderValues;
{
NSDictionary *placeholderValues;
@synchronized (_mutablePlaceholderValues) {
placeholderValues = [self.mutablePlaceholderValues copy];
}
return placeholderValues;
}
- (void)setObject:(id)object forKeyedSubscript:(id<NSCopying>)aKey
{
@synchronized (_mutablePlaceholderValues) {
[_mutablePlaceholderValues setObject:object forKey:aKey];
}
}
- (id)objectForKeyedSubscript:(id<NSCopying>)aKey;
{
NSString *value;
@synchronized (_mutablePlaceholderValues) {
value = [[_mutablePlaceholderValues objectForKey:aKey] copy];
}
return value;
}
- (NSSet *)mockResponses;
{
NSSet *mockResponses;
@synchronized (_mutableMockResponses) {
mockResponses = [_mutableMockResponses copy];
}
return mockResponses;
}
+ (MocktailResponse *)mockResponseForURL:(NSURL *)url method:(NSString *)method;
{
NSAssert(url && method, @"Expected a valid URL and method.");
MocktailResponse *matchingResponse = nil;
NSUInteger matchingRegexLength = 0;
for (Mocktail *mocktail in [Mocktail allMocktails]) {
NSMutableString *absoluteURL = [[url absoluteString] mutableCopy];
BOOL hasQuery = url.query != nil;
if (mocktail.additionalQueryParameters) {
[absoluteURL appendString:hasQuery ? @"&" : @"?"];
for (NSString *key in mocktail.additionalQueryParameters) {
[absoluteURL appendFormat:@"%@=%@&", key, mocktail.additionalQueryParameters[key]];
}
hasQuery = YES;
}
NSString *pasteboardExtras = [[UIPasteboard pasteboardWithName:MocktailPasteboardName create:NO] string];
if (pasteboardExtras.length > 0) {
[absoluteURL appendString:hasQuery ? @"&" : @"?"];
[absoluteURL appendString:pasteboardExtras];
hasQuery = YES;
}
for (MocktailResponse *response in mocktail.mockResponses) {
if ([response.absoluteURLRegex numberOfMatchesInString:absoluteURL options:0 range:NSMakeRange(0, absoluteURL.length)] > 0) {
if ([response.methodRegex numberOfMatchesInString:method options:0 range:NSMakeRange(0, method.length)] > 0) {
if (response.absoluteURLRegex.pattern.length > matchingRegexLength) {
matchingResponse = response;
matchingRegexLength = response.absoluteURLRegex.pattern.length;
}
}
}
}
}
return matchingResponse;
}
- (void)start;
{
NSAssert([NSThread isMainThread], @"Please start and stop Mocktail from the main thread");
NSAssert(![[Mocktail allMocktails] containsObject:self], @"Tried to start Mocktail twice");
if ([Mocktail allMocktails].count == 0) {
if (self.configuration) {
NSArray *classes = [[NSArray arrayWithObject:[MocktailURLProtocol class]] arrayByAddingObjectsFromArray:self.configuration.protocolClasses];
self.configuration.protocolClasses = classes;
} else {
NSAssert([NSURLProtocol registerClass:[MocktailURLProtocol class]], @"Unsuccessful Class Registration");
}
}
[[Mocktail allMocktails] addObject:self];
}
- (void)stop;
{
NSAssert([NSThread isMainThread], @"Please start and stop Mocktail from the main thread");
NSAssert([[Mocktail allMocktails] containsObject:self], @"Tried to stop unstarted Mocktail");
[[Mocktail allMocktails] removeObject:self];
if ([Mocktail allMocktails].count == 0) {
if (self.configuration) {
NSMutableArray *newClasses = [self.configuration.protocolClasses mutableCopy];
[newClasses removeObject:[MocktailURLProtocol class]];
self.configuration.protocolClasses = newClasses;
} else {
[NSURLProtocol unregisterClass:[MocktailURLProtocol class]];
}
}
}
#pragma mark - Parsing files
- (void)registerContentsOfDirectoryAtURL:(NSURL *)url;
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *fileURLs = [fileManager contentsOfDirectoryAtURL:url includingPropertiesForKeys:nil options:0 error:&error];
if (error) {
NSLog(@"Error opening %@: %@", url, error);
return;
}
for (NSURL *fileURL in fileURLs) {
if (![[fileURL absoluteString] hasSuffix:MocktailFileExtension]) {
continue;
}
[self registerFileAtURL:fileURL];
}
}
- (void)registerFileAtURL:(NSURL *)url;
{
NSAssert(url, @"Expected valid URL.");
NSError *error;
NSStringEncoding originalEncoding;
NSString *contentsOfFile = [NSString stringWithContentsOfURL:url usedEncoding:&originalEncoding error:&error];
if (error) {
NSLog(@"Error opening %@: %@", url, error);
return;
}
NSScanner *scanner = [NSScanner scannerWithString:contentsOfFile];
NSString *headerMatter = nil;
[scanner scanUpToString:@"\n\n" intoString:&headerMatter];
NSArray *lines = [headerMatter componentsSeparatedByString:@"\n"];
if ([lines count] < 4) {
NSLog(@"Invalid amount of lines: %u", (unsigned)[lines count]);
return;
}
MocktailResponse *response = [MocktailResponse new];
response.mocktail = self;
response.methodRegex = [NSRegularExpression regularExpressionWithPattern:lines[0] options:NSRegularExpressionCaseInsensitive error:nil];
response.absoluteURLRegex = [NSRegularExpression regularExpressionWithPattern:lines[1] options:NSRegularExpressionCaseInsensitive error:nil];
response.statusCode = [lines[2] integerValue];
NSMutableDictionary *headers = [[NSMutableDictionary alloc] init];
for (NSString *line in [lines subarrayWithRange:NSMakeRange(3, lines.count - 3)]) {
NSArray* parts = [line componentsSeparatedByString:@":"];
[headers setObject:[[parts lastObject] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
forKey:[parts firstObject]];
}
response.headers = headers;
response.fileURL = url;
response.bodyOffset = [headerMatter dataUsingEncoding:originalEncoding].length + 2;
@synchronized (_mutableMockResponses) {
[_mutableMockResponses addObject:response];
}
}
@end