diff options
author | Marcello Stanisci <stanisci.m@gmail.com> | 2017-11-22 12:33:31 +0100 |
---|---|---|
committer | Marcello Stanisci <stanisci.m@gmail.com> | 2017-11-22 12:33:31 +0100 |
commit | 4f80d3a38f75360eff8c9936924f269d666e044f (patch) | |
tree | a2f2ca3718ec3430a3c58f1345786971de24a62f /talerbank | |
parent | 1669a8b457306ca4fcea7a75e705dd439f7f98ad (diff) | |
download | bank-4f80d3a38f75360eff8c9936924f269d666e044f.tar.gz bank-4f80d3a38f75360eff8c9936924f269d666e044f.tar.bz2 bank-4f80d3a38f75360eff8c9936924f269d666e044f.zip |
linting
Diffstat (limited to 'talerbank')
-rw-r--r-- | talerbank/app/checks.py | 2 | ||||
-rw-r--r-- | talerbank/app/management/commands/dump_talerdb.py | 11 | ||||
-rw-r--r-- | talerbank/app/management/commands/helpers.py | 24 | ||||
-rw-r--r-- | talerbank/app/management/commands/provide_accounts.py | 26 | ||||
-rw-r--r-- | talerbank/app/models.py | 2 | ||||
-rw-r--r-- | talerbank/app/schemas.py | 5 | ||||
-rw-r--r-- | talerbank/app/tests.py | 58 | ||||
-rw-r--r-- | talerbank/app/tests_alt.py | 21 | ||||
-rw-r--r-- | talerbank/app/views.py | 25 |
9 files changed, 88 insertions, 86 deletions
diff --git a/talerbank/app/checks.py b/talerbank/app/checks.py index 3b505bb..7865868 100644 --- a/talerbank/app/checks.py +++ b/talerbank/app/checks.py @@ -2,7 +2,7 @@ from django.core.checks import register, Warning from django.db.utils import OperationalError @register() -def example_check(app_configs, **kwargs): +def example_check(): errors = [] try: from .models import User diff --git a/talerbank/app/management/commands/dump_talerdb.py b/talerbank/app/management/commands/dump_talerdb.py index 5685da1..ba81444 100644 --- a/talerbank/app/management/commands/dump_talerdb.py +++ b/talerbank/app/management/commands/dump_talerdb.py @@ -19,6 +19,7 @@ import logging from django.core.management.base import BaseCommand from django.db.utils import OperationalError, ProgrammingError from ...models import BankAccount, BankTransaction +from .helpers import hard_db_error_log LOGGER = logging.getLogger(__name__) @@ -31,10 +32,7 @@ def dump_accounts(): for acc in accounts: print(acc.user.username + " has account number " + str(acc.account_no)) except (OperationalError, ProgrammingError): - LOGGER.error("likely causes: non existent DB or unmigrated project\n" - "(try 'taler-bank-manage django migrate' in the latter case)", - stack_info=False, - exc_info=True) + hard_db_error_log() sys.exit(1) @@ -51,10 +49,7 @@ def dump_history(): msg.append(item.subject) print(''.join(msg)) except (OperationalError, ProgrammingError): - LOGGER.error("likely causes: non existent DB or unmigrated project\n" - "(try 'taler-bank-manage django migrate' in the latter case)", - stack_info=False, - exc_info=True) + hard_db_error_log() sys.exit(1) diff --git a/talerbank/app/management/commands/helpers.py b/talerbank/app/management/commands/helpers.py new file mode 100644 index 0000000..62137e9 --- /dev/null +++ b/talerbank/app/management/commands/helpers.py @@ -0,0 +1,24 @@ +# This file is part of TALER +# (C) 2017 Taler Systems SA +# +# TALER is free software; you can redistribute it and/or modify it under the +# terms of the GNU General Public License as published by the Free Software +# Foundation; either version 3, or (at your option) any later version. +# +# TALER is distributed in the hope that it will be useful, but WITHOUT ANY +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR +# A PARTICULAR PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/> +# +# @author Marcello Stanisci + +import logging +LOGGER = logging.getLogger(__name__) + +def hard_db_error_log(): + LOGGER.error("likely causes: non existent DB or unmigrated project\n" + "(try 'taler-bank-manage django migrate' in the latter case)", + stack_info=False, + exc_info=True) diff --git a/talerbank/app/management/commands/provide_accounts.py b/talerbank/app/management/commands/provide_accounts.py index de5067d..c719296 100644 --- a/talerbank/app/management/commands/provide_accounts.py +++ b/talerbank/app/management/commands/provide_accounts.py @@ -18,12 +18,13 @@ import sys import logging from django.contrib.auth.models import User -from django.db.utils import ProgrammingError, DataError, OperationalError +from django.db.utils import ProgrammingError, OperationalError from django.core.management.base import BaseCommand -from ...models import BankAccount from django.conf import settings +from ...models import BankAccount +from .helpers import hard_db_error_log -logger = logging.getLogger(__name__) +LOGGER = logging.getLogger(__name__) def demo_accounts(): @@ -31,25 +32,21 @@ def demo_accounts(): try: User.objects.get(username=name) except User.DoesNotExist: - u = User.objects.create_user(username=name, password='x') - b = BankAccount(user=u, is_public=True) - b.save() - logger.info("Creating account '%s' with number %s", name, b.account_no) + BankAccount(user=User.objects.create_user(username=name, password='x'), + is_public=True).save() + LOGGER.info("Creating account for '%s'", name) def ensure_account(name): - logger.info("ensuring account '{}'".format(name)) + LOGGER.info("ensuring account '%s'", name) user = None try: user = User.objects.get(username=name) except (OperationalError, ProgrammingError): - logger.error("likely causes: non existent DB or unmigrated project\n" - "(try 'taler-bank-manage django migrate' in the latter case)", - stack_info=False, - exc_info=True) + hard_db_error_log() sys.exit(1) except User.DoesNotExist: - logger.info("Creating *user* account '{}'".format(name)) + LOGGER.info("Creating *user* account '%s'", name) user = User.objects.create_user(username=name, password='x') try: @@ -58,7 +55,8 @@ def ensure_account(name): except BankAccount.DoesNotExist: acc = BankAccount(user=user, is_public=True) acc.save() - logger.info("Creating *bank* account number '{}' for user '{}'".format(acc.account_no, name)) + LOGGER.info("Creating *bank* account number \ + '%s' for user '%s'", acc.account_no, name) def basic_accounts(): diff --git a/talerbank/app/models.py b/talerbank/app/models.py index d254cc4..fb86f41 100644 --- a/talerbank/app/models.py +++ b/talerbank/app/models.py @@ -42,7 +42,7 @@ class AmountField(models.Field): return "%s:0.0" % settings.TALER_CURRENCY return value.stringify(settings.TALER_DIGITS) - def from_db_value(self, value, expression, connection, context): + def from_db_value(self, value, *args): if None is value: return amount.Amount.parse(settings.TALER_CURRENCY) return amount.Amount.parse(value) diff --git a/talerbank/app/schemas.py b/talerbank/app/schemas.py index 73ce80c..b823595 100644 --- a/talerbank/app/schemas.py +++ b/talerbank/app/schemas.py @@ -19,9 +19,9 @@ definitions of JSON schemas for validating data """ -from django.conf import settings -import validictory import json +import validictory +from django.conf import settings AMOUNT_SCHEMA = { "type": "object", @@ -125,4 +125,3 @@ def validate_incoming_request(incoming_request): def check_withdraw_session(session): validictory.validate(session, WITHDRAW_SESSION_SCHEMA) - diff --git a/talerbank/app/tests.py b/talerbank/app/tests.py index 7e1ea26..5387fff 100644 --- a/talerbank/app/tests.py +++ b/talerbank/app/tests.py @@ -19,7 +19,7 @@ from django.test import TestCase, Client from django.core.urlresolvers import reverse from django.conf import settings from django.contrib.auth.models import User -from mock import patch, MagicMock, Mock +from mock import patch, MagicMock from .models import BankAccount, BankTransaction from . import urls from .views import wire_transfer @@ -43,7 +43,7 @@ class WithdrawTestCase(TestCase): password=""), account_no=99) exchange_bankaccount.save() - + @patch('hashlib.new') # Need to patch update() and hexdigest() methods. @patch('requests.post') @patch('time.time') @@ -58,17 +58,17 @@ class WithdrawTestCase(TestCase): } }''' params = { - "amount_value": "0", - "amount_fraction": "1", - "amount_currency": settings.TALER_CURRENCY, - "exchange": "http://exchange.example/", - "reserve_pub": "UVZ789", - "wire_details": wire_details.replace("\n", "").replace(" ", "") + "amount_value": "0", + "amount_fraction": "1", + "amount_currency": settings.TALER_CURRENCY, + "exchange": "http://exchange.example/", + "reserve_pub": "UVZ789", + "wire_details": wire_details.replace("\n", "").replace(" ", "") } client.login(username="test_user", password="test_password") - response = client.get(reverse("pin-question", urlconf=urls), - params) + client.get(reverse("pin-question", urlconf=urls), + params) # We mock hashlib in order to fake the CAPTCHA. hasher = MagicMock() hasher.hexdigest = MagicMock() @@ -78,21 +78,21 @@ class WithdrawTestCase(TestCase): post.status_code = 200 mocked_post.return_value = post mocked_time.return_value = 0 - response = client.post(reverse("pin-verify", urlconf=urls), - {"pin_1": "0"}) + client.post(reverse("pin-verify", urlconf=urls), + {"pin_1": "0"}) expected_json = { "reserve_pub": "UVZ789", "execution_date": "/Date(0)/", "sender_account_details": { "type": "test", "bank_uri": "http://testserver/", - "account_number": 100 + "account_number": 100 }, "transfer_details": {"timestamp": 0}, "amount": { "value": 0, "fraction": 1, - "currency": settings.TALER_CURRENCY} + "currency": settings.TALER_CURRENCY} } mocked_post.assert_called_with("http://exchange.example/admin/add/incoming", json=expected_json) @@ -103,12 +103,10 @@ class WithdrawTestCase(TestCase): class InternalWireTransferTestCase(TestCase): def setUp(self): - gm = BankAccount(user=User.objects.create_user(username='give_money', - password="gm")) - gm.save() - tm = BankAccount(user=User.objects.create_user(username='take_money'), - account_no=88) - tm.save() + BankAccount(user=User.objects.create_user(username='give_money', + password="gm")).save() + BankAccount(user=User.objects.create_user(username='take_money'), + account_no=88).save() def test_internal_wire_transfer(self): client = Client() @@ -117,8 +115,8 @@ class InternalWireTransferTestCase(TestCase): {"amount": 3.0, "counterpart": 88, "subject": "charity"}) - tm = BankAccount.objects.get(account_no=88) - self.assertEqual(0, Amount.cmp(Amount(settings.TALER_CURRENCY, 3), tm.amount)) + self.assertEqual(0, Amount.cmp(Amount(settings.TALER_CURRENCY, 3), + BankAccount.objects.get(account_no=88).amount)) self.assertEqual(200, response.status_code) def tearDown(self): @@ -203,14 +201,8 @@ class AmountTestCase(TestCase): def test_cmp_diff_curr(self): amount1 = Amount("X", 1) amount2 = Amount("Y", 2) - try: + with self.assertRaises(CurrencyMismatch): Amount.cmp(amount1, amount2) - except CurrencyMismatch: - self.assertTrue(True) - return - # Should never get here - self.assertTrue(False) - class AddIncomingTestCase(TestCase): """Test money transfer's API""" @@ -312,11 +304,11 @@ class HistoryTestCase(TestCase): for ctx in (HistoryContext(expected_resp={"status": 200}, delta="4"), HistoryContext(expected_resp={ - "field": "row_id", "value": 6, - "status": 200}, delta="+1", start="5",), + "field": "row_id", "value": 6, + "status": 200}, delta="+1", start="5",), HistoryContext(expected_resp={ - "field": "wt_subject", "value": "h", - "status": 200}, delta="-1"), + "field": "wt_subject", "value": "h", + "status": 200}, delta="-1"), HistoryContext(expected_resp={"status": 204}, delta="1", start="11"), HistoryContext(expected_resp={"status": 204}, diff --git a/talerbank/app/tests_alt.py b/talerbank/app/tests_alt.py index 7d37586..33627ec 100644 --- a/talerbank/app/tests_alt.py +++ b/talerbank/app/tests_alt.py @@ -17,24 +17,17 @@ from django.test import TestCase from django.conf import settings from .amount import Amount, BadFormatAmount -class BadDatabaseStringTestCase(TestCase): - def test_baddbstring(self): - pass - class BadMaxDebtOptionTestCase(TestCase): def test_badmaxdebtoption(self): - try: + with self.assertRaises(BadFormatAmount): Amount.parse(settings.TALER_MAX_DEBT) - except BadFormatAmount: - self.assertTrue(True) - return - try: Amount.parse(settings.TALER_MAX_DEBT_BANK) - except BadFormatAmount: - self.assertTrue(True) - return - # Force to have at least one bad amount in config - self.assertTrue(False) + +# Note, the two following classes are used to check a faulty +# _config_ file, so they are not supposed to have any logic. +class BadDatabaseStringTestCase(TestCase): + def test_baddbstring(self): + pass class NoCurrencyOptionTestCase(TestCase): pass diff --git a/talerbank/app/views.py b/talerbank/app/views.py index 2723efa..40dcc01 100644 --- a/talerbank/app/views.py +++ b/talerbank/app/views.py @@ -26,8 +26,7 @@ import requests import django.contrib.auth import django.contrib.auth.views import django.contrib.auth.forms -from decimal import Decimal -from django.db import transaction, models +from django.db import transaction from django import forms from django.conf import settings from django.contrib.auth.decorators import login_required @@ -38,8 +37,7 @@ from django.contrib.auth.models import User from django.db.models import Q from simplemathcaptcha.fields import MathCaptchaField, MathCaptchaWidget from django.http import (JsonResponse, HttpResponse, - HttpResponseBadRequest as HRBR, - HttpResponseServerError) + HttpResponseBadRequest as HRBR) from django.shortcuts import render, redirect from validictory.validator import (RequiredFieldValidationError as RFVE, FieldValidationError as FVE) @@ -104,13 +102,15 @@ def profile_page(request): info_bar = None if request.method == "POST": wtf = WTForm(request.POST) - if wtf.is_valid(): + if wtf.is_valid(): amount_parts = (settings.TALER_CURRENCY, wtf.cleaned_data.get("amount") + 0.0) try: wire_transfer(Amount.parse("%s:%s" % amount_parts), - BankAccount.objects.get(user=request.user), - BankAccount.objects.get(account_no=wtf.cleaned_data.get("counterpart")), + BankAccount.objects.get( + user=request.user), + BankAccount.objects.get( + account_no=wtf.cleaned_data.get("counterpart")), wtf.cleaned_data.get("subject")) request.session["just_wire_transferred"] = True except BankAccount.DoesNotExist: @@ -140,14 +140,14 @@ def profile_page(request): precision=settings.TALER_DIGITS, currency=user_account.amount.currency, account_no=user_account.account_no, - wt_form = wtf, + wt_form=wtf, history=history, just_withdrawn=just_withdrawn, just_registered=just_registered, no_initial_bonus=no_initial_bonus, just_wire_transferred=just_wire_transferred, wire_transfer_error=wire_transfer_error, - info_bar = info_bar + info_bar=info_bar ) if settings.TALER_SUGGESTED_EXCHANGE: context["suggested_exchange"] = settings.TALER_SUGGESTED_EXCHANGE @@ -204,10 +204,12 @@ def pin_tan_verify(request): hasher = hashlib.new("sha1") hasher.update(settings.SECRET_KEY.encode("utf-8")) # pin_0 is the answer given by the user - hasher.update(request.POST.get("pin_0" ,"").encode("utf-8")) + hasher.update(request.POST.get("pin_0", "").encode("utf-8")) hashed_attempt = hasher.hexdigest() if hashed_attempt != request.POST.get("pin_1"): - LOGGER.warning("Wrong CAPTCHA answer: %s vs %s" % (type(hashed_attempt), type(request.POST.get("pin_1")))) + LOGGER.warning("Wrong CAPTCHA answer: %s vs %s", + type(hashed_attempt), + type(request.POST.get("pin_1"))) request.session["captcha_failed"] = True return redirect(request.POST.get("question_url", "profile")) # Check the session is a "pin tan" one @@ -363,7 +365,6 @@ def serve_history(request, user_account): delta = request.GET.get("delta") if not delta: return HRBR() - #FIXME: make the '+' sign optional parsed_delta = re.search(r"([\+-])?([0-9]+)", delta) try: parsed_delta.group(0) |