def shorten(url): """Shortens a given URL, returning the unique id of that URL :url: a valid URL string The URL will be recorded in the database if it does not already exist. Returns a string id composed of lowercase alphanumeric characters """ existing_url = rdb.get('urls|' + url) if existing_url: return existing_url else: counter = rdb.incr('url_counter') short = int_to_base36(counter) rdb.set('urls|' + url, short) rdb.set('shorts|' + short, url) return short
def test_expand_url_404_passes_through(self): rdb.set('shorts|404g', 'http://google.com/404') response = self.app.get('/404g') self.assertEqual(response.status, '302 FOUND') self.assertEqual(response.location, 'http://google.com/404')
def test_expand_url_redirects(self): rdb.set('shorts|asdf', TEST_URL) response = self.app.get('/asdf') self.assertEqual(response.status, '302 FOUND')
def test_expands_is_case_insensitive(self): rdb.set('shorts|2bogus', TEST_URL) self.assertEqual(expand('2BogUs'), TEST_URL)
def test_expands_exists(self): rdb.set('shorts|1g', TEST_URL) self.assertEqual(expand('1g'), TEST_URL)
def test_shorten_doesnt_exist_creates_new_next(self): rdb.set('url_counter', 51) shorten(TEST_URL) self.assertEqual(rdb.get('urls|' + TEST_URL), '1g') self.assertEqual(rdb.get('shorts|1g'), TEST_URL)
def test_shorten_doesnt_exist_returns_next(self): rdb.set('url_counter', 51) self.assertEqual(shorten(TEST_URL), '1g')
def test_shorten_already_exists(self): rdb.set('urls|' + TEST_URL, 'a1f') self.assertEqual(shorten(TEST_URL), 'a1f')
def test_expand_url_inexistent_passes_through(self): rdb.set('shorts|bad', 'http://bad.badbad') response = self.app.get('/bad') self.assertEqual(response.status, '302 FOUND') self.assertEqual(response.location, 'http://bad.badbad')
def test_expand_url(self): rdb.set('shorts|myshorturl', TEST_URL) self.driver.get(BASE_URL + '/myshorturl') self.assertIn('IANA', self.driver.title)