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
|
# File 'lib/shark/rspec/fake_double_opt_in/request.rb', line 16
def stub_requests
WebMock.stub_request(:post, %r{^#{host}/requests}).to_return do |request|
log_info "Faking POST request with body: #{request.body}"
data = JSON.parse(request.body)['data']
attributes = data['attributes'] || {}
ObjectCache.instance.create_request(attributes)
fake_response(200, {
data: {
id: SecureRandom.uuid,
attributes: attributes,
type: 'requests'
}
})
end
WebMock.stub_request(:post, %r{^#{host}/executions/.+/verify}).to_return do |request|
log_info 'Faking POST request'
verification_token = request.uri.path.split('/').reverse[1]
object = ObjectCache.instance.find_execution(verification_token)
if verification_token_invalid?(object)
fake_response(404, { errors: [] })
else
verification_expires_at = object['attributes']['verification_expires_at']
max_verifications = object['attributes']['max_verifications']
verifications_count = object['attributes']['verifications_count']
is_verification_expired = Time.now.to_i > verification_expires_at
is_number_of_requests_exceeded = max_verifications <= verifications_count
if is_verification_expired
errors = [{ code: 'verification_expired' }]
fake_response(422, { errors: errors })
elsif is_number_of_requests_exceeded
errors = [{ code: 'exceeded_number_of_verification_requests' }]
fake_response(422, { errors: errors })
else
fake_response(200, { data: object })
end
end
end
WebMock.stub_request(:get, %r{^#{host}/executions/.+}).to_return do |request|
log_info 'Faking GET request'
verification_token = request.uri.path.split('/').reverse[0]
object = ObjectCache.instance.find_execution(verification_token)
if verification_token_invalid?(object)
fake_response(404, { errors: [] })
else
attributes = object['attributes']
if attributes['verifications_count'].zero?
fake_response(422, { errors: [{ code: 'requested_unverified_execution' }] })
else
fake_response(200, { data: object })
end
end
end
WebMock.stub_request(:delete, %r{^#{host}/executions/.+}).to_return do |request|
log_info 'Faking DELETE request'
verification_token = request.uri.path.split('/').reverse[0]
object = ObjectCache.instance.find_execution(verification_token)
if verification_token_invalid?(object)
fake_response(404, { errors: [] })
else
ObjectCache.instance.remove_execution(verification_token)
fake_response(200, { data: object })
end
end
end
|