81 lines
2.7 KiB
Python
81 lines
2.7 KiB
Python
# -*- coding: utf-8 -*-
|
|
import unittest
|
|
from collections import OrderedDict
|
|
|
|
import mock
|
|
|
|
from ..utils import Base64, Encoder, get_user_ip
|
|
|
|
|
|
TESTING_MODULE = 'sqrl.utils'
|
|
|
|
|
|
class TestBase64(unittest.TestCase):
|
|
def test_encode(self):
|
|
value = Base64.encode(b'hello')
|
|
|
|
# normal base64 is aGVsbG8= however = should be missing
|
|
self.assertEqual(value, 'aGVsbG8')
|
|
self.assertIsInstance(value, str)
|
|
|
|
def test_encode_not_binary(self):
|
|
with self.assertRaises(AssertionError):
|
|
Base64.encode('hello')
|
|
|
|
def test_decode(self):
|
|
value = Base64.decode('aGVsbG8')
|
|
|
|
# normal base64 is aGVsbG8= however = should be missing
|
|
self.assertEqual(value, b'hello')
|
|
self.assertIsInstance(value, bytes)
|
|
|
|
def test_decode_not_unicode(self):
|
|
with self.assertRaises(AssertionError):
|
|
Base64.decode(b'aGVsbG8')
|
|
|
|
|
|
class TestEncode(unittest.TestCase):
|
|
def test_base64_dumps(self):
|
|
self.assertEqual(Encoder.base64_dumps(5), '5')
|
|
self.assertEqual(Encoder.base64_dumps('hello'), 'hello')
|
|
self.assertEqual(Encoder.base64_dumps(b'hello'), 'aGVsbG8')
|
|
self.assertEqual(Encoder.base64_dumps([b'hello', 'hello']), 'aGVsbG8~hello')
|
|
self.assertEqual(
|
|
Encoder.base64_dumps(OrderedDict([('a', b'hello'), ('b', 'hello')])),
|
|
'YT1hR1ZzYkc4DQpiPWhlbGxvDQo'
|
|
)
|
|
|
|
def test_dumps(self):
|
|
self.assertEqual(Encoder.dumps(5), '5')
|
|
self.assertEqual(Encoder.dumps('hello'), 'hello')
|
|
self.assertEqual(Encoder.dumps(b'hello'), 'aGVsbG8')
|
|
self.assertEqual(Encoder.dumps([b'hello', 'hello']), 'aGVsbG8~hello')
|
|
self.assertEqual(Encoder.dumps(OrderedDict()), '')
|
|
self.assertEqual(
|
|
Encoder.dumps(OrderedDict([('a', b'hello'), ('b', 'hello')])),
|
|
'a=aGVsbG8\r\nb=hello\r\n'
|
|
)
|
|
|
|
def test_normalize(self):
|
|
self.assertEqual(Encoder.normalize(b'hello'), 'aGVsbG8')
|
|
self.assertEqual(Encoder.normalize('hello'), 'hello')
|
|
self.assertEqual(Encoder.normalize(5), '5')
|
|
self.assertEqual(Encoder.normalize([b'hello', 'hello']), ['aGVsbG8', 'hello'])
|
|
self.assertEqual(Encoder.normalize(OrderedDict()), '')
|
|
self.assertEqual(
|
|
Encoder.normalize(OrderedDict([('a', b'hello'), ('b', 'hello')])),
|
|
OrderedDict([('a', 'aGVsbG8'), ('b', 'hello')])
|
|
)
|
|
|
|
|
|
class TestUtils(unittest.TestCase):
|
|
def test_get_user_ip(self):
|
|
request = mock.MagicMock(META={'REMOTE_ADDR': mock.sentinel.ip})
|
|
|
|
self.assertEqual(get_user_ip(request), mock.sentinel.ip)
|
|
|
|
def test_get_user_ip_proxy(self):
|
|
request = mock.MagicMock(META={'HTTP_X_REAL_IP': mock.sentinel.ip})
|
|
|
|
self.assertEqual(get_user_ip(request), mock.sentinel.ip)
|