pax_global_header00006660000000000000000000000064143704316750014524gustar00rootroot0000000000000052 comment=8f4158c2071003aa4b2b5b9bfc4fb0c7dc941a42 compat-fork-aiohttp-sse-client-8f4158c/000077500000000000000000000000001437043167500200245ustar00rootroot00000000000000compat-fork-aiohttp-sse-client-8f4158c/.editorconfig000066400000000000000000000004441437043167500225030ustar00rootroot00000000000000# http://editorconfig.org root = true [*] indent_style = space indent_size = 4 trim_trailing_whitespace = true insert_final_newline = true charset = utf-8 end_of_line = lf [*.bat] indent_style = tab end_of_line = crlf [LICENSE] insert_final_newline = false [Makefile] indent_style = tab compat-fork-aiohttp-sse-client-8f4158c/.github/000077500000000000000000000000001437043167500213645ustar00rootroot00000000000000compat-fork-aiohttp-sse-client-8f4158c/.github/ISSUE_TEMPLATE.md000066400000000000000000000004761437043167500241000ustar00rootroot00000000000000* Python version: * Operating System: * aiohttp version: ### Description Describe what you were trying to get done. Tell us what happened, what went wrong, and what you expected to happen. ### What I Did ``` Paste the command(s) you ran and the output. If there was a crash, please include the traceback here. ``` compat-fork-aiohttp-sse-client-8f4158c/.github/workflows/000077500000000000000000000000001437043167500234215ustar00rootroot00000000000000compat-fork-aiohttp-sse-client-8f4158c/.github/workflows/pullrequest.yaml000066400000000000000000000034341437043167500266760ustar00rootroot00000000000000name: python on: [push] jobs: build: runs-on: ubuntu-latest strategy: matrix: python-version: [3.7, 3.8, 3.9, "3.10", "3.11"] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Cache pip uses: actions/cache@v2 with: # This path is specific to Ubuntu path: ~/.cache/pip # Look to see if there is a cache hit for the corresponding requirements file key: ${{ runner.os }}-${{ matrix.python-version }}-pip-${{ hashFiles('requirements_dev.txt') }}-${{ hashFiles('setup.py') }} restore-keys: | ${{ runner.os }}-${{ matrix.python-version }}-pip- ${{ runner.os }}-${{ matrix.python-version }}- - name: Install dev dependencies run: | python -m pip install --upgrade pip pip install -r requirements_dev.txt - name: Lint with flake8 run: | flake8 aiohttp_sse_client2 - name: Install run: | pip install -e . - name: Test with pytest run: | pytest - name: Build wheel if: matrix.python-version == 3.7 run: | python setup.py sdist bdist_wheel - name: Publish distribution 📦 to Test PyPI if: matrix.python-version == 3.7 && startsWith(github.ref, 'refs/tags') uses: pypa/gh-action-pypi-publish@master with: password: ${{ secrets.TEST_PYPI_API_TOKEN }} repository_url: https://test.pypi.org/legacy/ - name: Publish distribution 📦 to PyPI if: matrix.python-version == 3.7 && startsWith(github.ref, 'refs/tags') uses: pypa/gh-action-pypi-publish@master with: password: ${{ secrets.PYPI_API_TOKEN }} compat-fork-aiohttp-sse-client-8f4158c/.gitignore000066400000000000000000000012311437043167500220110ustar00rootroot00000000000000# 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/ wheels/ *.egg-info/ .installed.cfg *.egg # 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/ .pytest_cache/ # Translations *.mo *.pot # Sphinx documentation docs/_build/ # pyenv .python-version # dotenv .env # virtualenv .venv venv/ ENV/ # mkdocs documentation /site # mypy .mypy_cache/ # IDE .idea .vscode compat-fork-aiohttp-sse-client-8f4158c/AUTHORS.rst000066400000000000000000000002751437043167500217070ustar00rootroot00000000000000======= Credits ======= Development Lead ---------------- * Jason Hu Contributors ------------ * Ron Serruya @Ronserruya * tjstub @tjstub * Pavel Filatov @paulefoe compat-fork-aiohttp-sse-client-8f4158c/CONTRIBUTING.rst000066400000000000000000000070251437043167500224710ustar00rootroot00000000000000.. highlight:: shell ============ Contributing ============ Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given. You can contribute in many ways: Types of Contributions ---------------------- Report Bugs ~~~~~~~~~~~ Report bugs at https://github.com/rtfol/aiohttp-sse-client/issues. If you are reporting a bug, please include: * Your operating system name and version. * Any details about your local setup that might be helpful in troubleshooting. * Detailed steps to reproduce the bug. Fix Bugs ~~~~~~~~ Look through the GitHub issues for bugs. Anything tagged with "bug" and "help wanted" is open to whoever wants to implement it. Implement Features ~~~~~~~~~~~~~~~~~~ Look through the GitHub issues for features. Anything tagged with "enhancement" and "help wanted" is open to whoever wants to implement it. Write Documentation ~~~~~~~~~~~~~~~~~~~ SSE Client could always use more documentation, whether as part of the official SSE Client docs, in docstrings, or even on the web in blog posts, articles, and such. Submit Feedback ~~~~~~~~~~~~~~~ The best way to send feedback is to file an issue at https://github.com/rtfol/aiohttp-sse-client/issues. If you are proposing a feature: * Explain in detail how it would work. * Keep the scope as narrow as possible, to make it easier to implement. * Remember that this is a volunteer-driven project, and that contributions are welcome :) Get Started! ------------ Ready to contribute? Here's how to set up `aiohttp_sse_client` for local development. 1. Fork the `aiohttp_sse_client` repo on GitHub. 2. Clone your fork locally:: $ git clone git@github.com:your_name_here/aiohttp-sse-client.git 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: $ mkvirtualenv aiohttp-sse-client $ cd aiohttp-sse-client/ $ python setup.py develop 4. Create a branch for local development:: $ git checkout -b name-of-your-bugfix-or-feature Now you can make your changes locally. 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: $ flake8 aiohttp_sse_client tests $ python setup.py test or py.test $ tox To get flake8 and tox, just pip install them into your virtualenv. 6. Commit your changes and push your branch to GitHub:: $ git add . $ git commit -m "Your detailed description of your changes." $ git push origin name-of-your-bugfix-or-feature 7. Submit a pull request through the GitHub website. Pull Request Guidelines ----------------------- Before you submit a pull request, check that it meets these guidelines: 1. The pull request should include tests. 2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst. 3. The pull request should work for Python 3.6, 3.7 and 3.8. Check https://travis-ci.org/rtfol/aiohttp-sse-client/pull_requests and make sure that the tests pass for all supported Python versions. Tips ---- To run a subset of tests:: $ py.test tests.test_aiohttp_sse_client Deploying --------- A reminder for the maintainers on how to deploy. Make sure all your changes are committed (including an entry in HISTORY.rst). Then run:: $ bumpversion patch # possible: major / minor / patch $ git push $ git push --tags GitHub Actions will then deploy to PyPI if tests pass. compat-fork-aiohttp-sse-client-8f4158c/HISTORY.rst000066400000000000000000000017301437043167500217200ustar00rootroot00000000000000======= History ======= 0.2.1 (2021-02-27) ------------------ * Allow sending request with different HTTP methods (by @paulefoe) * Migrate to GitHub Actions 0.2.0 (2020-10-20) ------------------ **Breaking Changes** * Drop Python 3.5 support * Add Python 3.8 support **Non functional changes** * Clarify the license (Apache Software License 2.0), thanks @fabaff * Update dependency packages 0.1.7 (2020-03-30) ------------------ * Allow passing kwargs without specifying headers 0.1.6 (2019-08-06) ------------------ * Fix Unicode NULL handling in event id field 0.1.5 (2019-08-06) ------------------ * Fix last id reconnection (by @Ronserruya) 0.1.4 (2018-10-04) ------------------ * Switch to Apache Software License 2.0 0.1.3 (2018-10-03) ------------------ * Change the error handling, better fit the live specification. 0.1.2 (2018-10-03) ------------------ * Implement auto-reconnect feature. 0.1.1 (2018-10-02) ------------------ * First release on PyPI. compat-fork-aiohttp-sse-client-8f4158c/LICENSE000066400000000000000000000011041437043167500210250ustar00rootroot00000000000000Apache Software License 2.0 Copyright (c) 2018, Jason Hu 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. compat-fork-aiohttp-sse-client-8f4158c/MANIFEST.in000066400000000000000000000004061437043167500215620ustar00rootroot00000000000000include AUTHORS.rst include CONTRIBUTING.rst include HISTORY.rst include LICENSE include README.rst recursive-include tests * recursive-exclude * __pycache__ recursive-exclude * *.py[co] recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif compat-fork-aiohttp-sse-client-8f4158c/Makefile000066400000000000000000000043651437043167500214740ustar00rootroot00000000000000.PHONY: clean clean-test clean-pyc clean-build docs help .DEFAULT_GOAL := help define BROWSER_PYSCRIPT import os, webbrowser, sys try: from urllib import pathname2url except: from urllib.request import pathname2url webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) endef export BROWSER_PYSCRIPT define PRINT_HELP_PYSCRIPT import re, sys for line in sys.stdin: match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) if match: target, help = match.groups() print("%-20s %s" % (target, help)) endef export PRINT_HELP_PYSCRIPT BROWSER := python -c "$$BROWSER_PYSCRIPT" help: @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts clean-build: ## remove build artifacts rm -fr build/ rm -fr dist/ rm -fr .eggs/ find . -name '*.egg-info' -exec rm -fr {} + find . -name '*.egg' -exec rm -f {} + clean-pyc: ## remove Python file artifacts find . -name '*.pyc' -exec rm -f {} + find . -name '*.pyo' -exec rm -f {} + find . -name '*~' -exec rm -f {} + find . -name '__pycache__' -exec rm -fr {} + clean-test: ## remove test and coverage artifacts rm -fr .tox/ rm -f .coverage rm -fr htmlcov/ rm -fr .pytest_cache lint: ## check style with flake8 flake8 aiohttp_sse_client2 tests test: ## run tests quickly with the default Python py.test test-all: ## run tests on every Python version with tox tox coverage: ## check code coverage quickly with the default Python coverage run --source aiohttp_sse_client2 -m pytest coverage report -m coverage html $(BROWSER) htmlcov/index.html docs: ## generate Sphinx HTML documentation, including API docs rm -f docs/aiohttp_sse_client2.rst rm -f docs/modules.rst sphinx-apidoc -o docs/ aiohttp_sse_client2 $(MAKE) -C docs clean $(MAKE) -C docs html $(BROWSER) docs/_build/html/index.html servedocs: docs ## compile the docs watching for changes watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . release: dist ## package and upload a release twine upload dist/* dist: clean ## builds source and wheel package python setup.py sdist python setup.py bdist_wheel ls -l dist install: clean ## install the package to the active Python's site-packages python setup.py install compat-fork-aiohttp-sse-client-8f4158c/README.rst000066400000000000000000000047201437043167500215160ustar00rootroot00000000000000This is a fork of the `aiohttp-sse-client `__ project by Jason Hu. The motivations for the fork are: * Better error messages when the request fails (`#190 `__) * Update the library to support new Python versions The fork will be retired if the upstream package comes back alive. Fork changelog -------------- * 0.3.0 (February 7, 2023) * Drop support for Python 3.6 * Support Python 3.10 and 3.11 * Include response body in exception for non-200 response codes Original README follows: ========== SSE Client ========== .. image:: https://img.shields.io/pypi/v/aiohttp_sse_client.svg :target: https://pypi.python.org/pypi/aiohttp_sse_client .. image:: https://img.shields.io/travis/com/rtfol/aiohttp-sse-client.svg :target: https://travis-ci.com/rtfol/aiohttp-sse-client .. image:: https://readthedocs.org/projects/aiohttp-sse-client/badge/?version=latest :target: https://aiohttp-sse-client.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status .. image:: https://pyup.io/repos/github/rtfol/aiohttp-sse-client/shield.svg :target: https://pyup.io/repos/github/rtfol/aiohttp-sse-client/ :alt: Updates A Server-Sent Event python client base on aiohttp, provides a simple interface to process `Server-Sent Event `_. * Free software: Apache Software License 2.0 * Documentation: https://aiohttp-sse-client.readthedocs.io. Features -------- * Full asyncio support * Easy to integrate with other aiohttp based project * Auto-reconnect for network issue * Support python 3.6 and above Usage -------- .. code-block:: python from aiohttp_sse_client2 import client as sse_client async with sse_client.EventSource( 'https://stream.wikimedia.org/v2/stream/recentchange' ) as event_source: try: async for event in event_source: print(event) except ConnectionError: pass Credits ------- This project was inspired by `aiosseclient `_, `sseclient `_, and `sseclient-py `_. This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template. .. _Cookiecutter: https://github.com/audreyr/cookiecutter .. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage compat-fork-aiohttp-sse-client-8f4158c/aiohttp_sse_client2/000077500000000000000000000000001437043167500237665ustar00rootroot00000000000000compat-fork-aiohttp-sse-client-8f4158c/aiohttp_sse_client2/__init__.py000066400000000000000000000002251437043167500260760ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Top-level package for SSE Client.""" __author__ = """Jason Hu""" __email__ = 'awaregit@gmail.com' __version__ = '0.3.0' compat-fork-aiohttp-sse-client-8f4158c/aiohttp_sse_client2/client.py000066400000000000000000000267741437043167500256360ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Main module.""" import asyncio import logging from datetime import timedelta from typing import Optional, Dict, Any import attr from aiohttp import hdrs, ClientSession, ClientConnectionError from multidict import MultiDict from yarl import URL READY_STATE_CONNECTING = 0 READY_STATE_OPEN = 1 READY_STATE_CLOSED = 2 DEFAULT_RECONNECTION_TIME = timedelta(seconds=5) DEFAULT_MAX_CONNECT_RETRY = 5 DEFAULT_MAX_READ_RETRY = 10 CONTENT_TYPE_EVENT_STREAM = 'text/event-stream' LAST_EVENT_ID_HEADER = 'Last-Event-Id' _LOGGER = logging.getLogger(__name__) @attr.s(slots=True, frozen=True) class MessageEvent: """Represent DOM MessageEvent Interface .. seealso:: https://www.w3.org/TR/eventsource/#dispatchMessage section 4 .. seealso:: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent """ type = attr.ib(type=str) message = attr.ib(type=str) data = attr.ib(type=str) origin = attr.ib(type=str) last_event_id = attr.ib(type=str) class EventSource: """Represent EventSource Interface as an async context manager. .. code-block:: python from aiohttp_sse_client2 import client as sse_client async with sse_client.EventSource( 'https://stream.wikimedia.org/v2/stream/recentchange' ) as event_source: try: async for event in event_source: print(event) except ConnectionError: pass .. seealso:: https://www.w3.org/TR/eventsource/#eventsource """ def __init__(self, url: str, option: Optional[Dict[str, Any]] = None, reconnection_time: timedelta = DEFAULT_RECONNECTION_TIME, max_connect_retry: int = DEFAULT_MAX_CONNECT_RETRY, session: Optional[ClientSession] = None, on_open=None, on_message=None, on_error=None, **kwargs): """Construct EventSource instance. :param url: specifies the URL to which to connect :param option: specifies the settings, if any, in the form of an Dict[str, Any]. Accept the "method" key for specifying the HTTP method with which connection should be established :param reconnection_time: wait time before try to reconnect in case connection broken :param session: specifies a aiohttp.ClientSession, if not, create a default ClientSession :param on_open: event handler for open event :param on_message: event handler for message event :param on_error: event handler for error event :param kwargs: keyword arguments will pass to underlying aiohttp request() method. """ self._url = URL(url) self._ready_state = READY_STATE_CONNECTING if session is not None: self._session = session self._need_close_session = False else: self._session = ClientSession() self._need_close_session = True self._on_open = on_open self._on_message = on_message self._on_error = on_error self._reconnection_time = reconnection_time self._orginal_reconnection_time = reconnection_time self._max_connect_retry = max_connect_retry self._last_event_id = '' self._kwargs = kwargs if 'headers' not in self._kwargs: self._kwargs['headers'] = MultiDict() self._event_id = '' self._event_type = '' self._event_data = '' self._origin = None self._response = None self._method = 'GET' if option is None else option.get('method', 'GET') def __enter__(self): """Use async with instead.""" raise TypeError("Use async with instead") def __exit__(self, *exc): """Should exist in pair with __enter__ but never executed.""" pass # pragma: no cover async def __aenter__(self) -> 'EventSource': """Connect and listen Server-Sent Event.""" await self.connect(self._max_connect_retry) return self async def __aexit__(self, *exc): """Close connection and session if need.""" await self.close() if self._need_close_session: await self._session.close() pass @property def url(self) -> URL: """Return URL to which to connect.""" return self._url @property def ready_state(self) -> int: """Return ready state.""" return self._ready_state def __aiter__(self): """Return""" return self async def __anext__(self) -> MessageEvent: """Process events""" if not self._response: raise ValueError # async for ... in StreamReader only split line by \n while self._response.status != 204: async for line_in_bytes in self._response.content: line = line_in_bytes.decode('utf8') # type: str line = line.rstrip('\n').rstrip('\r') if line == '': # empty line event = self._dispatch_event() if event is not None: return event continue if line[0] == ':': # comment line, ignore continue if ':' in line: # contains ':' fields = line.split(':', 1) field_name = fields[0] field_value = fields[1].lstrip(' ') self._process_field(field_name, field_value) else: self._process_field(line, '') self._ready_state = READY_STATE_CONNECTING if self._on_error: self._on_error() self._reconnection_time *= 2 _LOGGER.debug('wait %s seconds for retry', self._reconnection_time.total_seconds()) await asyncio.sleep( self._reconnection_time.total_seconds()) await self.connect() raise StopAsyncIteration async def connect(self, retry=0): """Connect to resource.""" _LOGGER.debug('connect') headers = self._kwargs['headers'] # For HTTP connections, the Accept header may be included; # if included, it must contain only formats of event framing that are # supported by the user agent (one of which must be text/event-stream, # as described below). headers[hdrs.ACCEPT] = CONTENT_TYPE_EVENT_STREAM # If the event source's last event ID string is not the empty string, # then a Last-Event-Id HTTP header must be included with the request, # whose value is the value of the event source's last event ID string, # encoded as UTF-8. if self._last_event_id != '': headers[LAST_EVENT_ID_HEADER] = self._last_event_id # User agents should use the Cache-Control: no-cache header in # requests to bypass any caches for requests of event sources. headers[hdrs.CACHE_CONTROL] = 'no-cache' try: response = await self._session.request( self._method, self._url, **self._kwargs ) except ClientConnectionError: if retry <= 0 or self._ready_state == READY_STATE_CLOSED: await self._fail_connect() raise else: self._ready_state = READY_STATE_CONNECTING if self._on_error: self._on_error() self._reconnection_time *= 2 _LOGGER.debug('wait %s seconds for retry', self._reconnection_time.total_seconds()) await asyncio.sleep( self._reconnection_time.total_seconds()) await self.connect(retry - 1) return if response.status >= 400 or response.status == 305: body = await response.read() error_message = 'fetch {} failed: {}: {!r}'.format( self._url, response.status, body) _LOGGER.error(error_message) await self._fail_connect() if response.status in [305, 401, 407]: raise ConnectionRefusedError(error_message, body) raise ConnectionError(error_message, body) if response.status != 200: body = await response.read() error_message = ( 'fetch {} failed with wrong response status: {}: {}'. format(self._url, response.status, body) ) _LOGGER.error(error_message) await self._fail_connect() raise ConnectionAbortedError(error_message, body) if response.content_type != CONTENT_TYPE_EVENT_STREAM: error_message = \ 'fetch {} failed with wrong Content-Type: {}'.format( self._url, response.headers.get(hdrs.CONTENT_TYPE)) _LOGGER.error(error_message) await self._fail_connect() raise ConnectionAbortedError(error_message) # only status == 200 and content_type == 'text/event-stream' await self._connected() self._response = response self._origin = str(response.real_url.origin()) async def close(self): """Close connection.""" _LOGGER.debug('close') self._ready_state = READY_STATE_CLOSED if self._response is not None: self._response.close() self._response = None async def _connected(self): """Announce the connection is made.""" if self._ready_state != READY_STATE_CLOSED: self._ready_state = READY_STATE_OPEN if self._on_open: self._on_open() self._reconnection_time = self._orginal_reconnection_time async def _fail_connect(self): """Announce the connection is failed.""" if self._ready_state != READY_STATE_CLOSED: self._ready_state = READY_STATE_CLOSED if self._on_error: self._on_error() pass def _dispatch_event(self): """Dispatch event.""" self._last_event_id = self._event_id if self._event_data == '': self._event_type = '' return self._event_data = self._event_data.rstrip('\n') message = MessageEvent( type=self._event_type if self._event_type != '' else None, message=self._event_type, data=self._event_data, origin=self._origin, last_event_id=self._last_event_id ) _LOGGER.debug(message) if self._on_message: self._on_message(message) self._event_type = '' self._event_data = '' return message def _process_field(self, field_name, field_value): """Process field.""" if field_name == 'event': self._event_type = field_value elif field_name == 'data': self._event_data += field_value self._event_data += '\n' elif field_name == 'id' and field_value not in ('\u0000', '\x00\x00'): self._event_id = field_value elif field_name == 'retry': try: retry_in_ms = int(field_value) self._reconnection_time = timedelta(milliseconds=retry_in_ms) except ValueError: _LOGGER.warning('Received invalid retry value %s, ignore it', field_value) pass pass compat-fork-aiohttp-sse-client-8f4158c/docs/000077500000000000000000000000001437043167500207545ustar00rootroot00000000000000compat-fork-aiohttp-sse-client-8f4158c/docs/Makefile000066400000000000000000000011541437043167500224150ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = python -msphinx SPHINXPROJ = aiohttp_sse_client2 SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) compat-fork-aiohttp-sse-client-8f4158c/docs/authors.rst000066400000000000000000000000341437043167500231700ustar00rootroot00000000000000.. include:: ../AUTHORS.rst compat-fork-aiohttp-sse-client-8f4158c/docs/conf.py000077500000000000000000000116051437043167500222610ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # aiohttp_sse_client2 documentation build configuration file, created by # sphinx-quickstart on Fri Jun 9 13:47:02 2017. # # 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. # import os import sys sys.path.insert(0, os.path.abspath('..')) import aiohttp_sse_client2 # -- 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.viewcode'] # 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 master toctree document. master_doc = 'index' # General information about the project. project = u'SSE Client' copyright = u"2018-2020, Jason Hu" author = u"Jason Hu" # The version info for the project you're documenting, acts as replacement # for |version| and |release|, also used in various other places throughout # the built documents. # # The short X.Y version. version = aiohttp_sse_client2.__version__ # The full version, including alpha/beta/rc tags. release = aiohttp_sse_client2.__version__ # 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 # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # 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 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'] # -- Options for HTMLHelp output --------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'aiohttp_sse_clientdoc' # -- 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, 'aiohttp_sse_client2.tex', u'SSE Client Documentation', u'Jason Hu', 'manual'), ] # -- 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, 'aiohttp_sse_client2', u'SSE Client Documentation', [author], 1) ] # -- 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, 'aiohttp_sse_client2', u'SSE Client Documentation', author, 'aiohttp_sse_client2', 'A Server-Sent Event python client base on aiohttp, provides a simple interface to process Server-Sent Event.', 'Miscellaneous'), ] compat-fork-aiohttp-sse-client-8f4158c/docs/contributing.rst000066400000000000000000000000411437043167500242100ustar00rootroot00000000000000.. include:: ../CONTRIBUTING.rst compat-fork-aiohttp-sse-client-8f4158c/docs/history.rst000066400000000000000000000000341437043167500232040ustar00rootroot00000000000000.. include:: ../HISTORY.rst compat-fork-aiohttp-sse-client-8f4158c/docs/index.rst000066400000000000000000000005011437043167500226110ustar00rootroot00000000000000Welcome to SSE Client's documentation! ====================================== .. toctree:: :maxdepth: 2 :caption: Contents: readme installation usage references modules contributing authors history Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` compat-fork-aiohttp-sse-client-8f4158c/docs/installation.rst000066400000000000000000000022161437043167500242100ustar00rootroot00000000000000.. highlight:: shell ============ Installation ============ Stable release -------------- To install SSE Client, run this command in your terminal: .. code-block:: console $ pip install aiohttp-sse-client This is the preferred method to install SSE Client, as it will always install the most recent stable release. If you don't have `pip`_ installed, this `Python installation guide`_ can guide you through the process. .. _pip: https://pip.pypa.io .. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/ From sources ------------ The sources for SSE Client can be downloaded from the `Github repo`_. You can either clone the public repository: .. code-block:: console $ git clone git://github.com/rtfol/aiohttp-sse-client Or download the `tarball`_: .. code-block:: console $ curl -OL https://github.com/rtfol/aiohttp-sse-client/tarball/master Once you have a copy of the source, you can install it with: .. code-block:: console $ python setup.py install .. _Github repo: https://github.com/rtfol/aiohttp-sse-client .. _tarball: https://github.com/rtfol/aiohttp-sse-client/tarball/master compat-fork-aiohttp-sse-client-8f4158c/docs/make.bat000066400000000000000000000014611437043167500223630ustar00rootroot00000000000000@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=python -msphinx ) set SOURCEDIR=. set BUILDDIR=_build set SPHINXPROJ=aiohttp_sse_client2 if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The Sphinx module was not found. Make sure you have Sphinx installed, echo.then set the SPHINXBUILD environment variable to point to the full echo.path of the 'sphinx-build' executable. Alternatively you may add the echo.Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% :end popd compat-fork-aiohttp-sse-client-8f4158c/docs/readme.rst000066400000000000000000000000331437043167500227370ustar00rootroot00000000000000.. include:: ../README.rst compat-fork-aiohttp-sse-client-8f4158c/docs/references.rst000066400000000000000000000004261437043167500236310ustar00rootroot00000000000000========== References ========== Class EventSource ----------------- .. autoclass:: aiohttp_sse_client2.client.EventSource :members: .. automethod:: __init__ Class MessageEvent ------------------ .. autoclass:: aiohttp_sse_client2.client.MessageEvent :members: compat-fork-aiohttp-sse-client-8f4158c/docs/usage.rst000066400000000000000000000006161437043167500226150ustar00rootroot00000000000000===== Usage ===== To use SSE Client in a project: .. code-block:: python from aiohttp_sse_client2 import client as sse_client async with sse_client.EventSource( 'https://stream.wikimedia.org/v2/stream/recentchange' ) as event_source: try: async for event in event_source: print(event) except ConnectionError: pass compat-fork-aiohttp-sse-client-8f4158c/requirements_dev.txt000066400000000000000000000002731437043167500241500ustar00rootroot00000000000000pip==23.0 bump2version==1.0.1 wheel==0.38.4 watchdog==2.2.1 flake8==5.0.4 tox==3.28.0 coverage==7.1.0 Sphinx==4.3.2 twine==4.0.2 pytest==7.2.1 pytest-aiohttp==1.0.4 pytest-runner==6.0.0 compat-fork-aiohttp-sse-client-8f4158c/setup.cfg000066400000000000000000000005711437043167500216500ustar00rootroot00000000000000[bumpversion] current_version = 0.3.0 commit = True tag = True [bumpversion:file:setup.py] search = version='{current_version}' replace = version='{new_version}' [bumpversion:file:aiohttp_sse_client2/__init__.py] search = __version__ = '{current_version}' replace = __version__ = '{new_version}' [bdist_wheel] universal = 1 [flake8] exclude = docs [aliases] test = pytest compat-fork-aiohttp-sse-client-8f4158c/setup.py000066400000000000000000000031061437043167500215360ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = ['aiohttp>=3', 'attrs', 'multidict', 'yarl', ] setup_requirements = ['pytest-runner', ] test_requirements = ['pytest', ] setup( author="Jason Hu", author_email='awaregit@gmail.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Framework :: AsyncIO', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Topic :: Internet :: WWW/HTTP', ], description="A Server-Sent Event python client base on aiohttp", install_requires=requirements, license="Apache License 2.0", long_description=readme + '\n\n' + history, include_package_data=True, keywords='aiohttp_sse_client', name='aiohttp-sse-client2', packages=find_packages(include=['aiohttp_sse_client2']), setup_requires=setup_requirements, test_suite='tests', tests_require=test_requirements, url='https://github.com/JelleZijlstra/aiohttp-sse-client2', version='0.3.0', zip_safe=False, ) compat-fork-aiohttp-sse-client-8f4158c/tests/000077500000000000000000000000001437043167500211665ustar00rootroot00000000000000compat-fork-aiohttp-sse-client-8f4158c/tests/conftest.py000066400000000000000000000000711437043167500233630ustar00rootroot00000000000000import logging logging.basicConfig(level=logging.DEBUG) compat-fork-aiohttp-sse-client-8f4158c/tests/test_client.py000066400000000000000000000016061437043167500240600ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `aiohttp_sse_client` package.""" import json import pytest from aiohttp_sse_client2 import client as sse_client @pytest.mark.asyncio async def test_basic_usage(): """Test basic usage.""" messages = [] async with sse_client.EventSource( 'https://stream.wikimedia.org/v2/stream/recentchange' ) as event_source: async for message in event_source: if len(messages) > 1: break messages.append(message) print(messages) assert messages[0].type == 'message' assert messages[0].origin == 'https://stream.wikimedia.org' assert messages[1].type == 'message' assert messages[1].origin == 'https://stream.wikimedia.org' data_0 = json.loads(messages[0].data) data_1 = json.loads(messages[1].data) assert data_0['meta']['id'] != data_1['meta']['id'] compat-fork-aiohttp-sse-client-8f4158c/tests/web_platform_tests/000077500000000000000000000000001437043167500250715ustar00rootroot00000000000000compat-fork-aiohttp-sse-client-8f4158c/tests/web_platform_tests/__init__.py000066400000000000000000000002161437043167500272010ustar00rootroot00000000000000"""Tests against web-platform-tests eventsource test suite. ..seealso: https://github.com/web-platform-tests/wpt/tree/master/eventsource """ compat-fork-aiohttp-sse-client-8f4158c/tests/web_platform_tests/const.py000066400000000000000000000000541437043167500265700ustar00rootroot00000000000000WPT_SERVER = 'http://wpt.live/eventsource/' compat-fork-aiohttp-sse-client-8f4158c/tests/web_platform_tests/test_event_data.py000066400000000000000000000047251437043167500306240ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime, timedelta import pytest from aiohttp_sse_client2 import client as sse_client from .const import WPT_SERVER @pytest.mark.asyncio async def test_event_data(): """Test EventSource: lines and data parsing. ..seealso: https://github.com/web-platform-tests/wpt/blob/master/ eventsource/event-data.html """ counter = 0 source = sse_client.EventSource(WPT_SERVER + 'resources/message2.py') await source.connect() async for e in source: if counter == 0: assert e.data == "msg\nmsg" elif counter == 1: assert e.data == "" elif counter == 2: assert e.data == "end" await source.close() break else: assert False counter += 1 @pytest.mark.asyncio async def test_eventsource_close(): """Test EventSource: close. ..seealso: https://github.com/web-platform-tests/wpt/blob/master/ eventsource/eventsource-close.htm """ source = sse_client.EventSource(WPT_SERVER + 'resources/message.py') assert source.ready_state == sse_client.READY_STATE_CONNECTING await source.connect() assert source.ready_state == sse_client.READY_STATE_OPEN await source.close() assert source.ready_state == sse_client.READY_STATE_CLOSED count = 0 reconnected = False def on_error(): nonlocal count, reconnected if count == 1: assert source.ready_state == sse_client.READY_STATE_CONNECTING reconnected = True elif count == 2: assert source.ready_state == sse_client.READY_STATE_CONNECTING count += 1 elif count == 3: assert source.ready_state == sse_client.READY_STATE_CLOSED else: assert False async with sse_client.EventSource( WPT_SERVER + 'resources/reconnect-fail.py?id=' + str(datetime.utcnow().timestamp()), reconnection_time=timedelta(milliseconds=2), on_error=on_error ) as source: try: async for e in source: if count == 0: assert reconnected is False assert e.data == "opened" elif count == 1: assert reconnected is True assert e.data == "reconnected" else: assert False count += 1 except ConnectionError: pass compat-fork-aiohttp-sse-client-8f4158c/tests/web_platform_tests/test_eventsource_close.py000066400000000000000000000040541437043167500322340ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime, timedelta import pytest from aiohttp_sse_client2 import client as sse_client from .const import WPT_SERVER @pytest.mark.asyncio async def test_eventsource_close(): """Test EventSource: close. ..seealso: https://github.com/web-platform-tests/wpt/blob/master/ eventsource/eventsource-close.htm """ source = sse_client.EventSource(WPT_SERVER + 'resources/message.py') assert source.ready_state == sse_client.READY_STATE_CONNECTING await source.connect() assert source.ready_state == sse_client.READY_STATE_OPEN await source.close() assert source.ready_state == sse_client.READY_STATE_CLOSED @pytest.mark.asyncio async def test_eventsource_close_reconnect(): """Test EventSource: close/reconnect. ..seealso: https://github.com/web-platform-tests/wpt/blob/master/ eventsource/eventsource-close.htm """ count = 0 reconnected = False def on_error(): nonlocal count, reconnected if count == 1: assert source.ready_state == sse_client.READY_STATE_CONNECTING reconnected = True elif count == 2: assert source.ready_state == sse_client.READY_STATE_CONNECTING count += 1 elif count == 3: assert source.ready_state == sse_client.READY_STATE_CLOSED else: assert False async with sse_client.EventSource( WPT_SERVER + 'resources/reconnect-fail.py?id=' + str(datetime.utcnow().timestamp()), reconnection_time=timedelta(milliseconds=2), on_error=on_error ) as source: try: async for e in source: if count == 0: assert reconnected is False assert e.data == "opened" elif count == 1: assert reconnected is True assert e.data == "reconnected" else: assert False count += 1 except ConnectionError: pass compat-fork-aiohttp-sse-client-8f4158c/tests/web_platform_tests/test_eventsource_onmessage.py000066400000000000000000000014011437043167500331010ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime, timedelta import pytest from aiohttp_sse_client2 import client as sse_client from .const import WPT_SERVER @pytest.mark.asyncio async def test_eventsource_onmessage(): """Test EventSource: onmessage. ..seealso: https://github.com/web-platform-tests/wpt/blob/master/ eventsource/eventsource-onmessage.htm """ def on_message(event): """Callback for message event.""" assert event.data == "data" source = sse_client.EventSource(WPT_SERVER + 'resources/message.py', on_message=on_message) await source.connect() async for e in source: assert e.data == "data" break await source.close() compat-fork-aiohttp-sse-client-8f4158c/tests/web_platform_tests/test_eventsource_onopen.py000066400000000000000000000015251437043167500324250ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime, timedelta import pytest from aiohttp_sse_client2 import client as sse_client from .const import WPT_SERVER @pytest.mark.asyncio async def test_eventsource_onopen(): """Test EventSource: open (announcing the connection). ..seealso: https://github.com/web-platform-tests/wpt/blob/master/ eventsource/eventsource-onopen.htm """ def on_open(): """Callback for open event.""" assert source.ready_state == sse_client.READY_STATE_OPEN source = sse_client.EventSource(WPT_SERVER + 'resources/message.py', on_open=on_open) assert source.ready_state == sse_client.READY_STATE_CONNECTING await source.connect() assert source.ready_state == sse_client.READY_STATE_OPEN await source.close() compat-fork-aiohttp-sse-client-8f4158c/tests/web_platform_tests/test_eventsource_reconnect.py000066400000000000000000000031011437043167500330770ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime, timedelta import pytest from aiohttp_sse_client2 import client as sse_client from .const import WPT_SERVER @pytest.mark.asyncio async def test_eventsource_reconnect(): """Test EventSource: reconnection. ..seealso: https://github.com/web-platform-tests/wpt/blob/master/ eventsource/eventsource-reconnect.htm """ source = sse_client.EventSource( WPT_SERVER + 'resources/status-reconnect.py?status=200') await source.connect() async for e in source: assert e.data == 'data' break await source.close() @pytest.mark.asyncio async def test_eventsource_reconnect_event(): """Test EventSource: reconnection event. ..seealso: https://github.com/web-platform-tests/wpt/blob/master/ eventsource/eventsource-reconnect.htm """ opened = False reconnected = False def on_error(): nonlocal reconnected assert source.ready_state == sse_client.READY_STATE_CONNECTING assert opened is True reconnected = True async with sse_client.EventSource( WPT_SERVER + 'resources/status-reconnect.py?status=200&ok_first&id=2', reconnection_time=timedelta(milliseconds=2), on_error=on_error ) as source: async for e in source: if not opened: opened = True assert reconnected is False assert e.data == "ok" else: assert reconnected is True assert e.data == "data" break test_eventsource_request_cancellation.py000066400000000000000000000020621437043167500352510ustar00rootroot00000000000000compat-fork-aiohttp-sse-client-8f4158c/tests/web_platform_tests#!/usr/bin/env python # -*- coding: utf-8 -*- import asyncio from datetime import datetime, timedelta import pytest from aiohttp_sse_client2 import client as sse_client from .const import WPT_SERVER @pytest.mark.asyncio async def test_eventsource_request_cancellation(): """Test EventSource: reconnection event. ..seealso: https://github.com/web-platform-tests/wpt/blob/master/ eventsource/eventsource-request-cancellation.htm """ closed = False def on_open(): if closed: assert False def on_error(): assert source.ready_state == sse_client.READY_STATE_CLOSED try: async with sse_client.EventSource( WPT_SERVER + 'resources/message.py?sleep=1000&message=' + "retry:1000\ndata:abc\n\n", on_open=on_open, on_error=on_error ) as source: raise ConnectionAbortedError except ConnectionAbortedError: closed = True await asyncio.sleep(1) assert source.ready_state == sse_client.READY_STATE_CLOSED pass compat-fork-aiohttp-sse-client-8f4158c/tests/web_platform_tests/test_format_field_id.py000066400000000000000000000050401437043167500316100ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime, timedelta import pytest from pytest import fail from aiohttp_sse_client2 import client as sse_client from .const import WPT_SERVER @pytest.mark.asyncio async def test_format_field_id(): """Test EventSource: Last-Event-ID. ..seealso: https://github.com/web-platform-tests/wpt/blob/master/ eventsource/format-field-id.htm """ seen_hello = False async with sse_client.EventSource( WPT_SERVER + 'resources/last-event-id.py', ) as source: async for e in source: if not seen_hello: assert e.data == "hello" seen_hello = True # default last event id is Unicode U+2026 assert e.last_event_id == "…" last_id = e.last_event_id else: assert e.data == last_id assert e.last_event_id == last_id break @pytest.mark.asyncio async def test_format_field_id_2(): """Test EventSource: Last-Event-ID (2). ..seealso: https://github.com/web-platform-tests/wpt/blob/master/ eventsource/format-field-id-2.htm """ counter = 0 async with sse_client.EventSource( WPT_SERVER + 'resources/last-event-id.py', ) as source: async for e in source: if counter == 0: counter += 1 assert e.data == "hello" # default last event id is Unicode U+2026 assert e.last_event_id == "…" last_id = e.last_event_id elif counter in (1, 2): counter += 1 assert e.data == last_id assert e.last_event_id == last_id break else: fail("Unexpected counter {}".format(counter)) @pytest.mark.asyncio async def test_format_field_id_null(): """Test EventSource: U+0000 in id field. ..seealso: https://github.com/web-platform-tests/wpt/blob/master/ eventsource/format-field-id-null.htm """ seen_hello = False async with sse_client.EventSource( WPT_SERVER + 'resources/last-event-id.py?idvalue=%00%00', ) as source: async for e in source: if not seen_hello: assert e.data == "hello" seen_hello = True # Unicode U+0000 will be ignored as Event ID assert e.last_event_id == "" else: assert e.data == "hello" assert e.last_event_id == "" break compat-fork-aiohttp-sse-client-8f4158c/tests/web_platform_tests/test_request.py000066400000000000000000000057521437043167500302030ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from aiohttp_sse_client2 import client as sse_client from .const import WPT_SERVER @pytest.mark.asyncio async def test_rquest_accept(): """Test EventSource: Accept header. ..seealso: https://github.com/web-platform-tests/wpt/blob/master/ eventsource/request-accept.htm """ source = sse_client.EventSource( WPT_SERVER + 'resources/accept.event_stream?pipe=sub') await source.connect() async for e in source: assert e.data == "text/event-stream" break await source.close() @pytest.mark.asyncio async def test_rquest_cache_control(): """Test EventSource: Cache-Control. ..seealso: https://github.com/web-platform-tests/wpt/blob/master/ eventsource/request-cache-control.htm """ source = sse_client.EventSource( WPT_SERVER + 'resources/cache-control.event_stream?pipe=sub') await source.connect() async for e in source: assert e.data == "no-cache" break await source.close() @pytest.mark.asyncio async def test_request_redirect(): """Test EventSource: redirect. ..seealso: https://github.com/web-platform-tests/wpt/blob/master/ eventsource/request-redirect.htm """ async def test(status): def on_error(): assert False def on_open(): assert source.ready_state == sse_client.READY_STATE_OPEN source = sse_client.EventSource( WPT_SERVER.replace('eventsource', 'common/redirect.py?' 'location=/eventsource/resources/message.py&status=' + str(status)), on_open=on_open, on_error=on_error) await source.connect() await source.close() await test(301) await test(302) await test(303) await test(307) @pytest.mark.asyncio async def test_request_status_error(): """Test EventSource: redirect. ..seealso: https://github.com/web-platform-tests/wpt/blob/master/ eventsource/request-status-error.htm """ async def test(status): def on_error(): assert source.ready_state == sse_client.READY_STATE_CLOSED def on_message(): assert source.ready_state == sse_client.READY_STATE_OPEN source = sse_client.EventSource( WPT_SERVER + 'resources/status-error.py?status=' + str(status), on_message=on_message, on_error=on_error) with pytest.raises(ConnectionError): await source.connect() await test(204) await test(205) await test(210) await test(299) await test(404) await test(410) await test(503) @pytest.mark.asyncio async def test_request_post_to_connect(): """Test EventSource option method for connection. """ source = sse_client.EventSource( WPT_SERVER + 'resources/message.py', option={'method': "POST"} ) await source.connect() async for e in source: assert e.data == "data" break await source.close() compat-fork-aiohttp-sse-client-8f4158c/tox.ini000066400000000000000000000011671437043167500213440ustar00rootroot00000000000000[tox] envlist = py36, py37, py38, flake8 [travis] python = 3.8: py38 3.7: py37 3.6: py36 [testenv:flake8] basepython = python deps = flake8 commands = flake8 aiohttp_sse_client2 [testenv] setenv = PYTHONPATH = {toxinidir} deps = -r{toxinidir}/requirements_dev.txt ; If you want to make tox run the tests with the same versions, create a ; requirements.txt with the pinned versions and uncomment the following line: ; -r{toxinidir}/requirements.txt commands = pip install -U pip py.test --basetemp={envtmpdir} [testenv:py36] deps = cryptography>=3,<3.4 -r{toxinidir}/requirements_dev.txt