././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1743430565.9930825 aiohttp_cors-0.8.1/0000755000175100001660000000000014772521646013637 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1743430557.0 aiohttp_cors-0.8.1/CHANGES.rst0000644000175100001660000000500614772521635015440 0ustar00runnerdocker========= CHANGES ========= 0.8.1 (2025-03-31) ================== - Fix packaging to not install on Python 3.8. 0.8.0 (2025-03-11) ================== - Make the library compatible with aiohttp 3.9+ and Python 3.9+ 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. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1743430557.0 aiohttp_cors-0.8.1/LICENSE0000644000175100001660000002615014772521635014646 0ustar00runnerdocker 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. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1743430557.0 aiohttp_cors-0.8.1/MANIFEST.in0000644000175100001660000000017514772521635015376 0ustar00runnerdockerinclude LICENSE include CHANGES.rst include README.rst recursive-include tests *.py include tests/integration/test_page.html ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1743430565.9930825 aiohttp_cors-0.8.1/PKG-INFO0000644000175100001660000004757114772521646014752 0ustar00runnerdockerMetadata-Version: 2.4 Name: aiohttp-cors Version: 0.8.1 Summary: CORS support for aiohttp Home-page: https://github.com/aio-libs/aiohttp-cors Author: Vladimir Rutsky and aio-libs team Author-email: vladimir@rutsky.org License: Apache License, Version 2.0 Classifier: License :: OSI Approved :: Apache Software License Classifier: Intended Audience :: Developers Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Software Development :: Libraries Classifier: Topic :: Internet :: WWW/HTTP Classifier: Framework :: AsyncIO Classifier: Operating System :: MacOS :: MacOS X Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: POSIX Classifier: Development Status :: 3 - Alpha Classifier: Framework :: aiohttp Requires-Python: >=3.9 Description-Content-Type: text/x-rst License-File: LICENSE Requires-Dist: aiohttp>=3.9 Dynamic: author Dynamic: author-email Dynamic: classifier Dynamic: description Dynamic: description-content-type Dynamic: home-page Dynamic: license Dynamic: license-file Dynamic: requires-dist Dynamic: requires-python Dynamic: summary ======================== 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 `` ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1743430557.0 aiohttp_cors-0.8.1/tests/integration/test_real_browser.py0000644000175100001660000002376214772521635023433 0ustar00runnerdocker# 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 asyncio import json import logging import os import pathlib import socket import webbrowser import pytest import selenium.common.exceptions from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from aiohttp import hdrs, web from aiohttp_cors import CorsViewMixin, ResourceOptions, setup as _setup 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 = f"http://{hostaddr}:{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(): runner = web.AppRunner(server_descr.app) await runner.setup() site = web.SockSite(runner, server_sockets[server_name]) await site.start() server_descr.runner = runner 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(): runner = server_descr.runner await runner.shutdown() await runner.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() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1743430565.9920826 aiohttp_cors-0.8.1/tests/unit/0000755000175100001660000000000014772521646015760 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1743430557.0 aiohttp_cors-0.8.1/tests/unit/__init__.py0000644000175100001660000000000014772521635020055 0ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1743430557.0 aiohttp_cors-0.8.1/tests/unit/test___about__.py0000644000175100001660000000146614772521635021304 0ustar00runnerdocker# 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 packaging.version import parse import aiohttp_cors def test_version(): """Test package version string""" # not raised parse(aiohttp_cors.__version__) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1743430557.0 aiohttp_cors-0.8.1/tests/unit/test_cors_config.py0000644000175100001660000000704414772521635021667 0ustar00runnerdocker# 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 pytest from aiohttp import web from aiohttp_cors import CorsConfig, CorsViewMixin, ResourceOptions async def _handler(request): return web.Response(text="Done") class _View(web.View, CorsViewMixin): async 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(app, cors, options_route): """Test configuring OPTIONS route""" with pytest.raises(ValueError, match="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 isinstance(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) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1743430557.0 aiohttp_cors-0.8.1/tests/unit/test_mixin.py0000644000175100001660000000540014772521635020512 0ustar00runnerdockerimport asyncio from unittest import mock import pytest from aiohttp import web from aiohttp_cors import ( APP_CONFIG_KEY, CorsConfig, CorsViewMixin, ResourceOptions, 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["*"] ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1743430557.0 aiohttp_cors-0.8.1/tests/unit/test_preflight_handler.py0000644000175100001660000000047714772521635023060 0ustar00runnerdockerfrom 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") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1743430557.0 aiohttp_cors-0.8.1/tests/unit/test_resource_options.py0000644000175100001660000000336514772521635023000 0ustar00runnerdocker# 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 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1743430557.0 aiohttp_cors-0.8.1/tests/unit/test_urldispatcher_router_adapter.py0000644000175100001660000000644514772521635025351 0ustar00runnerdocker# 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 import ResourceOptions from aiohttp_cors.urldispatcher_router_adapter import ( ResourcesUrlDispatcherRouterAdapter, ) 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(), }