def find_or_create_short_url(self, target_url): link = self.session.query(ShortUrl) \ .filter_by(target_url=target_url).first() if link == None: key = random_short_url() while self.url_key_exists(key): key = random_short_url() link = self.save_short_url(key, target_url) return link
def test_save_short_url(self): count1 = self.db.all_links().count() key = random_short_url() self.db.save_short_url(key, 'http://save-short-url.test') count2 = self.db.all_links().count() assert count2 - count1 == 1
def test_find_or_create_short_url(self): # It locates the correct short url if it exists # It does not create a duplicate url key = random_short_url() target_url = 'http://target-video.com' link1 = self.db.save_short_url(key, target_url) count1 = self.db.all_links().count() link2 = self.db.find_or_create_short_url(target_url) count2 = self.db.all_links().count() assert link1 == link2 assert count1 == count2
def test_length(): url_key = random_short_url() assert len(url_key) == 6
def test_uniqueness(): urls = {} for _ in range(1000): key = random_short_url() assert key not in urls urls[key] = 1
def test_composition(): url_key = random_short_url() match = re.match('[a-zA-Z0-9]{6}', url_key) assert match.group(0) == url_key
def test_url_key_exists(self): key = random_short_url() assert self.db.url_key_exists(key) == False self.db.save_short_url(key, 'http://target-link.org') assert self.db.url_key_exists(key) == True