[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[GNUnet-SVN] [taler-bank] branch master updated (c8f9b7a -> 3d1d4bb)
From: |
gnunet |
Subject: |
[GNUnet-SVN] [taler-bank] branch master updated (c8f9b7a -> 3d1d4bb) |
Date: |
Tue, 05 Dec 2017 13:21:42 +0100 |
This is an automated email from the git hooks/post-receive script.
marcello pushed a change to branch master
in repository bank.
from c8f9b7a measuring time to query a user's history
new 2cc5448 port to django2
new 3611f61 provide __str__ to custom exceptions
new 9dd4af1 linting
new 711be52 remove fixme
new da36d0b done linting talerconfig
new 5745f9e linting done with views
new 91da3bb default log level = warning
new d459d63 linting models. WARNING/NOTE: tests passed but this change
altered - although did NOT break - the recommended way to use the model API.
new 3d1d4bb remove initial checks. They pollute tests, and the way the
bank is launched makes sure they always pass. Moreover, they check for obvious
conditions like: is a 'Bank' user present? Is a database accessible?
The 9 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
talerbank/__init__.py | 6 +++---
talerbank/app/__init__.py | 2 --
talerbank/app/amount.py | 41 ++++++++++++++++++++--------------------
talerbank/app/checks.py | 15 ---------------
talerbank/app/models.py | 7 +++----
talerbank/app/tests.py | 47 +++++++++++++++++++++++-----------------------
talerbank/app/tests_alt.py | 5 +++++
talerbank/app/views.py | 6 ++++--
talerbank/jinja2.py | 43 ++++++++++++++++++++----------------------
talerbank/settings.py | 4 ++--
talerbank/talerconfig.py | 20 +++++++++-----------
11 files changed, 89 insertions(+), 107 deletions(-)
delete mode 100644 talerbank/app/checks.py
diff --git a/talerbank/__init__.py b/talerbank/__init__.py
index 4efb025..ca35fb3 100644
--- a/talerbank/__init__.py
+++ b/talerbank/__init__.py
@@ -1,8 +1,8 @@
import logging
-log_conf = {
+LOG_CONF = {
'format': '%(asctime)-15s %(module)s %(levelname)s %(message)s',
- 'level': logging.INFO
+ 'level': logging.WARNING
}
-logging.basicConfig(**log_conf)
+logging.basicConfig(**LOG_CONF)
diff --git a/talerbank/app/__init__.py b/talerbank/app/__init__.py
index ecc3dff..e69de29 100644
--- a/talerbank/app/__init__.py
+++ b/talerbank/app/__init__.py
@@ -1,2 +0,0 @@
-# make sure that checks are registered
-from . import checks
diff --git a/talerbank/app/amount.py b/talerbank/app/amount.py
index 0453c35..46e3446 100644
--- a/talerbank/app/amount.py
+++ b/talerbank/app/amount.py
@@ -23,26 +23,24 @@
# which might need it.
class CurrencyMismatch(Exception):
- def __init__(self, msg):
- self.msg = msg
- def __str__(self):
- return self.msg
+ def __init__(self, curr1, curr2):
+ super(CurrencyMismatch, self).__init__(
+ "%s vs %s" % (curr1, curr2))
class BadFormatAmount(Exception):
def __init__(self, faulty_str):
- self.faulty_str = faulty_str
- def __str__(self):
- return self.faulty_str
+ super(BadFormatAmount, self).__init__(
+ "Bad format amount: " + faulty_str)
class Amount:
# How many "fraction" units make one "value" unit of currency
# (Taler requires 10^8). Do not change this 'constant'.
@staticmethod
- def FRACTION():
+ def _fraction():
return 10 ** 8
@staticmethod
- def MAX_VALUE():
+ def _max_value():
return (2 ** 53) - 1
def __init__(self, currency, value=0, fraction=0):
@@ -52,13 +50,13 @@ class Amount:
self.fraction = fraction
self.currency = currency
self.__normalize()
- assert self.value <= Amount.MAX_VALUE()
+ assert self.value <= Amount._max_value()
# Normalize amount
def __normalize(self):
- if self.fraction >= Amount.FRACTION():
- self.value += int(self.fraction / Amount.FRACTION())
- self.fraction = self.fraction % Amount.FRACTION()
+ if self.fraction >= Amount._fraction():
+ self.value += int(self.fraction / Amount._fraction())
+ self.fraction = self.fraction % Amount._fraction()
# Parse a string matching the format "A:B.C"
# instantiating an amount object.
@@ -72,7 +70,7 @@ class Amount:
value = int(parsed.group(2))
fraction = 0
for i, digit in enumerate(parsed.group(3)):
- fraction += int(int(digit) * (Amount.FRACTION() / 10 ** (i+1)))
+ fraction += int(int(digit) * (Amount._fraction() / 10 ** (i+1)))
return cls(parsed.group(1), value, fraction)
# Comare two amounts, return:
@@ -82,7 +80,7 @@ class Amount:
@staticmethod
def cmp(am1, am2):
if am1.currency != am2.currency:
- raise CurrencyMismatch("%s vs %s" % (am1.currency, am2.currency))
+ raise CurrencyMismatch(am1.currency, am2.currency)
if am1.value == am2.value:
if am1.fraction < am2.fraction:
return -1
@@ -101,7 +99,7 @@ class Amount:
# Add the given amount to this one
def add(self, amount):
if self.currency != amount.currency:
- raise CurrencyMismatch()
+ raise CurrencyMismatch(self.currency, amount.currency)
self.value += amount.value
self.fraction += amount.fraction
self.__normalize()
@@ -109,9 +107,9 @@ class Amount:
# Subtract passed amount from this one
def subtract(self, amount):
if self.currency != amount.currency:
- raise CurrencyMismatch()
+ raise CurrencyMismatch(self.currency, amount.currency)
if self.fraction < amount.fraction:
- self.fraction += Amount.FRACTION()
+ self.fraction += Amount._fraction()
self.value -= 1
if self.value < amount.value:
raise ValueError('self is lesser than amount to be subtracted')
@@ -124,9 +122,10 @@ class Amount:
assert ndigits > 0
ret = '%s:%s.' % (self.currency, str(self.value))
fraction = self.fraction
- for i in range(0, ndigits):
- ret += str(int(fraction / (Amount.FRACTION() / 10)))
- fraction = (fraction * 10) % (Amount.FRACTION())
+ while ndigits > 0:
+ ret += str(int(fraction / (Amount._fraction() / 10)))
+ fraction = (fraction * 10) % (Amount._fraction())
+ ndigits -= 1
return ret
# Dump the Taler-compliant 'dict' amount
diff --git a/talerbank/app/checks.py b/talerbank/app/checks.py
deleted file mode 100644
index 3b505bb..0000000
--- a/talerbank/app/checks.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from django.core.checks import register, Warning
-from django.db.utils import OperationalError
-
address@hidden()
-def example_check(app_configs, **kwargs):
- errors = []
- try:
- from .models import User
- User.objects.get(username='Bank')
- except User.DoesNotExist:
- errors.append(Warning("The bank user does not exist, run the \
- 'provide_accounts' management command."))
- except OperationalError:
- errors.append(Warning("Presumably non existent database."))
- return errors
diff --git a/talerbank/app/models.py b/talerbank/app/models.py
index fb86f41..7ec54cb 100644
--- a/talerbank/app/models.py
+++ b/talerbank/app/models.py
@@ -26,9 +26,6 @@ class AmountField(models.Field):
description = 'Amount object in Taler style'
- def __init__(self, *args, **kwargs):
- super(AmountField, self).__init__(*args, **kwargs)
-
def deconstruct(self):
name, path, args, kwargs = super(AmountField, self).deconstruct()
return name, path, args, kwargs
@@ -42,7 +39,9 @@ class AmountField(models.Field):
return "%s:0.0" % settings.TALER_CURRENCY
return value.stringify(settings.TALER_DIGITS)
- def from_db_value(self, value, *args):
+ @staticmethod
+ def from_db_value(value, *args):
+ del args # pacify PEP checkers
if None is value:
return amount.Amount.parse(settings.TALER_CURRENCY)
return amount.Amount.parse(value)
diff --git a/talerbank/app/tests.py b/talerbank/app/tests.py
index 8baed5a..3a74f5f 100644
--- a/talerbank/app/tests.py
+++ b/talerbank/app/tests.py
@@ -18,7 +18,7 @@ import json
import timeit
import logging
from django.test import TestCase, Client
-from django.core.urlresolvers import reverse
+from django.urls import reverse
from django.conf import settings
from django.contrib.auth.models import User
from mock import patch, MagicMock
@@ -27,6 +27,9 @@ from . import urls
from .views import wire_transfer
from .amount import Amount, CurrencyMismatch, BadFormatAmount
+LOGGER = logging.getLogger()
+LOGGER.setLevel(logging.WARNING)
+
def clear_db():
User.objects.all().delete()
BankAccount.objects.all().delete()
@@ -34,23 +37,23 @@ def clear_db():
class WithdrawTestCase(TestCase):
def setUp(self):
- user_bankaccount = BankAccount(
- user=User.objects.create_user(username="test_user",
- password="test_password"),
- account_no=100)
- user_bankaccount.save()
-
- exchange_bankaccount = BankAccount(
- user=User.objects.create_user(username="test_exchange",
- password=""),
- account_no=99)
- exchange_bankaccount.save()
+ BankAccount(
+ user=User.objects.create_user(
+ username="test_user",
+ password="test_password"),
+ account_no=100).save()
+
+ BankAccount(
+ user=User.objects.create_user(
+ username="test_exchange",
+ password=""),
+ account_no=99).save()
+ self.client = Client()
@patch('hashlib.new') # Need to patch update() and hexdigest() methods.
@patch('requests.post')
@patch('time.time')
def test_withdraw(self, mocked_time, mocked_post, mocked_hashlib):
- client = Client()
wire_details = '''{
"test": {
"type":"test",
@@ -67,10 +70,10 @@ class WithdrawTestCase(TestCase):
"reserve_pub": "UVZ789",
"wire_details": wire_details.replace("\n", "").replace(" ", "")
}
- client.login(username="test_user", password="test_password")
+ self.client.login(username="test_user", password="test_password")
- client.get(reverse("pin-question", urlconf=urls),
- params)
+ self.client.get(reverse("pin-question", urlconf=urls),
+ params)
# We mock hashlib in order to fake the CAPTCHA.
hasher = MagicMock()
hasher.hexdigest = MagicMock()
@@ -80,8 +83,8 @@ class WithdrawTestCase(TestCase):
post.status_code = 200
mocked_post.return_value = post
mocked_time.return_value = 0
- client.post(reverse("pin-verify", urlconf=urls),
- {"pin_1": "0"})
+ self.client.post(reverse("pin-verify", urlconf=urls),
+ {"pin_1": "0"})
expected_json = {
"reserve_pub": "UVZ789",
"execution_date": "/Date(0)/",
@@ -326,7 +329,6 @@ class HistoryTestCase(TestCase):
except (json.JSONDecodeError, KeyError):
data = {}
- # FIXME print urls which break the test.
self.assertEqual(data.get(ctx.expected_resp.get("field")),
ctx.expected_resp.get("value"))
self.assertEqual(ctx.expected_resp.get("status"),
@@ -422,8 +424,8 @@ class MeasureHistory(TestCase):
# Make sure logging level is WARNING, otherwise the loop
# will overwhelm the console.
- logging.getLogger().setLevel(logging.WARNING)
for i in range(self.ntransfers):
+ del i # to pacify PEP checkers
wire_transfer(Amount(settings.TALER_CURRENCY, 1),
self.user_bankaccount0,
self.user_bankaccount,
@@ -437,8 +439,5 @@ class MeasureHistory(TestCase):
setup="from talerbank.app.views import
extract_history",
globals=locals())
total_time = timer.timeit(number=1)
- logging.getLogger().setLevel(logging.INFO)
- logging.getLogger().info("%d records needed %.3f secs" \
- % (self.ntransfers, total_time))
- allowed_time_per_record = 0.0017
+ allowed_time_per_record = 0.002
self.assertLess(total_time, self.ntransfers*allowed_time_per_record)
diff --git a/talerbank/app/tests_alt.py b/talerbank/app/tests_alt.py
index 33627ec..423ebb4 100644
--- a/talerbank/app/tests_alt.py
+++ b/talerbank/app/tests_alt.py
@@ -13,10 +13,15 @@
# TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
#
# @author Marcello Stanisci
+
+import logging
from django.test import TestCase
from django.conf import settings
from .amount import Amount, BadFormatAmount
+LOGGER = logging.getLogger()
+LOGGER.setLevel(logging.WARNING)
+
class BadMaxDebtOptionTestCase(TestCase):
def test_badmaxdebtoption(self):
with self.assertRaises(BadFormatAmount):
diff --git a/talerbank/app/views.py b/talerbank/app/views.py
index f31f3e4..7f8aed4 100644
--- a/talerbank/app/views.py
+++ b/talerbank/app/views.py
@@ -32,7 +32,7 @@ from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST, require_GET
-from django.core.urlresolvers import reverse
+from django.urls import reverse
from django.contrib.auth.models import User
from django.db.models import Q
from django.http import (JsonResponse, HttpResponse,
@@ -49,7 +49,9 @@ from .schemas import (validate_pin_tan_args,
check_withdraw_session,
LOGGER = logging.getLogger(__name__)
class DebtLimitExceededException(Exception):
- pass
+ def __init__(self):
+ super().__init__("Debt limit exceeded")
+
class SameAccountException(Exception):
pass
diff --git a/talerbank/jinja2.py b/talerbank/jinja2.py
index 9169a93..713e613 100644
--- a/talerbank/jinja2.py
+++ b/talerbank/jinja2.py
@@ -14,37 +14,35 @@
#
# @author Florian Dold
-from django.contrib.staticfiles.storage import staticfiles_storage
-from django.core.urlresolvers import reverse
-from django.conf import settings
-from django.core.urlresolvers import get_script_prefix
+import os
from urllib.parse import urlparse
+from django.urls import reverse, get_script_prefix
+from django.conf import settings
from jinja2 import Environment
-import os
-def is_absolute(url):
- return bool(urlparse(url).netloc)
+def is_absolute(urloc):
+ return bool(urlparse(urloc).netloc)
def join_urlparts(*parts):
- s = ""
- i = 0
- while i < len(parts):
- n = parts[i]
- i += 1
- if s.endswith("/"):
- n = n.lstrip("/")
- elif s and not n.startswith("/"):
- n = "/" + n
- s += n
- return s
+ ret = ""
+ part = 0
+ while part < len(parts):
+ buf = parts[part]
+ part += 1
+ if ret.endswith("/"):
+ buf = buf.lstrip("/")
+ elif ret and not buf.startswith("/"):
+ buf = "/" + buf
+ ret += buf
+ return ret
-def static(url):
- if is_absolute(url):
- return url
- return join_urlparts(get_script_prefix(), settings.STATIC_URL, url)
+def static(urloc):
+ if is_absolute(urloc):
+ return urloc
+ return join_urlparts(get_script_prefix(), settings.STATIC_URL, urloc)
def settings_value(name):
@@ -71,4 +69,3 @@ def environment(**options):
'env': env_get,
})
return env
-
diff --git a/talerbank/settings.py b/talerbank/settings.py
index 19c4d8e..6380937 100644
--- a/talerbank/settings.py
+++ b/talerbank/settings.py
@@ -58,13 +58,13 @@ INSTALLED_APPS = [
'talerbank.app'
]
-MIDDLEWARE_CLASSES = [
+MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
- 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
+ 'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
diff --git a/talerbank/talerconfig.py b/talerbank/talerconfig.py
index ec4bd76..a7ca065 100644
--- a/talerbank/talerconfig.py
+++ b/talerbank/talerconfig.py
@@ -18,9 +18,6 @@
Parse GNUnet-style configurations in pure Python
"""
-# FIXME: make sure that autovivification of config entries
-# does not leave garbage behind (use weakrefs!)
-
import logging
import collections
import os
@@ -111,8 +108,6 @@ class OptionDict(collections.defaultdict):
class SectionDict(collections.defaultdict):
- def __init__(self):
- super().__init__()
def __missing__(self, key):
value = OptionDict(self, key)
self[key] = value
@@ -174,10 +169,10 @@ class Entry:
return None
def value_filename(self, default=None, required=False, warn=False):
- value = self.value_string(default, warn, required)
+ value = self.value_string(default, required, warn)
if value is None:
return None
- return expand(value, lambda x: self._getsubst(x))
+ return expand(value, self._getsubst)
def location(self):
if self.filename is None or self.lineno is None:
@@ -306,10 +301,13 @@ class TalerConfig:
def dump(self):
- for section_name, section in self.sections.items():
- print("[%s]" % (section.section_name,))
- for option_name, entry in section.items():
- print("%s = %s # %s" % (entry.option, entry.value,
entry.location()))
+ for kv_section in self.sections.items():
+ print("[%s]" % (kv_section[1].section_name,))
+ for kv_option in kv_section[1].items():
+ print("%s = %s # %s" % \
+ (kv_option[1].option,
+ kv_option[1].value,
+ kv_option[1].location()))
def __getitem__(self, chunk):
if isinstance(chunk, str):
--
To stop receiving notification emails like this one, please contact
address@hidden
- [GNUnet-SVN] [taler-bank] branch master updated (c8f9b7a -> 3d1d4bb),
gnunet <=
- [GNUnet-SVN] [taler-bank] 04/09: remove fixme, gnunet, 2017/12/05
- [GNUnet-SVN] [taler-bank] 02/09: provide __str__ to custom exceptions, gnunet, 2017/12/05
- [GNUnet-SVN] [taler-bank] 09/09: remove initial checks. They pollute tests, and the way the bank is launched makes sure they always pass. Moreover, they check for obvious conditions like: is a 'Bank' user present? Is a database accessible?, gnunet, 2017/12/05
- [GNUnet-SVN] [taler-bank] 03/09: linting, gnunet, 2017/12/05
- [GNUnet-SVN] [taler-bank] 07/09: default log level = warning, gnunet, 2017/12/05
- [GNUnet-SVN] [taler-bank] 05/09: done linting talerconfig, gnunet, 2017/12/05
- [GNUnet-SVN] [taler-bank] 08/09: linting models. WARNING/NOTE: tests passed but this change altered - although did NOT break - the recommended way to use the model API., gnunet, 2017/12/05
- [GNUnet-SVN] [taler-bank] 01/09: port to django2, gnunet, 2017/12/05
- [GNUnet-SVN] [taler-bank] 06/09: linting done with views, gnunet, 2017/12/05