Esempio n. 1
0
 def test_remote_addr(self):
     ips = ["1.2.3.4", "2.3.4.5", "3.4.5.6"]
     r = BaseRequest({})
     self.assertEqual(r.remote_addr, None)
     r.environ["HTTP_X_FORWARDED_FOR"] = ", ".join(ips)
     self.assertEqual(r.remote_addr, ips[0])
     r.environ["REMOTE_ADDR"] = ips[1]
     self.assertEqual(r.remote_addr, ips[0])
     del r.environ["HTTP_X_FORWARDED_FOR"]
     self.assertEqual(r.remote_addr, ips[1])
 def test_remote_addr(self):
     ips = ['1.2.3.4', '2.3.4.5', '3.4.5.6']
     r = BaseRequest({})
     self.assertEqual(r.remote_addr, None)
     r.environ['HTTP_X_FORWARDED_FOR'] = ', '.join(ips)
     self.assertEqual(r.remote_addr, ips[0])
     r.environ['REMOTE_ADDR'] = ips[1]
     self.assertEqual(r.remote_addr, ips[0])
     del r.environ['HTTP_X_FORWARDED_FOR']
     self.assertEqual(r.remote_addr, ips[1])
 def test_auth(self):
     user, pwd = 'marc', 'secret'
     basic = touni(base64.b64encode(tob('%s:%s' % (user, pwd))))
     r = BaseRequest({})
     self.assertEqual(r.auth, None)
     r.environ['HTTP_AUTHORIZATION'] = 'basic %s' % basic
     self.assertEqual(r.auth, (user, pwd))
     r.environ['REMOTE_USER'] = user
     self.assertEqual(r.auth, (user, pwd))
     del r.environ['HTTP_AUTHORIZATION']
     self.assertEqual(r.auth, (user, None))
Esempio n. 4
0
 def test_auth(self):
     user, pwd = "marc", "secret"
     basic = touni(base64.b64encode(tob("%s:%s" % (user, pwd))))
     r = BaseRequest({})
     self.assertEqual(r.auth, None)
     r.environ["HTTP_AUTHORIZATION"] = "basic %s" % basic
     self.assertEqual(r.auth, (user, pwd))
     r.environ["REMOTE_USER"] = user
     self.assertEqual(r.auth, (user, pwd))
     del r.environ["HTTP_AUTHORIZATION"]
     self.assertEqual(r.auth, (user, None))
Esempio n. 5
0
 def test_maxparam(self):
     ips = ['1.2.3.4', '2.3.4.5', '3.4.5.6']
     e = {}
     wsgiref.util.setup_testing_defaults(e)
     e['wsgi.input'].write(tob('a=a&b=b&c=c'))
     e['wsgi.input'].seek(0)
     e['CONTENT_LENGTH'] = '11'
     e['REQUEST_METHOD'] = "POST"
     e['HTTP_COOKIE'] = 'a=1,b=1,c=1;d=1'
     e['QUERY_STRING'] = 'a&b&c&d'
     r = BaseRequest(e)
     r.MAX_PARAMS = 2
     self.assertEqual(len(list(r.query.allitems())), 2)
     self.assertEqual(len(list(r.cookies.allitems())), 2)
     self.assertEqual(len(list(r.forms.allitems())), 2)
     self.assertEqual(len(list(r.params.allitems())), 4)
Esempio n. 6
0
 def test_method(self):
     self.assertEqual(BaseRequest({}).method, 'GET')
     self.assertEqual(BaseRequest({'REQUEST_METHOD':'GET'}).method, 'GET')
     self.assertEqual(BaseRequest({'REQUEST_METHOD':'GeT'}).method, 'GET')
     self.assertEqual(BaseRequest({'REQUEST_METHOD':'get'}).method, 'GET')
     self.assertEqual(BaseRequest({'REQUEST_METHOD':'POst'}).method, 'POST')
     self.assertEqual(BaseRequest({'REQUEST_METHOD':'FanTASY'}).method, 'FANTASY')
Esempio n. 7
0
 def test_url(self):
     """ Environ: URL building """
     request = BaseRequest({'HTTP_HOST': 'example.com'})
     self.assertEqual('http://example.com/', request.url)
     request = BaseRequest({'SERVER_NAME': 'example.com'})
     self.assertEqual('http://example.com/', request.url)
     request = BaseRequest({
         'SERVER_NAME': 'example.com',
         'SERVER_PORT': '81'
     })
     self.assertEqual('http://example.com:81/', request.url)
     request = BaseRequest({
         'wsgi.url_scheme': 'https',
         'SERVER_NAME': 'example.com'
     })
     self.assertEqual('https://example.com/', request.url)
     request = BaseRequest({
         '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)
     request = BaseRequest({
         'HTTP_HOST': 'example.com',
         'PATH_INFO': '/pa th',
         'SCRIPT_NAME': '/s p'
     })
     self.assertEqual('http://example.com/s%20p/pa%20th', request.url)
Esempio n. 8
0
def post_validation(req: BaseRequest, *args) -> Tuple[dict, Optional[Error]]:
    if req.method != "POST":
        return {}, Error(405, "GET method is not allowed.")
    if req.get_header("Content-Type") != "application/json":
        return {}, Error(400, "HTTP request header `Content-Type` must be `application/json`.")
    if req.body.getvalue().decode() == "":
        return {}, Error(400, "Request body is empty.")
    if not isinstance(req.json, dict):
        return {}, Error(400, "Request body is not JSON string.")
    for k in args:
        if not req.json.get(k):
            return {}, Error(400, f"The field {k} does not exist in the request body.")
    return req.json, None
Esempio n. 9
0
 def test_bigbody(self):
     """ Environ: Request.body should handle big uploads using files """
     e = {}
     wsgiref.util.setup_testing_defaults(e)
     e['wsgi.input'].write(tob('x') * 1024 * 1000)
     e['wsgi.input'].seek(0)
     e['CONTENT_LENGTH'] = str(1024 * 1000)
     request = BaseRequest(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)))
Esempio n. 10
0
 def test_body_noclose(self):
     """ Test that the body file handler is not closed after request.POST """
     sq = tob('a=a&a=1&b=b&c=&d')
     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 = BaseRequest(e)
     self.assertEqual(sq, request.body.read())
     request.POST  # This caused a body.close() with Python 3.x
     self.assertEqual(sq, request.body.read())
Esempio n. 11
0
 def test_dict_access(self):
     """ Environ: request objects are environment dicts """
     e = {}
     wsgiref.util.setup_testing_defaults(e)
     request = BaseRequest(e)
     self.assertEqual(list(request), list(e.keys()))
     self.assertEqual(len(request), len(e))
     for k, v in e.items():
         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)
Esempio n. 12
0
 def test_post(self):
     """ Environ: POST data """ 
     sq = tob('a=a&a=1&b=b&c=&d')
     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 = BaseRequest(e)
     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'])
     self.assertEqual('', request.POST['c'])
     self.assertEqual('', request.POST['d'])
Esempio n. 13
0
 def test_maxparam(self):
     ips = ['1.2.3.4', '2.3.4.5', '3.4.5.6']
     e = {}
     wsgiref.util.setup_testing_defaults(e)
     e['wsgi.input'].write(tob('a=a&b=b&c=c'))
     e['wsgi.input'].seek(0)
     e['CONTENT_LENGTH'] = '11'
     e['REQUEST_METHOD'] = "POST"
     e['HTTP_COOKIE'] = 'a=1,b=1,c=1;d=1'
     e['QUERY_STRING'] = 'a&b&c&d'
     old_value = BaseRequest.MAX_PARAMS
     r = BaseRequest(e)
     try:
         BaseRequest.MAX_PARAMS = 2
         self.assertEqual(len(list(r.query.allitems())), 2)
         self.assertEqual(len(list(r.cookies.allitems())), 2)
         self.assertEqual(len(list(r.forms.allitems())), 2)
         self.assertEqual(len(list(r.params.allitems())), 4)
     finally:
         BaseRequest.MAX_PARAMS = old_value
