Browse Source

Changed assertions to exceptions.

master
Franco Masotti 2 years ago
parent
commit
78a344ed7e
Signed by: frnmst
GPG Key ID: 24116ED85666780A
  1. 6
      .pre-commit-config.yaml
  2. 4
      README.rst
  3. 2
      assets/buy_me_a_coffee.svg
  4. 2
      docs/Makefile
  5. 2
      docs/api.rst
  6. 2
      docs/conf.py
  7. 2
      docs/install.rst
  8. 176
      fattura_elettronica_reader/api.py
  9. 3
      fattura_elettronica_reader/cli.py
  10. 2
      tests/tests.py

6
.pre-commit-config.yaml

@ -19,17 +19,17 @@ repos:
rev: '3.8.3' # Use the sha / tag you want to point at
hooks:
- id: flake8
args: ['--ignore=E501,W503,W504']
args: ['--ignore=E125,E126,F401,E501,W503,W504']
additional_dependencies: [flake8-docstrings]
- repo: https://github.com/PyCQA/bandit
rev: '1.6.2' # Use the sha / tag you want to point at
hooks:
- id: bandit
args: ['--skip', 'B404,B506,B410,B603', '--level', 'LOW']
args: ['--skip', 'B320,B404,B410,B603', '--level', 'LOW']
- repo: https://github.com/twu/skjold
rev: 'v0.1.5'
rev: 'v0.1.6'
hooks:
- id: skjold
args: ['-s', 'gemnasium', '-s', 'pyup']

4
README.rst

@ -42,7 +42,7 @@ API examples
------------
fattura-elettronica-reader has a `public API`_.
This means for example that you can you easily read invoice files within another
This means for example that you can you easily read invoice files within another
Python program:
@ -75,7 +75,7 @@ Python program:
file_type='p7m',
data=data,
)
Have a look at the `archive_invoice_files <https://raw.githubusercontent.com/frnmst/automated-tasks/master/src/archiving/archive_invoice_files.py>`_
script in the `automated tasks <https://github.com/frnmst/automated-tasks>`_ repository.

2
assets/buy_me_a_coffee.svg

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="106" height="20"><linearGradient id="b" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="a"><rect width="106" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#a)"><path fill="#555555" d="M0 0h31v20H0z"/><path fill="#ff813f" d="M31 0h75v20H31z"/><path fill="url(#b)" d="M0 0h106v20H0z"/></g><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="110"> <text x="165" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="210">buy</text><text x="165" y="140" transform="scale(.1)" textLength="210">buy</text><text x="675" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="650">me a coffee</text><text x="675" y="140" transform="scale(.1)" textLength="650">me a coffee</text></g> </svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="106" height="20"><linearGradient id="b" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="a"><rect width="106" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#a)"><path fill="#555555" d="M0 0h31v20H0z"/><path fill="#ff813f" d="M31 0h75v20H31z"/><path fill="url(#b)" d="M0 0h106v20H0z"/></g><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="110"> <text x="165" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="210">buy</text><text x="165" y="140" transform="scale(.1)" textLength="210">buy</text><text x="675" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="650">me a coffee</text><text x="675" y="140" transform="scale(.1)" textLength="650">me a coffee</text></g> </svg>

Before

Width:  |  Height:  |  Size: 964 B

After

Width:  |  Height:  |  Size: 965 B

2
docs/Makefile

@ -17,4 +17,4 @@ help:
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

2
docs/api.rst

@ -7,7 +7,7 @@ Main Interface
--------------
Examples for the most relevant api functions can be viewed in the test
file. fattura_elettronica_reader's API uses `type hints`_ instead of assertions to check input and
file. fattura_elettronica_reader's API uses `type hints`_ instead of assertions to check input and
output types.
.. _type hints: https://docs.python.org/3/library/typing.html

2
docs/conf.py

@ -12,6 +12,7 @@
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
r"""conf.py."""
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
@ -212,4 +213,3 @@ html_theme_options = {
'includehidden': True,
'titles_only': False
}

2
docs/install.rst

@ -22,5 +22,3 @@ Dependencies
------------
- Python >= 3.5

176
fattura_elettronica_reader/api.py

