Skip to content

Commit

Permalink
implement main behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
hitnik committed Aug 19, 2021
1 parent 268c10c commit 2d97753
Show file tree
Hide file tree
Showing 11 changed files with 72 additions and 49 deletions.
4 changes: 3 additions & 1 deletion app/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
2 changes: 1 addition & 1 deletion app/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import os

SCHEME = os.environ.get("API_SCHEME", "http")
NETLOC = os.environ.get("API_NETLOC", "ex.com")
NETLOC = os.environ.get("API_NETLOC", "ex.com")
12 changes: 3 additions & 9 deletions app/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

DB_PATH = os.path.join(BASEDIR, 'db.sqlite3')


def init_db(db_path):
"""init sqlite database, create sqlite file if needed
Expand Down Expand Up @@ -49,15 +50,6 @@ def db_manager():
close_db(db)


@contextmanager
def cur_manager(db):
cur = db.cursor()
try:
yield cur
finally:
cur.close()


def long_url_exist(url):
""" checks if row with long_rurl = url exists
Expand Down Expand Up @@ -152,6 +144,7 @@ def get_short_url(short):
short = cur.execute(sql, (short,)).fetchone()
return short


def get_short_url_by_long(long_id):
""" get short_url instance by long id
Expand All @@ -167,6 +160,7 @@ def get_short_url_by_long(long_id):
short = cur.execute(sql, (long_id,)).fetchone()
return short


def get_long_url_from_db(id=None, url=None):
""" get long_url instance by id
Expand Down
9 changes: 5 additions & 4 deletions app/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from db import (insert_long_url, short_url_exist, get_short_url,
get_long_url_from_db, long_url_exist,
get_short_url_by_long, insert_short_url,
insert_long_url
)
import shortuuid
from urllib.parse import urlunsplit
Expand Down Expand Up @@ -37,10 +36,12 @@ def parser():
"""),
)
parser.add_argument('--generate', action='store_true', default=False,
help="""If argument presented, URL param will be defined as long url and it wil be shorten."""
help="If argument presented, URL param will be " +
"defined as long url and it wil be shorten."
)
parser.add_argument('--short_url', action='store', default=None,
help="""Use this argument and cpecify short URL, if you want to use custom short_url."""
help="Use this argument and cpecify short URL, " +
"if you want to use custom short_url."
)

return parser
Expand All @@ -50,7 +51,7 @@ class Shortener:

@staticmethod
def get_long_url(short):
""" get long url by short url
""" get long url by short url
Args:
short (str): short url
Expand Down
13 changes: 9 additions & 4 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import os
import sys
from app.utils import (
parser, Shortener,
URLExistsError, URLNotFoundError
Expand All @@ -11,12 +10,18 @@ def main():
if not os.path.exists(DB_PATH):
init_db(DB_PATH)
args = parser().parse_args()
print(args)
if not args.generate:
try:
Shortener.get_long_url(args.url)
print(Shortener.get_long_url(args.url))
except URLNotFoundError:
print("URL does not exists", file=sys.stderr)
print("ERROR!!! URL does not exists")
elif args.short_url is None:
print(Shortener.gen_short_url(args.url))
else:
try:
print(Shortener.save_url(args.short_url, args.url))
except URLExistsError:
print("ERROR!!! This url already in database")


if __name__ == '__main__':
Expand Down
4 changes: 3 additions & 1 deletion tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
1 change: 1 addition & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ def db_path():
def db_mock(db_path):
return init_db(db_path)


@pytest.fixture
def argparser():
return parser()
13 changes: 6 additions & 7 deletions tests/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@


def test_parser(argparser):
args = argparser.parse_args(['test_url', '--generate', '--short_url', 'short'])

assert type(args) is Namespace
assert args.url is 'test_url'
args = argparser.parse_args(['test_url', '--generate',
'--short_url', 'short']
)
assert type(args) == Namespace
assert args.url == 'test_url'
assert args.generate is True
assert args.short_url is 'short'


assert args.short_url == 'short'
12 changes: 9 additions & 3 deletions tests/test_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,16 @@
(1, 1, 'goo.gl'),
(2, 2, 'yu.tu');
"""


@contextmanager
def manager_mock(db_mock, init_db, db_manager):
with mock.patch(init_db) as get_db:
get_db.return_value = db_mock
with mock.patch(db_manager) as manager:
manager.return_value = db_mock
yield lambda : manager
yield lambda: manager