Esempio n. 14
0
 def test_multipart(self):
     """ Environ: POST (multipart files and multible values per key) """
     fields = [('field1', 'value1'), ('field2', 'value2'), ('field2', '万难')]
     files = [('file1', 'filename1.txt', 'content1'),
              ('万难', '万难foo.py', 'ä\nö\rü')]
     e = tools.multipart_environ(fields=fields, files=files)
     request = BaseRequest(e)
     # File content
     self.assertTrue('file1' in request.POST)
     self.assertTrue('file1' in request.files)
     self.assertTrue('file1' not in request.forms)
     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('万难' in request.POST)
     self.assertTrue('万难' in request.files)
     self.assertTrue('万难' not in request.forms)
     self.assertEqual('foo.py', request.POST['万难'].filename)
     self.assertTrue(request.files['万难'])
     self.assertFalse(request.files.file77)
     # UTF-8 files
     x = request.POST['万难'].file.read()
     if (3, 2, 0) > sys.version_info >= (3, 0, 0):
         x = x.encode('utf8')
     self.assertEqual(tob('ä\nö\rü'), x)
     # No file
     self.assertTrue('file3' not in request.POST)
     self.assertTrue('file3' not in request.files)
     self.assertTrue('file3' not in request.forms)
     # Field (single)
     self.assertEqual('value1', request.POST['field1'])
     self.assertTrue('field1' not in request.files)
     self.assertEqual('value1', request.forms['field1'])
     print(request.forms.dict, request.forms.recode_unicode)
     self.assertEqual('万难', request.forms['field2'])
     self.assertEqual(touni('万难'), request.forms.field2)
     # Field (multi)
     self.assertEqual(2, len(request.POST.getall('field2')))
     self.assertEqual(['value2', '万难'], request.POST.getall('field2'))
     self.assertEqual(['value2', '万难'], request.forms.getall('field2'))
     self.assertTrue('field2' not in request.files)
Esempio n. 15
0
 def test_route_property(self):
     e = {'bottle.route': 5}
     r = BaseRequest(e)
     self.assertEqual(r.route, 5)
Esempio n. 16
0
 def test_shift(s, p, c):
     request = BaseRequest({'SCRIPT_NAME': s, 'PATH_INFO': p})
     request.path_shift(c)
     return [request['SCRIPT_NAME'], request.path]
Esempio n. 17
0
 def test_isajax(self):
     e = {}
     wsgiref.util.setup_testing_defaults(e)
     self.assertFalse(BaseRequest(e.copy()).is_ajax)
     e['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
     self.assertTrue(BaseRequest(e.copy()).is_ajax)
Esempio n. 18
0
 def test_json_empty(self):
     """ Environ: Request.json property with empty body. """
     self.assertEqual(BaseRequest({}).json, None)
Esempio n. 19
0
 def test_app(self):
     e = {}
     r = BaseRequest(e)
     self.assertRaises(RuntimeError, lambda: r.app)
     e.update({'bottle.app': 5})
     self.assertEqual(r.app, 5)
Esempio n. 20
0
 def test_url_for_property(self):
     e = {}
     r = BaseRequest(e)
     self.assertRaises(RuntimeError, lambda: r.url_args)
     e.update({'route.url_args': {'a': 5}})
     self.assertEqual(r.url_args, {'a': 5})
Esempio n. 21
0
 def test_readonly_environ(self):
     request = BaseRequest({'bottle.request.readonly':True})
     def test(): request['x']='y'
     self.assertRaises(KeyError, test)