This repository has been archived by the owner on Dec 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 664
/
Copy pathtests.py
executable file
·365 lines (318 loc) · 12 KB
/
tests.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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#!/usr/bin/env python
#
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import argparse
import json
import nose
import os
import signal
import subprocess
import sys
import unittest
import urllib
import urllib2
LOCAL_TEST_PORT = 9002
REGRESSION_TEST_URLS = [
'http://www.blackanddecker.fr',
'http://www.google.com',
'http://dota2.gamepedia.com/',
'http://www.orange.fr',
'http://librarian.codes',
'http://fredrikthalberg.com',
'http://harleykwyn.com',
]
REGRESSION_TEST_BAD_URLS = [
'http://google.com/asdfasdfasdfasdfa',
'http://www.',
]
class PwsTest(unittest.TestCase):
_HOST = None # Set in main()
_ENABLE_EXPERIMENTAL = False
@property
def HOST(self):
PwsTest._HOST
@property
def ENABLE_EXPERIMENTAL(self):
PwsTest._ENABLE_EXPERIMENTAL
def request(self, params=None, payload=None):
"""
Makes an http request to our endpoint
If payload is None, this performs a GET request.
Otherwise, the payload is json-serialized and a POST request is sent.
"""
JSON = getattr(self, 'JSON', False)
url = '{}/{}'.format(self.HOST, self.PATH)
if params:
url += '?{}'.format(urllib.urlencode(params))
args = [url]
if payload is not None:
args.append(json.dumps(payload))
req = urllib2.Request(*args)
req.add_header("Content-Type", "application/json")
response = urllib2.urlopen(req)
data = response.read()
if JSON:
data = json.loads(data)
# Print so we have something nice to look at when we fail
print json.dumps(data, indent=2)
else:
print data
return response.code, data
class TestResolveScan(PwsTest):
PATH = 'resolve-scan'
JSON = True
def call(self, values):
return self.request(payload=values)[1]
def test_demo_data(self):
result = self.call({
'objects': [
{ 'url': 'http://www.caltrain.com/schedules/realtime/stations/mountainviewstation-mobile.html' },
{ 'url': 'http://benfry.com/distellamap/' },
{ 'url': 'http://en.wikipedia.org/wiki/Le_D%C3%A9jeuner_sur_l%E2%80%99herbe' },
{ 'url': 'http://sfmoma.org' }
]
})
self.assertIn('metadata', result)
self.assertEqual(len(result['metadata']), 4)
self.assertIn('description', result['metadata'][0])
self.assertIn('title', result['metadata'][0])
self.assertIn('url', result['metadata'][0])
self.assertIn('displayUrl', result['metadata'][0])
self.assertIn('rank', result['metadata'][0])
self.assertIn('id', result['metadata'][0])
self.assertIn('icon', result['metadata'][0])
def test_invalid_data(self):
result = self.call({
'objects': [
{ 'url': 'http://totallybadurlthatwontwork.com/' },
{ 'usdf': 'http://badkeys' },
]
})
self.assertIn('metadata', result)
self.assertEqual(len(result['metadata']), 0)
#self.assertEqual(len(result['unresolved']), 1)
def test_secure_only(self):
result = self.call({
'objects': [
{ 'url': 'https://en.wikipedia.org/wiki/Le_D%C3%A9jeuner_sur_l%E2%80%99herbe' },
{ 'url': 'http://www.lemonde.fr/' },
],
'secureOnly': True
})
self.assertIn('metadata', result)
self.assertEqual(len(result['metadata']), 1)
self.assertEqual(result['metadata'][0]['id'],
'https://en.wikipedia.org/wiki/Le_D%C3%A9jeuner_sur_l%E2%80%99herbe')
def test_rssi_ranking(self):
result = self.call({
'objects': [
{
'url': 'http://www.caltrain.com/schedules/realtime/stations/mountainviewstation-mobile.html',
'rssi': -75,
'txpower': -22,
},
{
'url': 'http://benfry.com/distellamap/',
'rssi': -95,
'txpower': -63,
},
{
'url': 'http://en.wikipedia.org/wiki/Le_D%C3%A9jeuner_sur_l%E2%80%99herbe',
'rssi': -61,
'txpower': -22,
},
{
'url': 'http://sfmoma.org',
'rssi': -74,
'txpower': -22,
},
]
})
self.assertIn('metadata', result)
self.assertEqual(len(result['metadata']), 4)
self.assertEqual(result['metadata'][0]['id'],
'http://benfry.com/distellamap/')
self.assertEqual(result['metadata'][1]['id'],
'http://en.wikipedia.org/wiki/'
'Le_D%C3%A9jeuner_sur_l%E2%80%99herbe')
self.assertEqual(result['metadata'][2]['id'],
'http://sfmoma.org')
self.assertEqual(result['metadata'][3]['id'],
'http://www.caltrain.com/schedules/realtime/'
'stations/mountainviewstation-mobile.html')
def test_url_which_redirects(self):
result = self.call({
'objects': [
{
'url': 'http://goo.gl/KYvLwO',
},
]
})
self.assertIn('metadata', result)
self.assertEqual(len(result['metadata']), 1)
beaconResult = result['metadata'][0]
self.assertEqual(beaconResult['id'],
'http://goo.gl/KYvLwO')
self.assertEqual(beaconResult['url'],
'https://github.com/Google/physical-web')
self.assertEqual(beaconResult['displayUrl'],
'https://github.com/Google/physical-web')
def test_redirect_with_rssi_tx_power(self):
if not self.ENABLE_EXPERIMENTAL:
return
result = self.call({
'objects': [
{
'url': '{}/experimental/googl/KYvLwO'.format(self.HOST),
'rssi': -41,
'txpower': -22
},
{
'url': '{}/experimental/googl/r8iJqW'.format(self.HOST),
'rssi': -91,
'txpower': -22
},
]
})
self.assertIn('metadata', result)
self.assertEqual(len(result['metadata']), 1)
self.assertEqual(result['metadata'][0]['url'],
'https://github.com/Google/physical-web')
def test_regression_urls(self):
result = self.call({
'objects': [ {'url': url} for url in REGRESSION_TEST_URLS ]
})
self.assertIn('metadata', result)
self.assertEqual(len(result['metadata']), len(REGRESSION_TEST_URLS))
for beaconResult in result['metadata']:
self.assertIn('description', beaconResult)
self.assertIn('title', beaconResult)
self.assertIn('url', beaconResult)
self.assertIn('rank', beaconResult)
self.assertIn('id', beaconResult)
self.assertIn('icon', beaconResult)
def test_regression_bad_urls(self):
result = self.call({
'objects': [ {'url': url} for url in REGRESSION_TEST_BAD_URLS ]
})
self.assertIn('metadata', result)
self.assertEqual(len(result['metadata']), 0)
def test_invalid_rssi(self):
result = self.call({
'objects': [{
'url': 'http://github.com/google/physical-web/',
'rssi': 127,
'txpower': -41
}]
})
self.assertIn('metadata', result)
self.assertEqual(len(result['metadata']), 1)
beaconResult = result['metadata'][0]
self.assertIn('description', beaconResult)
self.assertIn('title', beaconResult)
self.assertIn('url', beaconResult)
self.assertIn('rank', beaconResult)
self.assertIn('id', beaconResult)
self.assertIn('icon', beaconResult)
self.assertEqual(1000, beaconResult['rank'])
class TestShortenUrl(PwsTest):
PATH = 'shorten-url'
JSON = True
def call(self, values):
return self.request(payload=values)[1]
def test_github_url(self):
result = self.call({
'longUrl': 'http://www.github.com/Google/physical-web'
})
self.assertIn('kind', result)
self.assertIn('id', result)
self.assertIn('longUrl', result)
self.assertTrue(result['id'].startswith('http://goo.gl/'))
class RefreshUrl(PwsTest):
PATH = 'refresh-url'
def call(self, url):
params = {'url': url}
return self.request(params=params, payload='')[1]
def test_github_url(self):
result = self.call('https://github.com/google/physical-web')
self.assertEqual(result, '')
class TestGo(PwsTest):
PATH = 'go'
def call(self, url):
params = {'url': url}
return self.request(params=params)[0]
def test_github_url(self):
result = self.call('https://github.com/google/physical-web')
self.assertEqual(result, 200)
def main():
"""The main routine."""
# Parse arguments
local_url = 'http://localhost:{}'.format(LOCAL_TEST_PORT)
parser = argparse.ArgumentParser(description='Run web-service tests')
parser.add_argument(
'-e', '--endpoint', dest='endpoint', default='auto',
help='Which server to test against.\n'
'auto: {} (server starts automatically)\n'
'local: http://localhost:8080\n'
'prod: https://url-caster.appspot.com\n'
'dev: https://url-caster-dev.appspot.com\n'
'*: Other values interpreted literally'
.format(local_url))
parser.add_argument('-x', '--experimental', dest='experimental', action='store_true', default=False)
args = parser.parse_args()
# Setup the endpoint
endpoint = args.endpoint
server = None
if endpoint.lower() == 'auto':
endpoint = local_url
print 'Starting local server...',
server = subprocess.Popen([
'dev_appserver.py', os.path.dirname(__file__),
'--port', str(LOCAL_TEST_PORT),
'--admin_port', str(LOCAL_TEST_PORT + 1),
], bufsize=1, stderr=subprocess.PIPE, preexec_fn=os.setsid)
# Wait for the server to start up
while True:
line = server.stderr.readline()
if 'Unable to bind' in line:
print 'Rogue server already running.'
return 1
if 'running at: {}'.format(local_url) in line:
break
print 'done'
elif endpoint.lower() == 'local':
endpoint = 'http://localhost:8080'
elif endpoint.lower() == 'prod':
endpoint = 'https://url-caster.appspot.com'
elif endpoint.lower() == 'dev':
endpoint = 'https://url-caster-dev.appspot.com'
PwsTest.HOST = endpoint
PwsTest.ENABLE_EXPERIMENTAL = args.experimental
# Run the tests
try:
nose.runmodule()
finally:
# Teardown the endpoint
if server:
os.killpg(os.getpgid(server.pid), signal.SIGINT)
server.wait()
# We should never get here since nose.runmodule will call exit
return 0
if __name__ == '__main__':
try:
exit(main())
except KeyboardInterrupt:
sys.stderr.write('Exiting due to KeyboardInterrupt!\n')