Commit 96e09ad7 authored by Patrick van der Leer's avatar Patrick van der Leer
Browse files

basics

parent 9955ff26
......@@ -4,8 +4,10 @@
<option name="enabled" value="true" />
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.6 (ebookhub-backend)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TemplatesService">
......
......@@ -4,8 +4,4 @@
<option name="languageLevel" value="ES6" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6 (ebookhub-backend)" project-jdk-type="Python SDK" />
<component name="VagrantProjectSettings">
<option name="instanceFolder" value="" />
<option name="provider" value="" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VagrantProjectSettings">
<option name="instanceFolder" value="" />
<option name="provider" value="" />
</component>
</project>
\ No newline at end of file
......@@ -5,6 +5,8 @@ import multiprocessing as mp
from flask_env import MetaFlaskEnv
__version__ = 1
class Config(metaclass=MetaFlaskEnv):
"""Base configuration."""
......
......@@ -11,6 +11,9 @@ class Book(object):
title = None
sortable_title = None
authors = []
class BookEdition(object):
language = None
serie = None
tags = []
......
from eBookHub.exceptions import EBookHubException
class ValidationException(EBookHubException):
""" abstract exception """
class ISBNException(ValidationException):
""" ISBN error """
from functools import wraps
from eBookHub.validators.exceptions import ISBNException
def _clean_isbn(isbn):
"""
Remove all non-digit and non "x" characters from given string.
Args:
isbn (str): isbn string, which will be cleaned.
Returns:
list: array of numbers (if "x" is found, it is converted to 10).
"""
if isinstance(isbn, str):
isbn = list(isbn.lower())
# filter digits and "x"
isbn = filter(lambda x: x.isdigit() or x == "x", isbn)
# convert ISBN to numbers
return list(map(lambda x: 10 if x == "x" else int(x), isbn))
def _isbn_cleaner(fn):
"""
Decorator for calling other functions from this module.
Purpose of this decorator is to clean the ISBN string from garbage and
return list of digits.
Args:
fn (function): function in which will be :func:`_clean_isbn(isbn)` call
wrapped.
"""
@wraps(fn)
def wrapper(isbn):
return fn(_clean_isbn(isbn))
return wrapper
@_isbn_cleaner
def get_isbn10_checksum(isbn):
"""
Args:
isbn (str/list): ISBN number as string or list of digits
Warning:
Function expects that `isbn` is only 9 digits long.
Returns:
int: Last (checksum) digit for given `isbn`.
"""
return sum([(i + 1) * x for i, x in enumerate(isbn)]) % 11
@_isbn_cleaner
def is_isbn10_valid(isbn):
"""
Check if given `isbn` 10 is valid.
Args:
isbn (str/list): ISBN number as string or list of digits.
Returns:
bool: ``True`` if ISBN is valid.
"""
if len(isbn) != 10:
raise ISBNException('Length of ISBN-10 is not 10')
return get_isbn10_checksum(isbn[:-1]) == isbn[-1]
@_isbn_cleaner
def get_isbn13_checksum(isbn):
"""
Args:
isbn (str/list): ISBN number as string or list of digits.
Warning:
Function expects that `isbn` is only 12 digits long.
Returns:
int: Last checksum digit for given `isbn`.
"""
multipliers = list(map(lambda x: int(x), list("13" * 6)))
rest = sum([i * x for i, x in zip(multipliers, isbn)]) % 10
if rest == 0:
return rest
return 10 - rest
@_isbn_cleaner
def is_isbn13_valid(isbn):
"""
Check if given `isbn` 13 is valid.
Args:
isbn (str/list): ISBN number as string or list of digits.
Returns:
bool: ``True`` if ISBN is valid.
"""
if len(isbn) != 13:
raise ISBNException('Length of ISBN-13 is not 13')
return get_isbn13_checksum(isbn[:-1]) == isbn[-1]
@_isbn_cleaner
def is_valid_isbn(isbn):
"""
Validate given `isbn`. Wrapper for :func:`is_isbn10_valid`/
:func:`is_isbn13_valid`.
Args:
isbn (str/list): ISBN number as string or list of digits.
Note:
Function doesn't require `isbn` type to be specified (it can be both
10/13 isbn's versions).
Returns:
bool: ``True`` if ISBN is valid.
"""
length = len(isbn)
if length == 10:
return is_isbn10_valid(isbn)
elif length == 13:
return is_isbn13_valid(isbn)
return False
def validate_isbn(value):
if not is_valid_isbn(value if isinstance(value, str) else str(value)):
raise ISBNException('Invalid ISBN')
def validate_isbn10(value):
if not is_isbn10_valid(value if isinstance(value, str) else str(value)):
raise ISBNException('Invalid ISBN-10')
def validate_isbn13(value):
if not is_isbn13_valid(value if isinstance(value, str) else str(value)):
raise ISBNException('Invalid ISBN-13')
# -*- coding: utf-8 -*-
from unittest import TestCase
from eBookHub.validators.exceptions import ISBNException
from eBookHub.validators.isbn import validate_isbn10, validate_isbn13, validate_isbn
class ISBNTestCase(TestCase):
isbn_10_valid = "0306406152"
isbn_13_valid = "9783161484100"
def test_isbn10_success(self):
validate_isbn10(self.isbn_10_valid)
def test_isbn10_fail(self):
self.assertRaises(ISBNException, validate_isbn10, 1234567891)
def test_isbn13_success(self):
validate_isbn13(self.isbn_13_valid)
def test_isbn13_fail(self):
self.assertRaises(ISBNException, validate_isbn13, 1234567891234)
def test_isbn_success(self):
validate_isbn(self.isbn_10_valid)
validate_isbn(self.isbn_13_valid)
# -*- coding: utf-8 -*-
from unittest import TestCase
from eBookHub.parser.filename import FilenameParser
class FileNameParserTestCase(TestCase):
parser = FilenameParser
# ToDo
todo = [
'Aebi, Belinda - containermeisje, Het',
'Amis, Kingsley - Huwelijk op de helling.epub',
'Allingham, Margery - [Albert Campion 09] man die twee keer stierf, De',
'Allingham, Margery - [Albert Campion 09] De man die twee keer stierf',
'Amis, Kingsley - Huwelijk op de helling',
'Dixon, Franklin W. - [Hardy\'s 31] geheim van de Schedelberg, Het',
'Rose, Karen - Vartanian Familie Trilogie -1- Sterf voor mij',
'Rose, Karen - Vartanian Familie Trilogie -2- Schreeuw voor mij',
'Rose, Karen - Vartanian Familie Trilogie -3- Moord voor mij',
'Aardenburg, A. van & Herson - [Bas Banning 11] Bas Banning en de zwarte ruiter',
'Eriksson, Jerker & Sundquist, Hakan Axlander - [Kihlberg & Zetterlund 01] Het kraaienmeisje.epub',
]
def setUp(self):
self.parser = self.parser()
def verify_parse(self, test_data, verified_data):
if isinstance(test_data, dict):
test_data = [test_data]
for attempt in test_data:
for key, value in attempt.items():
if value is None:
continue
if isinstance(verified_data[key], list):
if isinstance(value, list):
self.assertListEqual(value, verified_data[key])
else:
self.assertIn(value, verified_data[key])
else:
self.assertEqual(value, verified_data[key])
def test_parser(self):
lines = [
'Aardenburg, A van - [Bas Banning 03] Bas Banning en de Geheimzinnige Kabelbaan',
'Aardenburg, A van/Bas Banning 03/Bas Banning en de Geheimzinnige Kabelbaan',
'Aardenburg, A van/[Bas Banning 03] Bas Banning en de Geheimzinnige Kabelbaan',
'Aardenburg, A van/Aardenburg, A van - Bas Banning en de Geheimzinnige Kabelbaan',
'Aardenburg, A van/Aardenburg, A van - [Bas Banning 03] Bas Banning en de Geheimzinnige Kabelbaan',
]
data = {
'authors': [
'Aardenburg, A van',
],
'title': 'Bas Banning en de Geheimzinnige Kabelbaan',
'serie_full': 'Bas Banning 03',
'serie_name': 'Bas Banning',
'serie_index': ["03", 3],
}
for line in lines:
self.verify_parse(self.parser.parse(line), data)
self.verify_parse(self.parser.parse(line + ".epub"), data)
lines = [
'Eriksson, Jerker & Sundquist, Hakan Axlander - Het kraaienmeisje',
'Eriksson, Jerker & Sundquist, Hakan Axlander - Kihlberg & Zetterlund 01 - Het kraaienmeisje',
'Eriksson, Jerker & Sundquist, Hakan Axlander/Eriksson, Jerker & Sundquist, Hakan Axlander - [Kihlberg & Zetterlund 01] Het kraaienmeisje',
'Eriksson, Jerker & Sundquist, Hakan Axlander - [Kihlberg & Zetterlund 01] Het kraaienmeisje',
]
data = {
'authors': [
'Eriksson, Jerker',
'Sundquist, Hakan Axlander',
],
'title': 'Het kraaienmeisje',
'serie_full': 'Kihlberg & Zetterlund 01',
'serie_name': 'Kihlberg & Zetterlund',
'serie_index': ["01", 1],
}
for line in lines:
self.verify_parse(self.parser.parse(line), data)
self.verify_parse(self.parser.parse(line + ".epub"), data)
# THESE ARE EMPTY FILES FOR UNITTESTING
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment