forked from hypoyao/GYHttpMock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGYHttpMock.m
120 lines (103 loc) · 2.48 KB
/
GYHttpMock.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
//
// GYHttpMock.m
// GYNetwork
//
// Created by hypo on 16/1/13.
// Copyright © 2016年 hypoyao. All rights reserved.
//
#import "GYHttpMock.h"
#import "GYNSURLHook.h"
#import "GYNSURLSessionHook.h"
#import "GYHttpClientHook.h"
static GYHttpMock *sharedInstance = nil;
@implementation GYHttpMock
+ (GYHttpMock *)sharedInstance
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (id)init
{
self = [super init];
if (self) {
_stubbedRequests = [NSMutableArray array];
_hooks = [NSMutableArray array];
[self registerHook:[[GYNSURLHook alloc] init]];
if (NSClassFromString(@"NSURLSession") != nil) {
[self registerHook:[[GYNSURLSessionHook alloc] init]];
}
}
return self;
}
- (void)startMock
{
if (!self.isStarted){
[self loadHooks];
self.started = YES;
}
}
- (void)stopMock
{
[self unloadHooks];
self.started = NO;
[self clearMocks];
}
- (void)clearMocks
{
@synchronized(_stubbedRequests) {
[_stubbedRequests removeAllObjects];
}
}
- (void)addMockRequest:(GYMockRequest *)request {
@synchronized(_stubbedRequests) {
[self.stubbedRequests addObject:request];
}
}
- (void)registerHook:(GYHttpClientHook *)hook
{
if (![self hookWasRegistered:hook]) {
@synchronized(_hooks) {
[_hooks addObject:hook];
}
}
}
- (BOOL)hookWasRegistered:(GYHttpClientHook *)aHook {
@synchronized(_hooks) {
for (GYHttpClientHook *hook in _hooks) {
if ([hook isMemberOfClass: [aHook class]]) {
return YES;
}
}
return NO;
}
}
- (GYMockResponse *)responseForRequest:(id<GYHTTPRequest>)request
{
@synchronized(_stubbedRequests) {
for(GYMockRequest *someStubbedRequest in _stubbedRequests) {
if ([someStubbedRequest matchesRequest:request]) {
someStubbedRequest.response.isUpdatePartResponseBody = someStubbedRequest.isUpdatePartResponseBody;
return someStubbedRequest.response;
}
}
return nil;
}
}
- (void)loadHooks {
@synchronized(_hooks) {
for (GYHttpClientHook *hook in _hooks) {
[hook load];
}
}
}
- (void)unloadHooks {
@synchronized(_hooks) {
for (GYHttpClientHook *hook in _hooks) {
[hook unload];
}
}
}
@end