slinky/tests/test_slinky.py

73 lines
2 KiB
Python
Raw Normal View History

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
"""
2021-12-28 15:13:45 +00:00
self.assertEqual(
'https://example.com', Slinky(self.test_db).get_by_shortcode('egie').url
)
2021-12-27 18:34:31 +00:00
@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',
)
2021-12-28 13:51:57 +00:00
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')