-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.py
235 lines (186 loc) · 6.37 KB
/
helpers.py
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
import json
import os
from requests import PreparedRequest
from requests.structures import CaseInsensitiveDict
from requests.compat import OrderedDict
from requests.cookies import RequestsCookieJar
from stormpath.auth import Sauthc1Signer
from stormpath.client import Client
from flask_stormpath.models import User
from pydispatch import dispatcher
from pprint import pprint
# Env variables
os.environ['STORMPATH_API_KEY_ID'] = '34T89RR6UW2JWTTUCB0CF8D87'
os.environ['STORMPATH_API_KEY_SECRET'] = 'm2dPlw8ql20JdyPKA5uUB3Ppgs4nNSp45IJsqRRdp0g'
os.environ['AUTH_SCHEME'] = 'SAuthc1'
def generate_request(method, url, body):
"""
Generate our own custom request, so we can calculate digest auth.
"""
method = method.upper()
url = url
files = []
json_string = None
headers = CaseInsensitiveDict({
'Accept': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
'Content-Type': 'application/json',
'User-Agent': 'stormpath-flask/0.4.4 flask/0.10.1 stormpath-sdk-python/2.4.5 python/2.7.6 Linux/LinuxMint (Linux-3.13.0-37-generic-x86_64-with-LinuxMint-17.1-rebecca)'
})
if body:
headers.update({'Content-Length': str(len(json.dumps(body)))})
params = OrderedDict()
auth = Sauthc1Signer(
id=os.environ.get('STORMPATH_API_KEY_ID'),
secret=os.environ.get('STORMPATH_API_KEY_SECRET'))
cookies = RequestsCookieJar()
hooks = {'response': []}
pr = PreparedRequest()
if body:
json_body = json.dumps(body)
else:
json_body = None
pr.prepare(
method=method.upper(),
url=url,
files=files,
data=json_body,
json=json_string,
headers=headers,
params=params,
auth=auth,
cookies=cookies,
hooks=hooks,
)
return pr
def get_resources():
"""
Load all objects needed for developing new Stormpath resources.
"""
AUTH_SCHEME = os.environ.get('AUTH_SCHEME')
client = Client(
id=os.environ.get('STORMPATH_API_KEY_ID'),
secret=os.environ.get('STORMPATH_API_KEY_SECRET'),
base_url='https://api.stormpath.com/v1',
scheme=AUTH_SCHEME)
client.tenant.refresh()
resources = {
'client': client
}
return resources
def custom_create(cls, client, data, href, params=None):
"""
Resource create. Currently bypassing base.py create() method.
"""
SIGNAL_RESOURCE_CREATED = 'resource-created'
instance = cls(client=client, href=href)
created = instance.resource_class(
instance._client,
properties=instance._store.create_resource(
instance._get_create_path(), data, params=params))
dispatcher.send(
signal=SIGNAL_RESOURCE_CREATED,
sender=instance.resource_class,
data=data,
params=params)
return created
def assert_request(req, resp, expected_req, expected_resp):
"""
Make sure that the request and response match the one we are trying to get.
"""
def assert_values(value1, value2, value_info):
if value1 != value2:
error_msg = '%s != %s' % (str(value1), str(value2))
raise AssertionError({'error': error_msg, 'value': value_info})
def assert_headers(headers, expected_headers):
x_date = headers.pop('X-Stormpath-Date')
x_date_expected = expected_headers.pop('X-Stormpath-Date')
auth = headers.pop('Authorization')
auth_expected = expected_headers.pop('Authorization')
headers.pop('User-Agent')
expected_headers.pop('User-Agent')
assert_values(len(x_date), len(x_date_expected), 'x_date')
assert_values(len(auth), len(auth_expected), 'auth')
assert_values(headers, expected_headers, 'headers')
# Compare requests
attrs = ['url', 'method', 'body']
for attr in attrs:
value = getattr(req, attr)
expected_value = getattr(expected_req, attr)
if attr == 'body':
assert_values(json.loads(value), json.loads(expected_value), attr)
else:
assert_values(value, expected_value, attr)
assert_headers(req.headers, expected_req.headers)
# Compare responses
attrs = ['url', 'status_code']
for attr in attrs:
value = getattr(resp, attr)
expected_value = expected_resp.get(attr)
assert_values(value, expected_value, attr)
print '\n'
pprint(json.loads(resp.content))
print '\n'
return None
def delete_resource(client, acc_url, resource):
client.accounts.get(acc_url).factors.items[0]
res_list = getattr(client.accounts.get(acc_url), resource + 's').items
if len(res_list) == 1:
res_list[0].delete()
else:
raise Exception('Resource cannot be deleted.')
return None
def development(params):
# Additional imports
pass
# Setup method
def setup():
# Enable breakpoint flag
os.environ['MYFLAG'] = 'notbar'
# Teardown method
def teardown(objects):
for obj in objects:
obj.delete()
# Disable breakpoint flag
os.environ['MYFLAG'] = 'notbar'
def main():
# Reset flag
os.environ['MYFLAG'] = 'notbar'
# Set variables
resource_name = 'factor'
acc_url = 'https://api.stormpath.com/v1/accounts/6FZ1uG8uXob6TrxJJQB9j2'
method = 'POST'
url = acc_url + '/factors?challenge=true'
body = {
"phone": {"number": "+385 995734532"},
"challenge": {"message": "${code}"},
"type": "SMS"}
status_code = 201
expected_response = {
'url': url,
'status_code': status_code}
# Environ variables
os.environ['expected_resp'] = json.dumps(expected_response)
os.environ['exp_req_method'] = method
os.environ['exp_req_url'] = url
os.environ['exp_req_body'] = json.dumps(body)
# Main
resources = get_resources()
client = resources['client']
# Set flag
os.environ['MYFLAG'] = 'assert_request'
try:
created = eval(resource_name.title())(
client,
properties=client.data_store.create_resource(
url, body, params=None))
except Exception as error:
os.environ['MYFLAG'] = 'notbar'
delete_resource(client, acc_url, resource_name)
return error
# Reset flag
os.environ['MYFLAG'] = 'notbar'
delete_resource(client, acc_url, resource_name)
print '\nSUCCESS\n'
return None