def test_set_properties(self): morsel = cookies.Morsel() with self.assertRaises(AttributeError): morsel.key = '' with self.assertRaises(AttributeError): morsel.value = '' with self.assertRaises(AttributeError): morsel.coded_value = ''
def test_defaults(self): morsel = cookies.Morsel() self.assertIsNone(morsel.key) self.assertIsNone(morsel.value) self.assertIsNone(morsel.coded_value) self.assertEqual(morsel.keys(), cookies.Morsel._reserved.keys()) for key, val in morsel.items(): self.assertEqual(val, '', key)
def _BaseCookie__set(self, key, real_value, coded_value): key = str(key) try: M = self.get(key, Morsel()) M.set(key, real_value, coded_value) dict.__setitem__(self, key, M) except http_cookies.CookieError: self.bad_cookies.add(key) dict.__setitem__(self, key, http_cookies.Morsel())
def test_repr(self): morsel = cookies.Morsel() self.assertEqual(repr(morsel), '<Morsel: None=None>') self.assertEqual(str(morsel), 'Set-Cookie: None=None') morsel.set('key', 'val', 'coded_val') self.assertEqual(repr(morsel), '<Morsel: key=coded_val>') self.assertEqual(str(morsel), 'Set-Cookie: key=coded_val') morsel.update({ 'path': '/', 'comment': 'foo', 'domain': 'example.com', 'max-age': 0, 'secure': 0, 'version': 1 }) self.assertEqual( repr(morsel), '<Morsel: key=coded_val; Comment=foo; Domain=example.com; Max-Age=0; Path=/; Version=1>' ) self.assertEqual( str(morsel), 'Set-Cookie: key=coded_val; Comment=foo; Domain=example.com; Max-Age=0; Path=/; Version=1' ) morsel['secure'] = True morsel['httponly'] = 1 self.assertEqual( repr(morsel), '<Morsel: key=coded_val; Comment=foo; Domain=example.com; HttpOnly; Max-Age=0; Path=/; Secure; Version=1>' ) self.assertEqual( str(morsel), 'Set-Cookie: key=coded_val; Comment=foo; Domain=example.com; HttpOnly; Max-Age=0; Path=/; Secure; Version=1' ) morsel = cookies.Morsel() morsel.set('key', 'val', 'coded_val') morsel['expires'] = 0 self.assertRegex( repr(morsel), '<Morsel: key=coded_val; expires=\\w+, \\d+ \\w+ \\d+ \\d+:\\d+:\\d+ \\w+>' ) self.assertRegex( str(morsel), 'Set-Cookie: key=coded_val; expires=\\w+, \\d+ \\w+ \\d+ \\d+:\\d+:\\d+ \\w+' )
def test_pickle(self): morsel_a = cookies.Morsel() morsel_a.set('foo', 'bar', 'baz') morsel_a.update({'version': 2, 'comment': 'foo'}) for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(proto=proto): morsel_b = pickle.loads(pickle.dumps(morsel_a, proto)) self.assertIsInstance(morsel_b, cookies.Morsel) self.assertEqual(morsel_b, morsel_a) self.assertEqual(str(morsel_b), str(morsel_a))
def test_deprecation(self): morsel = cookies.Morsel() with self.assertWarnsRegex(DeprecationWarning, r'\bkey\b'): morsel.key = '' with self.assertWarnsRegex(DeprecationWarning, r'\bvalue\b'): morsel.value = '' with self.assertWarnsRegex(DeprecationWarning, r'\bcoded_value\b'): morsel.coded_value = '' with self.assertWarnsRegex(DeprecationWarning, r'\bLegalChars\b'): morsel.set('key', 'value', 'coded_value', LegalChars='.*')
def test_reserved_keys(self): M = cookies.Morsel() for i in M._reserved: self.assertTrue(M.isReservedKey(i)) M[i] = '%s_value' % i for i in M._reserved: self.assertEqual(M[i], '%s_value' % i) for i in 'the holy hand grenade'.split(): self.assertRaises(cookies.CookieError, M.__setitem__, i, '%s_value' % i)
def test_setitem(self): morsel = cookies.Morsel() morsel['expires'] = 0 self.assertEqual(morsel['expires'], 0) morsel['Version'] = 2 self.assertEqual(morsel['version'], 2) morsel['DOMAIN'] = 'example.com' self.assertEqual(morsel['domain'], 'example.com') with self.assertRaises(cookies.CookieError): morsel['invalid'] = 'value' self.assertNotIn('invalid', morsel)
def test_setdefault(self): morsel = cookies.Morsel() morsel.update({'domain': 'example.com', 'version': 2}) self.assertEqual(morsel.setdefault('expires', 'value'), '') self.assertEqual(morsel['expires'], '') self.assertEqual(morsel.setdefault('Version', 1), 2) self.assertEqual(morsel['version'], 2) self.assertEqual(morsel.setdefault('DOMAIN', 'value'), 'example.com') self.assertEqual(morsel['domain'], 'example.com') with self.assertRaises(cookies.CookieError): morsel.setdefault('invalid', 'value') self.assertNotIn('invalid', morsel)
def test_copy(self): morsel_a = cookies.Morsel() morsel_a.set('foo', 'bar', 'baz') morsel_a.update({'version': 2, 'comment': 'foo'}) morsel_b = morsel_a.copy() self.assertIsInstance(morsel_b, cookies.Morsel) self.assertIsNot(morsel_a, morsel_b) self.assertEqual(morsel_a, morsel_b) morsel_b = copy.copy(morsel_a) self.assertIsInstance(morsel_b, cookies.Morsel) self.assertIsNot(morsel_a, morsel_b) self.assertEqual(morsel_a, morsel_b)
def test_update(self): attribs = {'expires': 1, 'Version': 2, 'DOMAIN': 'example.com'} morsel = cookies.Morsel() morsel.update(attribs) self.assertEqual(morsel['expires'], 1) self.assertEqual(morsel['version'], 2) self.assertEqual(morsel['domain'], 'example.com') morsel = cookies.Morsel() morsel.update(list(attribs.items())) self.assertEqual(morsel['expires'], 1) self.assertEqual(morsel['version'], 2) self.assertEqual(morsel['domain'], 'example.com') morsel = cookies.Morsel() morsel.update((k, v) for k, v in attribs.items()) self.assertEqual(morsel['expires'], 1) self.assertEqual(morsel['version'], 2) self.assertEqual(morsel['domain'], 'example.com') with self.assertRaises(cookies.CookieError): morsel.update({'invalid': 'value'}) self.assertNotIn('invalid', morsel) self.assertRaises(TypeError, morsel.update) self.assertRaises(TypeError, morsel.update, 0)
def test_reserved_keys(self): M = cookies.Morsel() # tests valid and invalid reserved keys for Morsels for i in M._reserved: # Test that all valid keys are reported as reserved and set them self.assertTrue(M.isReservedKey(i)) M[i] = '%s_value' % i for i in M._reserved: # Test that valid key values come out fine self.assertEqual(M[i], '%s_value' % i) for i in "the holy hand grenade".split(): # Test that invalid keys raise CookieError self.assertRaises(cookies.CookieError, M.__setitem__, i, '%s_value' % i)
def generate_cookie(key: str, value: str, max_age: int = None, path: str = None) -> str: """ Generate the string usable in a Set-Cookie:-header. """ cookie = cookies.Morsel() cookie.set( key=key, val=value, coded_val=value, ) cookie['secure'] = True cookie['httponly'] = True if max_age is not None: cookie['expires'] = max_age if path is not None: cookie['path'] = path return cookie.OutputString()
def setCookie(self, name, value, expires='', max_age=0, domain=None, secure=False, httponly=False, path=None): try: morsel = cookies.Morsel() name, value = str(name), str( value ) #https://github.com/William-An/CloudPrint/blob/952f25341ea0423b83ee2ded1927ba0cf160a095/cloudprint/Lib/site-packages/web.py-0.40.dev0-py3.5.egg/web/utils.py morsel.set(name, value, parse.quote(value)) if isinstance(expires, int) and expires < 0: expires = -1000000000 if max_age > 0: morsel['max-age'] = max_age if type(expires) is not str: #morsel['expires'] = self.__handler.date_time_string(time.mktime(time.gmtime(expires))) morsel['expires'] = expires else: morsel['expires'] = expires if path is not None: morsel['path'] = path + '/' #or ctx.homepath+'/' if domain: morsel['domain'] = domain if secure: morsel['secure'] = secure value = morsel.OutputString() if httponly: value += '; httponly' self.sendResponse() self.send_header('Set-Cookie', value) print("setcookie pura chala h", value) except Exception as e: print(e) print(type(e)) print('Exception is raised on %s ' % inspect.trace()[-1][3])
def test_setter(self): M = cookies.Morsel() for i in M._reserved: self.assertRaises(cookies.CookieError, M.set, i, '%s_value' % i, '%s_value' % i) for i in 'thou cast _the- !holy! ^hand| +*grenade~'.split(): M['path'] = '/foo' M.set(i, '%s_val' % i, '%s_coded_val' % i) self.assertEqual( M.output(), 'Set-Cookie: %s=%s; Path=/foo' % (i, '%s_coded_val' % i)) expected_js_output = (""" <script type="text/javascript"> <!-- begin hiding document.cookie = "%s=%s; Path=/foo"; // end hiding --> </script> """ % (i, '%s_coded_val' % i)) self.assertEqual(M.js_output(), expected_js_output) for i in ['foo bar', 'foo@bar']: self.assertRaises(cookies.CookieError, M.set, i, '%s_value' % i, '%s_value' % i)
def setCookie(name, value, expires='', domain=None, secure=False, httponly=False, path=None): morsel = cookies.Morsel() # morsel.set(name, value, quote(value)) morsel.set(name, value, value) expires = datetime.utcnow() + timedelta(days=365) expireStr = expires.strftime("%a, %d %b %Y %X GMT") morsel['expires'] = expireStr # morsel['domain'] = '127.0.0.1:54194' # morsel['max-age'] = 604800 if path: morsel['path'] = path if secure: morsel['secure'] = secure value = morsel.OutputString() if httponly: value += '; HttpOnly' return value
def test_eq(self): base_case = ('key', 'value', '"value"') attribs = { 'path': '/', 'comment': 'foo', 'domain': 'example.com', 'version': 2, } morsel_a = cookies.Morsel() morsel_a.update(attribs) morsel_a.set(*base_case) morsel_b = cookies.Morsel() morsel_b.update(attribs) morsel_b.set(*base_case) self.assertTrue(morsel_a == morsel_b) self.assertFalse(morsel_a != morsel_b) cases = ( ('key', 'value', 'mismatch'), ('key', 'mismatch', '"value"'), ('mismatch', 'value', '"value"'), ) for case_b in cases: with self.subTest(case_b): morsel_b = cookies.Morsel() morsel_b.update(attribs) morsel_b.set(*case_b) self.assertFalse(morsel_a == morsel_b) self.assertTrue(morsel_a != morsel_b) morsel_b = cookies.Morsel() morsel_b.update(attribs) morsel_b.set(*base_case) morsel_b['comment'] = 'bar' self.assertFalse(morsel_a == morsel_b) self.assertTrue(morsel_a != morsel_b) # test mismatched types self.assertFalse(cookies.Morsel() == 1) self.assertTrue(cookies.Morsel() != 1) self.assertFalse(cookies.Morsel() == '') self.assertTrue(cookies.Morsel() != '') items = list(cookies.Morsel().items()) self.assertFalse(cookies.Morsel() == items) self.assertTrue(cookies.Morsel() != items) # morsel/dict morsel = cookies.Morsel() morsel.set(*base_case) morsel.update(attribs) self.assertTrue(morsel == dict(morsel)) self.assertFalse(morsel != dict(morsel))
def test_session(): """ Test `prewikka.session.session.Session` class. """ session_config = ConfigSection("") session_config.expiration = 60 # 1 hour create_session(env.request.user, session_id=TEST_SESSION_ID) req = deepcopy(env.request.web) # __init__() session = Session(session_config) # get_user() user_from_session = session.get_user(req) assert env.request.user == user_from_session # get_user() with old (but valid) cookie clean_sessions() create_session(env.request.user, time_=time.time() - 3600, session_id=TEST_SESSION_ID) user_from_session = session.get_user(req) assert env.request.user == user_from_session # get_user() with invalid session (empty cookie) with pytest.raises(SessionInvalid): req = deepcopy(env.request.web) req.input_cookie = {} session.get_user(req) # get_user() with expired session (AJAX request) with pytest.raises(SessionExpired): req = deepcopy(env.request.web) req.input_cookie = {} req.is_xhr = True session.get_user(req) # get_user() with invalid session (bad session_id) with pytest.raises(SessionInvalid): req = deepcopy(env.request.web) req.input_cookie['sessionid'] = cookies.Morsel() req.input_cookie['sessionid'].value = 'invalid' session.get_user(req) # get_user() with expired session (cookie expired) with pytest.raises(SessionExpired): clean_sessions() req = deepcopy(env.request.web) create_session(env.request.user, time_=time.time() - 3600 * 24, session_id=TEST_SESSION_ID) session = Session(session_config) session.get_user(req) # get_user() with invalid user backup_user = env.request.user with pytest.raises(SessionInvalid): req = deepcopy(env.request.web) env.request.user = User('test') session.get_user(req) env.request.user = backup_user # get_user() with changed backend backup_auth = env.auth with pytest.raises(SessionInvalid): req = deepcopy(env.request.web) clean_sessions() create_session(env.request.user, session_id=TEST_SESSION_ID) env.auth = FakeAuthBackend(ConfigSection("")) session.get_user(req) env.auth = backup_auth # logout() with pytest.raises(SessionInvalid): clean_sessions() create_session(env.request.user, session_id=TEST_SESSION_ID) session = Session(session_config) req = deepcopy(env.request.web) session.logout(req) # can_logout() assert session.can_logout() clean_sessions()
def _BaseCookie__set(self, key, real_value, coded_value): """Inserts a morsel into the Cookie, strictly on the first occurrance.""" if key not in self: morsel = cookie.Morsel() morsel.set(key, real_value, coded_value) dict.__setitem__(self, key, morsel)