2021-12-27 18:34:31 +00:00
|
|
|
"""
|
|
|
|
Test Slinky
|
|
|
|
"""
|
|
|
|
import random
|
|
|
|
from typing import Any
|
|
|
|
from unittest import TestCase, mock
|
2021-12-19 11:48:42 +00:00
|
|
|
|
2021-12-27 18:34:31 +00:00
|
|
|
from slinky import Slinky, random_string
|
2021-12-19 11:48:42 +00:00
|
|
|
|
|
|
|
|
|
|
|
class TestSlinky(TestCase):
|
2021-12-27 18:34:31 +00:00
|
|
|
"""
|
|
|
|
Class to test Slinky code
|
|
|
|
"""
|
|
|
|
|
|
|
|
test_db = 'sqlite:///tests/test.db'
|
|
|
|
|
2021-12-19 11:48:42 +00:00
|
|
|
def test_random_string(self) -> None:
|
|
|
|
"""
|
|
|
|
Ensure the random string generates correctly
|
|
|
|
"""
|
|
|
|
|
2021-12-27 18:34:31 +00:00
|
|
|
rnd_len = random.randint(8, 128)
|
|
|
|
|
|
|
|
self.assertEqual(4, len(random_string()))
|
|
|
|
self.assertEqual(rnd_len, len(random_string(rnd_len)))
|
|
|
|
|
|
|
|
self.assertTrue(random_string(128).isalnum(), True)
|
|
|
|
|
|
|
|
@mock.patch('sqlalchemy.orm.session.Session.add', return_value=None)
|
|
|
|
@mock.patch('slinky.random_string', return_value='abcd')
|
|
|
|
def test_add(self, *_: Any) -> None:
|
|
|
|
"""
|
|
|
|
Ensure we can add a shortcode to the DB
|
|
|
|
"""
|
|
|
|
self.assertEqual(
|
|
|
|
Slinky(self.test_db).add('https://www.example.com'),
|
|
|
|
'abcd',
|
|
|
|
)
|
|
|
|
|
|
|
|
def test_get(self) -> None:
|
|
|
|
"""
|
|
|
|
Ensure we can fetch a URL for a known shortcode
|
|
|
|
"""
|
|
|
|
|
|
|
|
self.assertEqual('https://example.com', Slinky(self.test_db).get('egie').url)
|
|
|
|
|
|
|
|
@mock.patch('sqlalchemy.orm.session.Session.add', return_value=None)
|
|
|
|
@mock.patch('slinky.random_string', return_value='egie')
|
|
|
|
def test_duplicate_shortcode(self, *_: Any) -> None:
|
|
|
|
"""
|
|
|
|
Ensure duplicate shortcodes raise a ValueError exception
|
|
|
|
"""
|
|
|
|
self.assertRaises(
|
|
|
|
ValueError,
|
|
|
|
Slinky(self.test_db).add,
|
|
|
|
'https://www.example.com',
|
|
|
|
)
|