def test_multipart(self): """ Environ: POST (multipart files and multible values per key) """ fields = [('field1', 'value1'), ('field2', 'value2'), ('field2', 'value3')] files = [('file1', 'filename1.txt', 'content1'), ('file2', 'filename2.py', u'ä\nö\rü')] e = tools.multipart_environ(fields=fields, files=files) request.bind(e) # File content self.assertTrue('file1' in request.POST) cmp = tob('content1') if sys.version_info >= (3, 2, 0) else 'content1' self.assertEqual(cmp, request.POST['file1'].file.read()) # File name and meta data self.assertTrue('file2' in request.POST) self.assertEqual('filename2.py', request.POST['file2'].filename) # UTF-8 files x = request.POST['file2'].file.read() if (3, 2, 0) > sys.version_info >= (3, 0, 0): x = x.encode('ISO-8859-1') self.assertEqual(u'ä\nö\rü'.encode('utf8'), x) # No file self.assertTrue('file3' not in request.POST) # Field (single) self.assertEqual('value1', request.POST['field1']) # Field (multi) self.assertEqual(2, len(request.POST.getall('field2'))) self.assertEqual(['value2', 'value3'], request.POST.getall('field2'))
def test_send_event(self): output = file.Output({'jsonpath': '/dev/null'}) with unittest.mock.patch.object(output, '_outputfile') as fp: app = Bottle() app.config = {'elasticpot': {'nodeid': 'foo'}} default_app.push(app) request.bind({'bottle.app': app}) try: output.send({ 'timestamp': '', 'src_ip': '127.0.0.1', 'src_port': '11111', 'dest_ip': '127.0.10.1', 'dest_port': '22222', 'querystring': '/?pretty', 'body': '', 'raw': '', }) finally: default_app.pop() assert fp.write.call_count == 1 assert fp.write.call_args[0][0].endswith('\n') event = json.loads(fp.write.call_args[0][0]) assert isinstance(event, dict) assert event['honeypot']['name'] == 'Elasticpot'
def test_multipart(self): """ Environ: POST (multipart files and multible values per key) """ fields = [("field1", "value1"), ("field2", "value2"), ("field2", "value3")] files = [("file1", "filename1.txt", "content1"), ("file2", "filename2.py", u"ä\nö\rü")] e = tools.multipart_environ(fields=fields, files=files) request.bind(e) # File content self.assertTrue("file1" in request.POST) cmp = tob("content1") if sys.version_info >= (3, 2, 0) else "content1" self.assertEqual(cmp, request.POST["file1"].file.read()) # File name and meta data self.assertTrue("file2" in request.POST) self.assertEqual("filename2.py", request.POST["file2"].filename) # UTF-8 files x = request.POST["file2"].file.read() if (3, 2, 0) > sys.version_info >= (3, 0, 0): x = x.encode("ISO-8859-1") self.assertEqual(u"ä\nö\rü".encode("utf8"), x) # No file self.assertTrue("file3" not in request.POST) # Field (single) self.assertEqual("value1", request.POST["field1"]) # Field (multi) self.assertEqual(2, len(request.POST.getall("field2"))) self.assertEqual(["value2", "value3"], request.POST.getall("field2"))
def _handle(self, environ): path = environ['bottle.raw_path'] = environ['PATH_INFO'] try: environ['PATH_INFO'] = path.encode('latin1').decode('utf8') except UnicodeError: return HTTPError(400, 'Invalid path string. Expected UTF-8') try: environ['bottle.app'] = self request.bind(environ) response.bind() try: self.trigger_hook("before_request") route, args = self.router.match(environ) environ['route.handle'] = route environ['bottle.route'] = route environ['route.url_args'] = args out = route.call(**args) if isinstance(out, asyncio.Future) or inspect.isgenerator(out): out = yield from out return out finally: self.trigger_hook("after_request") except HTTPResponse: return _e() except RouteReset: route.reset() return (yield from self._handle(environ)) except (KeyboardInterrupt, SystemExit, MemoryError): raise except Exception: if not self.catchall: raise stacktrace = format_exc() environ['wsgi.errors'].write(stacktrace) return HTTPError(500, "Internal Server Error", _e(), stacktrace)
def test_send_event(self): output = ews.Output({ 'username': '******', 'token': 'abcdefghijklmnop', 'rhost_first': 'http://localhost' }) with unittest.mock.patch('requests.post') as post: app = Bottle() app.config = {'elasticpot': {'nodeid': 'foo'}} default_app.push(app) request.bind({'bottle.app': app}) try: output.send({ 'timestamp': '1 January 1900', 'src_ip': '127.0.0.1', 'src_port': '11111', 'dest_ip': '127.0.10.1', 'dest_port': '22222', 'querystring': '/?pretty', 'body': '--PAYLOAD DATA HERE--', 'raw': '--BASE64 ENCODED STRING HERE--', }) finally: default_app.pop() assert post.call_count == 1 assert post.call_args[0][0] == 'http://localhost' assert post.call_args[1]['data'].strip() == EXPECTED.strip()
def test_isajax(self): e = {} wsgiref.util.setup_testing_defaults(e) request.bind(e) self.assertFalse(request.is_ajax) e['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' self.assertTrue(request.is_ajax)
def test_multipart(self): """ Environ: POST (multipart files and multible values per key) """ fields = [('field1','value1'), ('field2','value2'), ('field2','value3')] files = [('file1','filename1.txt','content1'), ('file2','filename2.py',u'ä\nö\rü')] e = tools.multipart_environ(fields=fields, files=files) request.bind(e) # File content self.assertTrue('file1' in request.POST) cmp = tob('content1') if sys.version_info >= (3,2,0) else 'content1' self.assertEqual(cmp, request.POST['file1'].file.read()) # File name and meta data self.assertTrue('file2' in request.POST) self.assertEqual('filename2.py', request.POST['file2'].filename) # UTF-8 files x = request.POST['file2'].file.read() if (3,2,0) > sys.version_info >= (3,0,0): x = x.encode('ISO-8859-1') self.assertEqual(u'ä\nö\rü'.encode('utf8'), x) # No file self.assertTrue('file3' not in request.POST) # Field (single) self.assertEqual('value1', request.POST['field1']) # Field (multi) self.assertEqual(2, len(request.POST.getall('field2'))) self.assertEqual(['value2', 'value3'], request.POST.getall('field2'))
def test_multipart(self): """ Environ: POST (multipart files and multible values per key) """ e = {} e['SERVER_PROTOCOL'] = "HTTP/1.1" e['REQUEST_METHOD'] = 'POST' e['CONTENT_TYPE'] = 'multipart/form-data; boundary=----------------314159265358979323846' e['wsgi.input'] = '------------------314159265358979323846\n' e['wsgi.input'] += 'Content-Disposition: form-data; name=test.txt; filename=test.txt\n' e['wsgi.input'] += 'Content-Type: application/octet-stream; charset=ISO-8859-1\n' e['wsgi.input'] += 'Content-Transfer-Encoding: binary\n' e['wsgi.input'] += 'This is a test.\n' e['wsgi.input'] += '------------------314159265358979323846\n' e['wsgi.input'] += 'Content-Disposition: form-data; name=sample.txt; filename=sample.txt\n' e['wsgi.input'] += 'Content-Type: text/plain; charset=ISO-8859-1\n' e['wsgi.input'] += 'Content-Transfer-Encoding: binary\n' e['wsgi.input'] += 'This is a sample\n' e['wsgi.input'] += '------------------314159265358979323846\n' e['wsgi.input'] += 'Content-Disposition: form-data; name=sample.txt; filename=sample2.txt\n' e['wsgi.input'] += 'Content-Type: text/plain; charset=ISO-8859-1\n' e['wsgi.input'] += 'Content-Transfer-Encoding: binary\n' e['wsgi.input'] += 'This is a second sample\n' e['wsgi.input'] += '------------------314159265358979323846--\n' e['CONTENT_LENGTH'] = len(e['wsgi.input']) e['wsgi.input'] = StringIO(e['wsgi.input']) e['wsgi.input'].seek(0) request.bind(e) self.assertTrue('test.txt' in request.POST) self.assertTrue('sample.txt' in request.POST) self.assertEqual('This is a test.', request.POST['test.txt'].file.read()) self.assertEqual('test.txt', request.POST['test.txt'].filename) self.assertEqual(2, len(request.POST['sample.txt'])) self.assertEqual('This is a sample', request.POST['sample.txt'][0].file.read()) self.assertEqual('This is a second sample', request.POST['sample.txt'][1].file.read())
def __call__(self, environ, start_response): """ Apple WSGI-interface. """ try: environ['bottle.app'] = self request.bind(environ) response.bind(self) handler, args = self.match_url(request.path, request.method) # If its a Websocket or Async call if isinstance( handler, Async ): return handler( environ, start_response, args ) result = handler( **args ) status = '%d %s' % (response.status, HTTP_CODES[response.status]) start_response(status, response.headerlist) # RFC2616 Section 4.3 if response.status in (100, 101, 204, 304) or request.method == 'HEAD': return [] socket = Socket( environ['eventlet.input'].get_socket(), environ ) for value in iter(result): socket.write( self._cast( value, request, response ) ) return [] except (KeyboardInterrupt, SystemExit): raise except HTTPResponse, e: start_response( '%s %s' % (e.status, HTTP_CODES[e.status]), [('Content-Type', 'text/html')] ) return e
def test_send_event(self): output = console.Output({}) with unittest.mock.patch('sys.stdout') as stdout: app = Bottle() app.config = {'elasticpot': {'nodeid': 'foo'}} default_app.push(app) request.bind({'bottle.app': app}) try: output.send({ 'timestamp': '', 'src_ip': '127.0.0.1', 'src_port': '11111', 'dest_ip': '127.0.10.1', 'dest_port': '22222', 'querystring': '/?pretty', 'body': '', 'raw': '', }) finally: default_app.pop() '''assert stdout.write.call_count == 1''' assert stdout.write.call_args[0][0].endswith('\n') event = json.loads(stdout.write.call_args_list[0][0][0]) assert isinstance(event, dict) assert event['src_ip'] == '127.0.0.1'
def _handle(self, environ): try: environ['bottle.app'] = self request.bind(environ) response.bind() route, args = self.router.match(environ) environ['route.handle'] = route environ['bottle.route'] = route environ['route.url_args'] = args out = route.call(**args) if isinstance(out, asyncio.Future) or inspect.isgenerator(out): out = yield from out return out except HTTPResponse: return _e() except RouteReset: route.reset() return (yield from self._handle(environ)) except (KeyboardInterrupt, SystemExit, MemoryError): raise except Exception: if not self.catchall: raise stacktrace = format_exc() environ['wsgi.errors'].write(stacktrace) return HTTPError(500, "Internal Server Error", _e(), stacktrace)
def test_multipart(self): """ Environ: POST (multipart files and multible values per key) """ fields = [('field1','value1'), ('field2','value2'), ('field2','value3')] files = [('file1','filename1.txt','content1'), ('file2','filename2.py',u'äöü')] e = tools.multipart_environ(fields=fields, files=files) request.bind(e, None) self.assertTrue(e['CONTENT_LENGTH'], request.input_length) # File content self.assertTrue('file1' in request.POST) self.assertEqual('content1', request.POST['file1'].file.read()) # File name and meta data self.assertTrue('file2' in request.POST) self.assertEqual('filename2.py', request.POST['file2'].filename) # UTF-8 files x = request.POST['file2'].file.read() if sys.version_info >= (3,0,0): x = x.encode('ISO-8859-1') self.assertEqual(u'äöü'.encode('utf8'), x) # No file self.assertTrue('file3' not in request.POST) # Field (single) self.assertEqual('value1', request.POST['field1']) # Field (multi) self.assertEqual(2, len(request.POST['field2'])) self.assertTrue('value2' in request.POST['field2']) self.assertTrue('value3' in request.POST['field2'])
def test_dict_access(self): """ Environ: request objects are environment dicts """ e = {} wsgiref.util.setup_testing_defaults(e) request.bind(e, None) for k, v in e.iteritems(): self.assertTrue(k in request) self.assertTrue(request[k] == v)
def test_header_access_special(self): e = {} wsgiref.util.setup_testing_defaults(e) request.bind(e) request['CONTENT_TYPE'] = 'test' request['CONTENT_LENGTH'] = '123' self.assertEqual(request.headers['Content-Type'], 'test') self.assertEqual(request.headers['Content-Length'], '123')
def test_header_access_special(self): e = {} wsgiref.util.setup_testing_defaults(e) request.bind(e) request['CONTENT_TYPE'] = 'test' request['CONTENT_LENGTH'] = '123' self.assertEqual(request.header['Content-Type'], 'test') self.assertEqual(request.header['Content-Length'], '123')
def test_header_access_special(self): e = {} wsgiref.util.setup_testing_defaults(e) request.bind(e) request["CONTENT_TYPE"] = "test" request["CONTENT_LENGTH"] = "123" self.assertEqual(request.header["Content-Type"], "test") self.assertEqual(request.header["Content-Length"], "123")
def test_cookie(self): """ Environ: COOKIES """ t = dict() t['a=a'] = {'a': 'a'} t['a=a; b=b'] = {'a': 'a', 'b': 'b'} t['a=a; a=b'] = {'a': 'b'} for k, v in t.iteritems(): request.bind({'HTTP_COOKIE': k}) self.assertEqual(v, request.COOKIES)
def test_cookie(self): """ Environ: COOKIES """ t = dict() t["a=a"] = {"a": "a"} t["a=a; b=b"] = {"a": "a", "b": "b"} t["a=a; a=b"] = {"a": "b"} for k, v in t.iteritems(): request.bind({"HTTP_COOKIE": k}) self.assertEqual(v, request.COOKIES)
def test_cookie(self): """ Environ: COOKIES """ t = dict() t['a=a'] = {'a': 'a'} t['a=a; b=b'] = {'a': 'a', 'b':'b'} t['a=a; a=b'] = {'a': 'b'} for k, v in t.iteritems(): request.bind({'HTTP_COOKIE': k}) self.assertEqual(v, request.COOKIES)
def test_bodypost(self): sq = u"foobar".encode("utf8") e = {} wsgiref.util.setup_testing_defaults(e) e["wsgi.input"].write(sq) e["wsgi.input"].seek(0) e["CONTENT_LENGTH"] = str(len(sq)) e["REQUEST_METHOD"] = "POST" request.bind(e) self.assertEqual("", request.POST["foobar"])
def test_getpost(self): """ Environ: GET and POST (simple) """ sq = 'a=a&b=b&c=c' qd = {'a':'a', 'b':'b','c':'c'} e = {} e['wsgi.input'] = sq e['QUERY_STRING'] = sq request.bind(e) self.assertEqual(qd, request.GET) self.assertEqual(qd, request.POST)
def test_multigetpost(self): """ Environ: GET and POST (multi values) """ sq = 'a=a&a=1' qd = {'a':['a','1']} e = {} e['wsgi.input'] = sq e['QUERY_STRING'] = sq request.bind(e) self.assertEqual(qd, request.GET) self.assertEqual(qd, request.POST)
def test_header_access(self): """ Environ: Request objects decode headers """ e = {} wsgiref.util.setup_testing_defaults(e) e["HTTP_SOME_HEADER"] = "some value" request.bind(e) request["HTTP_SOME_OTHER_HEADER"] = "some other value" self.assertTrue("Some-Header" in request.headers) self.assertTrue(request.header["Some-Header"] == "some value") self.assertTrue(request.header["Some-Other-Header"] == "some other value")
def test_redirect_preserve_cookies(self): env = {'SERVER_PROTOCOL': 'HTTP/1.1'} request.bind(env) bottle.response.bind() try: bottle.response.set_cookie('xxx', 'yyy') bottle.redirect('...') except bottle.HTTPResponse as E: h = [v for (k, v) in E.headerlist if k == 'Set-Cookie'] self.assertEqual(h, ['xxx=yyy'])
def test_bodypost(self): sq = u'foobar'.encode('utf8') e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(sq) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = str(len(sq)) e['REQUEST_METHOD'] = "POST" request.bind(e) self.assertEqual('', request.POST['foobar'])
def test_header_access(self): """ Environ: Request objects decode headers """ e = {} wsgiref.util.setup_testing_defaults(e) e['HTTP_SOME_HEADER'] = 'some value' request.bind(e) request['HTTP_SOME_OTHER_HEADER'] = 'some other value' self.assertTrue('Some-Header' in request.headers) self.assertTrue(request.header['Some-Header'] == 'some value') self.assertTrue(request.header['Some-Other-Header'] == 'some other value')
def test_redirect_preserve_cookies(self): env = {'SERVER_PROTOCOL':'HTTP/1.1'} request.bind(env) bottle.response.bind() try: bottle.response.set_cookie('xxx', 'yyy') bottle.redirect('...') except bottle.HTTPResponse: h = [v for (k, v) in _e().headerlist if k == 'Set-Cookie'] self.assertEqual(h, ['xxx=yyy'])
def test_header_access(self): """ Environ: Request objects decode headers """ e = {} wsgiref.util.setup_testing_defaults(e) e['HTTP_SOME_HEADER'] = 'some value' request.bind(e) request['HTTP_SOME_OTHER_HEADER'] = 'some other value' self.assertTrue('Some-Header' in request.headers) self.assertTrue(request.header['Some-Header'] == 'some value') self.assertTrue( request.header['Some-Other-Header'] == 'some other value')
def test_get(self): """ Environ: GET data """ e = {} e["QUERY_STRING"] = "a=a&a=1&b=b&c=c" request.bind(e) self.assertTrue("a" in request.GET) self.assertTrue("b" in request.GET) self.assertEqual(["a", "1"], request.GET.getall("a")) self.assertEqual(["b"], request.GET.getall("b")) self.assertEqual("1", request.GET["a"]) self.assertEqual("b", request.GET["b"])
def test_get(self): """ Environ: GET data """ e = {} e['QUERY_STRING'] = 'a=a&a=1&b=b&c=c' request.bind(e) self.assertTrue('a' in request.GET) self.assertTrue('b' in request.GET) self.assertEqual(['a', '1'], request.GET.getall('a')) self.assertEqual(['b'], request.GET.getall('b')) self.assertEqual('1', request.GET['a']) self.assertEqual('b', request.GET['b'])
def test_getpostleak(self): """ Environ: GET and POST shuld not leak into each other """ e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(u'b=b'.encode('utf8')) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = '3' e['QUERY_STRING'] = 'a=a' request.bind(e, None) self.assertTrue('b' not in request.GET) self.assertTrue('a' not in request.POST)
def test_get(self): """ Environ: GET data """ e = {} e['QUERY_STRING'] = 'a=a&a=1&b=b&c=c' request.bind(e) self.assertTrue('a' in request.GET) self.assertTrue('b' in request.GET) self.assertEqual(['a','1'], request.GET.getall('a')) self.assertEqual(['b'], request.GET.getall('b')) self.assertEqual('1', request.GET['a']) self.assertEqual('b', request.GET['b'])
def test_body(self): """ Environ: Request.body should behave like a file object factory """ e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(u'abc'.encode('utf8')) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = str(3) request.bind(e) self.assertEqual(u'abc'.encode('utf8'), request.body.read()) self.assertEqual(u'abc'.encode('utf8'), request.body.read(3)) self.assertEqual(u'abc'.encode('utf8'), request.body.readline()) self.assertEqual(u'abc'.encode('utf8'), request.body.readline(3))
def test_getpostleak(self): """ Environ: GET and POST sh0uld not leak into each other """ e = {} wsgiref.util.setup_testing_defaults(e) e["wsgi.input"].write(u"b=b".encode("utf8")) e["wsgi.input"].seek(0) e["CONTENT_LENGTH"] = "3" e["QUERY_STRING"] = "a=a" e["REQUEST_METHOD"] = "POST" request.bind(e) self.assertEqual(["a"], request.GET.keys()) self.assertEqual(["b"], request.POST.keys())
def test_tobigbody(self): """ Environ: Request.body should truncate to Content-Length bytes """ e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write((u'x' * 1024).encode('utf8')) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = '42' request.bind(e) self.assertEqual(42, len(request.body.read())) self.assertEqual(42, len(request.body.read(1024))) self.assertEqual(42, len(request.body.readline())) self.assertEqual(42, len(request.body.readline(1024)))
def test_getpost(self): """ Environ: GET and POST (simple) """ sq = 'a=a&b=b&c=c' qd = {'a': 'a', 'b': 'b', 'c': 'c'} e = {} e['wsgi.input'] = StringIO(sq) e['wsgi.input'].seek(0) e['QUERY_STRING'] = sq request.bind(e) self.assertEqual(qd, request.GET) self.assertEqual(qd, request.POST) self.assertEqual(qd, request.params)
def test_url(self): """ Environ: URL building """ request.bind({'HTTP_HOST':'example.com'}) self.assertEqual('http://example.com/', request.url) request.bind({'SERVER_NAME':'example.com'}) self.assertEqual('http://example.com/', request.url) request.bind({'SERVER_NAME':'example.com', 'SERVER_PORT':'81'}) self.assertEqual('http://example.com:81/', request.url) request.bind({'wsgi.url_scheme':'https', 'SERVER_NAME':'example.com'}) self.assertEqual('https://example.com:80/', request.url) request.bind({'HTTP_HOST':'example.com', 'PATH_INFO':'/path', 'QUERY_STRING':'1=b&c=d', 'SCRIPT_NAME':'/sp'}) self.assertEqual('http://example.com/sp/path?1=b&c=d', request.url)
def test_tobigbody(self): """ Environ: Request.body should truncate to Content-Length bytes """ e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write((u'x'*1024).encode('utf8')) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = '42' request.bind(e) self.assertEqual(42, len(request.body.read())) self.assertEqual(42, len(request.body.read(1024))) self.assertEqual(42, len(request.body.readline())) self.assertEqual(42, len(request.body.readline(1024)))
def test_params(self): """ Environ: GET and POST are combined in request.param """ e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(tob('b=b&c=p')) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = '7' e['QUERY_STRING'] = 'a=a&c=g' e['REQUEST_METHOD'] = "POST" request.bind(e) self.assertEqual(['a','b','c'], sorted(request.params.keys())) self.assertEqual('p', request.params['c'])
def test_getpostleak(self): """ Environ: GET and POST sh0uld not leak into each other """ e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(u'b=b'.encode('utf8')) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = '3' e['QUERY_STRING'] = 'a=a' e['REQUEST_METHOD'] = "POST" request.bind(e) self.assertEqual(['a'], request.GET.keys()) self.assertEqual(['b'], request.POST.keys())
def test_params(self): """ Environ: GET and POST are combined in request.param """ e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(tob('b=b&c=p')) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = '7' e['QUERY_STRING'] = 'a=a&c=g' e['REQUEST_METHOD'] = "POST" request.bind(e) self.assertEqual(['a', 'b', 'c'], sorted(request.params.keys())) self.assertEqual('p', request.params['c'])
def test_tobigbody(self): """ Environ: Request.body should truncate to Content-Length bytes """ e = {} wsgiref.util.setup_testing_defaults(e) e["wsgi.input"].write((u"x" * 1024).encode("utf8")) e["wsgi.input"].seek(0) e["CONTENT_LENGTH"] = "42" request.bind(e) self.assertEqual(42, len(request.body.read())) self.assertEqual(42, len(request.body.read(1024))) self.assertEqual(42, len(request.body.readline())) self.assertEqual(42, len(request.body.readline(1024)))
def test_multigetpost(self): """ Environ: GET and POST (multi values) """ sq = 'a=a&a=1' qd = {'a': ['a', '1']} e = {} e['wsgi.input'] = StringIO(sq) e['wsgi.input'].seek(0) e['QUERY_STRING'] = sq request.bind(e) self.assertEqual(qd, request.GET) self.assertEqual(qd, request.POST) self.assertEqual(qd, request.params)
def test_body_noclose(self): """ Test that the body file handler is not closed after request.POST """ sq = u'a=a&a=1&b=b&c=&d'.encode('utf8') e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(sq) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = str(len(sq)) e['REQUEST_METHOD'] = "POST" request.bind(e) self.assertEqual(sq, request.body.read()) request.POST # This caused a body.close() with Python 3.x self.assertEqual(sq, request.body.read())
def test_bigbody(self): """ Environ: Request.body should handle big uploads using files """ e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write((u'x' * 1024 * 1000).encode('utf8')) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = str(1024 * 1000) request.bind(e) self.assertTrue(hasattr(request.body, 'fileno')) self.assertEqual(1024 * 1000, len(request.body.read())) self.assertEqual(1024, len(request.body.read(1024))) self.assertEqual(1024 * 1000, len(request.body.readline())) self.assertEqual(1024, len(request.body.readline(1024)))
def test_path(self): """ Environ: PATH_INFO """ t = dict() t[''] = '/' t['bla'] = '/bla' t['bla/'] = '/bla/' t['/bla'] = '/bla' t['/bla/'] = '/bla/' for k, v in t.iteritems(): request.bind({'PATH_INFO': k}) self.assertEqual(v, request.path) request.bind({}) self.assertEqual('/', request.path)
def assertRedirect(self, target, result, query=None, status=303, **args): env = {'SERVER_PROTOCOL': 'HTTP/1.1'} for key in args: if key.startswith('wsgi'): args[key.replace('_', '.', 1)] = args[key] del args[key] env.update(args) request.bind(env) try: bottle.redirect(target, **(query or {})) except bottle.HTTPResponse, r: self.assertEqual(status, r.status) self.assertTrue(r.headers) self.assertEqual(result, r.headers['Location'])
def test_dict_access(self): """ Environ: request objects are environment dicts """ e = {} wsgiref.util.setup_testing_defaults(e) request.bind(e) self.assertEqual(list(request), e.keys()) self.assertEqual(len(request), len(e)) for k, v in e.iteritems(): self.assertTrue(k in request) self.assertEqual(request[k], v) request[k] = 'test' self.assertEqual(request[k], 'test') del request['PATH_INFO'] self.assertTrue('PATH_INFO' not in request)
def test_post(self): """ Environ: POST data """ sq = u'a=a&a=1&b=b&c=c'.encode('utf8') e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(sq) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = str(len(sq)) e['REQUEST_METHOD'] = "POST" request.bind(e, None) self.assertTrue('a' in request.POST) self.assertTrue('b' in request.POST) self.assertEqual(['a', '1'], request.POST.getall('a')) self.assertEqual(['b'], request.POST.getall('b')) self.assertEqual('1', request.POST['a']) self.assertEqual('b', request.POST['b'])
def test_url(self): """ Environ: URL building """ request.bind({'HTTP_HOST': 'example.com'}, None) self.assertEqual('http://example.com/', request.url) request.bind({'SERVER_NAME': 'example.com'}, None) self.assertEqual('http://example.com/', request.url) request.bind({'SERVER_NAME': 'example.com', 'SERVER_PORT': '81'}, None) self.assertEqual('http://example.com:81/', request.url) request.bind({ 'wsgi.url_scheme': 'https', 'SERVER_NAME': 'example.com' }, None) self.assertEqual('https://example.com:80/', request.url) request.bind( { 'HTTP_HOST': 'example.com', 'PATH_INFO': '/path', 'QUERY_STRING': '1=b&c=d', 'SCRIPT_NAME': '/sp' }, None) self.assertEqual('http://example.com/sp/path?1=b&c=d', request.url)
def test_multipart(self): """ Environ: POST (multipart files and multible values per key) """ e = {} e['SERVER_PROTOCOL'] = "HTTP/1.1" e['REQUEST_METHOD'] = 'POST' e['CONTENT_TYPE'] = 'multipart/form-data; boundary=----------------314159265358979323846' e['wsgi.input'] = '------------------314159265358979323846\n' e['wsgi.input'] += 'Content-Disposition: form-data; name=test.txt; filename=test.txt\n' e['wsgi.input'] += 'Content-Type: application/octet-stream; charset=ISO-8859-1\n' e['wsgi.input'] += 'Content-Transfer-Encoding: binary\n' e['wsgi.input'] += 'This is a test.\n' e['wsgi.input'] += '------------------314159265358979323846\n' e['wsgi.input'] += 'Content-Disposition: form-data; name=sample.txt; filename=sample.txt\n' e['wsgi.input'] += 'Content-Type: text/plain; charset=ISO-8859-1\n' e['wsgi.input'] += 'Content-Transfer-Encoding: binary\n' e['wsgi.input'] += 'This is a sample\n' e['wsgi.input'] += '------------------314159265358979323846\n' e['wsgi.input'] += 'Content-Disposition: form-data; name=sample.txt; filename=sample2.txt\n' e['wsgi.input'] += 'Content-Type: text/plain; charset=ISO-8859-1\n' e['wsgi.input'] += 'Content-Transfer-Encoding: binary\n' e['wsgi.input'] += 'This is a second sample\n' e['wsgi.input'] += '------------------314159265358979323846--\n' e['CONTENT_LENGTH'] = len(e['wsgi.input']) e['wsgi.input'] = StringIO(e['wsgi.input']) e['wsgi.input'].seek(0) request.bind(e) self.assertTrue(e['CONTENT_LENGTH'], request.input_length) self.assertTrue('test.txt' in request.POST) self.assertTrue('sample.txt' in request.POST) self.assertEqual('This is a test.', request.POST['test.txt'].file.read()) self.assertEqual('test.txt', request.POST['test.txt'].filename) self.assertEqual(2, len(request.POST['sample.txt'])) self.assertEqual('This is a sample', request.POST['sample.txt'][0].file.read()) self.assertEqual('This is a second sample', request.POST['sample.txt'][1].file.read())
def test_ilength(self): """ Environ: CONTENT_LENGTH """ t = dict() t[''] = 0 t['0815'] = 815 t['-666'] = 0 t['0'] = 0 t['a'] = 0 # print(t) """ { '': 0, '0': 0, '0815': 815, '-666': 0, 'a': 0 } """ for k, v in t.iteritems(): request.bind({'CONTENT_LENGTH': k}) self.assertEqual(v, request.input_length) request.bind({}) self.assertEqual(0, request.input_length)
def test_shift(s, p, c): request.bind({'SCRIPT_NAME': s, 'PATH_INFO': p}) request.path_shift(c) return [request['SCRIPT_NAME'], request.path]
def setUp(self): e = dict() wsgiref.util.setup_testing_defaults(e) b = Bottle() request.bind(e) response.bind()
('a=a; a=b', {'a': 'b'}) Set-Cookie: a=b Set-Cookie: a=b {'a': 'b'} """ sq = 'a=a&b=b&c=c' qd = {'a': 'a', 'b': 'b', 'c': 'c'} e = {} e['wsgi.input'] = StringIO(sq) e['wsgi.input'].seek(0) e['QUERY_STRING'] = sq print( e ) # {'QUERY_STRING': 'a=a&b=b&c=c', 'wsgi.input': <StringIO.StringIO instance at 0x7f500f1b3830>} request.bind(e) print(request.GET) # {'a': 'a', 'c': 'c', 'b': 'b'} print(request.POST) # {'a': 'a', 'c': 'c', 'b': 'b'} print(request.params) # {'a': 'a', 'c': 'c', 'b': 'b'} print(parse_qs(e['QUERY_STRING'], keep_blank_values=True)) # {'a': ['a'], 'c': ['c'], 'b': ['b']} print(parse_qs('a=a&a=1', keep_blank_values=True)) # {'a': ['a', '1']} class TestEnviron(unittest.TestCase): def test_path(self): """ Environ: PATH_INFO """ t = dict() t[''] = '/' t['bla'] = '/bla' t['bla/'] = '/bla/'