-
Notifications
You must be signed in to change notification settings - Fork 1
/
URLShortenerTest.py
86 lines (67 loc) · 2.75 KB
/
URLShortenerTest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import unittest, os
from URLShortener import URLShortener
import string, random
def generateRandomString(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
class TestURLShortener(unittest.TestCase):
def setUp(self):
self.dbfile = "/tmp/testshortener.db"
self.shortener = URLShortener(self.dbfile)
def tearDown(self):
os.remove(self.dbfile)
def test_shorten(self):
shortUrl = self.shortener.shorten("https://example.com")
self.assertEqual(shortUrl, '1')
shortUrl = self.shortener.shorten("https://example.com")
self.assertEqual(shortUrl, '2')
shortUrl = self.shortener.shorten("https://example.com", "example")
self.assertEqual(shortUrl, 'example')
shortUrl = self.shortener.shorten("https://example.com", "example")
self.assertEqual(shortUrl, '3')
def test_get(self):
fullUrl = "https://example.com"
shortUrl = self.shortener.shorten(fullUrl)
self.assertEqual(self.shortener.get(shortUrl), fullUrl)
fullUrl = "https://example2.com"
shortUrl = self.shortener.shorten(fullUrl)
self.assertEqual(self.shortener.get(shortUrl), fullUrl)
def test_remove(self):
fullUrl = "https://example.com"
shortUrl = self.shortener.shorten(fullUrl)
self.assertTrue(shortUrl in self.shortener.shortUrlMap)
self.shortener.remove(shortUrl)
self.assertFalse(shortUrl in self.shortener.shortUrlMap)
def test_list(self):
NUM_URLS = 6
fullUrls = [generateRandomString() for x in range(NUM_URLS)]
shortUrls = [self.shortener.shorten(x) for x in range(NUM_URLS)]
listing = self.shortener.list()
self.assertEqual(len(listing), NUM_URLS)
self.assertTrue(all(x in listing for x in shortUrls))
def test_handleCommand(self):
def handle(cmd):
return self.shortener.handleCommand(cmd)
exit_out = handle("exit")
self.assertEqual(exit_out, False)
add_out = handle("add")
self.assertEqual(add_out, "Usage: add <fullUrl> [shortUrl]")
add_out = handle("add myfullUrl")
self.assertEqual(add_out, '1')
get_out = handle("get")
self.assertEqual(get_out, 'Usage: get <shortUrl>')
get_out = handle("get 2")
self.assertEqual(get_out, "Key '2' not found.")
get_out = handle("get 1")
self.assertEqual(get_out, "myfullUrl")
del_out = handle("del")
self.assertEqual(del_out, 'Usage: del <shortUrl>')
del_out = handle("del 1")
self.assertEqual(del_out, "")
surl1 = self.shortener.shorten("foo")
surl2 = self.shortener.shorten("bar")
list_out = handle("list")
self.assertTrue(all(str(x) in list_out for x in [surl1,surl2]))
list_out = handle("list -l")
self.assertTrue(all(str(x) in list_out for x in [2,3, "foo", "bar"]))
if __name__ == '__main__':
unittest.main()