forked from binux/pyspider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_run.py
336 lines (293 loc) · 12 KB
/
test_run.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
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# Author: Binux<[email protected]>
# http://binux.me
# Created on 2014-11-21 22:32:35
from __future__ import print_function
import os
import sys
import six
import time
import json
import signal
import shutil
import inspect
import requests
import unittest2 as unittest
from pyspider import run
from pyspider.libs import utils
from tests import data_sample_handler
class TestRun(unittest.TestCase):
@classmethod
def setUpClass(self):
shutil.rmtree('./data/tests', ignore_errors=True)
os.makedirs('./data/tests')
import tests.data_test_webpage
import httpbin
self.httpbin_thread = utils.run_in_subprocess(httpbin.app.run, port=14887)
self.httpbin = 'http://127.0.0.1:14887'
@classmethod
def tearDownClass(self):
self.httpbin_thread.terminate()
self.httpbin_thread.join()
shutil.rmtree('./data/tests', ignore_errors=True)
def test_10_cli(self):
ctx = run.cli.make_context('test', [], None, obj=dict(testing_mode=True))
ctx = run.cli.invoke(ctx)
self.assertEqual(ctx.obj.debug, False)
for db in ('taskdb', 'projectdb', 'resultdb'):
self.assertIsNotNone(getattr(ctx.obj, db))
for name in ('newtask_queue', 'status_queue', 'scheduler2fetcher',
'fetcher2processor', 'processor2result'):
self.assertIsNotNone(getattr(ctx.obj, name))
self.assertEqual(len(ctx.obj.instances), 0)
def test_20_cli_config(self):
with open('./data/tests/config.json', 'w') as fp:
json.dump({
'debug': True,
'taskdb': 'mysql+taskdb://localhost:23456/taskdb',
'amqp-url': 'amqp://guest:guest@localhost:23456/%%2F'
}, fp)
ctx = run.cli.make_context('test',
['--config', './data/tests/config.json'],
None, obj=dict(testing_mode=True))
ctx = run.cli.invoke(ctx)
self.assertEqual(ctx.obj.debug, True)
import mysql.connector
with self.assertRaises(mysql.connector.InterfaceError):
ctx.obj.taskdb
with self.assertRaisesRegexp(Exception, 'Connection refused'):
ctx.obj.newtask_queue
def test_30_cli_command_line(self):
ctx = run.cli.make_context(
'test',
['--projectdb', 'mongodb+projectdb://localhost:23456/projectdb'],
None,
obj=dict(testing_mode=True)
)
ctx = run.cli.invoke(ctx)
from pymongo.errors import ConnectionFailure
with self.assertRaises(ConnectionFailure):
ctx.obj.projectdb
def test_40_cli_env(self):
try:
os.environ['RESULTDB'] = 'sqlite+resultdb://'
ctx = run.cli.make_context('test', [], None,
obj=dict(testing_mode=True))
ctx = run.cli.invoke(ctx)
from pyspider.database.sqlite import resultdb
self.assertIsInstance(ctx.obj.resultdb, resultdb.ResultDB)
finally:
del os.environ['RESULTDB']
@unittest.skipIf(os.environ.get('IGNORE_RABBITMQ'), 'no rabbitmq server for test.')
def test_50_docker_rabbitmq(self):
try:
os.environ['RABBITMQ_NAME'] = 'rabbitmq'
os.environ['RABBITMQ_PORT_5672_TCP_ADDR'] = 'localhost'
os.environ['RABBITMQ_PORT_5672_TCP_PORT'] = '5672'
ctx = run.cli.make_context('test', [], None,
obj=dict(testing_mode=True))
ctx = run.cli.invoke(ctx)
queue = ctx.obj.newtask_queue
queue.put('abc')
queue.delete()
except Exception as e:
self.assertIsNone(e)
finally:
del os.environ['RABBITMQ_NAME']
del os.environ['RABBITMQ_PORT_5672_TCP_ADDR']
del os.environ['RABBITMQ_PORT_5672_TCP_PORT']
@unittest.skipIf(os.environ.get('IGNORE_MONGODB'), 'no mongodb server for test.')
def test_60_docker_mongodb(self):
try:
os.environ['MONGODB_NAME'] = 'mongodb'
os.environ['MONGODB_PORT_27017_TCP_ADDR'] = 'localhost'
os.environ['MONGODB_PORT_27017_TCP_PORT'] = '27017'
ctx = run.cli.make_context('test', [], None,
obj=dict(testing_mode=True))
ctx = run.cli.invoke(ctx)
ctx.obj.resultdb
except Exception as e:
self.assertIsNone(e)
finally:
del os.environ['MONGODB_NAME']
del os.environ['MONGODB_PORT_27017_TCP_ADDR']
del os.environ['MONGODB_PORT_27017_TCP_PORT']
@unittest.skipIf(os.environ.get('IGNORE_MYSQL'), 'no mysql server for test.')
def test_70_docker_mysql(self):
try:
os.environ['MYSQL_NAME'] = 'mysql'
os.environ['MYSQL_PORT_3306_TCP_ADDR'] = 'localhost'
os.environ['MYSQL_PORT_3306_TCP_PORT'] = '3306'
ctx = run.cli.make_context('test', [], None,
obj=dict(testing_mode=True))
ctx = run.cli.invoke(ctx)
ctx.obj.resultdb
except Exception as e:
self.assertIsNone(e)
finally:
del os.environ['MYSQL_NAME']
del os.environ['MYSQL_PORT_3306_TCP_ADDR']
del os.environ['MYSQL_PORT_3306_TCP_PORT']
def test_80_docker_phantomjs(self):
try:
os.environ['PHANTOMJS_NAME'] = 'phantomjs'
os.environ['PHANTOMJS_PORT'] = 'tpc://binux:25678'
ctx = run.cli.make_context('test', [], None,
obj=dict(testing_mode=True))
ctx = run.cli.invoke(ctx)
self.assertEqual(ctx.obj.phantomjs_proxy, 'binux:25678')
except Exception as e:
self.assertIsNone(e)
finally:
del os.environ['PHANTOMJS_NAME']
del os.environ['PHANTOMJS_PORT']
def test_90_docker_scheduler(self):
try:
os.environ['SCHEDULER_NAME'] = 'scheduler'
os.environ['SCHEDULER_PORT_23333_TCP'] = 'tpc://binux:25678'
ctx = run.cli.make_context('test', [], None,
obj=dict(testing_mode=True))
ctx = run.cli.invoke(ctx)
webui = run.cli.get_command(ctx, 'webui')
webui_ctx = webui.make_context('webui', [], ctx)
app = webui.invoke(webui_ctx)
rpc = app.config['scheduler_rpc']
self.assertEqual(rpc._ServerProxy__host, 'binux:25678')
except Exception as e:
self.assertIsNone(e)
finally:
del os.environ['SCHEDULER_NAME']
del os.environ['SCHEDULER_PORT_23333_TCP']
def test_a100_all(self):
import subprocess
#cmd = [sys.executable]
cmd = ['coverage', 'run']
p = subprocess.Popen(cmd+[
inspect.getsourcefile(run),
'--taskdb', 'sqlite+taskdb:///data/tests/all_test_task.db',
'--resultdb', 'sqlite+resultdb:///data/tests/all_test_result.db',
'--projectdb', 'local+projectdb://'+inspect.getsourcefile(data_sample_handler),
'all',
], close_fds=True)
try:
limit = 30
while limit >= 0:
time.sleep(3)
# click run
try:
requests.post('http://localhost:5000/run', data={
'project': 'data_sample_handler',
})
except requests.exceptions.ConnectionError:
limit -= 1
continue
break
limit = 30
data = requests.get('http://localhost:5000/counter?time=5m&type=sum')
self.assertEqual(data.status_code, 200)
while data.json().get('data_sample_handler', {}).get('success', 0) < 5:
time.sleep(1)
data = requests.get('http://localhost:5000/counter?time=5m&type=sum')
limit -= 1
if limit <= 0:
break
self.assertGreater(limit, 0)
rv = requests.get('http://localhost:5000/results?project=data_sample_handler')
self.assertIn('<th>url</th>', rv.text)
self.assertIn('class=url', rv.text)
except:
raise
finally:
while p.returncode is None:
time.sleep(1)
p.send_signal(signal.SIGINT)
p.poll()
def test_a110_one(self):
pid, fd = os.forkpty()
#cmd = [sys.executable]
cmd = ['coverage', 'run']
cmd += [
inspect.getsourcefile(run),
'one',
'-i',
inspect.getsourcefile(data_sample_handler)
]
if pid == 0:
# child
os.execvp(cmd[0], cmd)
else:
# parent
def wait_text(timeout=1):
import select
text = []
while True:
rl, wl, xl = select.select([fd], [], [], timeout)
if not rl:
break
try:
t = os.read(fd, 1024)
except OSError:
break
if not t:
break
t = utils.text(t)
text.append(t)
print(t, end='')
return ''.join(text)
text = wait_text(3)
self.assertIn('new task data_sample_handler:on_start', text)
self.assertIn('pyspider shell', text)
os.write(fd, utils.utf8('run()\n'))
text = wait_text()
self.assertIn('task done data_sample_handler:on_start', text)
os.write(fd, utils.utf8('crawl("%s/pyspider/test.html")\n' % self.httpbin))
text = wait_text()
self.assertIn('/robots.txt', text)
os.write(fd, utils.utf8('crawl("%s/links/10/0")\n' % self.httpbin))
text = wait_text()
if '"title": "Links"' not in text:
os.write(fd, utils.utf8('crawl("%s/links/10/1")\n' % self.httpbin))
text = wait_text()
self.assertIn('"title": "Links"', text)
os.write(fd, utils.utf8('crawl("%s/404")\n' % self.httpbin))
text = wait_text()
self.assertIn('task retry', text)
os.write(fd, b'quit_pyspider()\n')
text = wait_text()
self.assertIn('scheduler exiting...', text)
os.close(fd)
os.kill(pid, signal.SIGINT)
class TestSendMessage(unittest.TestCase):
@classmethod
def setUpClass(self):
shutil.rmtree('./data/tests', ignore_errors=True)
os.makedirs('./data/tests')
ctx = run.cli.make_context('test', [
'--taskdb', 'sqlite+taskdb:///data/tests/task.db',
'--projectdb', 'sqlite+projectdb:///data/tests/projectdb.db',
'--resultdb', 'sqlite+resultdb:///data/tests/resultdb.db',
], None, obj=dict(testing_mode=True))
self.ctx = run.cli.invoke(ctx)
ctx = run.scheduler.make_context('scheduler', [], self.ctx)
scheduler = run.scheduler.invoke(ctx)
utils.run_in_thread(scheduler.xmlrpc_run)
utils.run_in_thread(scheduler.run)
time.sleep(1)
@classmethod
def tearDownClass(self):
for each in self.ctx.obj.instances:
each.quit()
time.sleep(1)
shutil.rmtree('./data/tests', ignore_errors=True)
def test_10_send_message(self):
ctx = run.send_message.make_context('send_message', [
'test_project', 'test_message'
], self.ctx)
self.assertTrue(run.send_message.invoke(ctx))
while True:
task = self.ctx.obj.scheduler2fetcher.get(timeout=1)
if task['url'] == 'data:,on_message':
break
self.assertEqual(task['process']['callback'], '_on_message')