pax_global_header00006660000000000000000000000064132472402760014521gustar00rootroot0000000000000052 comment=6dd1107e7b71820dd96875bfe9908788caef4f73 aiohttp-cors-0.7.0/000077500000000000000000000000001324724027600141415ustar00rootroot00000000000000aiohttp-cors-0.7.0/.gitignore000066400000000000000000000012601324724027600161300ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # 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 # Sphinx documentation docs/_build/ # PyBuilder target/ geckodriver.log .pytest_cacheaiohttp-cors-0.7.0/.jscs.json000066400000000000000000000032521324724027600160560ustar00rootroot00000000000000{ "requireCurlyBraces": [ "if", "else", "for", "while", "do", "try", "catch" ], "requireOperatorBeforeLineBreak": true, "requireCamelCaseOrUpperCaseIdentifiers": true, "maximumLineLength": { "value": 80, "allowComments": true, "allowRegex": true }, "validateIndentation": 2, "validateQuoteMarks": "'", "disallowMultipleLineStrings": true, "disallowMixedSpacesAndTabs": true, "disallowTrailingWhitespace": true, "disallowSpaceAfterPrefixUnaryOperators": true, "disallowMultipleVarDecl": true, "requireSpaceAfterKeywords": [ "if", "else", "for", "while", "do", "switch", "return", "try", "catch" ], "requireSpaceBeforeBinaryOperators": [ "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", "+=", "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", "|", "^", "&&", "||", "===", "==", ">=", "<=", "<", ">", "!=", "!==" ], "requireSpaceAfterBinaryOperators": true, "requireSpacesInConditionalExpression": true, "requireSpaceBeforeBlockStatements": true, "requireSpacesInForStatement": true, "requireLineFeedAtFileEnd": true, "requireSpacesInFunctionExpression": { "beforeOpeningCurlyBrace": true }, "disallowSpacesInsideObjectBrackets": "all", "disallowSpacesInsideArrayBrackets": "all", "disallowSpacesInsideParentheses": true, "disallowMultipleLineBreaks": true, "disallowNewlineBeforeBlockStatements": [ "if", "else", "try", "catch", "finally", "do", "while", "for", "function" ] } aiohttp-cors-0.7.0/.jshintrc000066400000000000000000000022701324724027600157670ustar00rootroot00000000000000{ "asi": false, "bitwise": false, "boss": false, "browser": true, "camelcase": true, "couch": false, "curly": true, "debug": false, "devel": true, "dojo": false, "eqeqeq": true, "eqnull": true, "es3": true, "esnext": false, "evil": false, "expr": true, "forin": false, "funcscope": true, "globalstrict": false, "immed": true, "iterator": false, "jquery": false, "lastsemic": false, "latedef": false, "laxbreak": true, "laxcomma": false, "loopfunc": true, "mootools": false, "multistr": false, "newcap": true, "noarg": true, "node": false, "noempty": false, "nonew": true, "nonstandard": false, "nomen": false, "onecase": false, "onevar": false, "passfail": false, "plusplus": false, "proto": false, "prototypejs": false, "regexdash": true, "regexp": false, "rhino": false, "undef": true, "unused": "strict", "scripturl": true, "shadow": false, "smarttabs": true, "strict": false, "sub": false, "supernew": false, "trailing": true, "validthis": true, "withstmt": false, "white": true, "worker": false, "wsh": false, "yui": false, "indent": 4, "predef": ["require", "define", "JSON"], "quotmark": "single", "maxcomplexity": 10, "esnext": true } aiohttp-cors-0.7.0/.pep8rc000066400000000000000000000003331324724027600153420ustar00rootroot00000000000000; TODO: This configuration currently not used in pytest-pep8, see ; [pep8] show-source = yes statistics = yes count = yes aiohttp-cors-0.7.0/.pylintrc000066400000000000000000000304321324724027600160100ustar00rootroot00000000000000[MASTER] # Specify a configuration file. #rcfile= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Profiled execution. profile=no # Add files or directories to the blacklist. They should be base names, not # paths. ignore= # Pickle collected data for later comparisons. persistent=yes # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. load-plugins= # Deprecated. It was used to include message's id in output. Use --msg-template # instead. #include-ids=no # Deprecated. It was used to include symbolic ids of messages in output. Use # --msg-template instead. #symbols=no # Use multiple processes to speed up Pylint. jobs=1 # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. unsafe-load-any-extension=no # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code extension-pkg-whitelist= # Allow optimization of some AST trees. This will activate a peephole AST # optimizer, which will apply various small optimizations. For instance, it can # be used to obtain the result of joining multiple strings with the addition # operator. Joining a lot of strings can lead to a maximum recursion error in # Pylint and this flag can prevent that. It has one side effect, the resulting # AST will be different than the one from reality. optimize-ast=no [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED confidence= # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time. See also the "--disable" option for examples. #enable= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once).You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use"--disable=all --enable=classes # --disable=W" disable=E1604,W1629,W1605,I0020,W1609,W1615,W1610,W1618,W1608,W1622,W1640,E1603,W1635,W1636,W1634,W1628,W1614,E1601,W1601,I0021,E1605,W1611,W1612,W1619,W1616,W1638,W1626,W1630,W1607,E1602,W1623,W1613,W1606,W1625,W0704,W1639,W1603,W1632,E1606,W1602,W1637,W1624,W1620,E1608,W1627,E1607,W1633,W1604,W1617,W1621 [REPORTS] # Set the output format. Available formats are text, parseable, colorized, msvs # (visual studio) and html. You can also give a reporter class, eg # mypackage.mymodule.MyReporterClass. output-format=text # Put messages in a separate file for each module / package specified on the # command line instead of printing them on stdout. Reports (if any) will be # written in a file name "pylint_global.[txt|html]". files-output=no # Tells whether to display a full report or only the messages reports=yes # Python expression which should return a note less than 10 (10 is the highest # note). You have access to the variables errors warning, statement which # respectively contain the number of errors / warnings messages and the total # number of statements analyzed. This is used by the global evaluation report # (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Add a comment according to your evaluation note. This is used by the global # evaluation report (RP0004). comment=no # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details. # Path/line on separate added to allow IDE to parse error messages and # provide interactive link on the place of the error. msg-template={path}:{line}: {C}:{msg_id}:{line:3d},{column:2d}: {msg} ({symbol}) [LOGGING] # Logging modules to check that the string format arguments are in logging # function parameter format logging-modules=logging [FORMAT] # Maximum number of characters on a single line. max-line-length=100 # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=^\s*(# )??$ # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=no # List of optional constructs for which whitespace checking is disabled no-space-check=trailing-comma,dict-separator # Maximum number of lines in a module max-module-lines=1000 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' # Number of spaces of indent required inside a hanging or continued line. indent-after-paren=4 # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. expected-line-ending-format= [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME,XXX,TODO [VARIABLES] # Tells whether we should check for unused import in __init__ files. init-import=no # A regular expression matching the name of dummy variables (i.e. expectedly # not used). dummy-variables-rgx=_$|dummy # List of additional names supposed to be defined in builtins. Remember that # you should avoid to define new builtins when possible. additional-builtins= # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. callbacks=cb_,_cb [BASIC] # Required attributes for module, separated by a comma required-attributes= # List of builtins function names that should not be used, separated by a comma bad-functions=map,filter # Good variable names which should always be accepted, separated by a comma good-names=i,j,k,ex,Run,_ # Bad variable names which should always be refused, separated by a comma bad-names=foo,bar,baz,toto,tutu,tata # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. name-group= # Include a hint for the correct naming format with invalid-name include-naming-hint=no # Regular expression matching correct module names module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Naming hint for module names module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Regular expression matching correct method names method-rgx=[a-z_][a-z0-9_]{2,30}$ # Naming hint for method names method-name-hint=[a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct class attribute names class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ # Naming hint for class attribute names class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ # Regular expression matching correct class names class-rgx=[A-Z_][a-zA-Z0-9]+$ # Naming hint for class names class-name-hint=[A-Z_][a-zA-Z0-9]+$ # Regular expression matching correct function names function-rgx=[a-z_][a-z0-9_]{2,30}$ # Naming hint for function names function-name-hint=[a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct inline iteration names inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ # Naming hint for inline iteration names inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ # Regular expression matching correct constant names const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ # Naming hint for constant names const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ # Regular expression matching correct argument names argument-rgx=[a-z_][a-z0-9_]{2,30}$ # Naming hint for argument names argument-name-hint=[a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct attribute names attr-rgx=[a-z_][a-z0-9_]{2,30}$ # Naming hint for attribute names attr-name-hint=[a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct variable names variable-rgx=[a-z_][a-z0-9_]{2,30}$ # Naming hint for variable names variable-name-hint=[a-z_][a-z0-9_]{2,30}$ # Regular expression which should only match function or class names that do # not require a docstring. no-docstring-rgx=__.*__ # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=-1 [TYPECHECK] # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # List of module names for which member attributes should not be checked # (useful for modules/projects where namespaces are manipulated during runtime # and thus existing member attributes cannot be deduced by static analysis ignored-modules= # List of classes names for which member attributes should not be checked # (useful for classes with attributes dynamically set). ignored-classes=SQLObject # When zope mode is activated, add a predefined set of Zope acquired attributes # to generated-members. zope=no # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E0201 when accessed. Python regular # expressions are accepted. generated-members=REQUEST,acl_users,aq_parent [SPELLING] # Spelling dictionary name. Available dictionaries: none. To make it working # install python-enchant package. spelling-dict= # List of comma separated words that should not be checked. spelling-ignore-words= # A path to a file that contains private dictionary; one word per line. spelling-private-dict-file= # Tells whether to store unknown words to indicated private dictionary in # --spelling-private-dict-file option instead of raising a message. spelling-store-unknown-words=no [SIMILARITIES] # Minimum lines number of a similarity. min-similarity-lines=4 # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # Ignore imports when computing similarities. ignore-imports=no [IMPORTS] # Deprecated modules which should not be used, separated by a comma deprecated-modules=stringprep,optparse # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled) import-graph= # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled) ext-import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled) int-import-graph= [CLASSES] # List of interface methods to ignore, separated by a comma. This is used for # instance to not check methods defines in Zope's Interface base class. ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__,__new__,setUp # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=mcs # List of member names, which should be excluded from the protected access # warning. exclude-protected=_asdict,_fields,_replace,_source,_make [DESIGN] # Maximum number of arguments for function / method max-args=5 # Argument names that match this expression will be ignored. Default to name # with leading underscore ignored-argument-names=_.* # Maximum number of locals for function / method body max-locals=15 # Maximum number of return / yield for function / method body max-returns=6 # Maximum number of branch for function / method body max-branches=12 # Maximum number of statements in function / method body max-statements=50 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of attributes for a class (see R0902). max-attributes=7 # Minimum number of public methods for a class (see R0903). min-public-methods=2 # Maximum number of public methods for a class (see R0904). max-public-methods=20 [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "Exception" overgeneral-exceptions=Exception aiohttp-cors-0.7.0/.pyup.yml000066400000000000000000000001221324724027600157320ustar00rootroot00000000000000# Label PRs with `deps-update` label label_prs: deps-update schedule: every week aiohttp-cors-0.7.0/.travis.yml000066400000000000000000000037371324724027600162640ustar00rootroot00000000000000language: python python: - 3.5 - 3.6 # TODO: Use Travis apt addon, when chromium-chromedriver will be supported # three: https://github.com/travis-ci/apt-package-whitelist/issues/574 before_install: - sudo apt-get -qq update - sudo apt-get install -y chromium-browser chromium-chromedriver install: - pip install --upgrade pip setuptools wheel - pip install -Ur requirements-dev.txt - pip install codecov before_script: # Start X-server for Selenium tests. - "export DISPLAY=:99.0" - "sh -e /etc/init.d/xvfb start" - sleep 3 # give xvfb some time to start script: - '[ "$TYPE" != "test" ] || python setup.py test --addopts -v --addopts -s' - '[ "$TYPE" != "lint" ] || python setup.py check -rms' after_success: codecov env: global: - WEBDRIVER_CHROMEDRIVER_PATH=/usr/lib/chromium-browser/chromedriver matrix: # PYTHONASYNCIODEBUG environment variable is considered as enabled if it # is any non empty string. - TYPE=test matrix: include: # Environment to deploy project on PyPI. - python: "3.5" env: DEPLOY_ENV=1 - python: "3.5" env: TYPE=lint # Deploy on PyPI all tagged build on master branch. deploy: provider: pypi user: aiohttp-cors-deploy password: secure: KViGT/W2vWRWZkV5bZYLiI3v/qXVRGEFAs8G1OMx/OhLvHTj8vO6pZ+hlzLi9zTnBTVHG2xEOrwtjiuHxpJMcDPAul3rn0fwSXy9BRDAeR7B7RIlvLxegMRTnWtsj5x8/VkqQDrPW5YWmuXFb4tDJ+LEkadUrkF9YhJvtUnSQcEOOHVvJa4DekMhZEVM8AKA+7AT9FibWZbJ5s8bTjLke77/eyX7+1DdgC7G++ZesK2HKS1vlM7fN+cWPyUFofXwcEc42rwQwJ5FY2saqTvPN5GBOMpXdaBUmSyYT64447TVFoINbAFuCa3tUeY7ZQpC6B8bHVqEGq+UAujUGU7uhid29CHV03PTFeupTZRscVDkL+IEUjK6Ft+x/B9eStVpKh9d5Yh8INZkdoHVmybJo62k/YHwxAu7ftG+q1bUAHwgKkukXa+ZpmSD2v6BggVUBS6qFwv6tnKpuI0jRsneEUXPmJVUHpv6lPzVRPW/lQDZqxUvESz9w9mitwBiMA7q8jyL9w4zJVKAETjo6llWGQ2wOLjaz3LwuQ8vDOKfWOdvk78W8Usw5amkp2invyidU/2+Y1hlekRuhaMEaUdd4GPmP8beOh7CEXJr5bD3QjbqOpOMi+d+3rYVR0NZMWxawgtUGMBb/8DUNq4sD4Na5G3sGSy+rHMtDAuMOOUlLoU= distributions: sdist bdist_wheel on: tags: true branch: master condition: $DEPLOY_ENV = 1 aiohttp-cors-0.7.0/CHANGES.rst000066400000000000000000000045101324724027600157430ustar00rootroot00000000000000========= CHANGES ========= 0.7.0 (2018-03-05) ================== - Make web view check implicit and type based (#159) - Disable Python 3.4 support (#156) - Support aiohttp 3.0+ (#155) 0.6.0 (2017-12-21) ================== - Support aiohttp views by ``CorsViewMixin`` (#145) 0.5.3 (2017-04-21) ================== - Fix ``typing`` being installed on Python 3.6. 0.5.2 (2017-03-28) ================== - Fix tests compatibility with ``aiohttp`` 2.0. This release and release v0.5.0 should work on ``aiohttp`` 2.0. 0.5.1 (2017-03-23) ================== - Enforce ``aiohttp`` version to be less than 2.0. Newer ``aiohttp`` releases will be supported in the next release. 0.5.0 (2016-11-18) ================== - Fix compatibility with ``aiohttp`` 1.1 0.4.0 (2016-04-04) ================== - Fixed support with new Resources objects introduced in ``aiohttp`` 0.21.0. Minimum supported version of ``aiohttp`` is 0.21.4 now. - New Resources objects are supported. You can specify default configuration for a Resource and use ``allow_methods`` to explicitly list allowed methods (or ``*`` for all HTTP methods): .. code-block:: python # Allow POST and PUT requests from "http://client.example.org" origin. hello_resource = cors.add(app.router.add_resource("/hello"), { "http://client.example.org": aiohttp_cors.ResourceOptions( allow_methods=["POST", "PUT"]), }) # No need to add POST and PUT routes into CORS configuration object. hello_resource.add_route("POST", handler_post) hello_resource.add_route("PUT", handler_put) # Still you can add additional methods to CORS configuration object: cors.add(hello_resource.add_route("DELETE", handler_delete)) - ``AbstractRouterAdapter`` was completely rewritten to be more Router agnostic. 0.3.0 (2016-02-06) ================== - Rename ``UrlDistatcherRouterAdapter`` to ``UrlDispatcherRouterAdapter``. - Set maximum supported ``aiohttp`` version to ``0.20.2``, see bug #30 for details. 0.2.0 (2015-11-30) ================== - Move ABCs from ``aiohttp_cors.router_adapter`` to ``aiohttp_cors.abc``. - Rename ``RouterAdapter`` to ``AbstractRouterAdapter``. - Fix bug with configuring CORS for named routes. 0.1.0 (2015-11-05) ================== * Initial release. aiohttp-cors-0.7.0/LICENSE000066400000000000000000000261511324724027600151530ustar00rootroot00000000000000 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 2015-2018 Vladimir Rutsky and aio-libs team 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. aiohttp-cors-0.7.0/MANIFEST.in000066400000000000000000000001751324724027600157020ustar00rootroot00000000000000include LICENSE include CHANGES.rst include README.rst recursive-include tests *.py include tests/integration/test_page.html aiohttp-cors-0.7.0/Makefile000066400000000000000000000001221324724027600155740ustar00rootroot00000000000000all: test flake: flake8 aiohttp_cors tests setup.py test: flake pytest tests aiohttp-cors-0.7.0/README.rst000066400000000000000000000405171324724027600156370ustar00rootroot00000000000000======================== CORS support for aiohttp ======================== ``aiohttp_cors`` library implements `Cross Origin Resource Sharing (CORS) `__ support for `aiohttp `__ asyncio-powered asynchronous HTTP server. Jump directly to `Usage`_ part to see how to use ``aiohttp_cors``. Same-origin policy ================== Web security model is tightly connected to `Same-origin policy (SOP) `__. In short: web pages cannot *Read* resources which origin doesn't match origin of requested page, but can *Embed* (or *Execute*) resources and have limited ability to *Write* resources. Origin of a page is defined in the `Standard `__ as tuple ``(schema, host, port)`` (there is a notable exception with Internet Explorer: it doesn't use port to define origin, but uses it's own `Security Zones `__). Can *Embed* means that resource from other origin can be embedded into the page, e.g. by using `` aiohttp-cors-0.7.0/tests/integration/test_real_browser.py000066400000000000000000000245541324724027600237370ustar00rootroot00000000000000# Copyright 2015 Vladimir Rutsky # # 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. """System test using real browser. """ import os import json import asyncio import socket import pathlib import logging import webbrowser from aiohttp import web, hdrs import pytest import selenium.common.exceptions from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from aiohttp_cors import setup as _setup, ResourceOptions, CorsViewMixin class _ServerDescr: """Auxiliary class for storing server info""" def __init__(self): self.app = None self.cors = None self.handler = None self.server = None self.url = None class IntegrationServers: """Integration servers starting/stopping manager""" def __init__(self, use_resources, use_webview, *, loop=None): self.servers = {} self.loop = loop if self.loop is None: self.loop = asyncio.get_event_loop() self.use_resources = use_resources self.use_webview = use_webview self._logger = logging.getLogger("IntegrationServers") @property def origin_server_url(self): return self.servers["origin"].url async def start_servers(self): test_page_path = pathlib.Path(__file__).with_name("test_page.html") async def handle_test_page(request: web.Request) -> web.StreamResponse: with test_page_path.open("r", encoding="utf-8") as f: return web.Response( text=f.read(), headers={hdrs.CONTENT_TYPE: "text/html"}) async def handle_no_cors(request: web.Request) -> web.StreamResponse: return web.Response( text="""{"type": "no_cors.json"}""", headers={hdrs.CONTENT_TYPE: "application/json"}) async def handle_resource(request: web.Request) -> web.StreamResponse: return web.Response( text="""{"type": "resource"}""", headers={hdrs.CONTENT_TYPE: "application/json"}) async def handle_servers_addresses( request: web.Request) -> web.StreamResponse: servers_addresses = \ {name: descr.url for name, descr in self.servers.items()} return web.Response( text=json.dumps(servers_addresses)) class ResourceView(web.View, CorsViewMixin): async def get(self) -> web.StreamResponse: return await handle_resource(self.request) # For most resources: # "origin" server has no CORS configuration. # "allowing" server explicitly allows CORS requests to "origin" server. # "denying" server explicitly disallows CORS requests to "origin" # server. # "free_for_all" server allows CORS requests for all origins server. # "no_cors" server has no CORS configuration. cors_server_names = ["allowing", "denying", "free_for_all"] server_names = cors_server_names + ["origin", "no_cors"] for server_name in server_names: assert server_name not in self.servers self.servers[server_name] = _ServerDescr() server_sockets = {} # Create applications and sockets. for server_name, server_descr in self.servers.items(): server_descr.app = web.Application() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("127.0.0.1", 0)) sock.listen(10) server_sockets[server_name] = sock hostaddr, port = sock.getsockname() server_descr.url = "http://{host}:{port}".format( host=hostaddr, port=port) # Server test page from origin server. self.servers["origin"].app.router.add_route( "GET", "/", handle_test_page) self.servers["origin"].app.router.add_route( "GET", "/servers_addresses", handle_servers_addresses) # Add routes to all servers. for server_name in server_names: app = self.servers[server_name].app app.router.add_route("GET", "/no_cors.json", handle_no_cors) if self.use_webview: app.router.add_route("*", "/cors_resource", ResourceView, name="cors_resource") else: app.router.add_route("GET", "/cors_resource", handle_resource, name="cors_resource") cors_default_configs = { "allowing": { self.servers["origin"].url: ResourceOptions( allow_credentials=True, expose_headers="*", allow_headers="*") }, "denying": { # Allow requests to other than "origin" server. self.servers["allowing"].url: ResourceOptions( allow_credentials=True, expose_headers="*", allow_headers="*") }, "free_for_all": { "*": ResourceOptions( allow_credentials=True, expose_headers="*", allow_headers="*") }, } # Configure CORS. for server_name, server_descr in self.servers.items(): default_config = cors_default_configs.get(server_name) if default_config is None: continue server_descr.cors = _setup( server_descr.app, defaults=default_config) # Add CORS routes. for server_name in cors_server_names: server_descr = self.servers[server_name] # TODO: Starting from aiohttp 0.21.0 name-based access returns # Resource, not Route. Manually get route while aiohttp_cors # doesn't support configuring for Resources. resource = server_descr.app.router["cors_resource"] route = next(iter(resource)) if self.use_resources: server_descr.cors.add(resource) server_descr.cors.add(route) elif self.use_webview: server_descr.cors.add(route) else: server_descr.cors.add(route) # Start servers. for server_name, server_descr in self.servers.items(): handler = server_descr.app.make_handler() server = await self.loop.create_server( handler, sock=server_sockets[server_name]) server_descr.handler = handler server_descr.server = server self._logger.info("Started server '%s' at '%s'", server_name, server_descr.url) async def stop_servers(self): for server_descr in self.servers.values(): server_descr.server.close() await server_descr.handler.shutdown() await server_descr.server.wait_closed() await server_descr.app.cleanup() self.servers = {} def _get_chrome_driver(): driver_path_env = "WEBDRIVER_CHROMEDRIVER_PATH" if driver_path_env in os.environ: driver = webdriver.Chrome(executable_path=os.environ[driver_path_env]) else: driver = webdriver.Chrome() return driver @pytest.fixture(params=[(False, False), (True, False), (False, True)]) def server(request, loop): async def inner(): # to grab implicit loop return IntegrationServers(*request.param) return loop.run_until_complete(inner()) @pytest.fixture(params=[webdriver.Firefox, _get_chrome_driver]) def driver(request): try: driver = request.param() except selenium.common.exceptions.WebDriverException: pytest.skip("Driver is not supported") yield driver driver.close() async def test_in_webdriver(driver, server): loop = asyncio.get_event_loop() await server.start_servers() def selenium_thread(): driver.get(server.origin_server_url) assert "aiohttp_cors" in driver.title wait = WebDriverWait(driver, 10) run_button = wait.until(EC.element_to_be_clickable( (By.ID, "runTestsButton"))) # Start tests. run_button.send_keys(Keys.RETURN) # Wait while test will finish (until clear button is not # activated). wait.until(EC.element_to_be_clickable( (By.ID, "clearResultsButton"))) # Get results json results_area = driver.find_element_by_id("results") return json.loads(results_area.get_attribute("value")) try: results = await loop.run_in_executor( None, selenium_thread) assert results["status"] == "success" for test_name, test_data in results["data"].items(): assert test_data["status"] == "success" finally: await server.stop_servers() def _run_integration_server(): """Runs integration server for interactive debugging.""" logging.basicConfig(level=logging.INFO) logger = logging.getLogger("run_integration_server") loop = asyncio.get_event_loop() servers = IntegrationServers(False, True) logger.info("Starting integration servers...") loop.run_until_complete(servers.start_servers()) try: webbrowser.open(servers.origin_server_url) except webbrowser.Error: pass try: loop.run_forever() except KeyboardInterrupt: pass finally: logger.info("Stopping integration servers...") loop.run_until_complete(servers.stop_servers()) if __name__ == "__main__": # This module can be run in the following way: # $ python -m tests.integration.test_real_browser # from aiohttp_cors root directory. _run_integration_server() aiohttp-cors-0.7.0/tests/unit/000077500000000000000000000000001324724027600162625ustar00rootroot00000000000000aiohttp-cors-0.7.0/tests/unit/__init__.py000066400000000000000000000000001324724027600203610ustar00rootroot00000000000000aiohttp-cors-0.7.0/tests/unit/test___about__.py000066400000000000000000000015031324724027600216000ustar00rootroot00000000000000# Copyright 2015 Vladimir Rutsky # # 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. """Test aiohttp_cors package metainformation. """ from pkg_resources import parse_version import aiohttp_cors def test_version(): """Test package version string""" # not raised parse_version(aiohttp_cors.__version__) aiohttp-cors-0.7.0/tests/unit/test_cors_config.py000066400000000000000000000072641324724027600221770ustar00rootroot00000000000000# Copyright 2015 Vladimir Rutsky # # 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. """aiohttp_cors.cors_config unit tests. """ import asyncio import pytest from aiohttp import web from aiohttp_cors import CorsConfig, ResourceOptions, CorsViewMixin async def _handler(request): return web.Response(text="Done") class _View(web.View, CorsViewMixin): @asyncio.coroutine def get(self): return web.Response(text="Done") @pytest.fixture def app(): return web.Application() @pytest.fixture def cors(app): return CorsConfig(app, defaults={ "*": ResourceOptions() }) @pytest.fixture def get_route(app): return app.router.add_route( "GET", "/get_path", _handler) @pytest.fixture def options_route(app): return app.router.add_route( "OPTIONS", "/options_path", _handler) def test_add_options_route(cors, options_route): """Test configuring OPTIONS route""" with pytest.raises(ValueError, match="/options_path already has OPTIONS handler"): cors.add(options_route.resource) def test_plain_named_route(app, cors): """Test adding plain named route.""" # Adding CORS routes should not introduce new named routes. assert len(app.router.keys()) == 0 route = app.router.add_route( "GET", "/{name}", _handler, name="dynamic_named_route") assert len(app.router.keys()) == 1 cors.add(route) assert len(app.router.keys()) == 1 def test_dynamic_named_route(app, cors): """Test adding dynamic named route.""" assert len(app.router.keys()) == 0 route = app.router.add_route( "GET", "/{name}", _handler, name="dynamic_named_route") assert len(app.router.keys()) == 1 cors.add(route) assert len(app.router.keys()) == 1 def test_static_named_route(app, cors): """Test adding dynamic named route.""" assert len(app.router.keys()) == 0 route = app.router.add_static( "/file", "/", name="dynamic_named_route") assert len(app.router.keys()) == 1 cors.add(route) assert len(app.router.keys()) == 1 def test_static_resource(app, cors): """Test adding static resource.""" assert len(app.router.keys()) == 0 app.router.add_static( "/file", "/", name="dynamic_named_route") assert len(app.router.keys()) == 1 for resource in list(app.router.resources()): if issubclass(resource, web.StaticResource): cors.add(resource) assert len(app.router.keys()) == 1 def test_web_view_resource(app, cors): """Test adding resource with web.View as handler""" assert len(app.router.keys()) == 0 route = app.router.add_route( "GET", "/{name}", _View, name="dynamic_named_route") assert len(app.router.keys()) == 1 cors.add(route) assert len(app.router.keys()) == 1 def test_web_view_warning(app, cors): """Test adding resource with web.View as handler""" route = app.router.add_route("*", "/", _View) with pytest.warns(DeprecationWarning): cors.add(route, webview=True) def test_disable_bare_view(app, cors): class View(web.View): pass route = app.router.add_route("*", "/", View) with pytest.raises(ValueError): cors.add(route) aiohttp-cors-0.7.0/tests/unit/test_mixin.py000066400000000000000000000054511324724027600210240ustar00rootroot00000000000000import asyncio from unittest import mock import pytest from aiohttp import web from aiohttp_cors import CorsConfig, APP_CONFIG_KEY from aiohttp_cors import ResourceOptions, CorsViewMixin, custom_cors DEFAULT_CONFIG = { '*': ResourceOptions() } CLASS_CONFIG = { '*': ResourceOptions() } CUSTOM_CONFIG = { 'www.client1.com': ResourceOptions(allow_headers=['X-Host']) } class SimpleView(web.View, CorsViewMixin): async def get(self): return web.Response(text="Done") class SimpleViewWithConfig(web.View, CorsViewMixin): cors_config = CLASS_CONFIG async def get(self): return web.Response(text="Done") class CustomMethodView(web.View, CorsViewMixin): cors_config = CLASS_CONFIG async def get(self): return web.Response(text="Done") @custom_cors(CUSTOM_CONFIG) async def post(self): return web.Response(text="Done") @pytest.fixture def _app(): return web.Application() @pytest.fixture def cors(_app): ret = CorsConfig(_app, defaults=DEFAULT_CONFIG) _app[APP_CONFIG_KEY] = ret return ret @pytest.fixture def app(_app, cors): # a trick to install a cors into app return _app def test_raise_exception_when_cors_not_configure(): request = mock.Mock() request.app = {} view = CustomMethodView(request) with pytest.raises(ValueError): view.get_request_config(request, 'post') async def test_raises_forbidden_when_config_not_found(app): app[APP_CONFIG_KEY].defaults = {} request = mock.Mock() request.app = app request.headers = { 'Origin': '*', 'Access-Control-Request-Method': 'GET' } view = SimpleView(request) with pytest.raises(web.HTTPForbidden): await view.options() def test_method_with_custom_cors(app): """Test adding resource with web.View as handler""" request = mock.Mock() request.app = app view = CustomMethodView(request) assert hasattr(view.post, 'post_cors_config') assert asyncio.iscoroutinefunction(view.post) config = view.get_request_config(request, 'post') assert config.get('www.client1.com') == CUSTOM_CONFIG['www.client1.com'] def test_method_with_class_config(app): """Test adding resource with web.View as handler""" request = mock.Mock() request.app = app view = SimpleViewWithConfig(request) assert not hasattr(view.get, 'get_cors_config') config = view.get_request_config(request, 'get') assert config.get('*') == CLASS_CONFIG['*'] def test_method_with_default_config(app): """Test adding resource with web.View as handler""" request = mock.Mock() request.app = app view = SimpleView(request) assert not hasattr(view.get, 'get_cors_config') config = view.get_request_config(request, 'get') assert config.get('*') == DEFAULT_CONFIG['*'] aiohttp-cors-0.7.0/tests/unit/test_preflight_handler.py000066400000000000000000000004771324724027600233640ustar00rootroot00000000000000from unittest import mock import pytest from aiohttp_cors.preflight_handler import _PreflightHandler async def test_raises_when_handler_not_extend(): request = mock.Mock() handler = _PreflightHandler() with pytest.raises(NotImplementedError): await handler._get_config(request, 'origin', 'GET') aiohttp-cors-0.7.0/tests/unit/test_resource_options.py000066400000000000000000000033721324724027600233020ustar00rootroot00000000000000# Copyright 2015 Vladimir Rutsky # # 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. """aiohttp_cors.resource_options unit tests. """ import pytest from aiohttp_cors.resource_options import ResourceOptions def test_init_no_args(): """Test construction without arguments""" opts = ResourceOptions() assert not opts.allow_credentials assert not opts.expose_headers assert not opts.allow_headers assert opts.max_age is None def test_comparison(): assert ResourceOptions() == ResourceOptions() assert not (ResourceOptions() != ResourceOptions()) assert not (ResourceOptions(allow_credentials=True) == ResourceOptions()) assert ResourceOptions(allow_credentials=True) != ResourceOptions() def test_allow_methods(): assert ResourceOptions().allow_methods is None assert ResourceOptions(allow_methods='*').allow_methods == '*' assert ResourceOptions(allow_methods=[]).allow_methods == frozenset() assert (ResourceOptions(allow_methods=['get']).allow_methods == frozenset(['GET'])) assert (ResourceOptions(allow_methods=['get', 'Post']).allow_methods == {'GET', 'POST'}) with pytest.raises(ValueError): ResourceOptions(allow_methods='GET') # TODO: test arguments parsing aiohttp-cors-0.7.0/tests/unit/test_urldispatcher_router_adapter.py000066400000000000000000000067241324724027600256550ustar00rootroot00000000000000# Copyright 2015 Vladimir Rutsky # # 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. """aiohttp_cors.urldispatcher_router_adapter unit tests. """ from unittest import mock import pytest from aiohttp import web from aiohttp_cors.urldispatcher_router_adapter import \ ResourcesUrlDispatcherRouterAdapter from aiohttp_cors import ResourceOptions async def _handler(request): return web.Response(text="Done") @pytest.fixture def app(): return web.Application() @pytest.fixture def adapter(app): return ResourcesUrlDispatcherRouterAdapter( app.router, defaults={ "*": ResourceOptions() }) @pytest.fixture def get_route(app): return app.router.add_route( "GET", "/get_path", _handler) @pytest.fixture def options_route(app): return app.router.add_route( "OPTIONS", "/options_path", _handler) def test_add_get_route(adapter, get_route): """Test configuring GET route""" result = adapter.add_preflight_handler( get_route.resource, _handler) assert result is None assert len(adapter._resource_config) == 0 assert len(adapter._resources_with_preflight_handlers) == 1 assert len(adapter._preflight_routes) == 1 def test_add_options_route(adapter, options_route): """Test configuring OPTIONS route""" adapter.add_preflight_handler(options_route, _handler) assert not adapter._resources_with_preflight_handlers assert not adapter._preflight_routes def test_get_non_preflight_request_config(adapter, get_route): adapter.add_preflight_handler(get_route.resource, _handler) adapter.set_config_for_routing_entity( get_route.resource, { 'http://example.org': ResourceOptions(), }) adapter.add_preflight_handler(get_route, _handler) adapter.set_config_for_routing_entity( get_route, { 'http://test.example.org': ResourceOptions(), }) request = mock.Mock() with mock.patch('aiohttp_cors.urldispatcher_router_adapter.' 'ResourcesUrlDispatcherRouterAdapter.' 'is_cors_enabled_on_request' ) as is_cors_enabled_on_request, \ mock.patch('aiohttp_cors.urldispatcher_router_adapter.' 'ResourcesUrlDispatcherRouterAdapter.' '_request_resource' ) as _request_resource: is_cors_enabled_on_request.return_value = True _request_resource.return_value = get_route.resource assert (adapter.get_non_preflight_request_config(request) == { '*': ResourceOptions(), 'http://example.org': ResourceOptions(), }) request.method = 'GET' assert (adapter.get_non_preflight_request_config(request) == { '*': ResourceOptions(), 'http://example.org': ResourceOptions(), 'http://test.example.org': ResourceOptions(), }) aiohttp-cors-0.7.0/tox.ini000066400000000000000000000006741324724027600154630ustar00rootroot00000000000000[tox] envlist = py34, py35, check [testenv] commands = {envpython} setup.py test deps = pytest [testenv:check] deps = docutils pygments flake8 commands = {envpython} setup.py check -rms flake8 aiohttp_cors tests [pytest] testpaths = aiohttp_cors tests addopts= --cov=aiohttp_cors --cov-report=term --cov-report=html --cov-branch --no-cov-on-fail ;addopts = --cov aiohttp_cors ; --pylint-rcfile=.pylintrc --pylint