forked from nuxeo/FunkLoad
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecorder.py
More file actions
376 lines (344 loc) · 14 KB
/
Copy pathRecorder.py
File metadata and controls
376 lines (344 loc) · 14 KB
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
366
367
368
369
370
371
372
373
374
375
376
# (C) Copyright 2005 Nuxeo SAS <http://nuxeo.com>
# Author: [email protected]
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.
#
"""TCPWatch FunkLoad Test Recorder.
Requires tcpwatch.py available at:
* http://hathawaymix.org/Software/TCPWatch/tcpwatch-1.3.tar.gz
Credits goes to Ian Bicking for parsing tcpwatch files.
$Id$
"""
import os
import sys
import re
from cStringIO import StringIO
from optparse import OptionParser, TitledHelpFormatter
from tempfile import mkdtemp
import rfc822
from cgi import FieldStorage
from urlparse import urlsplit
from utils import truncate, trace, get_version, Data
class Request:
"""Store a tcpwatch request."""
def __init__(self, file_path):
"""Load a tcpwatch request file."""
self.file_path = file_path
f = open(file_path, 'rb')
line = f.readline().split(None, 2)
if not line:
trace('# Warning: empty first line on %s\n' % self.file_path)
line = f.readline().split(None, 2)
self.method = line[0]
url = line[1]
scheme, host, path, query, fragment = urlsplit(url)
self.host = scheme + '://' + host
self.rurl = url[len(self.host):]
self.url = url
self.path = path
self.version = line[2].strip()
self.headers = dict(rfc822.Message(f).items())
self.body = f.read()
f.close()
def extractParam(self):
"""Turn muti part encoded form into params."""
params = []
try:
environ = {
'CONTENT_TYPE': self.headers['content-type'],
'CONTENT_LENGTH': self.headers['content-length'],
'REQUEST_METHOD': 'POST',
}
except KeyError:
trace('# Warning: missing header content-type or content-length'
' in file: %s not an http request ?\n' % self.file_path)
return params
form = FieldStorage(fp=StringIO(self.body),
environ=environ,
keep_blank_values=True)
try:
keys = form.keys()
except TypeError:
trace('# Using custom data for request: %s ' % self.file_path)
params = Data(self.headers['content-type'], self.body)
return params
for key in keys:
if not isinstance(form[key], list):
values = [form[key]]
else:
values = form[key]
for form_value in values:
filename = form_value.filename
if filename is None:
params.append([key, form_value.value])
else:
# got a file upload
filename = filename or ''
params.append([key, 'Upload("%s")' % filename])
if filename:
if os.path.exists(filename):
trace('# Warning: uploaded file: %s already'
' exists, keep it.\n' % filename)
else:
trace('# Saving uploaded file: %s\n' % filename)
f = open(filename, 'w')
f.write(str(form_value.value))
f.close()
return params
def __repr__(self):
params = ''
if self.body:
params = self.extractParam()
return '<request method="%s" url="%s" %s/>' % (
self.method, self.url, str(params))
class Response:
"""Store a tcpwatch response."""
def __init__(self, file_path):
"""Load a tcpwatch response file."""
self.file_path = file_path
f = open(file_path, 'rb')
line = f.readline().split(None, 2)
self.version = line[0]
self.status_code = line[1].strip()
if len(line) > 2:
self.status_message = line[2].strip()
else:
self.status_message = ''
self.headers = dict(rfc822.Message(f).items())
self.body = f.read()
f.close()
def __repr__(self):
return '<response code="%s" type="%s" status="%s" />' % (
self.status_code, self.headers.get('content-type'),
self.status_message)
class RecorderProgram:
"""A tcpwatch to funkload recorder."""
MYFACES_STATE = 'org.apache.myfaces.trinidad.faces.STATE'
MYFACES_FORM = 'org.apache.myfaces.trinidad.faces.FORM'
USAGE = """%prog [options] [test_name]
%prog launch a TCPWatch proxy and record activities, then output
a FunkLoad script or generates a FunkLoad unit test if test_name is specified.
The default proxy port is 8090.
Note that tcpwatch.py executable must be accessible from your env.
See http://funkload.nuxeo.org/ for more information.
Examples
========
%prog foo_bar
Run a proxy and create a FunkLoad test case,
generates test_FooBar.py and FooBar.conf file.
To test it: fl-run-test -dV test_FooBar.py
%prog -p 9090
Run a proxy on port 9090, output script to stdout.
%prog -i /tmp/tcpwatch
Convert a tcpwatch capture into a script.
"""
def __init__(self, argv=None):
if argv is None:
argv = sys.argv[1:]
self.verbose = False
self.tcpwatch_path = None
self.prefix = 'watch'
self.port = "8090"
self.server_url = None
self.class_name = None
self.test_name = None
self.script_path = None
self.configuration_path = None
self.use_myfaces = False
self.parseArgs(argv)
def parseArgs(self, argv):
"""Parse programs args."""
parser = OptionParser(self.USAGE, formatter=TitledHelpFormatter(),
version="FunkLoad %s" % get_version())
parser.add_option("-v", "--verbose", action="store_true",
help="Verbose output")
parser.add_option("-p", "--port", type="string", dest="port",
default=self.port, help="The proxy port.")
parser.add_option("-i", "--tcp-watch-input", type="string",
dest="tcpwatch_path", default=None,
help="Path to an existing tcpwatch capture.")
options, args = parser.parse_args(argv)
if len(args) == 1:
test_name = args[0]
else:
test_name = None
self.verbose = options.verbose
self.tcpwatch_path = options.tcpwatch_path
self.port = options.port
if test_name:
class_name = ''.join([x.capitalize()
for x in re.split('_|-', test_name)])
self.test_name = test_name
self.class_name = class_name
self.script_path = './test_%s.py' % class_name
self.configuration_path = './%s.conf' % class_name
def startProxy(self):
"""Start a tcpwatch session."""
self.tcpwatch_path = mkdtemp('_funkload')
cmd = 'tcpwatch.py -p %s -s -r %s' % (self.port,
self.tcpwatch_path)
if os.name == 'posix':
if self.verbose:
cmd += ' | grep "T http"'
else:
cmd += ' > /dev/null'
trace("Hit Ctrl-C to stop recording.\n")
os.system(cmd)
def searchFiles(self):
"""Search tcpwatch file."""
items = {}
prefix = self.prefix
for filename in os.listdir(self.tcpwatch_path):
if not filename.startswith(prefix):
continue
name, ext = os.path.splitext(filename)
name = name[len(self.prefix):]
ext = ext[1:]
if ext == 'errors':
trace("Error in response %s\n" % name)
continue
assert ext in ('request', 'response'), "Bad extension: %r" % ext
items.setdefault(name, {})[ext] = os.path.join(
self.tcpwatch_path, filename)
items = items.items()
items.sort()
return [(v['request'], v['response'])
for name, v in items
if v.has_key('response')]
def extractRequests(self, files):
"""Filter and extract request from tcpwatch files."""
last_code = None
filter_ctypes = ('image', 'css', 'javascript')
filter_url = ('.jpg', '.png', '.gif', '.css', '.js')
requests = []
for request_path, response_path in files:
response = Response(response_path)
request = Request(request_path)
if self.server_url is None:
self.server_url = request.host
ctype = response.headers.get('content-type', '')
url = request.url
if request.method != "POST" and (
last_code in ('301', '302') or
[x for x in filter_ctypes if x in ctype] or
[x for x in filter_url if url.endswith(x)]):
last_code = response.status_code
continue
last_code = response.status_code
requests.append(request)
return requests
def reindent(self, code, indent=8):
"""Improve indentation."""
spaces = ' ' * indent
code = code.replace('], [', '],\n%s [' % spaces)
code = code.replace('[[', '[\n%s [' % spaces)
code = code.replace(', description=', ',\n%s description=' % spaces)
code = code.replace('self.', '\n%sself.' % spaces)
return code
def convertToFunkLoad(self, request):
"""return a funkload python instruction."""
text = []
if request.host != self.server_url:
text.append('self.%s("%s"' % (request.method.lower(),
request.url))
else:
text.append('self.%s(server_url + "%s"' % (
request.method.lower(), request.rurl.strip()))
description = "%s %s" % (request.method.capitalize(),
request.path | truncate(42))
if request.body:
params = request.extractParam()
if isinstance(params, Data):
params = "Data('%s', '''%s''')" % (params.content_type,
params.data)
else:
myfaces_form = None
if self.MYFACES_STATE not in [key for key, value in params]:
params = 'params=%s' % params
else:
# apache myfaces state add a wrapper
self.use_myfaces = True
new_params = []
for key, value in params:
if key == self.MYFACES_STATE:
continue
if key == self.MYFACES_FORM:
myfaces_form = value
continue
new_params.append([key, value])
params = " self.myfacesParams(%s, form='%s')" % (
new_params, myfaces_form)
params = re.sub("'Upload\(([^\)]*)\)'", "Upload(\\1)", params)
text.append(', ' + params)
text.append(', description="%s")' % description)
return ''.join(text)
def extractScript(self):
"""Convert a tcpwatch capture into a FunkLoad script."""
files = self.searchFiles()
requests = self.extractRequests(files)
code = [self.convertToFunkLoad(request)
for request in requests]
if not code:
trace("Sorry no action recorded.\n")
return ''
code.insert(0, '')
return self.reindent('\n'.join(code))
def writeScript(self, script):
"""Write the FunkLoad test script."""
trace('Creating script: %s.\n' % self.script_path)
from pkg_resources import resource_string
if self.use_myfaces:
tpl_name = 'data/MyFacesScriptTestCase.tpl'
else:
tpl_name = 'data/ScriptTestCase.tpl'
tpl = resource_string('funkload', tpl_name)
content = tpl % {'script': script,
'test_name': self.test_name,
'class_name': self.class_name}
if os.path.exists(self.script_path):
trace("Error file %s already exists.\n" % self.script_path)
return
f = open(self.script_path, 'w')
f.write(content)
f.close()
def writeConfiguration(self):
"""Write the FunkLoad configuration test script."""
trace('Creating configuration file: %s.\n' % self.configuration_path)
from pkg_resources import resource_string
tpl = resource_string('funkload', 'data/ConfigurationTestCase.tpl')
content = tpl % {'server_url': self.server_url,
'test_name': self.test_name,
'class_name': self.class_name}
if os.path.exists(self.configuration_path):
trace("Error file %s already exists.\n" %
self.configuration_path)
return
f = open(self.configuration_path, 'w')
f.write(content)
f.close()
def run(self):
"""run it."""
if self.tcpwatch_path is None:
self.startProxy()
script = self.extractScript()
if not script:
return
if self.test_name is not None:
self.writeScript(script)
self.writeConfiguration()
else:
print script
if __name__ == '__main__':
RecorderProgram().run()