def test_init_db(db_path):
db = init_db(db_path)
Expand Down Expand Up @@ -76,15 +79,18 @@ def test_short_url_exist(db_mock):
assert short_url_exist('') is False
assert short_url_exist('goo.gl') is True


def test_get_long_url(db_mock):
db_mock.executescript(script)
with manager_mock(db_mock, 'app.db.get_db', 'app.db.db_manager'):
with manager_mock(db_mock, 'app.db.get_db', 'app.db.db_manager'):
assert get_long_url_from_db() is None
assert type(get_long_url_from_db(id=1)) == tuple
assert get_long_url_from_db(id=1)[0] == 1
assert type(get_long_url_from_db(url='https://www.google.com/')) == tuple
assert type(get_long_url_from_db(
url='https://www.google.com/')) == tuple
assert get_long_url_from_db(url='https://www.google.com/')[0] == 1


def test_get_short_by_long(db_mock):
db_mock.executescript(script)
with manager_mock(db_mock, 'app.db.get_db', 'app.db.db_manager'):
Expand Down
40 changes: 27 additions & 13 deletions tests/test_main.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,43 @@
from main import main
from pytest_mock import mocker
import pytest
from argparse import Namespace
from test_db import script
from test_db import script, manager_mock
from unittest import mock
from app.db import get_db, close_db, init_db
from argparse import ArgumentParser
import re
from app.db import get_db, init_db
import shortuuid
from urllib.parse import urlunsplit
from app.config import SCHEME, NETLOC


def get_short_url(url):
uuid = shortuuid.uuid(name=url)[:7]
return urlunsplit((SCHEME, NETLOC, uuid, '', ''))


def test_main_noparams(db_path, mocker):
mocker.patch('main.DB_PATH', db_path)
with pytest.raises(SystemExit):
main()

def test_main_short_url(db_path, argparser, mocker, capsys):

@pytest.mark.parametrize('args, output',
[(['on.ln'], "ERROR!!! URL does not exists"),
(['goo.gl'], 'https://www.google.com/'), (['https://www.google.com/', '--generate'],
'goo.gl'),
(['https://www.onliner.by', '--generate'], get_short_url('https://www.onliner.by')),
(['https://www.onliner.by', '--generate', '--short_url', 'onl.by'], 'onl.by'),
(['https://www.google.com/', '--generate', '--short_url', 'goo.gl'],
"ERROR!!! This url already in database"),
]
)
def test_main(db_path, argparser, mocker, capsys, args, output):
mocker.patch('main.DB_PATH', db_path)
init_db(db_path=db_path)
with mock.patch('app.db.DB_PATH', db_path):
db = get_db()
db.executescript(script)
args = argparser.parse_args(['on.ln'])
parser = mocker.patch('argparse.ArgumentParser.parse_args', return_value=args)
main()
captured = capsys.readouterr()
print(captured)
assert 'URL does not exists\n' == captured.err
args = argparser.parse_args(args)
mocker.patch('argparse.ArgumentParser.parse_args', return_value=args)
with manager_mock(db, 'db.get_db', 'db.db_manager'):
main()
captured = capsys.readouterr()
assert output+'\n' == captured.out
11 changes: 5 additions & 6 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
from os import name
from urllib.parse import urlencode
from app.utils import Shortener, URLNotFoundError, URLExistsError
from tests.test_db import script, manager_mock
import pytest
from unittest import mock


def test_get_long_url(db_mock):
def test_get_long_url(db_mock):
db_mock.executescript(script)
with manager_mock(db_mock, 'db.get_db', 'db.db_manager'):
with pytest.raises(URLNotFoundError, match=r".* URL does not .*"):
with pytest.raises(URLNotFoundError):
Shortener.get_long_url('raise')
inst = Shortener.get_long_url('goo.gl')
assert type(inst) is str
assert inst == 'https://www.google.com/'

def test_get_long_url(db_mock):

def test_get_short_url(db_mock):
db_mock.executescript(script)
with manager_mock(db_mock, 'db.get_db', 'db.db_manager'):
inst = Shortener.gen_short_url('https://www.google.com/')
Expand All @@ -24,6 +22,7 @@ def test_get_long_url(db_mock):
inst = Shortener.gen_short_url('http://www.onliner.by')
assert type(inst) is str


def test_save_url(db_mock):
db_mock.executescript(script)
with manager_mock(db_mock, 'db.get_db', 'db.db_manager'):
Expand Down

0 comments on commit 2d97753

Please sign in to comment.