WebTest-2.0.18/ 0000755 0000000 0000000 00000000000 12560452473 011665 5 ustar root root WebTest-2.0.18/tests/ 0000755 0000000 0000000 00000000000 12560452473 013027 5 ustar root root WebTest-2.0.18/tests/html/ 0000755 0000000 0000000 00000000000 12560452473 013773 5 ustar root root WebTest-2.0.18/tests/html/form_inputs_with_defaults.html 0000644 0000000 0000000 00000001533 12464666730 022160 0 ustar root root
form page
WebTest-2.0.18/tests/html/form_unicode_inputs.html 0000644 0000000 0000000 00000001703 12464666730 020743 0 ustar root root
form page
WebTest-2.0.18/tests/html/app.js 0000644 0000000 0000000 00000000205 12464666730 015114 0 ustar root root $(document).ready(function() {
$('#myform').submit(function() {
$('#message').text('Form submited');
return false;
});
});
WebTest-2.0.18/tests/html/404.html 0000644 0000000 0000000 00000000260 12464666730 015174 0 ustar root root
WebTest-2.0.18/tests/html/form_inputs.html 0000644 0000000 0000000 00000004250 12464666730 017235 0 ustar root root
forms page
WebTest-2.0.18/tests/html/message.html 0000644 0000000 0000000 00000000426 12464666730 016315 0 ustar root root
%(message)s
WebTest-2.0.18/tests/html/index.html 0000644 0000000 0000000 00000004151 12464666730 015777 0 ustar root root
It Works!
It Works!
WebTest-2.0.18/tests/compat.py 0000644 0000000 0000000 00000000724 12464666730 014675 0 ustar root root # -*- coding: utf-8 -*-
try:
# py < 2.7
import unittest2 as unittest
except ImportError:
import unittest # noqa
try:
unicode()
except NameError:
b = bytes
def u(value):
if isinstance(value, bytes):
return value.decode('utf-8')
return value
else:
def b(value):
return str(value)
def u(value):
if isinstance(value, unicode):
return value
return unicode(value, 'utf-8')
WebTest-2.0.18/tests/test_utils.py 0000644 0000000 0000000 00000007547 12464666730 015623 0 ustar root root # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import json
from .compat import unittest
from webtest import utils
class NoDefaultTest(unittest.TestCase):
def test_nodefault(self):
from webtest.utils import NoDefault
self.assertEquals(repr(NoDefault), '')
class encode_paramsTest(unittest.TestCase):
def test_encode_params_None(self):
self.assertEquals(utils.encode_params(None, None), None)
def test_encode_params_NoDefault(self):
self.assertEquals(utils.encode_params(utils.NoDefault, None), '')
def test_encode_params_dict_or_list(self):
self.assertEquals(utils.encode_params({'foo': 'bar'}, None),
utils.encode_params([('foo', 'bar')], None))
def test_encode_params_no_charset(self):
# no content_type at all
self.assertEquals(utils.encode_params({'foo': 'bar'}, None), 'foo=bar')
# content_type without "charset=xxxx"
self.assertEquals(utils.encode_params({'foo': 'bar'}, 'ba'), 'foo=bar')
def test_encode_params_charset_utf8(self):
# charset is using inconsistent casing on purpose, it should still work
self.assertEquals(utils.encode_params({'f': '€'}, ' CHARset=uTF-8; '),
'f=%E2%82%AC')
class make_patternTest(unittest.TestCase):
def call_FUT(self, obj):
from webtest.utils import make_pattern
return make_pattern(obj)
def test_make_pattern_None(self):
self.assertEquals(self.call_FUT(None), None)
def test_make_pattern_regex(self):
regex = re.compile(r'foobar')
self.assertEquals(self.call_FUT(regex), regex.search)
def test_make_pattern_function(self):
func = lambda x: x
self.assertEquals(self.call_FUT(func), func)
def test_make_pattern_bytes(self):
# if we pass a string, it will get compiled into a regex
# that we can later call and match a string
self.assertEqual(self.call_FUT('a')('a').string, 'a')
def test_make_pattern_invalid(self):
self.assertRaises(ValueError, self.call_FUT, 0)
class stringifyTest(unittest.TestCase):
def test_stringify_text(self):
self.assertEquals(utils.stringify("foo"), "foo")
def test_stringify_binary(self):
self.assertEquals(utils.stringify(b"foo"), "foo")
def test_stringify_other(self):
self.assertEquals(utils.stringify(123), "123")
class json_methodTest(unittest.TestCase):
class MockTestApp(object):
"""Mock TestApp used to test the json_object decorator."""
from webtest.utils import json_method
JSONEncoder = json.JSONEncoder
foo_json = json_method('FOO')
def _gen_request(self, method, url, **kw):
return (method, url, kw)
mock = MockTestApp()
def test_json_method_request_calls(self):
from webtest.utils import NoDefault
# no params
self.assertEquals(self.mock.foo_json('url', params=NoDefault, c='c'),
('FOO', 'url', {'content_type': 'application/json',
'c': 'c',
'params': NoDefault,
'upload_files': None}))
# params dumped to json
self.assertEquals(self.mock.foo_json('url', params={'a': 'b'}, c='c'),
('FOO', 'url', {'content_type': 'application/json',
'c': 'c',
'params': json.dumps({'a': 'b'}),
'upload_files': None}))
def test_json_method_doc(self):
self.assertIn('FOO request', self.mock.foo_json.__doc__)
self.assertIn('TestApp.foo', self.mock.foo_json.__doc__)
def test_json_method_name(self):
self.assertEqual(self.mock.foo_json.__name__, 'foo_json')
WebTest-2.0.18/tests/test_response.py 0000644 0000000 0000000 00000034313 12464666730 016310 0 ustar root root #coding: utf-8
from __future__ import unicode_literals
import sys
import webtest
from webtest.debugapp import debug_app
from webob import Request
from webob.response import gzip_app_iter
from webtest.compat import PY3
from tests.compat import unittest
import webbrowser
def links_app(environ, start_response):
req = Request(environ)
status = "200 OK"
responses = {
'/': """
page with links
Foo
Bar
Baz
Baz
Baz
Click me!
Click me!
""",
'/foo/': (
'This is foo. Bar '
''
),
'/foo/bar': 'This is foobar.',
'/bar': 'This is bar.',
'/baz/': 'This is baz.',
'/spam/': 'This is spam.',
'/egg/': 'Just eggs.',
'/utf8/': """
Тестовая страница
Менделеев
Пушкин
""",
'/no_form/': """
Page without form
This is not the form you are looking for
""",
'/one_forms/': """
Page without form
""",
'/many_forms/': """
Page without form
""",
'/html_in_anchor/': """
Page with HTML in an anchor tag
Foo BarQuz
""",
'/json/': '{"foo": "bar"}',
}
utf8_paths = ['/utf8/']
body = responses[req.path_info]
body = body.encode('utf8')
headers = [
('Content-Type', str('text/html')),
('Content-Length', str(len(body)))
]
if req.path_info in utf8_paths:
headers[0] = ('Content-Type', str('text/html; charset=utf-8'))
start_response(str(status), headers)
return [body]
def gzipped_app(environ, start_response):
status = "200 OK"
encoded_body = list(gzip_app_iter([b'test']))
headers = [
('Content-Type', str('text/html')),
('Content-Encoding', str('gzip')),
]
start_response(str(status), headers)
return encoded_body
class TestResponse(unittest.TestCase):
def test_repr(self):
def _repr(v):
br = repr(v)
if len(br) > 18:
br = br[:10] + '...' + br[-5:]
br += '/%s' % len(v)
return br
app = webtest.TestApp(debug_app)
res = app.post('/')
self.assertEqual(
repr(res),
'<200 OK text/plain body=%s>' % _repr(res.body)
)
res.content_type = None
self.assertEqual(
repr(res),
'<200 OK body=%s>' % _repr(res.body)
)
res.location = 'http://pylons.org'
self.assertEqual(
repr(res),
'<200 OK location: http://pylons.org body=%s>' % _repr(res.body)
)
res.body = b''
self.assertEqual(
repr(res),
'<200 OK location: http://pylons.org no body>'
)
def test_mustcontains(self):
app = webtest.TestApp(debug_app)
res = app.post('/', params='foobar')
res.mustcontain('foobar')
self.assertRaises(IndexError, res.mustcontain, 'not found')
res.mustcontain('foobar', no='not found')
res.mustcontain('foobar', no=['not found', 'not found either'])
self.assertRaises(IndexError, res.mustcontain, no='foobar')
self.assertRaises(
TypeError,
res.mustcontain, invalid_param='foobar'
)
def test_click(self):
app = webtest.TestApp(links_app)
self.assertIn('This is foo.', app.get('/').click('Foo'))
self.assertIn(
'This is foobar.',
app.get('/').click('Foo').click('Bar')
)
self.assertIn('This is bar.', app.get('/').click('Bar'))
# should skip non-clickable links
self.assertIn(
'This is baz.',
app.get('/').click('Baz')
)
self.assertIn('This is baz.', app.get('/').click(linkid='id_baz'))
self.assertIn('This is baz.', app.get('/').click(href='baz/'))
self.assertIn(
'This is spam.',
app.get('/').click('Click me!', index=0)
)
self.assertIn(
'Just eggs.',
app.get('/').click('Click me!', index=1)
)
self.assertIn(
'This is foo.',
app.get('/html_in_anchor/').click('baz qux')
)
def dont_match_anchor_tag():
app.get('/html_in_anchor/').click('href')
self.assertRaises(IndexError, dont_match_anchor_tag)
def multiple_links():
app.get('/').click('Click me!')
self.assertRaises(IndexError, multiple_links)
def invalid_index():
app.get('/').click('Click me!', index=2)
self.assertRaises(IndexError, invalid_index)
def no_links_found():
app.get('/').click('Ham')
self.assertRaises(IndexError, no_links_found)
def tag_inside_script():
app.get('/').click('Boo')
self.assertRaises(IndexError, tag_inside_script)
def test_click_utf8(self):
app = webtest.TestApp(links_app, use_unicode=False)
resp = app.get('/utf8/')
self.assertEqual(resp.charset, 'utf-8')
if not PY3:
# No need to deal with that in Py3
self.assertIn("Тестовая страница".encode('utf8'), resp)
self.assertIn("Тестовая страница", resp, resp)
target = 'Менделеев'.encode('utf8')
self.assertIn('This is foo.', resp.click(target, verbose=True))
def test_click_u(self):
app = webtest.TestApp(links_app)
resp = app.get('/utf8/')
self.assertIn("Тестовая страница", resp)
self.assertIn('This is foo.', resp.click('Менделеев'))
def test_clickbutton(self):
app = webtest.TestApp(links_app)
self.assertIn(
'This is foo.',
app.get('/').clickbutton(buttonid='button1', verbose=True)
)
self.assertRaises(
IndexError,
app.get('/').clickbutton, buttonid='button2'
)
self.assertRaises(
IndexError,
app.get('/').clickbutton, buttonid='button3'
)
def test_xml_attribute(self):
app = webtest.TestApp(links_app)
resp = app.get('/no_form/')
self.assertRaises(
AttributeError,
getattr,
resp, 'xml'
)
resp.content_type = 'text/xml'
resp.xml
@unittest.skipIf('PyPy' in sys.version, 'skip lxml tests on pypy')
def test_lxml_attribute(self):
app = webtest.TestApp(links_app)
resp = app.post('/')
resp.content_type = 'text/xml'
print(resp.body)
print(resp.lxml)
def test_html_attribute(self):
app = webtest.TestApp(links_app)
res = app.post('/')
res.content_type = 'text/plain'
self.assertRaises(
AttributeError,
getattr, res, 'html'
)
def test_no_form(self):
app = webtest.TestApp(links_app)
resp = app.get('/no_form/')
self.assertRaises(
TypeError,
getattr,
resp, 'form'
)
def test_one_forms(self):
app = webtest.TestApp(links_app)
resp = app.get('/one_forms/')
self.assertEqual(resp.form.id, 'first_form')
def test_too_many_forms(self):
app = webtest.TestApp(links_app)
resp = app.get('/many_forms/')
self.assertRaises(
TypeError,
getattr,
resp, 'form'
)
def test_showbrowser(self):
def open_new(f):
self.filename = f
webbrowser.open_new = open_new
app = webtest.TestApp(debug_app)
res = app.post('/')
res.showbrowser()
def test_unicode_normal_body(self):
app = webtest.TestApp(debug_app)
res = app.post('/')
self.assertRaises(
AttributeError,
getattr, res, 'unicode_normal_body'
)
res.charset = 'latin1'
res.body = 'été'.encode('latin1')
self.assertEqual(res.unicode_normal_body, 'été')
def test_testbody(self):
app = webtest.TestApp(debug_app)
res = app.post('/')
res.charset = 'utf8'
res.body = 'été'.encode('latin1')
res.testbody
def test_xml(self):
app = webtest.TestApp(links_app)
resp = app.get('/no_form/')
self.assertRaises(
AttributeError,
getattr,
resp, 'xml'
)
resp.content_type = 'text/xml'
resp.xml
def test_json(self):
app = webtest.TestApp(links_app)
resp = app.get('/json/')
with self.assertRaises(AttributeError):
resp.json
resp.content_type = 'text/json'
self.assertIn('foo', resp.json)
resp.content_type = 'application/json'
self.assertIn('foo', resp.json)
resp.content_type = 'application/vnd.webtest+json'
self.assertIn('foo', resp.json)
def test_unicode(self):
app = webtest.TestApp(links_app)
resp = app.get('/')
if not PY3:
unicode(resp)
print(resp.__unicode__())
def test_content_dezips(self):
app = webtest.TestApp(gzipped_app)
resp = app.get('/')
self.assertEqual(resp.body, b'test')
class TestFollow(unittest.TestCase):
def get_redirects_app(self, count=1, locations=None):
"""Return an app that issues a redirect ``count`` times"""
remaining_redirects = [count] # this means "nonlocal"
if locations is None:
locations = ['/'] * count
def app(environ, start_response):
headers = [('Content-Type', str('text/html'))]
if remaining_redirects[0] == 0:
status = "200 OK"
body = b"done"
else:
status = "302 Found"
body = b''
nextloc = str(locations.pop(0))
headers.append(('location', nextloc))
remaining_redirects[0] -= 1
headers.append(('Content-Length', str(len(body))))
start_response(str(status), headers)
return [body]
return webtest.TestApp(app)
def test_follow_with_cookie(self):
app = webtest.TestApp(debug_app)
app.get('/?header-set-cookie=foo=bar')
self.assertEqual(app.cookies['foo'], 'bar')
resp = app.get('/?status=302%20Found&header-location=/')
resp = resp.follow()
resp.mustcontain('HTTP_COOKIE: foo=bar')
def test_follow(self):
app = self.get_redirects_app(1)
resp = app.get('/')
self.assertEqual(resp.status_int, 302)
resp = resp.follow()
self.assertEqual(resp.body, b'done')
# can't follow non-redirect
self.assertRaises(AssertionError, resp.follow)
def test_follow_relative(self):
app = self.get_redirects_app(2, ['hello/foo/', 'bar'])
resp = app.get('/')
self.assertEqual(resp.status_int, 302)
resp = resp.follow()
self.assertEqual(resp.status_int, 302)
resp = resp.follow()
self.assertEqual(resp.body, b'done')
self.assertEqual(resp.request.url, 'http://localhost/hello/foo/bar')
def test_follow_twice(self):
app = self.get_redirects_app(2)
resp = app.get('/').follow()
self.assertEqual(resp.status_int, 302)
resp = resp.follow()
self.assertEqual(resp.status_int, 200)
def test_maybe_follow_200(self):
app = self.get_redirects_app(0)
resp = app.get('/').maybe_follow()
self.assertEqual(resp.body, b'done')
def test_maybe_follow_once(self):
app = self.get_redirects_app(1)
resp = app.get('/').maybe_follow()
self.assertEqual(resp.body, b'done')
def test_maybe_follow_twice(self):
app = self.get_redirects_app(2)
resp = app.get('/').maybe_follow()
self.assertEqual(resp.body, b'done')
def test_maybe_follow_infinite(self):
app = self.get_redirects_app(100000)
self.assertRaises(AssertionError, app.get('/').maybe_follow)
WebTest-2.0.18/tests/deploy.ini 0000644 0000000 0000000 00000000124 12464666730 015027 0 ustar root root [app:main]
paste.app_factory = webtest.debugapp:make_debug_app
form =
WebTest-2.0.18/tests/test_lint.py 0000644 0000000 0000000 00000024040 12464666730 015414 0 ustar root root # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from six import PY3
from six import StringIO
from tests.compat import unittest
from webob import Request, Response
import warnings
import mock
from webtest import TestApp
from webtest.compat import to_bytes
from webtest.lint import check_headers
from webtest.lint import check_content_type
from webtest.lint import check_environ
from webtest.lint import IteratorWrapper
from webtest.lint import WriteWrapper
from webtest.lint import ErrorWrapper
from webtest.lint import InputWrapper
from webtest.lint import to_string
from webtest.lint import middleware
from six import BytesIO
def application(environ, start_response):
req = Request(environ)
resp = Response()
env_input = environ['wsgi.input']
len_body = len(req.body)
env_input.input.seek(0)
if req.path_info == '/read':
resp.body = env_input.read(len_body)
elif req.path_info == '/read_line':
resp.body = env_input.readline(len_body)
elif req.path_info == '/read_lines':
resp.body = b'-'.join(env_input.readlines(len_body))
elif req.path_info == '/close':
resp.body = env_input.close()
return resp(environ, start_response)
class TestToString(unittest.TestCase):
def test_to_string(self):
self.assertEqual(to_string('foo'), 'foo')
self.assertEqual(to_string(b'foo'), 'foo')
class TestMiddleware(unittest.TestCase):
def test_lint_too_few_args(self):
linter = middleware(application)
with self.assertRaisesRegexp(AssertionError, "Two arguments required"):
linter()
with self.assertRaisesRegexp(AssertionError, "Two arguments required"):
linter({})
def test_lint_no_keyword_args(self):
linter = middleware(application)
with self.assertRaisesRegexp(AssertionError, "No keyword arguments "
"allowed"):
linter({}, 'foo', baz='baz')
#TODO: test start_response_wrapper
@mock.patch.multiple('webtest.lint',
check_environ=lambda x: True, # don't block too early
InputWrapper=lambda x: True)
def test_lint_iterator_returned(self):
linter = middleware(lambda x, y: None) # None is not an iterator
msg = "The application must return an iterator, if only an empty list"
with self.assertRaisesRegexp(AssertionError, msg):
linter({'wsgi.input': 'foo', 'wsgi.errors': 'foo'}, 'foo')
class TestInputWrapper(unittest.TestCase):
def test_read(self):
app = TestApp(application)
resp = app.post('/read', 'hello')
self.assertEqual(resp.body, b'hello')
def test_readline(self):
app = TestApp(application)
resp = app.post('/read_line', 'hello\n')
self.assertEqual(resp.body, b'hello\n')
def test_readlines(self):
app = TestApp(application)
resp = app.post('/read_lines', 'hello\nt\n')
self.assertEqual(resp.body, b'hello\n-t\n')
def test_close(self):
input_wrapper = InputWrapper(None)
self.assertRaises(AssertionError, input_wrapper.close)
def test_iter(self):
data = to_bytes("A line\nAnother line\nA final line\n")
input_wrapper = InputWrapper(BytesIO(data))
self.assertEquals(to_bytes("").join(input_wrapper), data, '')
def test_seek(self):
data = to_bytes("A line\nAnother line\nA final line\n")
input_wrapper = InputWrapper(BytesIO(data))
input_wrapper.seek(0)
self.assertEquals(to_bytes("").join(input_wrapper), data, '')
class TestMiddleware2(unittest.TestCase):
def test_exc_info(self):
def application_exc_info(environ, start_response):
body = to_bytes('body stuff')
headers = [
('Content-Type', 'text/plain; charset=utf-8'),
('Content-Length', str(len(body)))]
start_response(to_bytes('200 OK'), headers, ('stuff',))
return [body]
app = TestApp(application_exc_info)
app.get('/')
# don't know what to assert here... a bit cheating, just covers code
class TestCheckContentType(unittest.TestCase):
def test_no_content(self):
status = "204 No Content"
headers = [
('Content-Type', 'text/plain; charset=utf-8'),
('Content-Length', '4')
]
self.assertRaises(AssertionError, check_content_type, status, headers)
def test_no_content_type(self):
status = "200 OK"
headers = [
('Content-Length', '4')
]
self.assertRaises(AssertionError, check_content_type, status, headers)
class TestCheckHeaders(unittest.TestCase):
@unittest.skipIf(not PY3, 'Useless in Python2')
def test_header_unicode_value(self):
self.assertRaises(AssertionError, check_headers, [('X-Price', '100€')])
@unittest.skipIf(not PY3, 'Useless in Python2')
def test_header_unicode_name(self):
self.assertRaises(AssertionError, check_headers, [('X-€', 'foo')])
class TestCheckEnviron(unittest.TestCase):
def test_no_query_string(self):
environ = {
'REQUEST_METHOD': str('GET'),
'SERVER_NAME': str('localhost'),
'SERVER_PORT': str('80'),
'wsgi.version': (1, 0, 1),
'wsgi.input': StringIO('test'),
'wsgi.errors': StringIO(),
'wsgi.multithread': None,
'wsgi.multiprocess': None,
'wsgi.run_once': None,
'wsgi.url_scheme': 'http',
'PATH_INFO': str('/'),
}
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
check_environ(environ)
self.assertEqual(len(w), 1, "We should have only one warning")
self.assertTrue(
"QUERY_STRING" in str(w[-1].message),
"The warning message should say something about QUERY_STRING")
def test_no_valid_request(self):
environ = {
'REQUEST_METHOD': str('PROPFIND'),
'SERVER_NAME': str('localhost'),
'SERVER_PORT': str('80'),
'wsgi.version': (1, 0, 1),
'wsgi.input': StringIO('test'),
'wsgi.errors': StringIO(),
'wsgi.multithread': None,
'wsgi.multiprocess': None,
'wsgi.run_once': None,
'wsgi.url_scheme': 'http',
'PATH_INFO': str('/'),
'QUERY_STRING': str(''),
}
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
check_environ(environ)
self.assertEqual(len(w), 1, "We should have only one warning")
self.assertTrue(
"REQUEST_METHOD" in str(w[-1].message),
"The warning message should say something "
"about REQUEST_METHOD")
def test_handles_native_strings_in_variables(self):
# "native string" means unicode in py3, but bytes in py2
path = '/umläut'
if not PY3:
path = path.encode('utf-8')
environ = {
'REQUEST_METHOD': str('GET'),
'SERVER_NAME': str('localhost'),
'SERVER_PORT': str('80'),
'wsgi.version': (1, 0, 1),
'wsgi.input': StringIO('test'),
'wsgi.errors': StringIO(),
'wsgi.multithread': None,
'wsgi.multiprocess': None,
'wsgi.run_once': None,
'wsgi.url_scheme': 'http',
'PATH_INFO': path,
'QUERY_STRING': str(''),
}
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
check_environ(environ)
self.assertEqual(0, len(w), "We should have no warning")
class TestIteratorWrapper(unittest.TestCase):
def test_close(self):
class MockIterator(object):
def __init__(self):
self.closed = False
def __iter__(self):
return self
def __next__(self):
return None
next = __next__
def close(self):
self.closed = True
mock = MockIterator()
wrapper = IteratorWrapper(mock, None)
wrapper.close()
self.assertTrue(mock.closed, "Original iterator has not been closed")
class TestWriteWrapper(unittest.TestCase):
def test_wrong_type(self):
write_wrapper = WriteWrapper(None)
self.assertRaises(AssertionError, write_wrapper, 'not a binary')
def test_normal(self):
class MockWriter(object):
def __init__(self):
self.written = []
def __call__(self, s):
self.written.append(s)
data = to_bytes('foo')
mock = MockWriter()
write_wrapper = WriteWrapper(mock)
write_wrapper(data)
self.assertEqual(
mock.written, [data],
"WriterWrapper should call original writer when data is binary "
"type")
class TestErrorWrapper(unittest.TestCase):
def test_dont_close(self):
error_wrapper = ErrorWrapper(None)
self.assertRaises(AssertionError, error_wrapper.close)
class FakeError(object):
def __init__(self):
self.written = []
self.flushed = False
def write(self, s):
self.written.append(s)
def writelines(self, lines):
for line in lines:
self.write(line)
def flush(self):
self.flushed = True
def test_writelines(self):
fake_error = self.FakeError()
error_wrapper = ErrorWrapper(fake_error)
data = [to_bytes('a line'), to_bytes('another line')]
error_wrapper.writelines(data)
self.assertEqual(fake_error.written, data,
"ErrorWrapper should call original writer")
def test_flush(self):
fake_error = self.FakeError()
error_wrapper = ErrorWrapper(fake_error)
error_wrapper.flush()
self.assertTrue(
fake_error.flushed,
"ErrorWrapper should have called original wsgi_errors's flush")
WebTest-2.0.18/tests/test_ext.py 0000644 0000000 0000000 00000000337 12464666730 015251 0 ustar root root # -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
from .compat import unittest
from webtest import ext
class TestSelenium(unittest.TestCase):
def test_raises(self):
self.assertRaises(ImportError, ext.casperjs)
WebTest-2.0.18/tests/test_http.py 0000644 0000000 0000000 00000004144 12464666730 015430 0 ustar root root # -*- coding: utf-8 -*-
from tests.compat import unittest
from webob import Request
from webtest.debugapp import debug_app
from webtest import http
class TestServer(unittest.TestCase):
def setUp(self):
self.s = http.StopableWSGIServer.create(debug_app)
def test_server(self):
s = self.s
s.wait()
self.assertEqual(200,
http.check_server(s.adj.host, s.adj.port,
'/__application__'))
self.assertEqual(200,
http.check_server(s.adj.host, s.adj.port,
'/__file__?__file__=' + __file__))
self.assertEqual(404,
http.check_server(s.adj.host, s.adj.port,
'/__file__?__file__=XXX'))
self.assertEqual(304,
http.check_server(s.adj.host, s.adj.port,
'/?status=304'))
def test_wsgi_wrapper(self):
s = self.s
s.wait()
req = Request.blank('/__application__')
resp = req.get_response(s.wrapper)
self.assertEqual(resp.status_int, 200)
req = Request.blank('/__file__?__file__=' + __file__)
resp = req.get_response(s.wrapper)
self.assertEqual(resp.status_int, 200)
req = Request.blank('/__file__?__file__=XXX')
resp = req.get_response(s.wrapper)
self.assertEqual(resp.status_int, 404)
req = Request.blank('/?status=304')
resp = req.get_response(s.wrapper)
self.assertEqual(resp.status_int, 304)
def tearDown(self):
self.s.shutdown()
class TestBrokenServer(unittest.TestCase):
def test_shutdown_non_running(self):
host, port = http.get_free_port()
s = http.StopableWSGIServer(debug_app, host=host, port=port)
self.assertFalse(s.wait(retries=-1))
self.assertTrue(s.shutdown())
class TestClient(unittest.TestCase):
def test_no_server(self):
host, port = http.get_free_port()
self.assertEqual(0, http.check_server(host, port, retries=2))
WebTest-2.0.18/tests/test_sel.py 0000644 0000000 0000000 00000000377 12464666730 015240 0 ustar root root # -*- coding: utf-8 -*-
from .compat import unittest
from webtest import sel
class TestSelenium(unittest.TestCase):
def test_raises(self):
self.assertRaises(ImportError, sel.SeleniumApp)
self.assertRaises(ImportError, sel.selenium)
WebTest-2.0.18/tests/__init__.py 0000644 0000000 0000000 00000000002 12464666730 015136 0 ustar root root #
WebTest-2.0.18/tests/test_debugapp.py 0000644 0000000 0000000 00000014245 12464666730 016243 0 ustar root root # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import sys
import six
import webtest
from webtest.debugapp import debug_app
from webtest.compat import PY3
from webtest.compat import to_bytes
from webtest.compat import print_stderr
from webtest.app import AppError
from tests.compat import unittest
import webbrowser
def test_print_unicode():
print_stderr('°C')
class TestTesting(unittest.TestCase):
def setUp(self):
self.app = webtest.TestApp(debug_app)
def test_url_class(self):
class U:
def __str__(self):
return '/'
res = self.app.get(U())
self.assertEqual(res.status_int, 200)
def test_testing(self):
res = self.app.get('/')
self.assertEqual(res.status_int, 200)
self.assertEqual(res.headers['content-type'], 'text/plain')
self.assertEqual(res.content_type, 'text/plain')
res = self.app.request('/', method='GET')
self.assertEqual(res.status_int, 200)
self.assertEqual(res.headers['content-type'], 'text/plain')
self.assertEqual(res.content_type, 'text/plain')
res = self.app.head('/')
self.assertEqual(res.status_int, 200)
self.assertEqual(res.headers['content-type'], 'text/plain')
self.assertTrue(res.content_length > 0)
self.assertEqual(res.body, to_bytes(''))
res = self.app.head('/', xhr=True)
self.assertEqual(res.status_int, 200)
def test_post_unicode(self):
res = self.app.post(
'/', params=dict(a='é'),
content_type='application/x-www-form-urlencoded;charset=utf8')
res.mustcontain('a=%C3%A9')
def test_post_unicode_body(self):
res = self.app.post(
'/', params='é',
content_type='text/plain; charset=utf8')
self.assertTrue(res.body.endswith(b'\xc3\xa9'))
res.mustcontain('é')
def test_post_params(self):
res = self.app.post('/', params=dict(a=1))
res.mustcontain('a=1')
res = self.app.post('/', params=[('a', '1')])
res.mustcontain('a=1')
res = self.app.post_json('/', params=dict(a=1))
res.mustcontain('{"a": 1}')
res = self.app.post_json('/', params=False)
res.mustcontain('false')
def test_put_params(self):
res = self.app.put('/', params=dict(a=1))
res.mustcontain('a=1')
res = self.app.put_json('/', params=dict(a=1))
res.mustcontain('{"a": 1}')
res = self.app.put_json('/', params=False)
res.mustcontain('false')
def test_delete_params(self):
res = self.app.delete('/', params=dict(a=1))
res.mustcontain('a=1')
res = self.app.delete_json('/', params=dict(a=1))
res.mustcontain('{"a": 1}')
def test_options(self):
res = self.app.options('/')
self.assertEqual(res.status_int, 200)
def test_exception(self):
self.assertRaises(Exception, self.app.get, '/?error=t')
self.assertRaises(webtest.AppError, self.app.get,
'/?status=404%20Not%20Found')
def test_bad_content_type(self):
resp = self.app.get('/')
self.assertRaises(AttributeError, lambda: resp.json)
resp = self.app.get('/?header-content-type=application/json')
self.assertRaises(AttributeError, lambda: resp.pyquery)
self.assertRaises(AttributeError, lambda: resp.lxml)
self.assertRaises(AttributeError, lambda: resp.xml)
def test_app_from_config_file(self):
config = os.path.join(os.path.dirname(__file__), 'deploy.ini')
app = webtest.TestApp('config:%s#main' % config)
resp = app.get('/')
self.assertEqual(resp.status_int, 200)
def test_errors(self):
try:
self.app.get('/?errorlog=somelogs')
assert(False, "An AppError should be raised")
except AppError:
e = sys.exc_info()[1]
assert six.text_type(e) \
== "Application had errors logged:\nsomelogs"
def test_request_obj(self):
res = self.app.get('/')
res = self.app.request(res.request)
def test_showbrowser(self):
open_new = webbrowser.open_new
self.filename = ''
def open_new(f):
self.filename = f
webbrowser.open_new = open_new
res = self.app.get('/')
res.showbrowser()
assert self.filename.startswith('file://'), self.filename
def test_303(self):
res = self.app.get('/?status=302%20Redirect&header-location=/foo')
self.assertEqual(res.status_int, 302)
print(res.location)
self.assertEqual(res.location, 'http://localhost/foo', res)
self.assertEqual(res.headers['location'], 'http://localhost/foo')
res = res.follow()
self.assertEqual(res.request.url, 'http://localhost/foo')
self.assertIn('Response: 200 OK', str(res))
self.assertIn('200 OK', repr(res))
self.app.get('/?status=303%20redirect', status='3*')
def test_204(self):
self.app.post('/?status=204%20OK')
def test_404(self):
self.app.get('/?status=404%20Not%20Found', status=404)
self.assertRaises(webtest.AppError, self.app.get, '/', status=404)
def test_print_stderr(self):
res = self.app.get('/')
res.charset = 'utf-8'
res.text = '°C'
print_stderr(str(res))
res.charset = None
print_stderr(str(res))
def test_app_error(self):
res = self.app.get('/')
res.charset = 'utf-8'
res.text = '°C'
AppError('%s %s %s %s', res.status, '', res.request.url, res)
res.charset = None
AppError('%s %s %s %s', res.status, '', res.request.url, res)
def test_exception_repr(self):
res = self.app.get('/')
res.charset = 'utf-8'
res.text = '°C'
if not PY3:
unicode(AssertionError(res))
str(AssertionError(res))
res.charset = None
if not PY3:
unicode(AssertionError(res))
str(AssertionError(res))
def test_fake_dict(self):
class FakeDict(object):
def items(self):
return [('a', '10'), ('a', '20')]
self.app.post('/params', params=FakeDict())
WebTest-2.0.18/tests/test_forms.py 0000644 0000000 0000000 00000110704 12464666730 015577 0 ustar root root # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os.path
import struct
import sys
import webtest
import six
from six import binary_type
from six import PY3
from webob import Request
from webtest.debugapp import DebugApp
from webtest.compat import to_bytes
from webtest.forms import NoValue, Submit, Upload
from tests.compat import unittest
from tests.compat import u
class TestForms(unittest.TestCase):
def callFUT(self, filename='form_inputs.html', formid='simple_form'):
dirname = os.path.join(os.path.dirname(__file__), 'html')
app = DebugApp(form=os.path.join(dirname, filename), show_form=True)
resp = webtest.TestApp(app).get('/form.html')
return resp.forms[formid]
def test_set_submit_field(self):
form = self.callFUT()
self.assertRaises(
AttributeError,
form['submit'].value__set,
'foo'
)
def test_button(self):
form = self.callFUT()
button = form['button']
self.assertTrue(isinstance(button, Submit),
"