-
Notifications
You must be signed in to change notification settings - Fork 2
/
pact-api-client
executable file
·294 lines (220 loc) · 10.6 KB
/
pact-api-client
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
#!/usr/bin/env python
"""pact-api-client [--help] [OPTIONS]
This is a reference implementation of a client that can interact with
the OAuth Enabled PaCT endpoints. It requires Python 2.7 and the
'restkit' library, available from https://pypi.python.org/pypi/restkit
With a school key, this client allows you to:
- Check your school OAuth credentials work.
- Upload an IDE file to PaCT.
- Download a PaCT/TWA results CSV.
With an SMS key, you can:
- List the schools that have selected you as an SMS.
- Create an OAuth key for a school.
- Delete the OAuth key for a school."""
from __future__ import print_function
import optparse
import logging
import pprint
import json
import restkit
def get_sms_data():
return {
'sms_product': 'PaCT Reference Client',
'sms_version': '0.1'
}
def monkeypatch_client():
"""Monkeypatch the restkit library so that it logs the body of the request."""
import restkit.client
def patched_perform(self, request):
body = request.body
result = self.old_perform(request)
logging.debug("The body of the request that was sent: %s", repr(body))
return result
restkit.client.Client.old_perform = restkit.client.Client.perform
restkit.client.Client.perform = patched_perform
def monkeypatch_signature_method_hmac_sha1():
"""Monkeypatch the OAuth library so it logs the base string used for signing"""
import restkit.oauth2
def patched_signing_base(self, request, consumer, token):
result = self.old_signing_base(request, consumer, token)
logging.debug("Signature base: %s", repr(result[1]))
return result
restkit.oauth2.SignatureMethod_HMAC_SHA1.old_signing_base = restkit.oauth2.SignatureMethod_HMAC_SHA1.signing_base
restkit.oauth2.SignatureMethod_HMAC_SHA1.signing_base = patched_signing_base
def get_oauth_filter(key, secret):
return restkit.OAuthFilter('*', restkit.oauth2.Consumer(key=key, secret=secret))
def oauth_test(oauth_filter, url):
resource = restkit.Resource(url + "/sms-api/v1/oauth-test", filters=[oauth_filter],
use_proxy=True)
data = get_sms_data()
logging.info("Connecting to PaCT to test OAuth Credentials...")
response = resource.post(payload=resource.make_params(data))
logging.info("...complete")
result = json.load(response.body_stream())
print (pprint.pformat(result))
def json_download(oauth_filter, url, from_date=None, to_date=None):
resource = restkit.Resource(url + "/sms-api/v2/download-results.json", filters=[oauth_filter],
use_proxy=True)
data = {}
if to_date:
data['to_date'] = to_date
if from_date:
data['from_date'] = from_date
logging.info("Requesting results JSON from PaCT...")
response = resource.get(**resource.make_params(data))
logging.info("...complete")
print(response.body_string())
def csv_download(oauth_filter, url, from_date=None, to_date=None):
resource = restkit.Resource(url + "/sms-api/v1/download-results-csv", filters=[oauth_filter],
use_proxy=True)
data = {}
if to_date:
data['to_date'] = to_date
if from_date:
data['from_date'] = from_date
logging.info("Requesting results CSV from PaCT...")
response = resource.get(**resource.make_params(data))
logging.info("...complete")
print(response.body_string())
def twa_csv_download(oauth_filter, url, from_date=None, to_date=None):
resource = restkit.Resource(url + "/sms-api/v1/download-twa-results-csv", filters=[oauth_filter],
use_proxy=True)
data = {}
if to_date:
data['to_date'] = to_date
if from_date:
data['from_date'] = from_date
logging.info("Requesting results CSV from PaCT...")
response = resource.get(**resource.make_params(data))
logging.info("...complete")
print(response.body_string())
def upload_ide(oauth_filter, url, filename):
# Note: this is just the 'urlencoded' version.
data = get_sms_data()
with open(filename) as f:
data['file'] = f.read()
resource = restkit.Resource(url + "/sms-api/v1/upload-ide", filters=[oauth_filter],
use_proxy=True)
logging.info("Uploading IDE file to PaCT...")
response = resource.post(payload=resource.make_params(data))
logging.info("...completed.")
print(response.body_string())
def list_schools(oauth_filter, url):
resource = restkit.Resource(url + "/sms-api/v1/manage-keys", filters=[oauth_filter],
use_proxy=True)
logging.info("Retrieving a list of my schools from PaCT...")
response = resource.get()
logging.info("...complete")
result = json.load(response.body_stream())
print (pprint.pformat(result))
def create_key(oauth_filter, url, moe_school_id):
full_url = "%s/sms-api/v1/manage-keys/%s/create" % (url, moe_school_id)
resource = restkit.Resource(full_url, filters=[oauth_filter],
use_proxy=True)
logging.info("Requesting a new key for school '%s' from PaCT..." % moe_school_id)
response = resource.post()
logging.info("...complete")
result = json.load(response.body_stream())
print (pprint.pformat(result))
def burn_key(oauth_filter, url, moe_school_id):
full_url = "%s/sms-api/v1/manage-keys/%s/delete" % (url, moe_school_id)
resource = restkit.Resource(full_url, filters=[oauth_filter],
use_proxy=True)
logging.info("Requestion removal of key for school '%s' from PaCT..." % moe_school_id)
response = resource.post()
logging.info("...complete")
result = json.load(response.body_stream())
print (pprint.pformat(result))
def parse_options():
parser = optparse.OptionParser(usage=__doc__)
general_options = optparse.OptionGroup(parser, "General Options")
general_options.add_option("-v", "--verbose", dest="verbose",
action="store_true",
help="enable debugging output")
general_options.add_option("-k", "--key", dest="key")
general_options.add_option("-s", "--secret", dest="secret")
general_options.add_option("-u", "--url", dest="url",
default="https://pact-sms-testing.example.com",
help="URL of the instance of PaCT, "
"defaults to %default")
parser.add_option_group(general_options)
csv_download = optparse.OptionGroup(parser, "PaCT CSV Result Download")
csv_download.add_option("-c", "--csv-download",
help="Download PaCT results CSV.",
action="store_true")
parser.add_option_group(csv_download)
twa_csv_download = optparse.OptionGroup(parser, "TWA CSV Result Download")
twa_csv_download.add_option("-C", "--twa-csv-download",
help="Download TWA results CSV.",
action="store_true")
parser.add_option_group(twa_csv_download)
json_download = optparse.OptionGroup(parser, "JSON Result Download")
json_download.add_option("-j", "--json-download",
help="Download PaCT results JSON.",
action="store_true")
parser.add_option_group(json_download)
daterange = optparse.OptionGroup(parser, "Judgment Result Filtering")
daterange.add_option("-f", "--from-date", metavar="YYYY-MM-DD")
daterange.add_option("-t", "--to-date", metavar="YYYY-MM-DD")
parser.add_option_group(daterange)
oauth_test = optparse.OptionGroup(parser, "OAuth Endpoint Test")
oauth_test.add_option('-o', '--oauth-test',
help='Ping the OAuth Endpoint Test',
action='store_true')
parser.add_option_group(oauth_test)
upload_ide = optparse.OptionGroup(parser, "Upload IDE file")
upload_ide.add_option('-i', '--upload-ide',
help="Upload an IDE file")
parser.add_option_group(upload_ide)
key_management = optparse.OptionGroup(parser, "Delegated Key Management")
key_management.add_option('-l', '--list-schools',
action='store_true',
help="List the schools using me as an SMS")
key_management.add_option('-n', '--new-key', metavar='SCHOOL_ID',
help="Issue a new key for school with id SCHOOL_ID")
key_management.add_option('-b', '--burn-key', metavar='SCHOOL_ID',
help="Burn key for school with id SCHOOL_ID")
parser.add_option_group(key_management)
options, args = parser.parse_args()
# Some option sanity checks.
if not (options.key and options.secret):
parser.error("You must provide both a key and a secret. See --help for details.")
if options.url.endswith('/'):
parser.error("You don't want the trailing '/' in your URL")
return options, args
def init_logging(verbose=False):
level = logging.DEBUG if verbose else logging.INFO
logging.basicConfig(level=level,
format='%(levelname)8s %(message)s')
def main(options, args):
monkeypatch_client()
monkeypatch_signature_method_hmac_sha1()
oauth_filter = get_oauth_filter(options.key, options.secret)
try:
if options.oauth_test:
oauth_test(oauth_filter, options.url)
if options.csv_download:
csv_download(oauth_filter, options.url, options.from_date, options.to_date)
if options.twa_csv_download:
twa_csv_download(oauth_filter, options.url, options.from_date, options.to_date)
if options.json_download:
json_download(oauth_filter, options.url, options.from_date, options.to_date)
if options.upload_ide:
upload_ide(oauth_filter, options.url, options.upload_ide)
if options.list_schools:
list_schools(oauth_filter, options.url)
if options.new_key:
create_key(oauth_filter, options.url, options.new_key)
if options.burn_key:
burn_key(oauth_filter, options.url, options.burn_key)
except restkit.errors.Unauthorized:
logging.error("Sorry, the server says your request was 'Unauthorized'")
except restkit.errors.ResourceNotFound:
logging.error("Sorry, the server says the resource you asked for was "
"not found, check your URL setting or your school ID (if provided).")
if __name__ == "__main__":
options, args = parse_options()
init_logging(options.verbose)
logging.debug("Options: %s", unicode(options))
logging.debug("Args: %s", unicode(args))
main(options, args)