pax_global_header00006660000000000000000000000064136160431500014511gustar00rootroot0000000000000052 comment=dbf8dd6bcf583f1f217fa74031af20f62f366f13 microversion-parse-1.0.0/000077500000000000000000000000001361604315000153365ustar00rootroot00000000000000microversion-parse-1.0.0/.gitignore000066400000000000000000000014131361604315000173250ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log # Sphinx documentation docs/_build/ # PyBuilder target/ #Ipython Notebook .ipynb_checkpoints .stestr cover microversion-parse-1.0.0/.gitreview000066400000000000000000000001251361604315000173420ustar00rootroot00000000000000[gerrit] host=review.opendev.org port=29418 project=openstack/microversion-parse.git microversion-parse-1.0.0/.stestr.conf000066400000000000000000000003201361604315000176020ustar00rootroot00000000000000[DEFAULT] test_path=./microversion_parse/tests top_dir=./ # This regex ensures each yaml file used by gabbi is run in only one # process. group_regex=microversion_parse\.tests\.test_middleware(?:\.|_)([^_]+) microversion-parse-1.0.0/.zuul.yaml000066400000000000000000000001331361604315000172740ustar00rootroot00000000000000- project: templates: - openstack-python3-ussuri-jobs - check-requirements microversion-parse-1.0.0/LICENSE000066400000000000000000000261351361604315000163520ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. microversion-parse-1.0.0/Makefile000066400000000000000000000017011361604315000167750ustar00rootroot00000000000000# simple Makefile for some common tasks .PHONY: clean test dist release pypi tagv docs clean: find . -name "*.pyc" |xargs rm || true rm -r dist || true rm -r build || true rm -r .tox || true rm -r .testrepository || true rm -r cover .coverage || true rm -r .eggs || true rm -r microversion_parse.egg-info || true tagv: git tag \ -m `python -c 'import microversion_parse; print microversion_parse.__version__'` \ `python -c 'import microversion_parse; print microversion_parse.__version__'` git push origin master --tags cleanagain: find . -name "*.pyc" |xargs rm || true rm -r dist || true rm -r build || true rm -r .tox || true rm -r .testrepository || true rm -r cover .coverage || true rm -r .eggs || true rm -r microversion_parse.egg-info || true docs: cd docs ; $(MAKE) html test: tox --skip-missing-interpreters dist: test python setup.py sdist release: clean test cleanagain tagv pypi pypi: python setup.py sdist upload microversion-parse-1.0.0/README.rst000066400000000000000000000100421361604315000170220ustar00rootroot00000000000000microversion_parse ================== A small set of functions to manage OpenStack `microversion`_ headers that can be used in middleware, application handlers and decorators to effectively manage microversions. Also included, in the ``middleware`` module, is a ``MicroversionMiddleware`` that will process incoming microversion headers. get_version ----------- A simple parser for OpenStack microversion headers:: import microversion_parse # headers is a dict of headers with folded (comma-separated # values) or a list of header, value tuples version = microversion_parse.get_version( headers, service_type='compute', legacy_headers=['x-openstack-nova-api-version']) # If headers are not already available, a dict of headers # can be extracted from the WSGI environ headers = microversion_parse.headers_from_wsgi_environ(environ) version = microversion_parse.get_version( headers, service_type='placement') It processes microversion headers with the standard form:: OpenStack-API-Version: compute 2.1 In that case, the response will be '2.1'. If provided with a ``legacy_headers`` argument, this is treated as a list of additional headers to check for microversions. Some examples of headers include:: OpenStack-telemetry-api-version: 2.1 OpenStack-nova-api-version: 2.1 X-OpenStack-nova-api-version: 2.1 If a version string cannot be found, ``None`` will be returned. If the input is incorrect usual Python exceptions (ValueError, TypeError) are allowed to raise to the caller. parse_version_string -------------------- A function to turn a version string into a ``Version``, a comparable ``namedtuple``:: version_tuple = microversion_parse.parse_version_string('2.1') If the provided string is not a valid microversion string, ``TypeError`` is raised. extract_version --------------- Combines ``get_version`` and ``parse_version_string`` to find and validate a microversion for a given service type in a collection of headers:: version_tuple = microversion_parse.extract_version( headers, # a representation of headers, as accepted by get_version service_type, # service type identify to match in headers versions_list, # an ordered list of strings of version numbers that # are the valid versions presented by this service ) ``latest`` will be translated to whatever the max version is in versions_list. If the found version is not in versions_list a ``ValueError`` is raised. Note that ``extract_version`` does not support ``legacy_headers``. MicroversionMiddleware ---------------------- A WSGI middleware that can wrap an application that needs to be microversion aware. The application will get a WSGI environ with a 'SERVICE_TYPE.microversion' key that has a value of the microversion found at an 'openstack-api-version' header that matches SERVICE_TYPE. If no header is found, the minimum microversion will be set. If the special keyword 'latest' is used, the maximum microversion will be set. If the requested microversion is not available a 406 response is returned. If there is an error parsing a provided header, a 400 response is returned. Otherwise the application is called. The middleware is configured when it is created. Three parameters are required: app The next WSGI middleware or application in the stack. service_type The service type of the application, used to identify microversion headers. versions_list An ordered list of legitimate microversions (as strings) for the application. It's assumed that any application that is using microversions will have such a list for its own housekeeping and documentation. One named parameter is optional: json_error_formatter A Webob error formatter that can be used to structure the response when JSON is expected. For example:: def app(): app = middleware.MicroversionMiddleware( MyWSGIApp(), 'cats', ['1.0', '1.1', '1.2']) return app .. _microversion: http://specs.openstack.org/openstack/api-wg/guidelines/microversion_specification.html microversion-parse-1.0.0/doc/000077500000000000000000000000001361604315000161035ustar00rootroot00000000000000microversion-parse-1.0.0/doc/requirements.txt000066400000000000000000000001141361604315000213630ustar00rootroot00000000000000openstackdocstheme>=1.18.1 # Apache-2.0 sphinx!=1.6.6,!=1.6.7,>=1.6.2 # BSD microversion-parse-1.0.0/doc/source/000077500000000000000000000000001361604315000174035ustar00rootroot00000000000000microversion-parse-1.0.0/doc/source/conf.py000066400000000000000000000221431361604315000207040ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # microversion-parse documentation build configuration file, created by # sphinx-quickstart on Thu Mar 31 11:40:03 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # 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('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #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.intersphinx', 'openstackdocstheme' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'microversion-parse' copyright = u'2016, OpenStack' author = u'OpenStack' # openstackdocstheme options repository_name = 'openstack/microversion-parse' bug_project = 'microversion-parse' bug_tag = '' html_theme = 'openstackdocs' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #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 = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #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 # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = 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 = 'alabaster' # 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 = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #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 # 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 # 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'] # 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 = [] # 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' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is 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 = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'microversion-parsedoc' # -- 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': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # 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 = [ (master_doc, 'microversion-parse.tex', u'microversion-parse Documentation', u'OpenStack', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #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 = [ (master_doc, 'microversion-parse', u'microversion-parse Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'microversion-parse', u'microversion-parse Documentation', author, 'microversion-parse', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'https://docs.python.org/': None} microversion-parse-1.0.0/doc/source/index.rst000066400000000000000000000005771361604315000212550ustar00rootroot00000000000000.. microversion-parse documentation master file, created by sphinx-quickstart on Thu Mar 31 11:40:03 2016. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. .. include:: ../../README.rst .. toctree:: :maxdepth: 2 Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` microversion-parse-1.0.0/microversion_parse/000077500000000000000000000000001361604315000212475ustar00rootroot00000000000000microversion-parse-1.0.0/microversion_parse/__init__.py000066400000000000000000000165411361604315000233670ustar00rootroot00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import collections ENVIRON_HTTP_HEADER_FMT = 'http_{}' STANDARD_HEADER = 'openstack-api-version' class Version(collections.namedtuple('Version', 'major minor')): """A namedtuple containing major and minor values. Since it is a tuple, it is automatically comparable. """ def __new__(cls, major, minor): """Add mix and max version attributes to the tuple.""" self = super(Version, cls).__new__(cls, major, minor) self.max_version = (-1, 0) self.min_version = (-1, 0) return self def __str__(self): return '%s.%s' % (self.major, self.minor) def matches(self, min_version=None, max_version=None): """Is this version within min_version and max_version. """ # NOTE(cdent): min_version and max_version are expected # to be set by the code that is creating the Version, if # they are known. if min_version is None: min_version = self.min_version if max_version is None: max_version = self.max_version return min_version <= self <= max_version def get_version(headers, service_type, legacy_headers=None): """Parse a microversion out of headers :param headers: The headers of a request, dict or list :param service_type: The service type being looked for in the headers :param legacy_headers: Other headers to look at for a version :returns: a version string or "latest" :raises: ValueError If headers is not a dict we assume is an iterator of tuple-like headers, which we will fold into a dict. The flow is that we first look for the new standard singular header: * openstack-api-version: If that's not present we fall back to the headers listed in legacy_headers. These often look like this: * openstack--api-version: * openstack--api-version: * x-openstack--api-version: Folded headers are joined by ','. """ folded_headers = fold_headers(headers) version = check_standard_header(folded_headers, service_type) if version: return version if legacy_headers: version = check_legacy_headers(folded_headers, legacy_headers) return version return None def check_legacy_headers(headers, legacy_headers): """Gather values from old headers.""" for legacy_header in legacy_headers: try: value = _extract_header_value(headers, legacy_header.lower()) return value.split(',')[-1].strip() except KeyError: pass return None def check_standard_header(headers, service_type): """Parse the standard header to get value for service.""" try: header = _extract_header_value(headers, STANDARD_HEADER) for header_value in reversed(header.split(',')): try: service, version = header_value.strip().split(None, 1) if service.lower() == service_type.lower(): return version.strip() except ValueError: pass except (KeyError, ValueError): return None def fold_headers(headers): """Turn a list of headers into a folded dict.""" # If it behaves like a dict, return it. Webob uses objects which # are not dicts, but behave like them. try: return dict((k.lower(), v) for k, v in headers.items()) except AttributeError: pass header_dict = collections.defaultdict(list) for header, value in headers: header_dict[header.lower()].append(value.strip()) folded_headers = {} for header, value in header_dict.items(): folded_headers[header] = ','.join(value) return folded_headers def headers_from_wsgi_environ(environ): """Extract all the HTTP_ keys and values from environ to a new dict. Note that this does not change the keys in any way in the returned dict. Nor is the incoming environ modified. :param environ: A PEP 3333 compliant WSGI environ dict. """ return {key: environ[key] for key in environ if key.startswith('HTTP_')} def _extract_header_value(headers, header_name): """Get the value of a header. The provided headers is a dict. If a key doesn't exist for header_name, try using the WSGI environ form of the name. Raises KeyError if neither key is found. """ try: value = headers[header_name] except KeyError: wsgi_header_name = ENVIRON_HTTP_HEADER_FMT.format( header_name.replace('-', '_')) value = headers[wsgi_header_name] return value def parse_version_string(version_string): """Turn a version string into a Version :param version_string: A string of two numerals, X.Y. :returns: a Version :raises: TypeError """ try: # The combination of int and a limited split with the # named tuple means that this incantation will raise # ValueError, TypeError or AttributeError when the incoming # data is poorly formed but will, however, naturally adapt to # extraneous whitespace. return Version(*(int(value) for value in version_string.split('.', 1))) except (ValueError, TypeError, AttributeError) as exc: raise TypeError('invalid version string: %s; %s' % ( version_string, exc)) def extract_version(headers, service_type, versions_list): """Extract the microversion from the headers. There may be multiple headers and some which don't match our service. If no version is found then the extracted version is the minimum available version. :param headers: Request headers as dict list or WSGI environ :param service_type: The service_type as a string :param versions_list: List of all possible microversions as strings, sorted from earliest to latest version. :returns: a Version with the optional min_version and max_version attributes set. :raises: ValueError """ found_version = get_version(headers, service_type=service_type) min_version_string = versions_list[0] max_version_string = versions_list[-1] # If there was no version found in the headers, choose the minimum # available version. version_string = found_version or min_version_string if version_string == 'latest': version_string = max_version_string request_version = parse_version_string(version_string) request_version.max_version = parse_version_string(max_version_string) request_version.min_version = parse_version_string(min_version_string) # We need a version that is in versions_list. This gives us the option # to administratively disable a version if we really need to. if str(request_version) in versions_list: return request_version raise ValueError('Unacceptable version header: %s' % version_string) microversion-parse-1.0.0/microversion_parse/middleware.py000066400000000000000000000071571361604315000237500ustar00rootroot00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """WSGI middleware for getting microversion info.""" import webob import webob.dec import microversion_parse class MicroversionMiddleware(object): """WSGI middleware for getting microversion info. The application will get a WSGI environ with a 'SERVICE_TYPE.microversion' key that has a value of the microversion found at an 'openstack-api-version' header that matches SERVICE_TYPE. If no header is found, the minimum microversion will be set. If the special keyword 'latest' is used, the maximum microversion will be set. If the requested microversion is not available a 406 response is returned. If there is an error parsing a provided header, a 400 response is returned. Otherwise the application is called. """ def __init__(self, application, service_type, versions, json_error_formatter=None): """Create the WSGI middleware. :param application: The application hosting the service. :param service_type: The service type (entry in keystone catalog) of the application. :param versions: An ordered list of legitimate versions for the application. :param json_error_formatter: A Webob exception error formatter. See Webob for details. """ self.application = application self.service_type = service_type self.microversion_environ = '%s.microversion' % service_type self.versions = versions self.json_error_formatter = json_error_formatter @webob.dec.wsgify def __call__(self, req): try: microversion = microversion_parse.extract_version( req.headers, self.service_type, self.versions) # TODO(cdent): These error response are not formatted according to # api-sig guidelines, unless a json_error_formatter is provided # that can do it. For an example, see the placement service. except ValueError as exc: raise webob.exc.HTTPNotAcceptable( ('Invalid microversion: %(error)s') % {'error': exc}, json_formatter=self.json_error_formatter) except TypeError as exc: raise webob.exc.HTTPBadRequest( ('Invalid microversion: %(error)s') % {'error': exc}, json_formatter=self.json_error_formatter) req.environ[self.microversion_environ] = microversion microversion_header = '%s %s' % (self.service_type, microversion) standard_header = microversion_parse.STANDARD_HEADER try: response = req.get_response(self.application) except webob.exc.HTTPError as exc: # If there was an HTTPError in the application we still need # to send the microversion header, so add the header and # re-raise the exception. exc.headers.add(standard_header, microversion_header) raise exc response.headers.add(standard_header, microversion_header) response.headers.add('vary', standard_header) return response microversion-parse-1.0.0/microversion_parse/tests/000077500000000000000000000000001361604315000224115ustar00rootroot00000000000000microversion-parse-1.0.0/microversion_parse/tests/__init__.py000066400000000000000000000000001361604315000245100ustar00rootroot00000000000000microversion-parse-1.0.0/microversion_parse/tests/gabbits/000077500000000000000000000000001361604315000240245ustar00rootroot00000000000000microversion-parse-1.0.0/microversion_parse/tests/gabbits/middleware.yaml000066400000000000000000000033461361604315000270330ustar00rootroot00000000000000# Tests that the middleware does microversioning as we expect # The min version of the service is 1.0, the max is 1.2, # the service type is "cats" (because the internet is for cats). defaults: request_headers: # We must guard against webob requiring an accept header. # We don't want to do this in the middleware itself as # we don't know what the application would prefer as a # default. accept: application/json tests: - name: min default GET: /good response_headers: openstack-api-version: cats 1.0 - name: max latest GET: /good request_headers: openstack-api-version: cats latest response_headers: openstack-api-version: cats 1.2 - name: explict GET: /good request_headers: openstack-api-version: cats 1.1 response_headers: openstack-api-version: cats 1.1 - name: out of range GET: /good request_headers: openstack-api-version: cats 1.9 status: 406 response_strings: - Unacceptable version header - name: invalid format GET: /good request_headers: openstack-api-version: cats 1.9.5 status: 400 response_strings: - invalid literal - name: different service desc: end up with default microversion GET: /good request_headers: openstack-api-version: dogs 1.9 response_headers: openstack-api-version: cats 1.0 - name: multiple services GET: /good request_headers: openstack-api-version: dogs 1.9, cats 1.1 response_headers: openstack-api-version: cats 1.1 - name: header present on exception GET: /bad request_headers: openstack-api-version: dogs 1.9, cats 1.1 response_headers: openstack-api-version: cats 1.1 status: 404 response_strings: - /bad not found microversion-parse-1.0.0/microversion_parse/tests/gabbits/simple.yaml000066400000000000000000000003221361604315000261760ustar00rootroot00000000000000# tests that the SimpleWSGI app is present tests: - name: get good GET: /good status: 200 response_strings: - good - name: get bad GET: /bad status: 404 response_strings: - not found microversion-parse-1.0.0/microversion_parse/tests/test_extract_version.py000066400000000000000000000127701361604315000272500ustar00rootroot00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import testtools import microversion_parse class TestVersion(testtools.TestCase): def setUp(self): super(TestVersion, self).setUp() self.version = microversion_parse.Version(1, 5) def test_version_is_tuple(self): self.assertEqual((1, 5), self.version) def test_version_stringifies(self): self.assertEqual('1.5', str(self.version)) def test_version_matches(self): max_version = microversion_parse.Version(1, 20) min_version = microversion_parse.Version(1, 3) self.assertTrue(self.version.matches(min_version, max_version)) self.assertFalse(self.version.matches(max_version, min_version)) def test_version_matches_inclusive(self): max_version = microversion_parse.Version(1, 5) min_version = microversion_parse.Version(1, 5) self.assertTrue(self.version.matches(min_version, max_version)) def test_version_matches_no_extremes(self): """If no extremes are present, never match.""" self.assertFalse(self.version.matches()) def test_version_zero_can_match(self): """If a version is '0.0' we want to it be able to match.""" version = microversion_parse.Version(0, 0) min_version = microversion_parse.Version(0, 0) max_version = microversion_parse.Version(0, 0) version.min_version = min_version version.max_version = max_version self.assertTrue(version.matches()) def test_version_zero_no_defaults(self): """Any version, even 0.0, should never match without a min and max being set. """ version = microversion_parse.Version(0, 0) self.assertFalse(version.matches()) def test_version_init_failure(self): self.assertRaises(TypeError, microversion_parse.Version, 1, 2, 3) class TestParseVersionString(testtools.TestCase): def test_good_version(self): version = microversion_parse.parse_version_string('1.1') self.assertEqual((1, 1), version) self.assertEqual(microversion_parse.Version(1, 1), version) def test_adapt_whitespace(self): version = microversion_parse.parse_version_string(' 1.1 ') self.assertEqual((1, 1), version) self.assertEqual(microversion_parse.Version(1, 1), version) def test_non_numeric(self): self.assertRaises(TypeError, microversion_parse.parse_version_string, 'hello') def test_mixed_alphanumeric(self): self.assertRaises(TypeError, microversion_parse.parse_version_string, '1.a') def test_too_many_numeric(self): self.assertRaises(TypeError, microversion_parse.parse_version_string, '1.1.1') def test_not_string(self): self.assertRaises(TypeError, microversion_parse.parse_version_string, 1.1) class TestExtractVersion(testtools.TestCase): def setUp(self): super(TestExtractVersion, self).setUp() self.headers = [ ('OpenStack-API-Version', 'service1 1.2'), ('OpenStack-API-Version', 'service2 1.5'), ('OpenStack-API-Version', 'service3 latest'), ('OpenStack-API-Version', 'service4 2.5'), ] self.version_list = ['1.1', '1.2', '1.3', '1.4', '2.1', '2.2', '2.3', '2.4'] def test_simple_extract(self): version = microversion_parse.extract_version( self.headers, 'service1', self.version_list) self.assertEqual((1, 2), version) def test_default_min(self): version = microversion_parse.extract_version( self.headers, 'notlisted', self.version_list) self.assertEqual((1, 1), version) def test_latest(self): version = microversion_parse.extract_version( self.headers, 'service3', self.version_list) self.assertEqual((2, 4), version) def test_min_max_extract(self): version = microversion_parse.extract_version( self.headers, 'service1', self.version_list) # below min self.assertFalse(version.matches((1, 3))) # at min self.assertTrue(version.matches((1, 2))) # within extremes self.assertTrue(version.matches()) # explicit max self.assertTrue(version.matches(max_version=(2, 3))) # explicit min self.assertFalse(version.matches(min_version=(2, 3))) # explicit both self.assertTrue(version.matches(min_version=(0, 3), max_version=(1, 5))) def test_version_disabled(self): self.assertRaises(ValueError, microversion_parse.extract_version, self.headers, 'service2', self.version_list) def test_version_out_of_range(self): self.assertRaises(ValueError, microversion_parse.extract_version, self.headers, 'service4', self.version_list) microversion-parse-1.0.0/microversion_parse/tests/test_get_version.py000066400000000000000000000177351361604315000263630ustar00rootroot00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import testtools import microversion_parse class TestFoldHeaders(testtools.TestCase): def test_dict_headers(self): headers = { 'header-one': 'alpha', 'header-two': 'beta', 'header-three': 'gamma', } folded_headers = microversion_parse.fold_headers(headers) self.assertEqual(3, len(folded_headers)) self.assertEqual(set(headers.keys()), set(folded_headers.keys())) self.assertEqual('gamma', folded_headers['header-three']) def test_listed_tuple_headers(self): headers = [ ('header-one', 'alpha'), ('header-two', 'beta'), ('header-one', 'gamma'), ] folded_headers = microversion_parse.fold_headers(headers) self.assertEqual(2, len(folded_headers)) self.assertEqual(set(['header-one', 'header-two']), set(folded_headers.keys())) self.assertEqual('alpha,gamma', folded_headers['header-one']) def test_bad_headers(self): headers = 'wow this is not a headers' self.assertRaises(ValueError, microversion_parse.fold_headers, headers) # TODO(cdent): Test with request objects from frameworks. class TestStandardHeader(testtools.TestCase): def test_simple_match(self): headers = { 'header-one': 'alpha', 'openstack-api-version': 'compute 2.1', 'header-two': 'beta', } version = microversion_parse.check_standard_header(headers, 'compute') # TODO(cdent): String or number. Choosing string for now # since 'latest' is always a string. self.assertEqual('2.1', version) def test_match_extra_whitespace(self): headers = { 'header-one': 'alpha', 'openstack-api-version': ' compute 2.1 ', 'header-two': 'beta', } version = microversion_parse.check_standard_header(headers, 'compute') self.assertEqual('2.1', version) def test_no_match_no_value(self): headers = { 'header-one': 'alpha', 'openstack-api-version': 'compute ', 'header-two': 'beta', } version = microversion_parse.check_standard_header(headers, 'compute') self.assertEqual(None, version) def test_no_match_wrong_service(self): headers = { 'header-one': 'alpha', 'openstack-api-version': 'network 5.9 ', 'header-two': 'beta', } version = microversion_parse.check_standard_header( headers, 'compute') self.assertEqual(None, version) def test_match_multiple_services(self): headers = { 'header-one': 'alpha', 'openstack-api-version': 'network 5.9 ,compute 2.1,telemetry 7.8', 'header-two': 'beta', } version = microversion_parse.check_standard_header( headers, 'compute') self.assertEqual('2.1', version) version = microversion_parse.check_standard_header( headers, 'telemetry') self.assertEqual('7.8', version) def test_match_multiple_same_service(self): headers = { 'header-one': 'alpha', 'openstack-api-version': 'compute 5.9 ,compute 2.1,compute 7.8', 'header-two': 'beta', } version = microversion_parse.check_standard_header( headers, 'compute') self.assertEqual('7.8', version) class TestLegacyHeaders(testtools.TestCase): def test_legacy_headers_straight(self): headers = { 'header-one': 'alpha', 'openstack-compute-api-version': ' 2.1 ', 'header-two': 'beta', } version = microversion_parse.get_version( headers, service_type='compute', legacy_headers=['openstack-CoMpUte-api-version']) self.assertEqual('2.1', version) def test_legacy_headers_folded(self): headers = { 'header-one': 'alpha', 'openstack-compute-api-version': ' 2.1, 9.2 ', 'header-two': 'beta', } version = microversion_parse.get_version( headers, service_type='compute', legacy_headers=['openstack-compute-api-version']) self.assertEqual('9.2', version) def test_older_legacy_headers(self): headers = { 'header-one': 'alpha', 'x-openstack-nova-api-version': ' 2.1, 9.2 ', 'header-two': 'beta', } version = microversion_parse.get_version( headers, service_type='compute', legacy_headers=['openstack-nova-api-version', 'x-openstack-nova-api-version']) # We don't do x- for service types. self.assertEqual('9.2', version) def test_legacy_headers_prefer(self): headers = { 'header-one': 'alpha', 'openstack-compute-api-version': '3.7', 'x-openstack-nova-api-version': ' 2.1, 9.2 ', 'header-two': 'beta', } version = microversion_parse.get_version( headers, service_type='compute', legacy_headers=['openstack-compute-api-version', 'x-openstack-nova-api-version']) self.assertEqual('3.7', version) version = microversion_parse.get_version( headers, service_type='compute', legacy_headers=['x-openstack-nova-api-version', 'openstack-compute-api-version']) self.assertEqual('9.2', version) class TestGetHeaders(testtools.TestCase): def test_preference(self): headers = { 'header-one': 'alpha', 'openstack-api-version': 'compute 11.12, telemetry 9.7', 'openstack-compute-api-version': '3.7', 'x-openstack-nova-api-version': ' 2.1, 9.2 ', 'header-two': 'beta', } version = microversion_parse.get_version( headers, service_type='compute', legacy_headers=['openstack-compute-api-version', 'x-openstack-nova-api-version']) self.assertEqual('11.12', version) def test_no_headers(self): headers = {} version = microversion_parse.get_version( headers, service_type='compute') self.assertEqual(None, version) def test_unfolded_service(self): headers = [ ('header-one', 'alpha'), ('openstack-api-version', 'compute 1.0'), ('openstack-api-version', 'compute 2.0'), ('openstack-api-version', '3.0'), ] version = microversion_parse.get_version( headers, service_type='compute') self.assertEqual('2.0', version) def test_unfolded_in_name(self): headers = [ ('header-one', 'alpha'), ('x-openstack-nova-api-version', '1.0'), ('x-openstack-nova-api-version', '2.0'), ('openstack-telemetry-api-version', '3.0'), ] version = microversion_parse.get_version( headers, service_type='compute', legacy_headers=['x-openstack-nova-api-version']) self.assertEqual('2.0', version) def test_capitalized_headers(self): headers = { 'X-Openstack-Ironic-Api-Version': '123.456' } version = microversion_parse.get_version( headers, service_type='ironic', legacy_headers=['X-Openstack-Ironic-Api-Version']) self.assertEqual('123.456', version) microversion-parse-1.0.0/microversion_parse/tests/test_headers_from_wsgi_environ.py000066400000000000000000000047121361604315000312550ustar00rootroot00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import testtools import microversion_parse class TestHeadersFromWSGIEnviron(testtools.TestCase): def test_empty_environ(self): environ = {} expected = {} self.assertEqual( expected, microversion_parse.headers_from_wsgi_environ(environ)) def test_non_empty_no_headers(self): environ = {'PATH_INFO': '/foo/bar'} expected = {} found_headers = microversion_parse.headers_from_wsgi_environ(environ) self.assertEqual(expected, found_headers) def test_headers(self): environ = {'PATH_INFO': '/foo/bar', 'HTTP_OPENSTACK_API_VERSION': 'placement 2.1', 'HTTP_CONTENT_TYPE': 'application/json'} expected = {'HTTP_OPENSTACK_API_VERSION': 'placement 2.1', 'HTTP_CONTENT_TYPE': 'application/json'} found_headers = microversion_parse.headers_from_wsgi_environ(environ) self.assertEqual(expected, found_headers) def test_get_version_from_environ(self): environ = {'PATH_INFO': '/foo/bar', 'HTTP_OPENSTACK_API_VERSION': 'placement 2.1', 'HTTP_CONTENT_TYPE': 'application/json'} expected_version = '2.1' headers = microversion_parse.headers_from_wsgi_environ(environ) version = microversion_parse.get_version(headers, 'placement') self.assertEqual(expected_version, version) def test_get_version_from_environ_legacy(self): environ = {'PATH_INFO': '/foo/bar', 'HTTP_X_OPENSTACK_PLACEMENT_API_VERSION': '2.1', 'HTTP_CONTENT_TYPE': 'application/json'} expected_version = '2.1' headers = microversion_parse.headers_from_wsgi_environ(environ) version = microversion_parse.get_version( headers, 'placement', legacy_headers=['x-openstack-placement-api-version']) self.assertEqual(expected_version, version) microversion-parse-1.0.0/microversion_parse/tests/test_middleware.py000066400000000000000000000033351361604315000261430ustar00rootroot00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # The microversion_parse middlware is tests using gabbi to run real # http requests through it. To do that, we need a simple WSGI # application running under wsgi-intercept (handled by gabbi). import os from gabbi import driver import webob from microversion_parse import middleware TESTS_DIR = 'gabbits' SERVICE_TYPE = 'cats' VERSIONS = [ '1.0', # initial version '1.1', # now with kittens '1.2', # added breeds ] class SimpleWSGI(object): """A WSGI application that can be contiained within a middlware.""" def __call__(self, environ, start_response): path_info = environ['PATH_INFO'] if path_info == '/good': start_response('200 OK', [('content-type', 'text/plain')]) return [b'good'] raise webob.exc.HTTPNotFound('%s not found' % path_info) def app(): app = middleware.MicroversionMiddleware( SimpleWSGI(), SERVICE_TYPE, VERSIONS) return app def load_tests(loader, tests, pattern): """Provide a TestSuite to the discovery process.""" test_dir = os.path.join(os.path.dirname(__file__), TESTS_DIR) return driver.build_tests( test_dir, loader, test_loader_name=__name__, intercept=app) microversion-parse-1.0.0/microversion_parse/tests/test_webob.py000066400000000000000000000057371361604315000251340ustar00rootroot00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import testtools from webob import headers as wb_headers import microversion_parse class TestWebobHeaders(testtools.TestCase): """Webob uses a dict-like header which is not actually a dict.""" def test_simple_headers(self): headers = wb_headers.EnvironHeaders({ 'HTTP_HEADER_ONE': 'alpha', 'HTTP_HEADER_TWO': 'beta', 'HTTP_HEADER_THREE': 'gamma', }) folded_headers = microversion_parse.fold_headers(headers) self.assertEqual(3, len(folded_headers)) self.assertEqual(set(['header-one', 'header-three', 'header-two']), set(folded_headers.keys())) self.assertEqual('gamma', folded_headers['header-three']) def test_simple_match(self): headers = wb_headers.EnvironHeaders({ 'HTTP_HEADER_ONE': 'alpha', 'HTTP_OPENSTACK_API_VERSION': 'compute 2.1', 'HTTP_HEADER_TWO': 'beta', }) version = microversion_parse.check_standard_header(headers, 'compute') self.assertEqual('2.1', version) def test_match_multiple_services(self): headers = wb_headers.EnvironHeaders({ 'HTTP_HEADER_ONE': 'alpha', 'HTTP_OPENSTACK_API_VERSION': 'network 5.9 ,compute 2.1,telemetry 7.8', 'HTTP_HEADER_TWO': 'beta', }) version = microversion_parse.check_standard_header( headers, 'compute') self.assertEqual('2.1', version) version = microversion_parse.check_standard_header( headers, 'telemetry') self.assertEqual('7.8', version) def test_legacy_headers_straight(self): headers = wb_headers.EnvironHeaders({ 'HTTP_HEADER_ONE': 'alpha', 'HTTP_X_OPENSTACK_NOVA_API_VERSION': ' 2.1 ', 'HTTP_HEADER_TWO': 'beta', }) version = microversion_parse.get_version( headers, service_type='compute', legacy_headers=['x-openstack-nova-api-version']) self.assertEqual('2.1', version) def test_legacy_headers_folded(self): headers = wb_headers.EnvironHeaders({ 'HTTP_HEADER_ONE': 'alpha', 'HTTP_X_OPENSTACK_NOVA_API_VERSION': ' 2.1, 9.2 ', 'HTTP_HEADER_TWO': 'beta', }) version = microversion_parse.get_version( headers, service_type='compute', legacy_headers=['x-openstack-nova-api-version']) self.assertEqual('9.2', version) microversion-parse-1.0.0/requirements.txt000066400000000000000000000000231361604315000206150ustar00rootroot00000000000000WebOb>=1.2.3 # MIT microversion-parse-1.0.0/setup.cfg000066400000000000000000000013531361604315000171610ustar00rootroot00000000000000[metadata] name = microversion_parse summary = OpenStack microversion header parser description-file = README.rst author = OpenStack author-email = openstack-discuss@lists.openstack.org home-page = http://www.openstack.org/ python-requires = >=3.6 classifier = Environment :: OpenStack Intended Audience :: Information Technology License :: OSI Approved :: Apache Software License Operating System :: POSIX :: Linux Programming Language :: Python Programming Language :: Python :: 3 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 Programming Language :: Python :: 3 :: Only Programming Language :: Python :: Implementation :: CPython [files] packages = microversion_parse microversion-parse-1.0.0/setup.py000066400000000000000000000011611361604315000170470ustar00rootroot00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import setuptools setuptools.setup( setup_requires=['pbr'], pbr=True) microversion-parse-1.0.0/test-requirements.txt000066400000000000000000000002071361604315000215760ustar00rootroot00000000000000hacking>=2.0,<2.1 # Apache-2.0 coverage>=3.6 # Apache-2.0 stestr>=1.0.0 # Apache-2.0 testtools>=1.4.0 # MIT gabbi>=1.35.0 # Apache-2.0 microversion-parse-1.0.0/tox.ini000066400000000000000000000022201361604315000166450ustar00rootroot00000000000000[tox] minversion = 3.1.1 skipsdist = True # If you want pypy or pypy3, do 'tox -epypy,pypy3', it might work! # And you can get coverage with 'tox -ecover'. envlist = py36,py35,pep8 ignore_basepython_conflict = True [testenv] deps = -r{toxinidir}/requirements.txt -r{toxinidir}/test-requirements.txt install_command = pip install -U {opts} {packages} usedevelop = True commands = stestr run {posargs} [testenv:venv] deps = -r{toxinidir}/requirements.txt -r{toxinidir}/test-requirements.txt commands = {posargs} [testenv:pep8] usedevelop = False commands = flake8 [testenv:cover] setenv = PYTHON=coverage run --source microversion_parse --parallel-mode commands = coverage erase find . -type f -name "*.pyc" -delete stestr run {posargs} coverage combine coverage html -d cover whitelist_externals = find [testenv:docs] deps = -r{toxinidir}/doc/requirements.txt commands = rm -rf doc/build sphinx-build -W --keep-going -b html -d doc/build/doctrees doc/source doc/build/html whitelist_externals = rm [flake8] ignore = H405,E126 exclude=.venv,.git,.tox,dist,*egg,*.egg-info,build,examples,doc show-source = True