Skip to content

Instantly share code, notes, and snippets.

@wreczek
Created April 16, 2020 20:02
Show Gist options
  • Save wreczek/f4fd7fe71c53759dd89ef0fb9824dcdb to your computer and use it in GitHub Desktop.
Save wreczek/f4fd7fe71c53759dd89ef0fb9824dcdb to your computer and use it in GitHub Desktop.
Implementation of the URL website for recruitment interview purposes
#!/usr/bin/env python
"""Server site implementation of the product, where users can
save URLs and retrieve them later."""
__author__ = "Wiktor Reczek"
class UrlService:
"""CRUD service without `update`."""
def __init__(self):
# We use dictionary here as we can get any user in O(1) time (in average case).
self.users_urls = {}
def saveUrl(self, userToken, URL):
"""Saves the URL to the specified user's collection.
Args:
userToken (str): user unique ID.
URL (str): uniform resource locator to save.
Returns:
bool: True, if new URL was saved, otherwise False.
"""
if userToken not in self.users_urls:
# We use the set here as we don't need to have our data to be ordered sequence.
self.users_urls[userToken] = set()
if URL in self.users_urls[userToken]:
return False
self.users_urls[userToken].add(URL)
return True
def getUrls(self, userToken):
"""Reads all saved URLs of given user.
Args:
userToken (str): unique user ID.
Returns:
set: all URLs that user have saved. Returns empty set
if no URLs have been stored for the user.
"""
if userToken not in self.users_urls:
return set()
return self.users_urls[userToken]
def removeUrl(self, userToken, URL):
"""Deletes given URL from the specified user's collection.
Args:
userToken (str): unique user ID.
URL (str): uniform resource locator to delete.
Returns:
bool: whether or not the URL was deleted. Returns False
if the URL to be deleted had never been saved for given user.
"""
if userToken not in self.users_urls:
raise KeyError(f"\tUser token {userToken} does not exist.")
try:
self.users_urls[userToken].remove(URL)
return True
except KeyError:
print(f"\tKey '{URL}' not found")
return False
def test_adding_and_removing_for_one_user():
print("### TEST CASE NO 1 ###")
service = UrlService()
service.saveUrl("tom", "www.example.com")
service.saveUrl("tom", "www.example.com/news")
service.saveUrl("john", "www.other.com")
found = len(service.getUrls("tom"))
if found != 2:
print(f"Something went wrong. "
f"There should be 2 URLs assigned to tom but {found} found")
service.removeUrl("john", "www.other.com")
print(f"\ttom's urls: {service.getUrls('tom')}")
print(f"\tjohn's urls: {service.getUrls('john')}")
print("### ############## ###\n")
def test_adding_and_removing_for_many_users():
print("### TEST CASE NO 2 ###")
service = UrlService()
service.saveUrl("victor", "https://www.montrosesoftware.com/#/")
service.saveUrl("victor", "https://www.google.com")
service.saveUrl("victor", "https://www.stackoverflow.com")
service.removeUrl("victor", "https://www.stackoverflow.com")
service.removeUrl("victor", "https://www.doesnotexist.com")
print(f"\tvictor's urls: {service.getUrls('victor')}")
service.saveUrl("paul", "https://www.montrosesoftware.com/contact.html#/")
print(f"\tpaul's urls: {service.getUrls('paul')}")
service.saveUrl("maria", "https://www.montrosesoftware.com/about.html#/")
print(f"\tmaria's's urls: {service.getUrls('maria')}")
assert service.getUrls("victor") == {'https://www.montrosesoftware.com/#/', 'https://www.google.com'}
assert service.getUrls("paul") == {'https://www.montrosesoftware.com/contact.html#/'}
assert service.getUrls("maria") == {'https://www.montrosesoftware.com/about.html#/'}
print("### ############## ###\n")
def test_add_methods():
print("### TEST CASE NO 3 ###")
service = UrlService()
firstSave = service.saveUrl("christopher", "https://www.somesite.com")
secondSave = service.saveUrl("christopher", "https://www.somesite.com")
assert firstSave == True, "Should be True as this site was saved for the first time for this user."
assert secondSave == False, "Should be False as this site was saved twice."
gotUrls = service.getUrls("unauthorized")
assert gotUrls == set(), "Should return empty list as this user haven't saved any URL yet."
print("### ############## ###\n")
def test_getting_from_not_registered_user():
print("### TEST CASE NO 4 ###")
service = UrlService()
gotUrls = service.getUrls("unauthorized")
assert gotUrls == set(), "Should return empty list as this user haven't saved any URL yet."
print("### ############## ###\n")
def test_removing_for_not_registered_user():
print("### TEST CASE NO 5 ###")
service = UrlService()
try:
service.removeUrl("victor", "https://www.youtube.com")
except Exception:
print("\tCaught exception as user haven't specified any URL yet.")
print("### ############## ###\n")
def test_removing_not_saved_url():
print("### TEST CASE NO 6 ###")
service = UrlService()
service.saveUrl("peter", "some_url")
removed = service.removeUrl("peter", "some_other_url")
assert removed == False, "\tShould be False as this user haven't specified this url."
print("### ############## ###\n")
if __name__ == '__main__':
test_adding_and_removing_for_one_user()
test_adding_and_removing_for_many_users()
test_add_methods()
test_getting_from_not_registered_user()
test_removing_for_not_registered_user()
test_removing_not_saved_url()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment