Skip to content

Commit

Permalink
[tst] unittests
Browse files Browse the repository at this point in the history
  • Loading branch information
grindsa committed Jan 18, 2025
1 parent 527e385 commit 6fc51e0
Show file tree
Hide file tree
Showing 7 changed files with 296 additions and 20 deletions.
5 changes: 0 additions & 5 deletions dkb_robo/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,8 @@


BASE_URL = 'https://banking.dkb.de/api'


logger = logging.getLogger(__name__)

for hdlr in logger.handlers[:]:
print(hdlr)


class Authentication:
""" Authentication class """
Expand Down
6 changes: 3 additions & 3 deletions dkb_robo/dkb_robo.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,14 +139,14 @@ def download(self, path: Path, download_all: bool, prepend_date: bool = False, m
list_only = True
postbox = PostBox(client=self.wrapper.client)
documents = postbox.fetch_items()

if not download_all:
# only unread documents
documents = {id: item for id, item in documents.items()
if item.message and item.message.read is False}

accounts_by_id = {acc['id']: acc['account'] for acc in self.wrapper.account_dic.values()}
for doc in documents.values():
self.download_doc(path=path, doc=doc, prepend_date=prepend_date, mark_read=mark_read, use_account_folders=use_account_folders, list_only=list_only, accounts_by_id=accounts_by_id)
if not list_only:
for doc in documents.values():
self.download_doc(path=path, doc=doc, prepend_date=prepend_date, mark_read=mark_read, use_account_folders=use_account_folders, list_only=list_only, accounts_by_id=accounts_by_id)

return documents
14 changes: 6 additions & 8 deletions dkb_robo/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from string import digits, ascii_letters
from typing import List, Tuple, Optional
from datetime import datetime, timezone
from dataclasses import dataclass, fields, asdict
from dataclasses import dataclass, fields, asdict, is_dataclass
import time
import re

Expand Down Expand Up @@ -68,14 +68,14 @@ def __post_init__(self):
try:
self.value = float(self.value)
except Exception as err:
logger.error('Account.__post_init: conversion error: %s', err)
logger.error('Account.__post_init: value conversion error: %s', str(err))
self.value = None
if self.conversionRate:
try:
self.conversionRate = float(self.conversionRate)
except Exception as err:
logger.error('Account.__post_init: conversion error: %s', err)
self.value = None
logger.error('Account.__post_init: converstionRate conversion error: %s', str(err))
self.conversionRate = None


@filter_unexpected_fields
Expand All @@ -92,7 +92,7 @@ def __post_init__(self):
try:
self.value = float(self.value)
except Exception as err:
logger.error('Account.__post_init: conversion error: %s', err)
logger.error('PerformanceValue.__post_init: conversion error: %s', str(err))
self.value = None


Expand Down Expand Up @@ -160,10 +160,8 @@ def object2dictionary(obj, key_lc=False, skip_list=None):
for k, v in asdict(obj).items():
if isinstance(skip_list, list) and k in skip_list:
continue
if isinstance(v, dict):
if is_dataclass(v):
output_dict[k] = object2dictionary(v, key_lc=key_lc)
elif isinstance(v, list):
output_dict[k] = [object2dictionary(i, key_lc=key_lc) for i in v]
else:
if key_lc:
output_dict[k.lower()] = v
Expand Down
118 changes: 118 additions & 0 deletions test/test_dkb_robo.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import sys
import os
import unittest
from pathlib import Path
from unittest.mock import patch, MagicMock, Mock, mock_open
from bs4 import BeautifulSoup
from mechanicalsoup import LinkNotFoundError
Expand Down Expand Up @@ -198,6 +199,123 @@ def test_015_scan_postbox(self):
self.dkb.download.return_value = {'foo': 'bar'}
self.assertEqual({'foo': 'bar'}, self.dkb.scan_postbox())

@patch('dkb_robo.postbox.PostBox.fetch_items')
@patch('dkb_robo.dkb_robo.DKBRobo.download_doc', autospec=True)
def test_016_download(self, mock_download_doc, mock_fetch_items):
""" download_all_documents"""
path = Path('/some/path')
self.dkb.wrapper = Mock()
self.dkb.wrapper.client = Mock()
self.dkb.wrapper.account_dic = {'id1': {'id': 'id1', 'account': 'account1', 'read': False, 'foo': 'bar', 'iban': 'iban'}, 'id2': {'id': 'id2', 'account': 'account2', 'read': True, 'foo': 'bar'}}
mock_fetch_items.return_value = {
'doc1': 'document1',
'doc2': 'document2'
}

documents = self.dkb.download(path=path, download_all=True)
self.assertEqual({'doc1': 'document1', 'doc2': 'document2'}, documents)
mock_download_doc.assert_any_call(self.dkb, path=path, doc=documents['doc1'], prepend_date=False, mark_read=True, use_account_folders=False, list_only=False, accounts_by_id={'id1': 'account1', 'id2': 'account2'})
mock_download_doc.assert_any_call(self.dkb, path=path, doc=documents['doc2'], prepend_date=False, mark_read=True, use_account_folders=False, list_only=False, accounts_by_id={'id1': 'account1', 'id2': 'account2'})

@patch('dkb_robo.postbox.PostBox.fetch_items')
@patch('dkb_robo.dkb_robo.DKBRobo.download_doc', autospec=True)
def test_017_download(self, mock_download_doc, mock_fetch_items):
""" download_all_documents"""
path = Path('/some/path')
self.dkb.wrapper = Mock()
self.dkb.wrapper.client = Mock()
self.dkb.wrapper.account_dic = {'id1': {'id': 'id1', 'account': 'account1', 'read': False, 'foo': 'bar', 'iban': 'iban'}, 'id2': {'id': 'id2', 'account': 'account2', 'read': True, 'foo': 'bar'}}
unread_doc = MagicMock()
unread_doc.message.read = False
read_doc = MagicMock()
read_doc.message.read = True
mock_fetch_items.return_value = {
'doc1': unread_doc,
'doc2': read_doc
}
documents = self.dkb.download(path=path, download_all=False)
self.assertEqual(1, len(documents))
mock_download_doc.assert_any_call(self.dkb, path=path, doc=documents['doc1'], prepend_date=False, mark_read=True, use_account_folders=False, list_only=False, accounts_by_id={'id1': 'account1', 'id2': 'account2'})

@patch('dkb_robo.postbox.PostBox.fetch_items')
@patch('dkb_robo.dkb_robo.DKBRobo.download_doc', autospec=True)
def test_018_download(self, mock_download_doc, mock_fetch_items):
""" download_all_documents"""
path = Path('/some/path')
self.dkb.wrapper = Mock()
self.dkb.wrapper.client = Mock()
self.dkb.wrapper.account_dic = {'id1': {'id': 'id1', 'account': 'account1', 'read': False, 'foo': 'bar', 'iban': 'iban'}, 'id2': {'id': 'id2', 'account': 'account2', 'read': True, 'foo': 'bar'}}
mock_fetch_items.return_value = {
'doc1': 'document1',
'doc2': 'document2'
}

documents = self.dkb.download(path=None, download_all=True)
self.assertEqual({'doc1': 'document1', 'doc2': 'document2'}, documents)
mock_download_doc.assert_not_called()

@patch('dkb_robo.dkb_robo.time.sleep', autospec=True)
def test_019_download_doc(self, mock_sleep):
""" download a single document """
path = Path('/some/path')
doc = MagicMock()
doc.category.return_value = 'category'
doc.account.return_value = 'account'
doc.date.return_value = '2022-01-01'
doc.filename.return_value = 'document.pdf'
doc.subject.return_value = 'Document Subject'
doc.download.return_value = True
self.dkb.wrapper = MagicMock()
with self.assertLogs('dkb_robo', level='INFO') as lcm:
self.dkb.download_doc(path=path, doc=doc, prepend_date=True, mark_read=True, use_account_folders=True, list_only=False, accounts_by_id={})
self.assertIn('INFO:dkb_robo:Downloading Document Subject to \\some\\path\\category\\account...', lcm.output)

target = path / 'category' / 'account'
filename = '2022-01-01_document.pdf'
doc.download.assert_called_with(self.dkb.wrapper.client, target / filename)
doc.mark_read.assert_called_with(self.dkb.wrapper.client, True)
mock_sleep.assert_called_once_with(0.5)

def test_020_download_doc(self):
""" list only """
path = Path('/some/path')
doc = MagicMock()
doc.category.return_value = 'category'
doc.account.return_value = 'account'
doc.date.return_value = '2022-01-01'
doc.filename.return_value = 'document.pdf'
doc.subject.return_value = 'Document Subject'
doc.download.return_value = True
self.dkb.logger = MagicMock()
self.dkb.wrapper = MagicMock()
self.dkb.download_doc(path=path, doc=doc, prepend_date=True, mark_read=True, use_account_folders=True, list_only=True, accounts_by_id={})
self.dkb.logger.info.assert_not_called()
doc.download.assert_not_called()
doc.mark_read.assert_not_called()

@patch('dkb_robo.dkb_robo.time.sleep', autospec=True)
def test_021_download_doc(self, mock_sleep):
""" test existing file """
path = Path('/some/path')
doc = MagicMock()
doc.category.return_value = 'category'
doc.account.return_value = 'account'
doc.date.return_value = '2022-01-01'
doc.filename.return_value = 'document.pdf'
doc.subject.return_value = 'Document Subject'
doc.download.return_value = False
self.dkb.logger = MagicMock()
self.dkb.wrapper = MagicMock()
self.dkb.download_doc(path=path, doc=doc, prepend_date=True, mark_read=True, use_account_folders=True, list_only=False, accounts_by_id={})
target = path / 'category' / 'account'
filename = '2022-01-01_document.pdf'
self.dkb.logger.info.assert_called_with("File already exists. Skipping %s.", filename)
doc.download.assert_called_with(self.dkb.wrapper.client, target / filename)
doc.mark_read.assert_not_called()
mock_sleep.assert_not_called()



if __name__ == '__main__':

unittest.main()
2 changes: 1 addition & 1 deletion test/test_exemptionorder.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def test_005__filter(self):
result = [{'amount': None, 'used': None, 'currencycode': 'EUR', 'validfrom': '2020-01-01', 'validto': '9999-12-31', 'receivedat': '2020-01-01', 'type': 'joint', 'partner': {'dateofbirth': '1970-01-01', 'firstname': 'Jane', 'lastname': 'Doe', 'salutation': 'Frau', 'taxid': '1234567890'}}]
with self.assertLogs('dkb_robo', level='INFO') as lcm:
self.assertEqual(result, self.exo._filter(full_list))
self.assertIn("ERROR:dkb_robo.utilities:Account.__post_init: conversion error: could not convert string to float: 'aa'", lcm.output)
self.assertIn("ERROR:dkb_robo.utilities:Account.__post_init: value conversion error: could not convert string to float: 'aa'", lcm.output)

def test_006__filter(self):
""" test StandingOrder._filter() with list """
Expand Down
2 changes: 1 addition & 1 deletion test/test_standingorder.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ def test_007__filter(self):
result = [{'amount': None, 'currencycode': None, 'purpose': 'description', 'recipient': 'cardname', 'creditoraccount': {'iban': 'crediban', 'bic': 'credbic'}, 'interval': {'from': '2020-01-01', 'until': '2025-12-01', 'frequency': 'monthly', 'nextExecutionAt': '2020-02-01', 'holidayExecutionStrategy': None}}]
with self.assertLogs('dkb_robo', level='INFO') as lcm:
self.assertEqual(result, self.dkb._filter(full_list))
self.assertIn("ERROR:dkb_robo.utilities:Account.__post_init: conversion error: could not convert string to float: 'aa'", lcm.output)
self.assertIn("ERROR:dkb_robo.utilities:Account.__post_init: value conversion error: could not convert string to float: 'aa'", lcm.output)

def test_008__filter(self):
""" test StandingOrders._filter() with incomplete list/conversion error """
Expand Down
Loading

0 comments on commit 6fc51e0

Please sign in to comment.