@ -109,8 +109,7 @@ def is_p7m_file_signed(p7m_file: str) -> bool:
"""
command = 'openssl pkcs7 -print_certs -text -noout -inform DER -in {}'.format(
shlex.quote(p7m_file))
return True if subprocess.run(
shlex.split(command)).returncode == 0 else False
return True if subprocess.run(shlex.split(command)).returncode == 0 else False
def invoice_file_checksum_matches(metadata_file_xml_root, invoice_file: str,
@ -265,8 +264,7 @@ def remove_signature_from_p7m_file(p7m_file: str, output_file: str) -> bool:
command = ('openssl smime -nosigs -verify -noverify -in {}'.format(
shlex.quote(p7m_file)) +
' -inform DER -out {}'.format(shlex.quote(output_file)))
return True if subprocess.run(
shlex.split(command)).returncode == 0 else False
return True if subprocess.run(shlex.split(command)).returncode == 0 else False
def extract_attachments_from_invoice_file(
@ -623,84 +621,137 @@ def assert_data_structure(source: str, file_type: str, data: dict):
:type data: dict
:returns: None
:rtype: None
:raises: AssertionError
:raises: ValueError or TypeError
"""
# Check if file_type is coherent with source.
ok = False
assert source in ['invoice', 'generic']
assert 'patched' in data
assert 'configuration file' in data
assert 'write default configuration file' in data
assert isinstance(data['patched'], bool)
assert isinstance(data['configuration file'], str)
assert isinstance(data['write default configuration file'], bool)
if source not in ['invoice', 'generic']:
raise ValueError
if 'patched' not in data:
raise ValueError
if'configuration file' not in data:
raise ValueError
if'write default configuration file' not in data:
raise ValueError
if not isinstance(data['patched'], bool):
raise TypeError
if not isinstance(data['configuration file'], str):
raise TypeError
if not isinstance(data['write default configuration file'], bool):
raise TypeError
if source == 'invoice':
assert 'extract attachments' in data
assert 'invoice xslt type' in data
assert 'no invoice xml validation' in data
assert 'force invoice schema file download' in data
assert 'generate html output' in data
assert 'invoice filename' in data
assert 'no checksum check' in data
assert 'force invoice xml stylesheet file download' in data
assert 'ignore attachment extension whitelist' in data
assert 'ignore attachment filetype whitelist' in data
assert isinstance(data['extract attachments'], bool)
assert isinstance(data['invoice xslt type'], str)
assert isinstance(data['no invoice xml validation'], bool)
assert isinstance(data['force invoice schema file download'], bool)
assert isinstance(data['generate html output'], bool)
assert isinstance(data['invoice filename'], str)
assert isinstance(data['no checksum check'], bool)
assert isinstance(data['force invoice xml stylesheet file download'],
bool)
assert isinstance(data['ignore attachment extension whitelist'], bool)
assert isinstance(data['ignore attachment filetype whitelist'], bool)
if 'extract attachments' not in data:
raise ValueError
if 'invoice xslt type' not in data:
raise ValueError
if 'no invoice xml validation' not in data:
raise ValueError
if 'force invoice schema file download' not in data:
raise ValueError
if 'generate html output' not in data:
raise ValueError
if 'invoice filename' not in data:
raise ValueError
if 'no checksum check' not in data:
raise ValueError
if 'force invoice xml stylesheet file download' not in data:
raise ValueError
if 'ignore attachment extension whitelist' not in data:
raise ValueError
if 'ignore attachment filetype whitelist' not in data:
raise ValueError
if not isinstance(data['extract attachments'], bool):
raise TypeError
if not isinstance(data['invoice xslt type'], str):
raise TypeError
if not isinstance(data['no invoice xml validation'], bool):
raise TypeError
if not isinstance(data['force invoice schema file download'], bool):
raise TypeError
if not isinstance(data['generate html output'], bool):
raise TypeError
if not isinstance(data['invoice filename'], str):
raise TypeError
if not isinstance(data['no checksum check'], bool):
raise TypeError
if not isinstance(data['force invoice xml stylesheet file download'],
bool):
raise TypeError
if not isinstance(data['ignore attachment extension whitelist'], bool):
raise TypeError
if not isinstance(data['ignore attachment filetype whitelist'], bool):
raise TypeError
if data['patched']:
assert 'metadata file' in data
assert isinstance(data['metadata file'], str)
if 'metadata file' not in data:
raise ValueError
if not isinstance(data['metadata file'], str):
raise TypeError
else:
assert 'metadata files' in data
assert isinstance(data['metadata files'], list)
if 'metadata files' not in data:
raise ValueError
if not isinstance(data['metadata files'], list):
raise TypeError
for m in data['metadata files']:
assert isinstance(m, str)
if not isinstance(m, str):
raise TypeError
if file_type == 'p7m':
assert 'ignore signature check' in data
assert 'ignore signers certificate check' in data
assert 'force trusted list file download' in data
assert 'keep original file' in data
assert isinstance(data['ignore signature check'], bool)
assert isinstance(data['ignore signers certificate check'], bool)
assert isinstance(data['force trusted list file download'], bool)
assert isinstance(data['keep original file'], bool)
if 'ignore signature check' not in data:
raise ValueError
if 'ignore signers certificate check' not in data:
raise ValueError
if 'force trusted list file download' not in data:
raise ValueError
if 'keep original file' not in data:
raise ValueError
if not isinstance(data['ignore signature check'], bool):
raise TypeError
if not isinstance(data['ignore signers certificate check'], bool):
raise TypeError
if not isinstance(data['force trusted list file download'], bool):
raise TypeError
if not isinstance(data['keep original file'], bool):
raise TypeError
ok = True
elif file_type == 'plain':
ok = True
elif source == 'generic':
if file_type == 'p7m':
assert 'ignore signature check' in data
assert 'ignore signers certificate check' in data
assert 'force trusted list file download' in data
assert 'keep original file' in data
assert isinstance(data['ignore signature check'], bool)
assert isinstance(data['ignore signers certificate check'], bool)
assert isinstance(data['force trusted list file download'], bool)
assert isinstance(data['keep original file'], bool)
if 'ignore signature check' not in data:
raise ValueError
if 'ignore signers certificate check' not in data:
raise ValueError
if 'force trusted list file download' not in data:
raise ValueError
if 'keep original file' not in data:
raise ValueError
if not isinstance(data['ignore signature check'], bool):
raise TypeError
if not isinstance(data['ignore signers certificate check'], bool):
raise TypeError
if not isinstance(data['force trusted list file download'], bool):
raise TypeError
if not isinstance(data['keep original file'], bool):
raise TypeError
if data['patched']:
assert 'p7m file' in data
assert isinstance(data['p7m file'], str)
if 'p7m file' not in data:
raise ValueError
if not isinstance(data['p7m file'], str):
raise TypeError
else:
assert 'p7m files' in data
assert isinstance(data['p7m files'], list)
if 'p7m files' not in data:
raise ValueError
if not isinstance(data['p7m files'], list):
raise TypeError
for p in data['p7m files']:
assert isinstance(p, str)
if not isinstance(p, str):
raise TypeError
ok = True
if not ok:
raise AssertionError
raise ValueError
def pipeline(source: str, file_type: str, data: dict):
@ -720,7 +771,8 @@ def pipeline(source: str, file_type: str, data: dict):
"""
assert_data_structure(source, file_type, data)
# data must be patched for this function to work.
assert data['patched']
if not data['patched']:
raise ValueError
project_name = 'fattura_elettronica_reader'
create_appdirs(project_name)

3
fattura_elettronica_reader/cli.py

@ -25,7 +25,6 @@ import argparse
import textwrap
from pkg_resources import (get_distribution, DistributionNotFound)
from .api import pipeline
from .constants import File
PROGRAM_DESCRIPTION = 'fattura-elettronica-reader: Validate, extract, and generate printables\nof electronic invoice files received from the "Sistema di Interscambio"\nas well as other P7M files'
VERSION_NAME = 'fattura_elettronica_reader'
@ -42,6 +41,7 @@ PROGRAM_EPILOG = RETURN_VALUES + '\n\n' + VERSION_COPYRIGHT + '\n' + VERSION_LIC
class CliToApi():
r"""An interface between the CLI and API functions."""
def run(self, args):
r"""Run the pipeline."""
common_data = {
@ -120,6 +120,7 @@ class CliToApi():
class CliInterface():
r"""The interface exposed to the final user."""
def __init__(self):
r"""Set the parser variable that will be used instead of using create_parser."""
self.parser = self.create_parser()

2
tests/tests.py

@ -20,7 +20,7 @@
#
"""The tests module."""
from fattura_elettronica_reader import (api, exceptions, constants)
# from fattura_elettronica_reader import (api, exceptions, constants)
import unittest
# Some static generic variables.

Loading…
Cancel
Save