slinky/tests/test_slinky.py

59 lines
1.5 KiB
Python

"""
Test Slinky
"""
import random
from typing import Any
from unittest import TestCase, mock
from slinky import Slinky, random_string
class TestSlinky(TestCase):
"""
Class to test Slinky code
"""
test_db = 'sqlite:///tests/test.db'
def test_random_string(self) -> None:
"""
Ensure the random string generates correctly
"""
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',
)