86 lines
2.4 KiB
Python
86 lines
2.4 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(url='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_by_shortcode('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,
|
|
url='https://www.example.com',
|
|
)
|
|
|
|
@mock.patch('sqlalchemy.orm.session.Session.add', return_value=None)
|
|
def test_supplied_shortcode(self, *_: Any) -> None:
|
|
"""
|
|
Ensure a shortcode can be supplied
|
|
"""
|
|
self.assertEqual(
|
|
'__TEST__',
|
|
Slinky(self.test_db).add(
|
|
shortcode='__TEST__',
|
|
url='https://www.example.com',
|
|
),
|
|
)
|
|
|
|
def test_get_all(self) -> None:
|
|
"""
|
|
Ensure multiple results are returned and that they return all fields
|
|
"""
|
|
shortcodes = Slinky(self.test_db).get_all()
|
|
|
|
self.assertGreater(len(shortcodes), 1)
|
|
assert hasattr(shortcodes[0], 'shortcode')
|
|
assert hasattr(shortcodes[0], 'url')
|
|
assert hasattr(shortcodes[0], 'fixed_views')
|
|
assert hasattr(shortcodes[0], 'expiry')
|