def test_constructor_status(self): self.assertEqual(200, BaseResponse('YAY', 200).status_code) self.assertEqual('200 OK', BaseResponse('YAY', 200).status_line) self.assertEqual('200 YAY', BaseResponse('YAY', '200 YAY').status_line) self.assertEqual('200 YAY', BaseResponse('YAY', '200 YAY').status_line)
def test_delete_cookie(self): response = BaseResponse() response.set_cookie('name', 'value') response.delete_cookie('name') cookies = [value for name, value in response.wsgiheader() if name.title() == 'Set-Cookie'] self.assertTrue('name=;' in cookies[0])
def test_delete_cookie(self): response = BaseResponse() response.set_cookie('name', 'value') response.delete_cookie('name') cookies = [value for name, value in response.headerlist if name.title() == 'Set-Cookie'] self.assertTrue('Max-Age=-1' in cookies[0])
def test_clone_cookie(self): r = BaseResponse() r.set_cookie('name1', 'value', same_site="strict") r2 = r.copy(BaseResponse) cookies = sorted([value for name, value in r2.headerlist if name.title() == 'Set-Cookie']) self.assertEqual('name1=value; samesite=strict', cookies[0].lower())
def test_charset(self): rs = BaseResponse() self.assertEqual(rs.charset, 'UTF-8') rs.content_type = 'text/html; charset=latin9' self.assertEqual(rs.charset, 'latin9') rs.content_type = 'text/html' self.assertEqual(rs.charset, 'UTF-8')
def test_non_string_header(self): response = BaseResponse() response['x-test'] = 5 self.assertEqual('5', response['x-test']) response['x-test'] = None self.assertEqual('', response['x-test']) response['x-test'] = touni('瓶') self.assertEqual(tonat(touni('瓶')), response['x-test'])
def test_set_cookie_secure(self): r = BaseResponse() r.set_cookie('name1', 'value', secure=True) r.set_cookie('name2', 'value', secure=False) cookies = sorted([value for name, value in r.headerlist if name.title() == 'Set-Cookie']) self.assertEqual(cookies[0].lower(), 'name1=value; secure') self.assertEqual(cookies[1], 'name2=value')
def test_set_cookie_maxage(self): import datetime r = BaseResponse() r.set_cookie('name1', 'value', max_age=5) r.set_cookie('name2', 'value', max_age=datetime.timedelta(days=1)) cookies = sorted([value for name, value in r.headerlist if name.title() == 'Set-Cookie']) self.assertEqual(cookies[0], 'name1=value; Max-Age=5') self.assertEqual(cookies[1], 'name2=value; Max-Age=86400')
def cmp(app, wire): rs = BaseResponse() rs.set_header('x-test', app) result = [v for (h, v) in rs.headerlist if h.lower() == 'x-test'][0] self.assertEqual(wire, result) cmp(1, tonat('1', 'latin1')) cmp('öäü', 'öäü'.encode('utf8').decode('latin1'))
def test_set_cookie_expires(self): import datetime r = BaseResponse() r.set_cookie('name1', 'value', expires=42) r.set_cookie('name2', 'value', expires=datetime.datetime(1970,1,1,0,0,43)) cookies = sorted([value for name, value in r.headerlist if name.title() == 'Set-Cookie']) self.assertEqual(cookies[0], 'name1=value; expires=Thu, 01 Jan 1970 00:00:42 GMT') self.assertEqual(cookies[1], 'name2=value; expires=Thu, 01 Jan 1970 00:00:43 GMT')
def test_set_cookie(self): r = BaseResponse() r.set_cookie('name1', 'value', max_age=5) r.set_cookie('name2', 'value 2', path='/foo') cookies = [value for name, value in r.headerlist if name.title() == 'Set-Cookie'] cookies.sort() self.assertEqual(cookies[0], 'name1=value; Max-Age=5') self.assertEqual(cookies[1], 'name2="value 2"; Path=/foo')
def test_expires_header(self): import datetime response = BaseResponse() now = datetime.datetime.now() response.expires = now self.assertEqual(0, int((response.expires - now).total_seconds())) now2 = datetime.datetime.utcfromtimestamp( parse_date(response.headers['Expires'])) self.assertEqual(0, int((now - now2).total_seconds()))
def test_set_cookie_httponly(self): if sys.version_info < (2,6,0): return r = BaseResponse() r.set_cookie('name1', 'value', httponly=True) r.set_cookie('name2', 'value', httponly=False) cookies = sorted([value for name, value in r.headerlist if name.title() == 'Set-Cookie']) self.assertEqual('name1=value; httponly', cookies[0].lower()) self.assertEqual('name2=value', cookies[1])
def test_set_header(self): response = BaseResponse() response['x-test'] = 'foo' headers = [value for name, value in response.wsgiheader() if name.title() == 'X-Test'] self.assertEqual(['foo'], headers) self.assertEqual('foo', response['x-test']) response['X-Test'] = 'bar' headers = [value for name, value in response.wsgiheader() if name.title() == 'X-Test'] self.assertEqual(['bar'], headers) self.assertEqual('bar', response['x-test'])
def test_append_header(self): response = BaseResponse() response.set_header('x-test', 'foo') headers = [value for name, value in response.wsgiheader() if name.title() == 'X-Test'] self.assertEqual(['foo'], headers) self.assertEqual('foo', response['x-test']) response.set_header('X-Test', 'bar', True) headers = [value for name, value in response.wsgiheader() if name.title() == 'X-Test'] self.assertEqual(['foo', 'bar'], headers) self.assertEqual('bar', response['x-test'])
def test_expires_header(self): import datetime response = BaseResponse() now = datetime.datetime.now() response.expires = now def seconds(a, b): td = max(a, b) - min(a, b) return td.days * 360 * 24 + td.seconds self.assertEqual(0, seconds(response.expires, now)) now2 = datetime.datetime.utcfromtimestamp( parse_date(response.headers['Expires'])) self.assertEqual(0, seconds(now, now2))
def test_set_cookie_samesite(self): r = BaseResponse() r.set_cookie('name1', 'value', same_site="lax") r.set_cookie('name2', 'value', same_site="strict") try: r.set_cookie('name3', 'value', same_site='invalid') self.fail("Should raise CookieError") except CookieError: pass cookies = sorted([value for name, value in r.headerlist if name.title() == 'Set-Cookie']) self.assertEqual('name1=value; samesite=lax', cookies[0].lower()) self.assertEqual('name2=value; samesite=strict', cookies[1].lower())
def hook(): update = request.json current_chat_id = update['message']['chat']['id'] sent_message = update['message']['text'] if re.match(help_regex, sent_message): sent_message = 'Сам себе помоги' elif sent_message[-1] == '?': sent_message = sent_message[0:len(sent_message) - 1] + '.' elif sent_message.lower() == 'анекдот': sent_message = 'тут был плохой анек' update_id = update['update_id'] if update_id >= bot.update_id or bot.update_id == -1: bot.send_message(current_chat_id, sent_message) bot.update_id += 1 return BaseResponse(status=200)
def test_non_string_header(self): response = BaseResponse() response['x-test'] = 5 self.assertEqual('5', response['x-test']) response['x-test'] = None self.assertEqual('None', response['x-test'])
def test_delete_header(self): response = BaseResponse() response['x-test'] = 'foo' self.assertEqual('foo', response['x-test']) del response['X-tESt'] self.assertRaises(KeyError, lambda: response['x-test'])
def handle(self) -> BaseResponse: return BaseResponse('Hello!')
def test_content_type(self): rs = BaseResponse() rs.content_type = 'test/some' self.assertEquals('test/some', rs.headers.get('Content-Type'))
def test_set_status(self): rs = BaseResponse() rs.status = 200 self.assertEqual(rs.status, rs.status_line) self.assertEqual(rs.status_code, 200) self.assertEqual(rs.status_line, '200 OK') rs.status = 999 self.assertEqual(rs.status, rs.status_line) self.assertEqual(rs.status_code, 999) self.assertEqual(rs.status_line, '999 Unknown') rs.status = 404 self.assertEqual(rs.status, rs.status_line) self.assertEqual(rs.status_code, 404) self.assertEqual(rs.status_line, '404 Not Found') def test(): rs.status = -200 self.assertRaises(ValueError, test) self.assertEqual(rs.status, rs.status_line) # last value self.assertEqual(rs.status_code, 404) # last value self.assertEqual(rs.status_line, '404 Not Found') # last value def test(): rs.status = 5 self.assertRaises(ValueError, test) self.assertEqual(rs.status, rs.status_line) # last value self.assertEqual(rs.status_code, 404) # last value self.assertEqual(rs.status_line, '404 Not Found') # last value rs.status = '999 Who knows?' # Illegal, but acceptable three digit code self.assertEqual(rs.status, rs.status_line) self.assertEqual(rs.status_code, 999) self.assertEqual(rs.status_line, '999 Who knows?') rs.status = 555 # Strange code self.assertEqual(rs.status, rs.status_line) self.assertEqual(rs.status_code, 555) self.assertEqual(rs.status_line, '555 Unknown') rs.status = '404 Brain not Found' # Custom reason self.assertEqual(rs.status, rs.status_line) self.assertEqual(rs.status_code, 404) self.assertEqual(rs.status_line, '404 Brain not Found') def test(): rs.status = '5 Illegal Code' self.assertRaises(ValueError, test) self.assertEqual(rs.status, rs.status_line) # last value self.assertEqual(rs.status_code, 404) # last value self.assertEqual(rs.status_line, '404 Brain not Found') # last value def test(): rs.status = '-99 Illegal Code' self.assertRaises(ValueError, test) self.assertEqual(rs.status, rs.status_line) # last value self.assertEqual(rs.status_code, 404) # last value self.assertEqual(rs.status_line, '404 Brain not Found') # last value def test(): rs.status = '1000 Illegal Code' self.assertRaises(ValueError, test) self.assertEqual(rs.status, rs.status_line) # last value self.assertEqual(rs.status_code, 404) # last value self.assertEqual(rs.status_line, '404 Brain not Found') # last value def test(): rs.status = '555' # No reason self.assertRaises(ValueError, test) self.assertEqual(rs.status, rs.status_line) # last value self.assertEqual(rs.status_code, 404) # last value self.assertEqual(rs.status_line, '404 Brain not Found') # last value
def handle(self) -> BaseResponse: users = list( map(lambda user: user.as_dict(), self.user_queries.find_all())) return BaseResponse(body=json.dumps(users, sort_keys=True, indent=4), headers={'Content-Type': 'application/json'})
def test_constructor_body(self): self.assertEqual('', BaseResponse('').body) self.assertEqual('YAY', BaseResponse('YAY').body)
def handle(self) -> BaseResponse: body = request.json self.command_factory.create_user_command(body['first_name'], body['last_name'], body['phone']).execute() return BaseResponse(status=201)
def cmp(app, wire): rs = BaseResponse() rs.set_header('x-test', app) result = [v for (h, v) in rs.headerlist if h.lower() == 'x-test'][0] self.assertEqual(wire, result)
def test_set_status(self): rs = BaseResponse() rs.status = 200 self.assertEqual(rs.status, rs.status_line) self.assertEqual(rs.status_code, 200) self.assertEqual(rs.status_line, '200 OK') rs.status = 999 self.assertEqual(rs.status, rs.status_line) self.assertEqual(rs.status_code, 999) self.assertEqual(rs.status_line, '999 Unknown') rs.status = 404 self.assertEqual(rs.status, rs.status_line) self.assertEqual(rs.status_code, 404) self.assertEqual(rs.status_line, '404 Not Found') def test(): rs.status = -200 self.assertRaises(ValueError, test) self.assertEqual(rs.status, rs.status_line) # last value self.assertEqual(rs.status_code, 404) # last value self.assertEqual(rs.status_line, '404 Not Found') # last value def test(): rs.status = 5 self.assertRaises(ValueError, test) self.assertEqual(rs.status, rs.status_line) # last value self.assertEqual(rs.status_code, 404) # last value self.assertEqual(rs.status_line, '404 Not Found') # last value rs.status = '999 Who knows?' # Illegal, but acceptable three digit code self.assertEqual(rs.status, rs.status_line) self.assertEqual(rs.status_code, 999) self.assertEqual(rs.status_line, '999 Who knows?') rs.status = 555 # Strange code self.assertEqual(rs.status, rs.status_line) self.assertEqual(rs.status_code, 555) self.assertEqual(rs.status_line, '555 Unknown') rs.status = '404 Brain not Found' # Custom reason self.assertEqual(rs.status, rs.status_line) self.assertEqual(rs.status_code, 404) self.assertEqual(rs.status_line, '404 Brain not Found') def test(): rs.status = '5 Illegal Code' self.assertRaises(ValueError, test) self.assertEqual(rs.status, rs.status_line) # last value self.assertEqual(rs.status_code, 404) # last value self.assertEqual(rs.status_line, '404 Brain not Found') # last value def test(): rs.status = '-99 Illegal Code' self.assertRaises(ValueError, test) self.assertEqual(rs.status, rs.status_line) # last value self.assertEqual(rs.status_code, 404) # last value self.assertEqual(rs.status_line, '404 Brain not Found') # last value def test(): rs.status = '1000 Illegal Code' self.assertRaises(ValueError, test) self.assertEqual(rs.status, rs.status_line) # last value self.assertEqual(rs.status_code, 404) # last value self.assertEqual(rs.status_line, '404 Brain not Found') # last value def test(): rs.status = '555' # No reason self.assertRaises(ValueError, test) self.assertEqual(rs.status, rs.status_line) # last value self.assertEqual(rs.status_code, 404) # last value self.assertEqual(rs.status_line, '404 Brain not Found') # last value # Unicode in status line (thanks RFC7230 :/) if bottle.py3k: rs.status = '400 Non-ASÎÎ' self.assertEqual(rs.status, rs.status_line) self.assertEqual(rs.status_code, 400) wire = rs._wsgi_status_line().encode('latin1') self.assertEqual(rs.status, wire.decode('utf8'))
def test_set_cookie_name_long_string(self): r = BaseResponse() self.assertRaises(ValueError, r.set_cookie, name='x' * 4097, value='simple_value')
def index(path): '''Proxy an arbitrary request. The route is http://localhost:5000/proxy/protocol/host/path Where path is [protocol/host/path] ''' # Looks like protocol/hostname/path print('ORIGINAL REQUEST: {path}'.format(path=path)) splitpath = path.split('/', 3) protocol = splitpath.pop(0) host = splitpath.pop(0) path = '/'.join(splitpath) # print 'PATH: {path} ? QUERY: {query}'.format(path=path,query=request.query_string) # print '[{protocol}]/[{host}]/[{path}]'.format(protocol=protocol,host=host,path=path) # if request.query_string != '': # print('trying to get {protocol}://{host}/{path}?{query}'.format(protocol=protocol, host=host, path=path, query=request.query_string)) # else: # print('trying to get {protocol}://{host}/{path}'.format(protocol=protocol, host=host, path=path)) headers = {k: v for k, v in request.headers.items()} headers['Host'] = '{host}'.format(host=host) remote = '{protocol}://{host}/'.format(protocol=protocol, host=host) newurl = '{protocol}://{host}/{path}'.format(protocol=protocol, host=host, path=path) if request.query_string != '': newurl = '{newurl}?{query}'.format(newurl=newurl,query=request.query_string) print ('Getting {newurl}'.format(newurl=newurl)) newrequest = dict() newrequest['method'] = request.method newrequest['headers'] = request.headers newrequest['storage'] = 'pip' newrequest['path'] = path newrequest['name'] = '.index.html' newrequest['actual_request'] = request print('Proxying TYPE: {type} {remote}'.format(type=__name__, remote=remote)) p = Proxy(__name__, remote) resp = p.proxy(newrequest, callback) print('header content-type={ct}'.format(ct=resp.headers['content-type'])) if resp.headers['content-type'].lower().startswith('text/'): # Make the xhtml response point back to this host # TODO: make this better parser = ET.XMLParser(recover=True) # print('trying to read content {content}'.format(content=resp.body)) doc = resp.body try: tree = ET.fromstring(doc, parser=parser) if tree: for node in tree.findall('.//*[@src]'): original = node.get('src') save_original = original if original.startswith('#'): original = '/{original}'.format(original=original) if original.startswith('/'): original = '{protocol}://{host}{original}'.format(protocol=protocol,host=host,original=original) original = original.replace('://', '/') original = 'http://*****:*****@src from {save_original} to {original}'.format(save_original=save_original, original=original)) node.set('src', original) for node in tree.findall('.//*[@href]'): original = node.get('href') if original.startswith('#'): original = '/{original}'.format(original=original) if original.startswith('/'): original = '{protocol}://{host}{original}'.format(protocol=protocol,host=host,original=original) original = original.replace('://', '/') original = 'http://localhost:5000/proxy/{original}'.format(protocol=protocol,host=host,original=original) node.set('href', original) for node in tree.iter(): if node.tag != 'link' and node.tag != 'video' and node.tag != 'source': if node.text is None: node.text = ''# print('registering {proxy}'.format(proxy=bp.url_prefix)) resp = BaseResponse(body=ET.tostring(tree), status='200 OK') # resp = make_response(ET.tostring(tree)) else: print('TODO: Send the proper mime type') print('ORIGINAL RESPONSE HEADERS ARE {headers}'.format(resp.headers)) resp = BaseResponse(body=resp.body, status=resp.status, headers={'content-type': contentType}) except: print('TODO 2: Send the proper mime type') print('ORIGINAL RESPONSE HEADERS ARE {headers}'.format(resp.headers)) resp = BaseResponse(body=resp.body, status=resp.status, headers={'content-type': contentType}) else: resp = BaseResponse(body=resp.body, status=resp.status) headers = {} for k, v in resp.headers.items(): # print('Headers: {k} = {v}'.format(k=k,v=v)) headers[k] = v # resp.headers = headers return resp