diff --git a/AUTHORS.rst b/AUTHORS.rst index 085523c..64aa1d8 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -5,12 +5,13 @@ Credits Development Lead ---------------- -* Quentin Vaudaine -* Boguta Maxime +* Nicolas Baccelli Contributors ------------ -* Nicolas Baccelli * Jocelyn Griselle * Salem Harrache +* Quentin Vaudaine +* Boguta Maxime +* Nicolas Baccelli diff --git a/CHANGES.rst b/CHANGES.rst index d7e6e32..bda4b2e 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -3,6 +3,15 @@ Shiba : Python API for PriceMinister WebServices ================================================ +Version 1.2.0 +------------------- + +Released on XXX 2021 + +- Reformat code using `black` +- Compatibility to python 3.9 +- Removes python 3.4, 3.5 + Version 1.1.12 ------------------- diff --git a/Makefile b/Makefile index a689efc..5486e76 100644 --- a/Makefile +++ b/Makefile @@ -34,7 +34,7 @@ init: ## Install the project in development mode (using virtualenv is highly re # Useful to build the documentation pip install sphinx sphinx-readable-theme # Useful for dev - pip install tox ipdb jedi pytest pytest-cov flake8 wheel bumpversion httpie + pip install tox ipdb jedi pytest pytest-cov flake8 wheel bumpversion httpie black clean: clean-build clean-pyc clean-test ## Remove all build, test, coverage and Python artifacts diff --git a/README.rst b/README.rst index b32c184..e6054c6 100644 --- a/README.rst +++ b/README.rst @@ -2,7 +2,7 @@ Shiba ===== **Shiba** is a Python package that provides interfaces to **PriceMinister Web services**. Currently, all features works -with *Python3.x*. (3.4, 3.5, 3.6, 3.7) +with *Python3.x*. (3.6, 3.7, 3.8, 3.9) Shiba supports all the Web services introduced by the *PriceMinister developper blog*. diff --git a/doc/conf.py b/doc/conf.py index 58ec337..1798539 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -19,36 +19,36 @@ # If extensions (or modules to document with autodoc) are in another directory, # 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. -sys.path.insert(0, os.path.abspath('/home/boguta_m/ABCCULTURE/shiba')) +sys.path.insert(0, os.path.abspath("/home/boguta_m/ABCCULTURE/shiba")) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' +# needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.viewcode', + "sphinx.ext.autodoc", + "sphinx.ext.viewcode", ] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix of source filenames. -source_suffix = '.rst' +source_suffix = ".rst" # The encoding of source files. -source_encoding = 'utf-8' +source_encoding = "utf-8" # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'Shiba' -copyright = u'2014, Maxime Boguta, Jocelyn Griselle, Nicolas Baccelli' +project = u"Shiba" +copyright = u"2014, Maxime Boguta, Jocelyn Griselle, Nicolas Baccelli" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -58,193 +58,186 @@ # for |version| and |release|, also used in various other places throughout # the built documents. # -version_file = os.path.join(HERE, os.pardir, - 'shiba', '__init__.py') +version_file = os.path.join(HERE, os.pardir, "shiba", "__init__.py") -release = re.search("__version__ = '([^']+)'", - open(version_file).read().strip()).group(1) +release = re.search("__version__ = '([^']+)'", open(version_file).read().strip()).group( + 1 +) # The short X.Y version. -version = '.'.join(release.split('.')[:2]) +version = ".".join(release.split(".")[:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -#language = None +# language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: -#today = '' +# today = '' # Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' +# today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build'] +exclude_patterns = ["_build"] # The reST default role (used for this markup: `text`) to use for all # documents. -#default_role = None +# default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True +# add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). -#add_module_names = True +# add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. -#show_authors = False +# show_authors = False # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] +# modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. -#keep_warnings = False +# keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = 'default' +html_theme = "default" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -html_theme_options = { -} +html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] +# html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". -#html_title = None +# html_title = None # A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None +# html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. -#html_logo = None +# html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. -#html_favicon = None +# html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. -#html_extra_path = [] +# html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' +# html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. -#html_use_smartypants = True +# html_use_smartypants = True # Custom sidebar templates, maps document names to template names. -#html_sidebars = {} +# html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. -#html_additional_pages = {} +# html_additional_pages = {} # If false, no module index is generated. -#html_domain_indices = True +# html_domain_indices = True # If false, no index is generated. -#html_use_index = True +# html_use_index = True # If true, the index is split into individual pages for each letter. -#html_split_index = False +# html_split_index = False # If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True +# html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True +# html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True +# html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. -#html_use_opensearch = '' +# html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None +# html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = 'Shibadoc' +htmlhelp_basename = "Shibadoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { -# The paper size ('letterpaper' or 'a4paper'). -#'papersize': 'letterpaper', - -# The font size ('10pt', '11pt' or '12pt'). -#'pointsize': '10pt', - -# Additional stuff for the LaTeX preamble. -#'preamble': '', + # The paper size ('letterpaper' or 'a4paper'). + #'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + #'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - ('index', 'Shiba.tex', u'Shiba Documentation', - u'Maxime Boguta', 'manual'), + ("index", "Shiba.tex", u"Shiba Documentation", u"Maxime Boguta", "manual"), ] # The name of an image file (relative to this directory) to place at the top of # the title page. -#latex_logo = None +# latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. -#latex_use_parts = False +# latex_use_parts = False # If true, show page references after internal links. -#latex_show_pagerefs = False +# latex_show_pagerefs = False # If true, show URL addresses after external links. -#latex_show_urls = False +# latex_show_urls = False # Documents to append as an appendix to all manuals. -#latex_appendices = [] +# latex_appendices = [] # If false, no module index is generated. -#latex_domain_indices = True +# latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'shiba', u'Shiba Documentation', - [u'Maxime Boguta'], 1) -] +man_pages = [("index", "shiba", u"Shiba Documentation", [u"Maxime Boguta"], 1)] # If true, show URL addresses after external links. -#man_show_urls = False +# man_show_urls = False # -- Options for Texinfo output ------------------------------------------- @@ -253,89 +246,95 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - ('index', 'Shiba', u'Shiba Documentation', - u'Maxime Boguta', 'Shiba', 'An Python API for PriceMinister WebServices.', - 'Miscellaneous'), + ( + "index", + "Shiba", + u"Shiba Documentation", + u"Maxime Boguta", + "Shiba", + "An Python API for PriceMinister WebServices.", + "Miscellaneous", + ), ] # Documents to append as an appendix to all manuals. -#texinfo_appendices = [] +# texinfo_appendices = [] # If false, no module index is generated. -#texinfo_domain_indices = True +# texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' +# texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. -#texinfo_no_detailmenu = False +# texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. -epub_title = u'Shiba' -epub_author = u'Maxime Boguta' -epub_publisher = u'Maxime Boguta' -epub_copyright = u'2014, Maxime Boguta' +epub_title = u"Shiba" +epub_author = u"Maxime Boguta" +epub_publisher = u"Maxime Boguta" +epub_copyright = u"2014, Maxime Boguta" # The basename for the epub file. It defaults to the project name. -#epub_basename = u'Shiba' +# epub_basename = u'Shiba' # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. -#epub_theme = 'epub' +# epub_theme = 'epub' # The language of the text. It defaults to the language option # or en if the language is not set. -#epub_language = '' +# epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. -#epub_scheme = '' +# epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. -#epub_identifier = '' +# epub_identifier = '' # A unique identification for the text. -#epub_uid = '' +# epub_uid = '' # A tuple containing the cover image and cover page html template filenames. -#epub_cover = () +# epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. -#epub_guide = () +# epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. -#epub_pre_files = [] +# epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. -#epub_post_files = [] +# epub_post_files = [] # A list of files that should not be packed into the epub file. -epub_exclude_files = ['search.html'] +epub_exclude_files = ["search.html"] # The depth of the table of contents in toc.ncx. -#epub_tocdepth = 3 +# epub_tocdepth = 3 # Allow duplicate toc entries. -#epub_tocdup = True +# epub_tocdup = True # Choose between 'default' and 'includehidden'. -#epub_tocscope = 'default' +# epub_tocscope = 'default' # Fix unsupported image types using the PIL. -#epub_fix_images = False +# epub_fix_images = False # Scale large images. -#epub_max_image_width = 0 +# epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. -#epub_show_urls = 'inline' +# epub_show_urls = 'inline' # If false, no index is generated. -#epub_use_index = True +# epub_use_index = True diff --git a/scripts/bumpversion.py b/scripts/bumpversion.py index 89672c8..a2619af 100755 --- a/scripts/bumpversion.py +++ b/scripts/bumpversion.py @@ -1,6 +1,5 @@ #!/usr/bin/env python # coding: utf-8 -from __future__ import unicode_literals, print_function import sys import os import re @@ -12,38 +11,39 @@ from argparse import RawTextHelpFormatter, ArgumentParser, FileType -if (sys.version_info[0] == 3): +if sys.version_info[0] == 3: bytes = bytes - str = type(u"") + str = type("") basestring = (str, bytes) def is_bytes(x): return isinstance(x, (bytes, memoryview, bytearray)) + else: bytes = str - str = type(u"") + str = type("") basestring = basestring def is_bytes(x): return isinstance(x, (buffer, bytearray)) -def to_unicode(obj, encoding='utf-8'): - """ Convert ``obj`` to unicode""" +def to_unicode(obj, encoding="utf-8"): + """Convert ``obj`` to unicode""" # unicode support if isinstance(obj, str): return obj # bytes support if is_bytes(obj): - if hasattr(obj, 'tobytes'): + if hasattr(obj, "tobytes"): return str(obj.tobytes(), encoding) return str(obj, encoding) # string support if isinstance(obj, basestring): - if hasattr(obj, 'decode'): + if hasattr(obj, "decode"): return obj.decode(encoding) else: return str(obj, encoding) @@ -68,29 +68,32 @@ def get_release_date(): def bump_release_version(args): """Automated software release workflow - * Bumps the release version number (with .bumpversion.cfg) - * Preloads the correct changelog template for editing - * Builds a source distribution - * Sets release date - * Tags the release + * Bumps the release version number (with .bumpversion.cfg) + * Preloads the correct changelog template for editing + * Builds a source distribution + * Sets release date + * Tags the release -You can run it like:: + You can run it like:: - $ python bumpversion.py + $ python bumpversion.py -which will create a 'release' version (Eg. 0.7.2-dev => 0.7.2). + which will create a 'release' version (Eg. 0.7.2-dev => 0.7.2). """ # Dry run 'bumpversion' to find out what the new version number # would be. Useful side effect: exits if the working directory is not # clean. changelog = args.changelog.name - bumpver = to_unicode(subprocess.check_output( - ['bumpversion', 'release', '--dry-run', '--verbose'], - stderr=subprocess.STDOUT)) - m = re.search(r'Parsing version \'(\d+\.\d+\.\d+)\.dev0\'', bumpver) + bumpver = to_unicode( + subprocess.check_output( + ["bumpversion", "release", "--dry-run", "--verbose"], + stderr=subprocess.STDOUT, + ) + ) + m = re.search(r"Parsing version \'(\d+\.\d+\.\d+)\.dev0\'", bumpver) current_version = m.groups(0)[0] + ".dev0" - m = re.search(r'New version will be \'(\d+\.\d+\.\d+)\'', bumpver) + m = re.search(r"New version will be \'(\d+\.\d+\.\d+)\'", bumpver) release_version = m.groups(0)[0] date = get_release_date() @@ -101,27 +104,29 @@ def bump_release_version(args): with open(changelog) as fd: changes += fd.read() - changes = changes.replace(current_version_title, release_version_title)\ - .replace("**unreleased**", "Released on %s" % date) + changes = changes.replace(current_version_title, release_version_title).replace( + "**unreleased**", "Released on %s" % date + ) with open(changelog, "w") as fd: - fd.write(changes) + fd.write(changes) # Tries to load the EDITOR environment variable, else falls back to vim - editor = os.environ.get('EDITOR', 'vim') + editor = os.environ.get("EDITOR", "vim") os.system("{} {}".format(editor, changelog)) - subprocess.check_output(['python', 'setup.py', 'sdist']) + subprocess.check_output(["python", "setup.py", "sdist"]) # Have to add it so it will be part of the commit - subprocess.check_output(['git', 'add', changelog]) + subprocess.check_output(["git", "add", changelog]) subprocess.check_output( - ['git', 'commit', '-m', 'Changelog for {}'.format(release_version)]) + ["git", "commit", "-m", "Changelog for {}".format(release_version)] + ) # Really run bumpver to set the new release and tag - bv_args = ['bumpversion', 'release'] + bv_args = ["bumpversion", "release"] - bv_args += ['--new-version', release_version] + bv_args += ["--new-version", release_version] subprocess.check_output(bv_args) @@ -129,32 +134,34 @@ def bump_release_version(args): def bump_new_version(args): """Increment the version number to the next development version - * Bumps the development version number (with .bumpversion.cfg) - * Preloads the correct changelog template for editing + * Bumps the development version number (with .bumpversion.cfg) + * Preloads the correct changelog template for editing -You can run it like:: + You can run it like:: - $ python bumpversion.py newversion + $ python bumpversion.py newversion -which, by default, will create a 'patch' dev version (0.0.1 => 0.0.2-dev). + which, by default, will create a 'patch' dev version (0.0.1 => 0.0.2-dev). -You can also specify a patch level (patch, minor, major) to change to:: + You can also specify a patch level (patch, minor, major) to change to:: - $ python bumpversion.py newversion major + $ python bumpversion.py newversion major -which will create a 'major' release (0.0.2 => 1.0.0-dev).""" + which will create a 'major' release (0.0.2 => 1.0.0-dev).""" pass # Dry run 'bumpversion' to find out what the new version number # would be. Useful side effect: exits if the working directory is not # clean. changelog = args.changelog.name part = args.part - bumpver = to_unicode(subprocess.check_output( - ['bumpversion', part, '--dry-run', '--verbose'], - stderr=subprocess.STDOUT)) - m = re.search(r'Parsing version \'(\d+\.\d+\.\d+)\'', bumpver) + bumpver = to_unicode( + subprocess.check_output( + ["bumpversion", part, "--dry-run", "--verbose"], stderr=subprocess.STDOUT + ) + ) + m = re.search(r"Parsing version \'(\d+\.\d+\.\d+)\'", bumpver) current_version = m.groups(0)[0] - m = re.search(r'New version will be \'(\d+\.\d+\.\d+)\.dev0\'', bumpver) + m = re.search(r"New version will be \'(\d+\.\d+\.\d+)\.dev0\'", bumpver) next_version = m.groups(0)[0] + ".dev0" current_version_title = generate_changelog_title(current_version) @@ -166,61 +173,72 @@ def bump_new_version(args): with open(changelog) as fd: changes += fd.read() - changes = changes.replace(current_version_title, - next_release_template + current_version_title) + changes = changes.replace( + current_version_title, next_release_template + current_version_title + ) with open(changelog, "w") as fd: - fd.write(changes) + fd.write(changes) # Tries to load the EDITOR environment variable, else falls back to vim - editor = os.environ.get('EDITOR', 'vim') + editor = os.environ.get("EDITOR", "vim") os.system("{} {}".format(editor, changelog)) - subprocess.check_output(['python', 'setup.py', 'sdist']) + subprocess.check_output(["python", "setup.py", "sdist"]) # Have to add it so it will be part of the commit - subprocess.check_output(['git', 'add', changelog]) + subprocess.check_output(["git", "add", changelog]) subprocess.check_output( - ['git', 'commit', '-m', 'Changelog for {}'.format(next_version)]) + ["git", "commit", "-m", "Changelog for {}".format(next_version)] + ) # Really run bumpver to set the new release and tag - bv_args = ['bumpversion', part, '--no-tag', '--new-version', next_version] + bv_args = ["bumpversion", part, "--no-tag", "--new-version", next_version] subprocess.check_output(bv_args) def main(): - '''Parse command-line arguments and execute bumpversion command.''' + """Parse command-line arguments and execute bumpversion command.""" - parser = ArgumentParser(prog='bumpversion', - description='Bumpversion wrapper') + parser = ArgumentParser(prog="bumpversion", description="Bumpversion wrapper") - default_changelog = os.path.join(os.getcwd(), 'CHANGES.rst') + default_changelog = os.path.join(os.getcwd(), "CHANGES.rst") - subparsers = parser.add_subparsers(title='bumpversion wrapper commands') + subparsers = parser.add_subparsers(title="bumpversion wrapper commands") # release command release_doc = bump_release_version.__doc__ - subparser = subparsers.add_parser("release", - description=release_doc, - formatter_class=RawTextHelpFormatter) - subparser.add_argument('--changelog', help='Project changelog', - type=FileType(), - default=default_changelog) + subparser = subparsers.add_parser( + "release", description=release_doc, formatter_class=RawTextHelpFormatter + ) + subparser.add_argument( + "--changelog", + help="Project changelog", + type=FileType(), + default=default_changelog, + ) subparser.set_defaults(func=bump_release_version) # newversion command newversion_doc = bump_new_version.__doc__ - subparser = subparsers.add_parser("newversion", - description=newversion_doc, - formatter_class=RawTextHelpFormatter) - subparser.add_argument('--changelog', help='Project changelog', - type=FileType(), - default=default_changelog) - subparser.add_argument('part', help='Part of the version to be bumped', - choices=['patch', 'minor', 'major']) + subparser = subparsers.add_parser( + "newversion", description=newversion_doc, formatter_class=RawTextHelpFormatter + ) + subparser.add_argument( + "--changelog", + help="Project changelog", + type=FileType(), + default=default_changelog, + ) + subparser.add_argument( + "part", + help="Part of the version to be bumped", + choices=["patch", "minor", "major"], + ) subparser.set_defaults(func=bump_new_version) # Parse argv arguments args = parser.parse_args() args.func(args) -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/setup.cfg b/setup.cfg index e12105e..5b677ed 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,7 +1,7 @@ [bumpversion] commit = True tag = True -current_version = 1.1.12 +current_version = 1.2.0 parse = (?P\d+)\.(?P\d+)\.(?P\d+)(\.(?P[a-z]+\d+))? serialize = {major}.{minor}.{patch}.{release} diff --git a/setup.py b/setup.py index ed3e296..08d34c3 100644 --- a/setup.py +++ b/setup.py @@ -9,14 +9,14 @@ def read(fname): - ''' Return the file content. ''' + """Return the file content.""" here = op.abspath(op.dirname(__file__)) - with open(op.join(here, fname), 'r', 'utf-8') as fd: + with open(op.join(here, fname), "r", "utf-8") as fd: return fd.read() -readme = read('README.rst') -changelog = read('CHANGES.rst').replace('.. :changelog:', '') +readme = read("README.rst") +changelog = read("CHANGES.rst").replace(".. :changelog:", "") requirements = [ "requests", @@ -26,34 +26,35 @@ def read(fname): "ftfy", ] -version = '' -version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', - read(op.join('shiba', '__init__.py')), - re.MULTILINE).group(1) +version = "" +version = re.search( + r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', + read(op.join("shiba", "__init__.py")), + re.MULTILINE, +).group(1) if not version: - raise RuntimeError('Cannot find version information') + raise RuntimeError("Cannot find version information") setup( - name='Shiba', - author="Maxime Boguta", - author_email="maxime.boguta@epitech.eu", + name="Shiba", + author="Nicolas Baccelli", + author_email="nicolas.baccelli@abc-culturel.fr", version=version, - url='https://github.com/ShibaAPI/shiba', + url="https://github.com/ShibaAPI/shiba", packages=["shiba"], install_requires=requirements, zip_safe=True, description="A Python API for PriceMinister WebServices", - long_description=readme + '\n\n' + changelog, + long_description=readme + "\n\n" + changelog, keywords=["api", "priceminister", "python", "webservices"], - license='GPLv3', + license="GPLv3", classifiers=[ - 'Development Status :: 4 - Beta', - 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', - 'Intended Audience :: Developers', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: Implementation :: CPython', - 'Topic :: Software Development :: Libraries :: Python Modules', + "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", + "Intended Audience :: Developers", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: Implementation :: CPython", + "Topic :: Software Development :: Libraries :: Python Modules", ], ) diff --git a/shiba/__init__.py b/shiba/__init__.py index d55b6c2..1091dc1 100644 --- a/shiba/__init__.py +++ b/shiba/__init__.py @@ -1,2 +1,2 @@ -__version__ = '1.1.12' +__version__ = "1.2.0" VERSION = __version__ diff --git a/shiba/accountingmanagement.py b/shiba/accountingmanagement.py index 65f18e3..82f3c2e 100644 --- a/shiba/accountingmanagement.py +++ b/shiba/accountingmanagement.py @@ -1,6 +1,4 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals - from datetime import date from .shibaconnection import ShibaConnection @@ -10,13 +8,15 @@ class AccountingManagement(object): - """ Accounting Management class, showing global financial operations on your account, or specific financial details - about an operation + """Accounting Management class, showing global financial operations on your account, or specific financial details + about an operation """ def __init__(self, connection): if not isinstance(connection, ShibaConnection): - raise ValueError("expecting a ShibaConnection instance, got '%s'" % type(connection)) + raise ValueError( + "expecting a ShibaConnection instance, got '%s'" % type(connection) + ) self.connection = connection def get_operations(self, lastoperationdate=""): @@ -27,8 +27,13 @@ def get_operations(self, lastoperationdate=""): """ operationcause = "salestransfer" - if not isinstance(lastoperationdate, date) and not isinstance(lastoperationdate, basestring): - raise ValueError("expected string or date for 'lastoperationdate', got '%s'" % type(lastoperationdate)) + if not isinstance(lastoperationdate, date) and not isinstance( + lastoperationdate, basestring + ): + raise ValueError( + "expected string or date for 'lastoperationdate', got '%s'" + % type(lastoperationdate) + ) if isinstance(lastoperationdate, date): lastoperationdate = lastoperationdate.strftime("%d/%m/%y-%H:%M:%S") diff --git a/shiba/compat.py b/shiba/compat.py index f856524..3427df0 100644 --- a/shiba/compat.py +++ b/shiba/compat.py @@ -5,23 +5,24 @@ _ver = sys.version_info #: Python 2.x? -is_py2 = (_ver[0] == 2) +is_py2 = _ver[0] == 2 #: Python 3.x? -is_py3 = (_ver[0] == 3) +is_py3 = _ver[0] == 3 #: Python 3.3.x -is_py33 = (is_py3 and _ver[1] == 3) +is_py33 = is_py3 and _ver[1] == 3 #: Python 3.4.x -is_py34 = (is_py3 and _ver[1] == 4) +is_py34 = is_py3 and _ver[1] == 4 #: Python 2.7.x -is_py27 = (is_py2 and _ver[1] == 7) +is_py27 = is_py2 and _ver[1] == 7 try: # pragma: no cover import __pypy__ + is_pypy = True except: # pragma: no cover __pypy__ = None @@ -33,8 +34,8 @@ str = str bytes = bytes basestring = (str, bytes) - integer_types = (int, ) - numeric_types = integer_types + (float, ) + integer_types = (int,) + numeric_types = integer_types + (float,) def iterkeys(d): return iter(d.keys()) @@ -53,18 +54,19 @@ def reraise(tp, value, tb=None): def is_bytes(x): return isinstance(x, (bytes, memoryview, bytearray)) - from collections import Callable + from collections.abc import Callable def callable(obj): return isinstance(obj, Callable) + else: builtin_str = str bytes = str str = unicode basestring = basestring integer_types = (int, long) - numeric_types = integer_types + (float, ) + numeric_types = integer_types + (float,) def iterkeys(d): return d.iterkeys() @@ -75,7 +77,7 @@ def itervalues(d): def iteritems(d): return d.iteritems() - exec('def reraise(tp, value, tb=None):\n raise tp, value, tb') + exec("def reraise(tp, value, tb=None):\n raise tp, value, tb") def is_bytes(x): return isinstance(x, (buffer, bytearray)) @@ -87,7 +89,7 @@ def with_metaclass(meta, base=object): return meta("NewBase", (base,), {}) -def to_unicode(obj, encoding='utf-8', errors='strict'): +def to_unicode(obj, encoding="utf-8", errors="strict"): """ Convert ``obj`` to unicode""" # unicode support @@ -96,13 +98,13 @@ def to_unicode(obj, encoding='utf-8', errors='strict'): # bytes support if is_bytes(obj): - if hasattr(obj, 'tobytes'): + if hasattr(obj, "tobytes"): return str(obj.tobytes(), encoding, errors=errors) return str(obj, encoding, errors=errors) # string support if isinstance(obj, basestring): - if hasattr(obj, 'decode'): + if hasattr(obj, "decode"): return obj.decode(encoding, errors=errors) else: return str(obj, encoding, errors=errors) diff --git a/shiba/inventorymanagement.py b/shiba/inventorymanagement.py index 7e0944c..14f4b20 100644 --- a/shiba/inventorymanagement.py +++ b/shiba/inventorymanagement.py @@ -1,17 +1,23 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals - from .shibaconnection import ShibaConnection from .shibaexceptions import ShibaCallingError -from .shibatools import inf_constructor, url_constructor, retrieve_obj_from_url, create_xml_from_item_obj +from .shibatools import ( + inf_constructor, + url_constructor, + retrieve_obj_from_url, + create_xml_from_item_obj, +) class InventoryManagement(object): """This class permits you to manage your inventory, get information about your products and even import products from XML to the PriceMinister platform""" + def __init__(self, connection): if isinstance(connection, ShibaConnection) is False: - raise ShibaCallingError("Shiba subclass init error : expecting a ShibaConnection instance") + raise ShibaCallingError( + "Shiba subclass init error : expecting a ShibaConnection instance" + ) self.connection = connection def product_types(self): @@ -46,7 +52,7 @@ def generic_import_report(self, fileid, nexttoken=""): obj = retrieve_obj_from_url(url) return obj - def generic_import_file(self, data,skip=False): + def generic_import_file(self, data, skip=False): """Import XML file to your PriceMinister inventory trough a POST request. :param data: must be a object/dict (OrderedDict is better) containing your inventory wished to be imported. \ diff --git a/shiba/marketplacemanagement.py b/shiba/marketplacemanagement.py index f53d5fe..8466455 100644 --- a/shiba/marketplacemanagement.py +++ b/shiba/marketplacemanagement.py @@ -1,20 +1,29 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals - from .shibaconnection import ShibaConnection from .shibatools import inf_constructor, url_constructor, retrieve_obj_from_url from .compat import basestring class MarketplaceManagement(object): - """ Marketplace informations retrieving, such as product lists and category mapping""" + """Marketplace informations retrieving, such as product lists and category mapping""" def __init__(self, connection): if not isinstance(connection, ShibaConnection): - raise ValueError("expecting a ShibaConnection instance, got '%s'" % type(connection)) + raise ValueError( + "expecting a ShibaConnection instance, got '%s'" % type(connection) + ) self.connection = connection - def get_product_list(self, scope="", kw="", nav="", refs="", productids="", nbproductsperpage="", pagenumber=""): + def get_product_list( + self, + scope="", + kw="", + nav="", + refs="", + productids="", + nbproductsperpage="", + pagenumber="", + ): """Prints a search list result from given parameters. :param scope: none (classic results), "PRICING" (classic results plus 10 best announces) @@ -27,16 +36,20 @@ def get_product_list(self, scope="", kw="", nav="", refs="", productids="", nbpr :param pagenumber: page number, default is 1. """ if not isinstance(refs, basestring) and not isinstance(refs, list): - raise ValueError("expected string or list for 'refs', got '%s'" % type(refs)) + raise ValueError( + "expected string or list for 'refs', got '%s'" % type(refs) + ) if not isinstance(productids, basestring) and not isinstance(productids, list): - raise ValueError("expected string or list for 'productids', got '%s'" % type(productids)) + raise ValueError( + "expected string or list for 'productids', got '%s'" % type(productids) + ) if isinstance(refs, list): - refs = ','.join(refs) + refs = ",".join(refs) if isinstance(productids, list): - productids = ','.join(productids) - if kw != u'': + productids = ",".join(productids) + if kw != "": # TODO: and ??? pass inf = inf_constructor(self.connection, "listing", **locals()) @@ -47,6 +60,8 @@ def get_product_list(self, scope="", kw="", nav="", refs="", productids="", nbpr def get_category_map(self): """Lists items categories from the PriceMinister platform""" inf = inf_constructor(self.connection, "categorymap", **locals()) - url = url_constructor(self.connection, inf, domain="https://ws.fr.shopping.rakuten.com") + url = url_constructor( + self.connection, inf, domain="https://ws.fr.shopping.rakuten.com" + ) obj = retrieve_obj_from_url(url) return obj diff --git a/shiba/salesmanagement.py b/shiba/salesmanagement.py index 98f9d10..813dfe4 100644 --- a/shiba/salesmanagement.py +++ b/shiba/salesmanagement.py @@ -1,6 +1,4 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals - from datetime import date from .shibaconnection import ShibaConnection @@ -11,9 +9,12 @@ class SalesManagement(object): """Primary sales management class, gather all sales-related methods.""" + def __init__(self, connection): if (isinstance(connection, ShibaConnection)) is False: - raise ShibaCallingError("error : you must give this class a ShibaConnection instance") + raise ShibaCallingError( + "error : you must give this class a ShibaConnection instance" + ) self.connection = connection def get_new_sales(self): @@ -23,10 +24,11 @@ def get_new_sales(self): obj = retrieve_obj_from_url(url) return obj - def accept_sale(self, itemid): + def accept_sale(self, itemid, shippingfromcountry): """Accept the "itemid" sale. :param itemid: string for item ID + :param shippingfromcountry: string ISO code for country """ inf = inf_constructor(self.connection, "acceptsale", **locals()) url = url_constructor(self.connection, inf) @@ -53,8 +55,13 @@ def get_current_sales(self, ispendingpreorder="", purchasedate="", nexttoken="") if ispendingpreorder != "" and ispendingpreorder != "y": raise ShibaCallingError("ispendingpreorder parameter must be empty or 'y'") - if not isinstance(purchasedate, date) and not isinstance(purchasedate, basestring): - raise ValueError("expected string or date for 'purchasedate', got '%s'" % type(purchasedate)) + if not isinstance(purchasedate, date) and not isinstance( + purchasedate, basestring + ): + raise ValueError( + "expected string or date for 'purchasedate', got '%s'" + % type(purchasedate) + ) if isinstance(purchasedate, date): purchasedate = purchasedate.strftime("%d/%m/%y-%H:%M:%S") @@ -140,7 +147,9 @@ def contact_user_about_item(self, itemid, content): obj = retrieve_obj_from_url(url) return obj - def set_tracking_package_infos(self, itemid, transporter_name, tracking_number, tracking_url=""): + def set_tracking_package_infos( + self, itemid, transporter_name, tracking_number, tracking_url="" + ): """Send to buyer tracking information, such as the transporter's name "transporter_name", tracking number "tracking_number" and the optional tracking url "tracking_url". Please note that giving "Autre" as transporter_name brings the tracking url as mandatory. @@ -152,8 +161,10 @@ def set_tracking_package_infos(self, itemid, transporter_name, tracking_number, :param tracking_url: tracking URL for the package, as string, mandatory if transporter_name is 'Autre' """ if transporter_name == "Autre" and len(tracking_url) == 0: - raise ShibaCallingError("Shiba code error : if 'Autre' is specified as transporter_name, a tracking_url " - "must be specified too") + raise ShibaCallingError( + "Shiba code error : if 'Autre' is specified as transporter_name, a tracking_url " + "must be specified too" + ) inf = inf_constructor(self.connection, "settrackingpackageinfos", **locals()) url = url_constructor(self.connection, inf) obj = retrieve_obj_from_url(url) @@ -167,7 +178,9 @@ def confirm_preorder(self, advertid, stock): :param stock: string or integer, must be positive """ if int(stock) <= 0: - raise ShibaCallingError("Shiba code error : stock must be a positive number") + raise ShibaCallingError( + "Shiba code error : stock must be a positive number" + ) inf = inf_constructor(self.connection, "confirmpreorder", **locals()) url = url_constructor(self.connection, inf) obj = retrieve_obj_from_url(url) diff --git a/shiba/shibaconnection.py b/shiba/shibaconnection.py index 3c0b575..b265e13 100644 --- a/shiba/shibaconnection.py +++ b/shiba/shibaconnection.py @@ -1,6 +1,4 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals - class ShibaConnection(object): """The main Shiba class, standing as an initialization and mandatory for each submodules instancing. @@ -14,34 +12,148 @@ class ShibaConnection(object): def __init__(self, login, pwd, sandbox=False): self.login = str(login) self.pwd = str(pwd) - self.domain = "https://ws.fr.shopping.rakuten.com" if sandbox is False else "https://ws.fr.shopping.rakuten.com" + self.domain = ( + "https://ws.fr.shopping.rakuten.com" + if sandbox is False + else "https://ws.fr.shopping.rakuten.com" + ) self.actionsinfo = { - "producttypes": {"cat": "stock_ws", "version": "2015-06-30", "login": self.login, "pwd": self.pwd}, - "producttypetemplate": {"cat": "stock_ws", "version": "2017-10-04", "login": self.login, "pwd": self.pwd}, - "genericimportfile": {"cat": "stock_ws", "version": "2015-02-02", "login": self.login, "pwd": self.pwd}, - "genericimportreport": {"cat": "stock_ws", "version": "2017-02-10", "login": self.login, "pwd": self.pwd}, - "getavailableshippingtypes": {"cat": "sales_ws", "version": "2013-06-25", "login": self.login, - "pwd": self.pwd}, - "export": {"cat": "stock_ws", "version": "2018-06-29", "login": self.login, "pwd": self.pwd}, - "listing": {"cat": "listing_ssl_ws", "version": "2018-06-28", "login": self.login, "pwd": self.pwd}, - "categorymap": {"cat": "categorymap_ws", "version": "2011-10-11", "login": self.login, "pwd": self.pwd}, - "getnewsales": {"cat": "sales_ws", "version": "2017-08-07", "login": self.login, "pwd": self.pwd}, - "acceptsale": {"cat": "sales_ws", "version": "2010-09-20", "login": self.login, "pwd": self.pwd}, - "refusesale": {"cat": "sales_ws", "version": "2010-09-20", "login": self.login, "pwd": self.pwd}, - "getcurrentsales": {"cat": "sales_ws", "version": "2017-08-07", "login": self.login, "pwd": self.pwd}, - "getbillinginformation": {"cat": "sales_ws", "version": "2016-03-16", "login": self.login, - "pwd": self.pwd}, - "getshippinginformation": {"cat": "sales_ws", "version": "2017-09-12", "login": self.login, - "pwd": self.pwd}, - "getitemtodolist": {"cat": "sales_ws", "version": "2011-09-01", "login": self.login, "pwd": self.pwd}, - "getiteminfos": {"cat": "sales_ws", "version": "2017-08-07", "login": self.login, "pwd": self.pwd}, - "cancelitem": {"cat": "sales_ws", "version": "2011-02-02", "login": self.login, "pwd": self.pwd}, - "contactusaboutitem": {"cat": "sales_ws", "version": "2011-09-01", "login": self.login, "pwd": self.pwd}, - "contactuseraboutitem": {"cat": "sales_ws", "version": "2011-02-02", "login": self.login, "pwd": self.pwd}, - "settrackingpackageinfos": {"cat": "sales_ws", "version": "2016-03-16", "login": self.login, - "pwd": self.pwd}, - "confirmpreorder": {"cat": "sales_ws", "version": "2013-01-09", "login": self.login, "pwd": self.pwd}, - "getoperations": {"cat": "wallet_ws", "version": "2011-03-29", "login": self.login, "pwd": self.pwd}, - "getcompensationdetails": {"cat": "sales_ws", "version": "2011-03-29", "login": self.login, - "pwd": self.pwd} + "producttypes": { + "cat": "stock_ws", + "version": "2015-06-30", + "login": self.login, + "pwd": self.pwd, + }, + "producttypetemplate": { + "cat": "stock_ws", + "version": "2017-10-04", + "login": self.login, + "pwd": self.pwd, + }, + "genericimportfile": { + "cat": "stock_ws", + "version": "2015-02-02", + "login": self.login, + "pwd": self.pwd, + }, + "genericimportreport": { + "cat": "stock_ws", + "version": "2017-02-10", + "login": self.login, + "pwd": self.pwd, + }, + "getavailableshippingtypes": { + "cat": "sales_ws", + "version": "2013-06-25", + "login": self.login, + "pwd": self.pwd, + }, + "export": { + "cat": "stock_ws", + "version": "2018-06-29", + "login": self.login, + "pwd": self.pwd, + }, + "listing": { + "cat": "listing_ssl_ws", + "version": "2018-06-28", + "login": self.login, + "pwd": self.pwd, + }, + "categorymap": { + "cat": "categorymap_ws", + "version": "2011-10-11", + "login": self.login, + "pwd": self.pwd, + }, + "getnewsales": { + "cat": "sales_ws", + "version": "2017-08-07", + "login": self.login, + "pwd": self.pwd, + }, + "acceptsale": { + "cat": "sales_ws", + "version": "2021-04-08", + "login": self.login, + "pwd": self.pwd, + }, + "refusesale": { + "cat": "sales_ws", + "version": "2010-09-20", + "login": self.login, + "pwd": self.pwd, + }, + "getcurrentsales": { + "cat": "sales_ws", + "version": "2017-08-07", + "login": self.login, + "pwd": self.pwd, + }, + "getbillinginformation": { + "cat": "sales_ws", + "version": "2016-03-16", + "login": self.login, + "pwd": self.pwd, + }, + "getshippinginformation": { + "cat": "sales_ws", + "version": "2017-09-12", + "login": self.login, + "pwd": self.pwd, + }, + "getitemtodolist": { + "cat": "sales_ws", + "version": "2011-09-01", + "login": self.login, + "pwd": self.pwd, + }, + "getiteminfos": { + "cat": "sales_ws", + "version": "2017-08-07", + "login": self.login, + "pwd": self.pwd, + }, + "cancelitem": { + "cat": "sales_ws", + "version": "2011-02-02", + "login": self.login, + "pwd": self.pwd, + }, + "contactusaboutitem": { + "cat": "sales_ws", + "version": "2011-09-01", + "login": self.login, + "pwd": self.pwd, + }, + "contactuseraboutitem": { + "cat": "sales_ws", + "version": "2011-02-02", + "login": self.login, + "pwd": self.pwd, + }, + "settrackingpackageinfos": { + "cat": "sales_ws", + "version": "2016-03-16", + "login": self.login, + "pwd": self.pwd, + }, + "confirmpreorder": { + "cat": "sales_ws", + "version": "2013-01-09", + "login": self.login, + "pwd": self.pwd, + }, + "getoperations": { + "cat": "wallet_ws", + "version": "2011-03-29", + "login": self.login, + "pwd": self.pwd, + }, + "getcompensationdetails": { + "cat": "sales_ws", + "version": "2011-03-29", + "login": self.login, + "pwd": self.pwd, + }, } diff --git a/shiba/shibaexceptions.py b/shiba/shibaexceptions.py index e0be3e5..bb9e550 100644 --- a/shiba/shibaexceptions.py +++ b/shiba/shibaexceptions.py @@ -1,20 +1,21 @@ # -*- coding: utf-8 -*- """ Those exception classes will usually be raised after an error returned from the WebServices.""" -from __future__ import unicode_literals - class ShibaException(Exception): """Main exception class, as you can catch the whole of Shiba exceptions from it""" + pass class ShibaParameterError(ShibaException): """Shiba parameter error, XML returned from the WebService told that one or more parameters are incorrect.""" + pass class ShibaLoginError(ShibaException): """Shiba login error, XML returned from the WebService told that the login informations given are incorrect.""" + pass @@ -25,27 +26,32 @@ class ShibaRightsError(ShibaException): class ShibaServiceError(ShibaException): """Shiba service error, WebService told that an error have been encountered, but may can't precise where""" + pass class ShibaUnknownServiceError(ShibaException): """Shiba unknown service error, WebService has caused/encoutered an error, but we can't know why (followed by a rough print of the XML retrieved""" + pass class ShibaConnectionError(ShibaException): """Shiba connection error, kind of an internal error: URL can't be reached, in case of bad URL formatting or internet connection failure (HTTP errors 404, 500...).""" + pass class ShibaCallingError(ShibaException): """Shiba internal error, for code relative errors. If such an exception is raised, look at given parameters to the API methods first as this is the major exception raising point for this type of exception""" + pass class ShibaQuotaExceededError(ShibaException): """Shiba throtlle error, you have sumbitted too many request of a type within a certain amount of time""" + pass diff --git a/shiba/shibaresponseobject.py b/shiba/shibaresponseobject.py index 5911d35..173a72d 100644 --- a/shiba/shibaresponseobject.py +++ b/shiba/shibaresponseobject.py @@ -1,6 +1,4 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals - class ShibaResponseObject(object): """This class gathers all content from the returned XML. Separating the namespace for further usage and the actual diff --git a/shiba/shibatools.py b/shiba/shibatools.py index 40b8738..b1a032b 100644 --- a/shiba/shibatools.py +++ b/shiba/shibatools.py @@ -1,7 +1,5 @@ # -*- coding: utf-8 -*- """ Tools used by Shiba data retrieving classes""" -from __future__ import unicode_literals - import re from collections import OrderedDict @@ -17,9 +15,16 @@ from .shibaconnection import ShibaConnection from .shibaresponseobject import ShibaResponseObject -from .shibaexceptions import (ShibaParameterError, ShibaLoginError, ShibaQuotaExceededError, - ShibaRightsError, ShibaConnectionError, ShibaUnknownServiceError, ShibaServiceError, - ShibaCallingError) +from .shibaexceptions import ( + ShibaParameterError, + ShibaLoginError, + ShibaQuotaExceededError, + ShibaRightsError, + ShibaConnectionError, + ShibaUnknownServiceError, + ShibaServiceError, + ShibaCallingError, +) from http.client import HTTPException @@ -31,8 +36,10 @@ def post_request(url, data): :rtype: plain text from servers response """ - header = {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 6.1; de-DE; rv:1.9.0.10) " - "Gecko/2009042316 Firefox/3.0.10 (.NET CLR 4.0.20506)"} + header = { + "User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 6.1; de-DE; rv:1.9.0.10) " + "Gecko/2009042316 Firefox/3.0.10 (.NET CLR 4.0.20506)" + } d = {"file": data} r = requests.post(url, files=d, headers=header) return r.text @@ -67,8 +74,8 @@ def retrieve_obj_from_url(url, data=None): else: namespace = "" - xmlepured = re.sub(pattern=' xmlns="[^"]+"', repl='', string=xml, flags=0) - xmlepured = fix_text(xmlepured).encode('utf-8') + xmlepured = re.sub(pattern=' xmlns="[^"]+"', repl="", string=xml, flags=0) + xmlepured = fix_text(xmlepured).encode("utf-8") try: obj = objectify.fromstring(xmlepured) @@ -79,15 +86,24 @@ def retrieve_obj_from_url(url, data=None): if _check_errors(obj) is not False: try: if "Unknown error" == obj.error.code: - raise ShibaServiceError("Unknown error from WebService (maybe the sale isn't confirmed yet?)" - " : " + obj.error.message + " - Reason : " + obj.error.details.detail) + raise ShibaServiceError( + "Unknown error from WebService (maybe the sale isn't confirmed yet?)" + " : " + + obj.error.message + + " - Reason : " + + obj.error.details.detail + ) except ShibaServiceError: - raise ShibaServiceError("Unknown error from WebService (maybe the sale isn't confirmed yet?)" - " : " + obj.error.message + " - Reason : " + obj.error.details.detail) + raise ShibaServiceError( + "Unknown error from WebService (maybe the sale isn't confirmed yet?)" + " : " + obj.error.message + " - Reason : " + obj.error.details.detail + ) except Exception: - raise ShibaUnknownServiceError("An unknown error from the WebService has occurred - XML dump : " + - etree.tostring(obj)) - return ShibaResponseObject(namespace, obj, xml.encode('utf-8')) + raise ShibaUnknownServiceError( + "An unknown error from the WebService has occurred - XML dump : " + + etree.tostring(obj) + ) + return ShibaResponseObject(namespace, obj, xml.encode("utf-8")) def create_xml_from_item_obj(inv): @@ -104,12 +120,16 @@ def create_xml_from_item_obj(inv): try: return xmltodict.unparse(inv) except Exception: - raise ShibaCallingError("error from dictionary to xml : can't create XML from dictionary," - " refers to xmltodict documentation" - "(you don't need to add a root element 'items' to your items)") + raise ShibaCallingError( + "error from dictionary to xml : can't create XML from dictionary," + " refers to xmltodict documentation" + "(you don't need to add a root element 'items' to your items)" + ) else: - raise ShibaCallingError("error : bad input parameter given, " - "expecting dict, objectify object or ElementTree element") + raise ShibaCallingError( + "error : bad input parameter given, " + "expecting dict, objectify object or ElementTree element" + ) def inf_constructor(shibaconnection, action, **kwargs): @@ -122,11 +142,16 @@ def inf_constructor(shibaconnection, action, **kwargs): :rtype epured and updated dict """ if isinstance(shibaconnection, ShibaConnection) is False: - raise ShibaCallingError("Internal parameter error : shibaconnection parameter is not " - "a ShibaConnection instance") + raise ShibaCallingError( + "Internal parameter error : shibaconnection parameter is not " + "a ShibaConnection instance" + ) if action not in shibaconnection.actionsinfo: - raise ShibaCallingError("Internal parameter error : action parameter " + - action + " is unknown from the actions list") + raise ShibaCallingError( + "Internal parameter error : action parameter " + + action + + " is unknown from the actions list" + ) newkwargs = {} for each in kwargs: if kwargs[each] is not None and kwargs[each] != "": @@ -164,20 +189,40 @@ def _check_errors(obj): """ if "errorresponse" in obj.tag: if "ServerError" == obj.error.code: - raise ShibaParameterError("Parameter error : " + obj.error.message + - " - Reason : " + obj.error.details.detail) + raise ShibaParameterError( + "Parameter error : " + + obj.error.message + + " - Reason : " + + obj.error.details.detail + ) if "ParameterError" == obj.error.code: - raise ShibaParameterError("Parameter error : " + obj.error.message + - " - Reason : " + obj.error.details.detail) + raise ShibaParameterError( + "Parameter error : " + + obj.error.message + + " - Reason : " + + obj.error.details.detail + ) if "InvalidUserConnection" == obj.error.code: - raise ShibaLoginError("Invalid user connection : " + obj.error.message + - " - Reason : " + obj.error.details.detail) + raise ShibaLoginError( + "Invalid user connection : " + + obj.error.message + + " - Reason : " + + obj.error.details.detail + ) if "InvalidUserRights" == obj.error.code: if "Quota exceeded" in obj.error.message.text: - raise ShibaQuotaExceededError("Too many requests : " + obj.error.message + - " - Reason : " + obj.error.details.detail) + raise ShibaQuotaExceededError( + "Too many requests : " + + obj.error.message + + " - Reason : " + + obj.error.details.detail + ) else: - raise ShibaRightsError("Invalid user rights : " + obj.error.message + - " - Reason : " + obj.error.details.detail) + raise ShibaRightsError( + "Invalid user rights : " + + obj.error.message + + " - Reason : " + + obj.error.details.detail + ) return obj return False diff --git a/tests/offline/Assets/sample_accept_sale.xml b/tests/offline/Assets/sample_accept_sale.xml index 500b723..f0fc2ca 100644 --- a/tests/offline/Assets/sample_accept_sale.xml +++ b/tests/offline/Assets/sample_accept_sale.xml @@ -1,11 +1,19 @@ - - - vendeur - 2010-09-20 - 1046920728 + + + 2021-04-08 + uuyu + 589871029 + 156 + 56 - 2010-09-20 - Refused + 2021-04-08 + Accepted + 156 + 56 + + myOSSType + myOSSValue + - \ No newline at end of file + diff --git a/tests/offline/__init__.py b/tests/offline/__init__.py index 4e74f42..efab47f 100644 --- a/tests/offline/__init__.py +++ b/tests/offline/__init__.py @@ -1,5 +1,4 @@ # coding: utf-8 -from __future__ import unicode_literals, print_function import os import pytest @@ -12,16 +11,26 @@ def make_requests_get_mock(filename): def mockreturn(*args, **kwargs): response = Response() - with open(os.path.join(os.path.dirname(__file__), 'Assets', filename), 'r', 'ISO-8859-1') as fd: - response._content = fd.read().encode('utf-8') + with open( + os.path.join(os.path.dirname(__file__), "Assets", filename), + "r", + "ISO-8859-1", + ) as fd: + response._content = fd.read().encode("utf-8") return response + return mockreturn def make_simple_text_mock(filename): def mockreturn(*args, **kwargs): - with open(os.path.join(os.path.dirname(__file__), 'Assets', filename), 'r', 'ISO-8859-1') as fd: + with open( + os.path.join(os.path.dirname(__file__), "Assets", filename), + "r", + "ISO-8859-1", + ) as fd: return fd.read() + return mockreturn @@ -31,5 +40,5 @@ def assert_raises(exception_class, msg=None): with pytest.raises(exception_class) as exception: yield if msg is not None: - message = '%s' % exception + message = "%s" % exception assert msg.lower() in message.lower() diff --git a/tests/offline/test_accountingmanagement.py b/tests/offline/test_accountingmanagement.py index 62dad65..3a33d3f 100644 --- a/tests/offline/test_accountingmanagement.py +++ b/tests/offline/test_accountingmanagement.py @@ -1,6 +1,4 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals - from shiba.accountingmanagement import AccountingManagement from shiba.shibaconnection import ShibaConnection @@ -8,8 +6,12 @@ def test_get_operations(monkeypatch): - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_getoperations.xml')) - account = AccountingManagement(ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com")) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_getoperations.xml") + ) + account = AccountingManagement( + ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com") + ) operations = account.get_operations() assert "getoperationsresult" in operations.content.tag assert operations.content.request.user == "vendeur" @@ -17,7 +19,11 @@ def test_get_operations(monkeypatch): def test_get_compensation_details(monkeypatch): - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_getcompensationdetails.xml')) - account = AccountingManagement(ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com")) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_getcompensationdetails.xml") + ) + account = AccountingManagement( + ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com") + ) compensation_details = account.get_compensation_details("1337") assert compensation_details.content.tag == "getcompensationdetailsresult" diff --git a/tests/offline/test_inventorymanagement.py b/tests/offline/test_inventorymanagement.py index c7a9f48..dc81f48 100644 --- a/tests/offline/test_inventorymanagement.py +++ b/tests/offline/test_inventorymanagement.py @@ -1,6 +1,4 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals - import os.path as op from shiba.inventorymanagement import InventoryManagement from shiba.shibaconnection import ShibaConnection @@ -12,31 +10,47 @@ def test_product_types(monkeypatch): - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_getproducttypes.xml')) - inventory_management = InventoryManagement(ShibaConnection("test", "test", sandbox=True)) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_getproducttypes.xml") + ) + inventory_management = InventoryManagement( + ShibaConnection("test", "test", sandbox=True) + ) ptypes = inventory_management.product_types() assert "producttypesresult" in ptypes.content.tag def test_product_type_template(monkeypatch): """product_type_template tests on two scopes, for a fixed alias, plus a fail result""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_getproducttypetemplate.xml')) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_getproducttypetemplate.xml") + ) alias = "insolites_produit" - inventory_management = InventoryManagement(ShibaConnection("test", "test", sandbox=True)) + inventory_management = InventoryManagement( + ShibaConnection("test", "test", sandbox=True) + ) ptemplate = inventory_management.product_type_template(alias, "") assert "producttypetemplateresult" in ptemplate.content.tag def test_get_available_shipping_types(monkeypatch): - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_getavailableshippingtypes.xml')) - inventory_management = InventoryManagement(ShibaConnection("test", "test", sandbox=True)) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_getavailableshippingtypes.xml") + ) + inventory_management = InventoryManagement( + ShibaConnection("test", "test", sandbox=True) + ) obj = inventory_management.get_available_shipping_types() assert "getavailableshippingtypesresult" in obj.content.tag def test_export_inventory(monkeypatch): - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_exportinventory.xml')) - inventory_management = InventoryManagement(ShibaConnection("test", "test", sandbox=True)) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_exportinventory.xml") + ) + inventory_management = InventoryManagement( + ShibaConnection("test", "test", sandbox=True) + ) obj = inventory_management.export_inventory() assert "inventoryresult" in obj.content.tag @@ -45,16 +59,23 @@ def test_generic_import_file(monkeypatch): """generic_import_file test, from an XML file. Conversion is done by xmltodict from a dict or OrderedDict , as well with objectify with an objectified ElementTree element""" - monkeypatch.setattr('shiba.shibatools.post_request', make_simple_text_mock('sample_genericimportfile.xml')) + monkeypatch.setattr( + "shiba.shibatools.post_request", + make_simple_text_mock("sample_genericimportfile.xml"), + ) - f = open(op.join(op.dirname(__file__), 'Assets', 'genericimportfile.xml'), 'rb') + f = open(op.join(op.dirname(__file__), "Assets", "genericimportfile.xml"), "rb") testdict = xmltodict.parse(f) - inventory_management = InventoryManagement(ShibaConnection("test", "test", sandbox=True)) + inventory_management = InventoryManagement( + ShibaConnection("test", "test", sandbox=True) + ) ret = inventory_management.generic_import_file(testdict) assert "OK" == ret.content.response.status - f = open(op.join(op.dirname(__file__), 'Assets', 'genericimportfile.xml'), 'rb') + f = open(op.join(op.dirname(__file__), "Assets", "genericimportfile.xml"), "rb") testobj = objectify.parse(f) - inventory_management = InventoryManagement(ShibaConnection("test", "test", sandbox=True)) + inventory_management = InventoryManagement( + ShibaConnection("test", "test", sandbox=True) + ) ret = inventory_management.generic_import_file(testobj) assert "OK" == ret.content.response.status diff --git a/tests/offline/test_marketplacemanagement.py b/tests/offline/test_marketplacemanagement.py index ba335f7..e6d507b 100644 --- a/tests/offline/test_marketplacemanagement.py +++ b/tests/offline/test_marketplacemanagement.py @@ -1,6 +1,4 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals - from shiba.marketplacemanagement import MarketplaceManagement from shiba.shibaconnection import ShibaConnection @@ -11,9 +9,13 @@ def test_get_product_list(monkeypatch): """testing get_product_list methods with different queries, with some invalid ones as well""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_getproductlist.xml')) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_getproductlist.xml") + ) - shiba_connection = ShibaConnection("test", "test" "https://ws.fr.shopping.rakuten.com") + shiba_connection = ShibaConnection( + "test", "test" "https://ws.fr.shopping.rakuten.com" + ) marketplace_management = MarketplaceManagement(shiba_connection) # TODO: to remove ? @@ -27,15 +29,21 @@ def test_get_product_list(monkeypatch): # with assert_raises(ShibaParameterError): # marketplace_management.get_product_list(nbproductsperpage=-15, kw="livre") - product_list = marketplace_management.get_product_list(kw="informatique", scope="PRICING") + product_list = marketplace_management.get_product_list( + kw="informatique", scope="PRICING" + ) assert "listingresult" in product_list.content.tag def test_product_list_bad(monkeypatch): """testing get_product_list methods with different queries, with some invalid ones as well""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_productlist_bad.xml')) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_productlist_bad.xml") + ) - shiba_connection = ShibaConnection("test", "test" "https://ws.fr.shopping.rakuten.com") + shiba_connection = ShibaConnection( + "test", "test" "https://ws.fr.shopping.rakuten.com" + ) marketplace_management = MarketplaceManagement(shiba_connection) product_list = marketplace_management.get_product_list(kw="livre") @@ -44,8 +52,12 @@ def test_product_list_bad(monkeypatch): def test_get_category_map(monkeypatch): """get_category_map regular test""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_getcategorymap.xml')) - shiba_connection = ShibaConnection("test", "test" "https://ws.fr.shopping.rakuten.com") + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_getcategorymap.xml") + ) + shiba_connection = ShibaConnection( + "test", "test" "https://ws.fr.shopping.rakuten.com" + ) marketplace_management = MarketplaceManagement(shiba_connection) obj = marketplace_management.get_category_map() diff --git a/tests/offline/test_salesmanagement.py b/tests/offline/test_salesmanagement.py index deed976..1eac575 100644 --- a/tests/offline/test_salesmanagement.py +++ b/tests/offline/test_salesmanagement.py @@ -1,17 +1,23 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals - from shiba.salesmanagement import SalesManagement from shiba.shibaconnection import ShibaConnection -from shiba.shibaexceptions import ShibaServiceError, ShibaParameterError, ShibaCallingError +from shiba.shibaexceptions import ( + ShibaServiceError, + ShibaParameterError, + ShibaCallingError, +) from . import make_requests_get_mock def test_get_new_sales(monkeypatch): """regular get_new_sales test""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_getnewsales.xml')) - sales_management = SalesManagement(ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com")) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_getnewsales.xml") + ) + sales_management = SalesManagement( + ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com") + ) obj = sales_management.get_new_sales() assert "getnewsalesresult" in obj.content.tag @@ -19,12 +25,17 @@ def test_get_new_sales(monkeypatch): def test_accept_sale(monkeypatch): """Only fail result, as accepting an actual sale is not simulable""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_accept_sale.xml')) - sales_management = SalesManagement(ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com")) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_accept_sale.xml") + ) + sales_management = SalesManagement( + ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com") + ) itemid = "000000" + shippingfromcountry = "CN" obj = None try: - obj = sales_management.accept_sale(itemid) + obj = sales_management.accept_sale(itemid, shippingfromcountry) except ShibaServiceError: pass except ShibaParameterError: @@ -32,10 +43,15 @@ def test_accept_sale(monkeypatch): assert obj is not None + def test_refuse_sale(monkeypatch): """Only fail result, as refusing an actual sale is not simulable""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_accept_sale.xml')) - sales_management = SalesManagement(ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com")) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_accept_sale.xml") + ) + sales_management = SalesManagement( + ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com") + ) itemid = "000000" obj = None try: @@ -49,8 +65,12 @@ def test_refuse_sale(monkeypatch): def test_get_current_sales(monkeypatch): """get_current_sales test, on variable parameters, plus some fail results""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_getcurrentsales.xml')) - sales_management = SalesManagement(ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com")) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_getcurrentsales.xml") + ) + sales_management = SalesManagement( + ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com") + ) obj = sales_management.get_current_sales() assert "getcurrentsalesresult" in obj.content.tag assert not obj.content.request.ispendingpreorder @@ -65,16 +85,24 @@ def test_get_current_sales(monkeypatch): def test_get_billing_information(monkeypatch): """get_billing_information test, will raise an error due to unknown purchaseid""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_getbillinginformation.xml')) - sales_management = SalesManagement(ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com")) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_getbillinginformation.xml") + ) + sales_management = SalesManagement( + ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com") + ) obj = sales_management.get_billing_information("1337") assert obj.content.tag == "getbillinginformationresult" def test_get_shipping_information(monkeypatch): """get_billing_information test""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_getshippinginformation.xml')) - sales_management = SalesManagement(ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com")) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_getshippinginformation.xml") + ) + sales_management = SalesManagement( + ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com") + ) obj = None obj = sales_management.get_shipping_information("1337") assert obj is not None @@ -83,48 +111,68 @@ def test_get_shipping_information(monkeypatch): def test_get_items_todo_list(monkeypatch): """get_items_todo_list routine test""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_getitemtodolist.xml')) - sales_management = SalesManagement(ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com")) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_getitemtodolist.xml") + ) + sales_management = SalesManagement( + ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com") + ) obj = sales_management.get_item_todo_list() assert "getitemtodolistresult" in obj.content.tag def test_get_item_infos(monkeypatch): """get_item_infos on a product""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_getiteminfos.xml')) - sales_management = SalesManagement(ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com")) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_getiteminfos.xml") + ) + sales_management = SalesManagement( + ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com") + ) obj = sales_management.get_item_infos("181063") assert obj.content.tag == "getiteminfosresult" def test_cancel_item(monkeypatch): """cancel_item test""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_cancelitem.xml')) - sales_management = SalesManagement(ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com")) + monkeypatch.setattr("requests.get", make_requests_get_mock("sample_cancelitem.xml")) + sales_management = SalesManagement( + ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com") + ) obj = sales_management.cancel_item("1337", "comment") assert obj.content.tag == "cancelitemresult" def test_contact_us_about_item(monkeypatch): """contact_us_about_item test""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_contactus.xml')) - sales_management = SalesManagement(ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com")) + monkeypatch.setattr("requests.get", make_requests_get_mock("sample_contactus.xml")) + sales_management = SalesManagement( + ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com") + ) obj = sales_management.contact_us_about_item("1337", "message", "1337") assert obj.content.tag == "contactusaboutitemresult" def test_contact_user_about_item(monkeypatch): """contact_user_about_item on a product""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_contactuser.xml')) - sales_management = SalesManagement(ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com")) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_contactuser.xml") + ) + sales_management = SalesManagement( + ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com") + ) obj = sales_management.contact_user_about_item("1337", "message") assert obj.content.tag == "contactuseraboutitemresult" def test_set_tracking_package_infos(monkeypatch): """set_tracking_package_infos on a product. Testing internal error catching as well.""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_settrackingpackageinfos.xml')) - sales_management = SalesManagement(ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com")) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_settrackingpackageinfos.xml") + ) + sales_management = SalesManagement( + ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com") + ) obj = sales_management.set_tracking_package_infos("1337", "UPS", "0000000000") assert obj.content.tag == "setshippingpackageinfosresult" obj = None @@ -137,8 +185,12 @@ def test_set_tracking_package_infos(monkeypatch): def test_confirm_preorder(monkeypatch): """confirm_preorder on an advert. Testing internal error catching as well.""" - monkeypatch.setattr('requests.get', make_requests_get_mock('sample_confirmpreorder.xml')) - sales_management = SalesManagement(ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com")) + monkeypatch.setattr( + "requests.get", make_requests_get_mock("sample_confirmpreorder.xml") + ) + sales_management = SalesManagement( + ShibaConnection("test", "test", "https://ws.fr.shopping.rakuten.com") + ) obj = sales_management.confirm_preorder("1337", 1) assert obj.content.tag == "confirmpreorder" obj = None diff --git a/tests/offline/test_shibatools.py b/tests/offline/test_shibatools.py index c91d2ce..c58066b 100644 --- a/tests/offline/test_shibatools.py +++ b/tests/offline/test_shibatools.py @@ -1,7 +1,5 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -from __future__ import unicode_literals - import os.path as op import xmltodict @@ -16,12 +14,15 @@ def test_retrieve_obj_from_url(monkeypatch): """retrieve_obj_from_url test with a remote XML file""" - monkeypatch.setattr('requests.get', make_requests_get_mock('note.xml')) + monkeypatch.setattr("requests.get", make_requests_get_mock("note.xml")) obj = retrieve_obj_from_url("http://www.w3schools.com/xml/note.xml") assert "note" in obj.content.tag assert "to" in obj.content.to.tag and obj.content.to == "Tove" assert "heading" in obj.content.heading.tag and obj.content.heading == "Reminder" - assert "body" in obj.content.body.tag and obj.content.body == "Don't forget me this weekend!" + assert ( + "body" in obj.content.body.tag + and obj.content.body == "Don't forget me this weekend!" + ) def test_inf_constructor(): @@ -37,10 +38,12 @@ def test_inf_constructor(): def test_url_constructor_with_accent(): connection = ShibaConnection("test", "test") action = "genericimportreport" - ret = inf_constructor(connection, action, inf1=u"é", inf2=u"à") + ret = inf_constructor(connection, action, inf1="é", inf2="à") url = url_constructor(connection, ret) - assert ("https://ws.fr.shopping.rakuten.com/stock_ws?action=genericimportreport&inf1=%C3%A9&inf2=%C3%A0&login=test&" - "pwd=test&version=2017-02-10" == url) + assert ( + "https://ws.fr.shopping.rakuten.com/stock_ws?action=genericimportreport&inf1=%C3%A9&inf2=%C3%A0&login=test&" + "pwd=test&version=2017-02-10" == url + ) def test_url_constructor(): @@ -48,17 +51,22 @@ def test_url_constructor(): action = "genericimportreport" ret = inf_constructor(connection, action, inf1="info1", inf2="info2") url = url_constructor(connection, ret) - assert ("https://ws.fr.shopping.rakuten.com/stock_ws?action=genericimportreport&inf1=info1&inf2=info2&login=test&" - "pwd=test&version=2017-02-10" == url) + assert ( + "https://ws.fr.shopping.rakuten.com/stock_ws?action=genericimportreport&inf1=info1&inf2=info2&login=test&" + "pwd=test&version=2017-02-10" == url + ) def test_assert_quota_exeeded(monkeypatch): """raises ShibaQuotaExceededError exception""" - monkeypatch.setattr('shiba.shibatools.post_request', make_simple_text_mock('quota_exceeded_message.xml')) + monkeypatch.setattr( + "shiba.shibatools.post_request", + make_simple_text_mock("quota_exceeded_message.xml"), + ) connection = ShibaConnection("test", "test") inventory = InventoryManagement(connection) - f = open(op.join(op.dirname(__file__), 'Assets', 'genericimportfile.xml'), 'rb') + f = open(op.join(op.dirname(__file__), "Assets", "genericimportfile.xml"), "rb") testdict = xmltodict.parse(f) with assert_raises(ShibaQuotaExceededError): inventory.generic_import_file(data=testdict) diff --git a/tests/online/__init__.py b/tests/online/__init__.py index 0eba3a4..59b1a83 100644 --- a/tests/online/__init__.py +++ b/tests/online/__init__.py @@ -1,6 +1,4 @@ # coding: utf-8 -from __future__ import unicode_literals, print_function - import pytest from contextlib import contextmanager @@ -12,5 +10,5 @@ def assert_raises(exception_class, msg=None): with pytest.raises(exception_class) as exception: yield if msg is not None: - message = '%s' % exception + message = "%s" % exception assert msg.lower() in message.lower() diff --git a/tests/online/conftest.py b/tests/online/conftest.py index 27eb454..efa595d 100644 --- a/tests/online/conftest.py +++ b/tests/online/conftest.py @@ -1,6 +1,4 @@ # coding: utf-8 -from __future__ import unicode_literals, print_function - import os import pytest @@ -12,8 +10,8 @@ def get_connection(): - login = os.environ['SHIBA_API_LOGIN'] - password = os.environ['SHIBA_API_PASSWORD'] + login = os.environ["SHIBA_API_LOGIN"] + password = os.environ["SHIBA_API_PASSWORD"] return ShibaConnection(login, password, "https://ws.fr.shopping.rakuten.com") @@ -26,11 +24,15 @@ def check_sandbox_up(): @pytest.fixture -@pytest.mark.skipif(not check_sandbox_up(), reason='need access to the sandbox') +@pytest.mark.skipif(not check_sandbox_up(), reason="need access to the sandbox") def connection(): return get_connection() @pytest.fixture def fake_connection(): - return ShibaConnection("Qvuik5bZVHbmg4mWsdsd0ik9", "RInDsddsdsdZ72tfA", "https://ws.fr.shopping.rakuten.com") + return ShibaConnection( + "Qvuik5bZVHbmg4mWsdsd0ik9", + "RInDsddsdsdZ72tfA", + "https://ws.fr.shopping.rakuten.com", + ) diff --git a/tests/online/test_accountingmanagement.py b/tests/online/test_accountingmanagement.py index 67be771..c3db3b1 100644 --- a/tests/online/test_accountingmanagement.py +++ b/tests/online/test_accountingmanagement.py @@ -1,6 +1,4 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals - from shiba.accountingmanagement import AccountingManagement from shiba.shibaexceptions import ShibaParameterError diff --git a/tests/online/test_inventorymanagement.py b/tests/online/test_inventorymanagement.py index d312ff6..d62612a 100644 --- a/tests/online/test_inventorymanagement.py +++ b/tests/online/test_inventorymanagement.py @@ -1,6 +1,4 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals - from shiba.shibaexceptions import ShibaRightsError from shiba.inventorymanagement import InventoryManagement @@ -38,12 +36,18 @@ def test_generic_import_file(connection): , as well with objectify with an objectified ElementTree element""" inventory_management = InventoryManagement(connection) - f = open(os.path.dirname(os.path.realpath(__file__)) + "/Assets/genericimportfile.xml", "rb") + f = open( + os.path.dirname(os.path.realpath(__file__)) + "/Assets/genericimportfile.xml", + "rb", + ) testdict = xmltodict.parse(f) ret = inventory_management.generic_import_file(testdict) assert "OK" == ret.content.response.status - f = open(os.path.dirname(os.path.realpath(__file__)) + "/Assets/genericimportfile.xml", "rb") + f = open( + os.path.dirname(os.path.realpath(__file__)) + "/Assets/genericimportfile.xml", + "rb", + ) testobj = objectify.parse(f) ret = inventory_management.generic_import_file(testobj) assert "OK" == ret.content.response.status @@ -52,7 +56,10 @@ def test_generic_import_file(connection): def test_generic_import_report(connection): """genreic_import_report method test from an import file call""" inventory_management = InventoryManagement(connection) - f = open(os.path.dirname(os.path.realpath(__file__)) + "/Assets/genericimportfile.xml", "rb") + f = open( + os.path.dirname(os.path.realpath(__file__)) + "/Assets/genericimportfile.xml", + "rb", + ) testobj = objectify.parse(f) ret = inventory_management.generic_import_file(testobj) importid = ret.content.response.importid diff --git a/tests/online/test_marketplacemanagement.py b/tests/online/test_marketplacemanagement.py index 2be7918..5f7b6b2 100644 --- a/tests/online/test_marketplacemanagement.py +++ b/tests/online/test_marketplacemanagement.py @@ -1,6 +1,3 @@ -#!/usr/bin/env python -from __future__ import unicode_literals - from shiba.marketplacemanagement import MarketplaceManagement from shiba.shibaexceptions import * diff --git a/tests/online/test_salesmanagement.py b/tests/online/test_salesmanagement.py index 319ff35..c926455 100644 --- a/tests/online/test_salesmanagement.py +++ b/tests/online/test_salesmanagement.py @@ -1,6 +1,4 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals - from shiba.salesmanagement import SalesManagement from shiba.shibaexceptions import * @@ -16,9 +14,10 @@ def test_accept_sale(connection): """Only fail result, as accepting an actual sale is not simulable""" sales_management = SalesManagement(connection) itemid = "000000" + shippingfromcountry = "CN" obj = None try: - obj = sales_management.accept_sale(itemid) + obj = sales_management.accept_sale(itemid, shippingfromcountry) except ShibaServiceError: pass except ShibaParameterError: diff --git a/tests/online/test_shibatools.py b/tests/online/test_shibatools.py index 9b00d01..80c7778 100644 --- a/tests/online/test_shibatools.py +++ b/tests/online/test_shibatools.py @@ -1,7 +1,10 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals - -from shiba.shibatools import inf_constructor, retrieve_obj_from_url, url_constructor, post_request +from shiba.shibatools import ( + inf_constructor, + retrieve_obj_from_url, + url_constructor, + post_request, +) from shiba.shibaconnection import ShibaConnection @@ -11,7 +14,10 @@ def test_retrieve_obj_from_url(): assert "note" in obj.content.tag assert "to" in obj.content.to.tag and obj.content.to == "Tove" assert "heading" in obj.content.heading.tag and obj.content.heading == "Reminder" - assert "body" in obj.content.body.tag and obj.content.body == "Don't forget me this weekend!" + assert ( + "body" in obj.content.body.tag + and obj.content.body == "Don't forget me this weekend!" + ) def test_post_request(): @@ -41,5 +47,8 @@ def test_url_constructor(fake_connection): action = "genericimportreport" ret = inf_constructor(connection, action, inf1="info1", inf2="info2") url = url_constructor(connection, ret) - assert (url == "https://ws.fr.shopping.rakuten.com/stock_ws?action=genericimportreport&inf1=info1&inf2=info2&login" - "=test&pwd=test&version=2017-02-10") + assert ( + url + == "https://ws.fr.shopping.rakuten.com/stock_ws?action=genericimportreport&inf1=info1&inf2=info2&login" + "=test&pwd=test&version=2017-02-10" + ) diff --git a/tox.ini b/tox.ini index 3b26fa9..24d4c8f 100644 --- a/tox.ini +++ b/tox.ini @@ -4,7 +4,7 @@ # and then run "tox" from this directory. [tox] -envlist = py34, py35, py36, py37 +envlist = py36, py37, py38, py39 [testenv] passenv = LC_ALL LANG HOME TRAVIS SHIBA_API_PASSWORD SHIBA_API_LOGIN