-
Notifications
You must be signed in to change notification settings - Fork 16
/
tests.py
427 lines (340 loc) · 13.2 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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Real test for file-upload and beginning of a better internal test framework
$Id$
"""
from zope.app.testing.functional import FunctionalDocFileSuite
from zope.testing import doctest
import cStringIO
import httplib
import mechanize
import os
import re
import socket
import sys
import unittest
import urllib2
import zope.app.testing.functional
import zope.testbrowser.browser
import zope.testing.renormalizing
def set_next_response(body, headers=None, status='200', reason='OK'):
global next_response_body
global next_response_headers
global next_response_status
global next_response_reason
if headers is None:
headers = (
'Content-Type: text/html\r\n'
'Content-Length: %s\r\n'
% len(body)
)
next_response_body = body
next_response_headers = headers
next_response_status = status
next_response_reason = reason
class FauxConnection(object):
"""A ``urllib2`` compatible connection object."""
def __init__(self, host, timeout=None):
pass
def set_debuglevel(self, level):
pass
def _quote(self, url):
# the publisher expects to be able to split on whitespace, so we have
# to make sure there is none in the URL
return url.replace(' ', '%20')
def request(self, method, url, body=None, headers=None):
if body is None:
body = ''
if url == '':
url = '/'
url = self._quote(url)
# Construct the headers.
header_chunks = []
if headers is not None:
for header in headers.items():
header_chunks.append('%s: %s' % header)
headers = '\n'.join(header_chunks) + '\n'
else:
headers = ''
# Construct the full HTTP request string, since that is what the
# ``HTTPCaller`` wants.
request_string = (method + ' ' + url + ' HTTP/1.1\n'
+ headers + '\n' + body)
print request_string.replace('\r', '')
def getresponse(self):
"""Return a ``urllib2`` compatible response.
The goal of this method is to convert the Zope Publisher's response to
a ``urllib2`` compatible response, which is also understood by
mechanize.
"""
return FauxResponse(next_response_body,
next_response_headers,
next_response_status,
next_response_reason,
)
class FauxResponse(object):
def __init__(self, content, headers, status, reason):
self.content = content
self.status = status
self.reason = reason
self.msg = httplib.HTTPMessage(cStringIO.StringIO(headers), 0)
self.content_as_file = cStringIO.StringIO(self.content)
def read(self, amt=None):
return self.content_as_file.read(amt)
def close(self):
"""To overcome changes in urllib2 and socket in python2.5"""
pass
class FauxHTTPHandler(urllib2.HTTPHandler):
http_request = urllib2.AbstractHTTPHandler.do_request_
def http_open(self, req):
"""Open an HTTP connection having a ``urllib2`` request."""
# Here we connect to the publisher.
if sys.version_info > (2, 6) and not hasattr(req, 'timeout'):
# Workaround mechanize incompatibility with Python
# 2.6. See: LP #280334
req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
return self.do_open(FauxConnection, req)
class FauxMechanizeBrowser(mechanize.Browser):
handler_classes = {
# scheme handlers
"http": FauxHTTPHandler,
"_http_error": mechanize.HTTPErrorProcessor,
"_http_request_upgrade": mechanize.HTTPRequestUpgradeProcessor,
"_http_default_error": urllib2.HTTPDefaultErrorHandler,
# feature handlers
"_authen": urllib2.HTTPBasicAuthHandler,
"_redirect": mechanize.HTTPRedirectHandler,
"_cookies": mechanize.HTTPCookieProcessor,
"_refresh": mechanize.HTTPRefreshProcessor,
"_referer": mechanize.Browser.handler_classes['_referer'],
"_equiv": mechanize.HTTPEquivProcessor,
}
default_schemes = ["http"]
default_others = ["_http_error", "_http_request_upgrade",
"_http_default_error"]
default_features = ["_authen", "_redirect", "_cookies"]
class Browser(zope.testbrowser.browser.Browser):
def __init__(self, url=None):
mech_browser = FauxMechanizeBrowser()
super(Browser, self).__init__(url=url, mech_browser=mech_browser)
def open(self, body, headers=None, status=200, reason='OK'):
set_next_response(body, headers, status, reason)
zope.testbrowser.browser.Browser.open(self, 'http://localhost/')
def test_submit_duplicate_name():
"""
This test was inspired by bug #723 as testbrowser would pick up the wrong
button when having the same name twice in a form.
>>> browser = Browser()
When given a form with two submit buttons that have the same name:
>>> browser.open('''\
... <html><body>
... <form action="." method="post" enctype="multipart/form-data">
... <input type="submit" name="submit_me" value="GOOD" />
... <input type="submit" name="submit_me" value="BAD" />
... </form></body></html>
... ''') # doctest: +ELLIPSIS
GET / HTTP/1.1
...
We can specify the second button through it's label/value:
>>> browser.getControl('BAD')
<SubmitControl name='submit_me' type='submit'>
>>> browser.getControl('BAD').value
'BAD'
>>> browser.getControl('BAD').click() # doctest: +REPORT_NDIFF
POST / HTTP/1.1
Content-length: 176
Connection: close
Content-type: multipart/form-data; boundary=---------------------------100167997466992641913031254
Host: localhost
User-agent: Python-urllib/2.4
<BLANKLINE>
-----------------------------100167997466992641913031254
Content-disposition: form-data; name="submit_me"
<BLANKLINE>
BAD
-----------------------------100167997466992641913031254--
<BLANKLINE>
This also works if the labels have whitespace around them (this tests a
regression caused by the original fix for the above):
>>> browser.open('''\
... <html><body>
... <form action="." method="post" enctype="multipart/form-data">
... <input type="submit" name="submit_me" value=" GOOD " />
... <input type="submit" name="submit_me" value=" BAD " />
... </form></body></html>
... ''') # doctest: +ELLIPSIS
GET / HTTP/1.1
...
>>> browser.getControl('BAD')
<SubmitControl name='submit_me' type='submit'>
>>> browser.getControl('BAD').value
' BAD '
>>> browser.getControl('BAD').click() # doctest: +REPORT_NDIFF
POST / HTTP/1.1
Content-length: 176
Connection: close
Content-type: multipart/form-data; boundary=---------------------------100167997466992641913031254
Host: localhost
User-agent: Python-urllib/2.4
<BLANKLINE>
-----------------------------100167997466992641913031254
Content-disposition: form-data; name="submit_me"
<BLANKLINE>
BAD
-----------------------------100167997466992641913031254--
<BLANKLINE>
"""
def test_file_upload():
"""
>>> browser = Browser()
When given a form with a file-upload
>>> browser.open('''\
... <html><body>
... <form action="." method="post" enctype="multipart/form-data">
... <input name="foo" type="file" />
... <input type="submit" value="OK" />
... </form></body></html>
... ''') # doctest: +ELLIPSIS
GET / HTTP/1.1
...
Fill in the form value using add_file:
>>> browser.getControl(name='foo').add_file(
... cStringIO.StringIO('sample_data'), 'text/foo', 'x.foo')
>>> browser.getControl('OK').click()
POST / HTTP/1.1
Content-length: 173
Connection: close
Content-type: multipart/form-data; boundary=127.0.0.11000318041146699896411
Host: localhost
User-agent: Python-urllib/2.99
<BLANKLINE>
--127.0.0.11000318041146699896411
Content-disposition: form-data; name="foo"; filename="x.foo"
Content-type: text/foo
<BLANKLINE>
sample_data
--127.0.0.11000318041146699896411--
<BLANKLINE>
You can pass a string to add_file:
>>> browser.getControl(name='foo').add_file(
... 'blah blah blah', 'text/blah', 'x.blah')
>>> browser.getControl('OK').click()
POST / HTTP/1.1
Content-length: 178
Connection: close
Content-type: multipart/form-data; boundary=127.0.0.11000318541146700017052
Host: localhost
User-agent: Python-urllib/2.98
<BLANKLINE>
--127.0.0.11000318541146700017052
Content-disposition: form-data; name="foo"; filename="x.blah"
Content-type: text/blah
<BLANKLINE>
blah blah blah
--127.0.0.11000318541146700017052--
<BLANKLINE>
"""
def test_new_instance_no_contents_should_not_fail(self):
"""
When first instantiated, the browser has no contents.
(Regression test for <http://bugs.launchpad.net/zope3/+bug/419119>)
>>> browser = Browser()
>>> print browser.contents
None
"""
def test_strip_linebreaks_from_textarea(self):
"""
>>> browser = Browser()
According to http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.1 line break
immediately after start tags or immediately before end tags must be ignored,
but real browsers only ignore a line break after a start tag. So if we give
the following form:
>>> browser.open('''
... <html><body>
... <form action="." method="post" enctype="multipart/form-data">
... <textarea name="textarea">
... Foo
... </textarea>
... </form></body></html>
... ''') # doctest: +ELLIPSIS
GET / HTTP/1.1
...
The value of the textarea won't contain the first line break:
>>> browser.getControl(name='textarea').value
'Foo\\n'
Of course, if we add line breaks, so that there are now two line breaks
after the start tag, the textarea value will start and end with a line break.
>>> browser.open('''
... <html><body>
... <form action="." method="post" enctype="multipart/form-data">
... <textarea name="textarea">
...
... Foo
... </textarea>
... </form></body></html>
... ''') # doctest: +ELLIPSIS
GET / HTTP/1.1
...
>>> browser.getControl(name='textarea').value
'\\nFoo\\n'
Also, if there is some other whitespace after the start tag, it will be preserved.
>>> browser.open('''
... <html><body>
... <form action="." method="post" enctype="multipart/form-data">
... <textarea name="textarea"> Foo </textarea>
... </form></body></html>
... ''') # doctest: +ELLIPSIS
GET / HTTP/1.1
...
>>> browser.getControl(name='textarea').value
' Foo '
"""
class win32CRLFtransformer(object):
def sub(self, replacement, text):
return text.replace(r'\r','')
checker = zope.testing.renormalizing.RENormalizing([
(re.compile(r'^--\S+\.\S+\.\S+', re.M), '-'*30),
(re.compile(r'boundary=\S+\.\S+\.\S+'), 'boundary='+'-'*30),
(re.compile(r'^---{10}.*', re.M), '-'*30),
(re.compile(r'boundary=-{10}.*'), 'boundary='+'-'*30),
(re.compile(r'User-agent:\s+\S+'), 'User-agent: Python-urllib/2.4'),
(re.compile(r'HTTP_USER_AGENT:\s+\S+'), 'HTTP_USER_AGENT: Python-urllib/2.4'),
(re.compile(r'Content-[Ll]ength:.*'), 'Content-Length: 123'),
(re.compile(r'Status: 200.*'), 'Status: 200 OK'),
(win32CRLFtransformer(), None),
(re.compile(r'User-Agent: Python-urllib/2.[567]'), 'User-agent: Python-urllib/2.4'),
(re.compile(r'Host: localhost'), 'Connection: close'),
(re.compile(r'Content-Type: '), 'Content-type: '),
(re.compile(r'Content-Disposition: '), 'Content-disposition: '),
])
TestBrowserLayer = zope.app.testing.functional.ZCMLLayer(
os.path.join(os.path.split(__file__)[0], 'ftests/ftesting.zcml'),
__name__, 'TestBrowserLayer', allow_teardown=True)
def test_suite():
flags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
readme = FunctionalDocFileSuite('README.txt', optionflags=flags,
checker=checker)
readme.layer = TestBrowserLayer
cookies = FunctionalDocFileSuite('cookies.txt', optionflags=flags,
checker=checker)
cookies.layer = TestBrowserLayer
fixed_bugs = FunctionalDocFileSuite('fixed-bugs.txt', optionflags=flags)
fixed_bugs.layer = TestBrowserLayer
wire = FunctionalDocFileSuite('over_the_wire.txt', optionflags=flags)
wire.level = 2
wire.layer = TestBrowserLayer
this_file = doctest.DocTestSuite(checker=checker)
return unittest.TestSuite((this_file, readme, fixed_bugs, wire, cookies))
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')