pax_global_header00006660000000000000000000000064134665305750014530gustar00rootroot0000000000000052 comment=02d369bbff0773eb39a06a170aaded8cc6748f07 pytest-tornado-0.8.0/000077500000000000000000000000001346653057500145315ustar00rootroot00000000000000pytest-tornado-0.8.0/.coveralls.yml000066400000000000000000000001251346653057500173220ustar00rootroot00000000000000service_name: travis-ci parallel: true # if the CI is running your build in parallel pytest-tornado-0.8.0/.gitignore000066400000000000000000000013221346653057500165170ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ 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 .cache nosetests.xml coverage.xml .ropeproject/ # Translations *.mo *.pot # Django stuff: *.log # Sphinx documentation docs/_build/ # PyBuilder target/ # Cert for testing testcert.pem pytest-tornado-0.8.0/.travis.yml000066400000000000000000000024451346653057500166470ustar00rootroot00000000000000language: python cache: pip dist: xenial python: - 2.7 - 3.5 - 3.6 - 3.7 env: - TORNADO_VERSION=6.0 PYTEST_VERSION=4.3 - TORNADO_VERSION=5.0 PYTEST_VERSION=4.0 - TORNADO_VERSION=5.0.0 PYTEST_VERSION=3.6 - TORNADO_VERSION=5.0.0 PYTEST_VERSION=4.0.0 - TORNADO_VERSION=4.3.0 PYTEST_VERSION=3.6 - TORNADO_VERSION=4.1.0 PYTEST_VERSION=3.6.4 install: - pip install -q tornado~=$TORNADO_VERSION pytest~=$PYTEST_VERSION - pip install PyOpenSSL # used to create a cert for testing - python setup.py install - pip install coverage coveralls matrix: exclude: # Tornado 6 only supports Python >= 3.5 - python: 2.7 env: TORNADO_VERSION=6.0 PYTEST_VERSION=4.3 script: - python test/create_cert.py --cert test/testcert.pem - coverage run --branch --source pytest_tornado.plugin -m pytest --strict - coverage report -m after_success: - coveralls jobs: include: - stage: deploy python: 3.7 deploy: provider: pypi distributions: sdist bdist_wheel user: eugeniy password: secure: gmpsfekSDT9LuF3XkJK64myhQ6Xg8WyqI/0m5Gnnb+hSrCFGD8/dgtRdLEULuDkFPvL/FsoE2L6XcdKuqaKkqSM3kk4Min8hqGapcfe/OSOkCDaYSUBCXmV2dlbtMTAzHfo3zpueToUelZvblw9y3wXVFWkmr1mf47Q9kUPIgnU= on: tags: true pytest-tornado-0.8.0/CHANGELOG000066400000000000000000000004611346653057500157440ustar00rootroot00000000000000# Unreleased # 0.8.0 * Added support for HTTPS testing (#50) * Group commandline options for pytest (#53) # 0.7 (2019-04-08) * Added support for Tornado 6 * Requires at least Tornado 4.1 # 0.6 (2019-03-28) * Added support for Tornado 5 * Requires at least pytest 3.6 * Removed support for Tornado 3 pytest-tornado-0.8.0/LICENSE000066400000000000000000000261361346653057500155460ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. pytest-tornado-0.8.0/MANIFEST.in000066400000000000000000000000341346653057500162640ustar00rootroot00000000000000include LICENSE prune test pytest-tornado-0.8.0/Makefile000066400000000000000000000003551346653057500161740ustar00rootroot00000000000000.PHONY: build clean upload test-upload default: build build: python setup.py sdist bdist_wheel clean: rm -rf build dist *.egg-info upload: clean build twine upload dist/* test-upload: clean build twine upload -r pypitest dist/* pytest-tornado-0.8.0/README.rst000066400000000000000000000101611346653057500162170ustar00rootroot00000000000000pytest-tornado ============== .. image:: https://travis-ci.org/eugeniy/pytest-tornado.svg?branch=master :target: https://travis-ci.org/eugeniy/pytest-tornado .. image:: https://coveralls.io/repos/eugeniy/pytest-tornado/badge.svg :target: https://coveralls.io/r/eugeniy/pytest-tornado A py.test_ plugin providing fixtures and markers to simplify testing of asynchronous tornado applications. Installation ------------ :: pip install pytest-tornado Example ------- .. code-block:: python import pytest import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/", MainHandler), ]) @pytest.fixture def app(): return application @pytest.mark.gen_test def test_hello_world(http_client, base_url): response = yield http_client.fetch(base_url) assert response.code == 200 Running tests ------------- :: py.test Fixtures -------- io_loop creates an instance of the `tornado.ioloop.IOLoop`_ for each test case http_port get a port used by the test server base_url Get an absolute base url for the test server, for example ``http://localhost:59828``. Can also be used in a test with HTTPS fixture and will then return a corresponding url, for example ``http://localhost:48372``. http_server start a tornado HTTP server, you must create an ``app`` fixture, which returns the `tornado.web.Application`_ to be tested http_client get an asynchronous HTTP client There is also the possibility to test applications with HTTPS. For running a server with HTTPS you need a certificate. https_port Get a port used by the test server. https_server Start a tornado HTTPS server. You must create an ``app`` fixture, which returns the `tornado.web.Application`_ to be tested, and an ``ssl_options`` fixture which returns the SSL options for the `tornado.httpserver.HTTPServer`_. https_client Get an asynchronous HTTP client. In case your test uses an self-signed certificate you can set ``verify=False`` on the fetch method. Show fixtures provided by the plugin:: py.test --fixtures Markers ------- A ``gen_test`` marker lets you write a coroutine-style tests used with the `tornado.gen`_ module: .. code-block:: python @pytest.mark.gen_test def test_tornado(http_client): response = yield http_client.fetch('http://www.tornadoweb.org/') assert response.code == 200 This marker supports writing tests with async/await syntax as well: .. code-block:: python @pytest.mark.gen_test async def test_tornado(http_client): response = await http_client.fetch('http://www.tornadoweb.org/') assert response.code == 200 Marked tests will time out after 5 seconds. The timeout can be modified by setting an ``ASYNC_TEST_TIMEOUT`` environment variable, ``--async-test-timeout`` command line argument or a marker argument. .. code-block:: python @pytest.mark.gen_test(timeout=5) def test_tornado(http_client): yield http_client.fetch('http://www.tornadoweb.org/') The mark can also receive a run_sync flag, which if turned off will, instead of running the test synchronously, will add it as a coroutine and run the IOLoop (until the timeout). For instance, this allows to test things on both a client and a server at the same time. .. code-block:: python @pytest.mark.gen_test(run_sync=False) def test_tornado(http_server, http_client): response = yield http_client.fetch('http://localhost:5555/my_local_server_test/') assert response.body == 'Run on the same IOLoop!' Show markers provided by the plugin:: py.test --markers .. _py.test: http://pytest.org/ .. _`tornado.httpserver.HTTPServer`: https://www.tornadoweb.org/en/latest/httpserver.html#http-server .. _`tornado.ioloop.IOLoop`: http://tornado.readthedocs.org/en/latest/ioloop.html#ioloop-objects .. _`tornado.web.Application`: http://tornado.readthedocs.org/en/latest/web.html#application-configuration .. _`tornado.gen`: http://tornado.readthedocs.org/en/latest/gen.html pytest-tornado-0.8.0/pytest_tornado/000077500000000000000000000000001346653057500176075ustar00rootroot00000000000000pytest-tornado-0.8.0/pytest_tornado/__init__.py000066400000000000000000000000001346653057500217060ustar00rootroot00000000000000pytest-tornado-0.8.0/pytest_tornado/plugin.py000066400000000000000000000157621346653057500214720ustar00rootroot00000000000000import os import sys import types import inspect import datetime import pytest import tornado import tornado.gen import tornado.testing import tornado.httpserver import tornado.httpclient if sys.version_info[:2] >= (3, 5): iscoroutinefunction = inspect.iscoroutinefunction else: iscoroutinefunction = lambda f: False def _get_async_test_timeout(): try: return float(os.environ.get('ASYNC_TEST_TIMEOUT')) except (ValueError, TypeError): return 5 def pytest_addoption(parser): tornado_group = parser.getgroup('tornado options') tornado_group.addoption('--async-test-timeout', type=float, default=_get_async_test_timeout(), help='timeout in seconds before failing the test') tornado_group.addoption('--app-fixture', default='app', help='fixture name returning a tornado application') tornado_group.addoption('--ssl-options-fixture', default='ssl_options', help='fixture name returning a certificate configuration') def pytest_configure(config): config.addinivalue_line("markers", "gen_test(timeout=None): " "mark the test as asynchronous, it will be " "run using tornado's event loop") def _argnames(func): if hasattr(inspect, "signature"): sig = inspect.signature(func) return [name for name, param in sig.parameters.items() if param.default is param.empty] else: spec = inspect.getargspec(func) if spec.defaults: return spec.args[:-len(spec.defaults)] if isinstance(func, types.FunctionType): return spec.args # Func is a bound method, skip "self" return spec.args[1:] def _timeout(item): default_timeout = item.config.getoption('async_test_timeout') gen_test = item.get_closest_marker('gen_test') if gen_test: return gen_test.kwargs.get('timeout', default_timeout) return default_timeout @pytest.mark.tryfirst def pytest_pycollect_makeitem(collector, name, obj): if collector.funcnamefilter(name) and inspect.isgeneratorfunction(obj): item = pytest.Function(name, parent=collector) if 'gen_test' in item.keywords: return list(collector._genfunctions(name, obj)) def pytest_runtest_setup(item): if 'gen_test' in item.keywords and 'io_loop' not in item.fixturenames: # inject an event loop fixture for all async tests item.fixturenames.append('io_loop') @pytest.mark.tryfirst def pytest_pyfunc_call(pyfuncitem): gen_test_mark = pyfuncitem.get_closest_marker('gen_test') if gen_test_mark: io_loop = pyfuncitem.funcargs.get('io_loop') run_sync = gen_test_mark.kwargs.get('run_sync', True) funcargs = dict((arg, pyfuncitem.funcargs[arg]) for arg in _argnames(pyfuncitem.obj)) if iscoroutinefunction(pyfuncitem.obj): coroutine = pyfuncitem.obj future = tornado.gen.convert_yielded(coroutine(**funcargs)) else: coroutine = tornado.gen.coroutine(pyfuncitem.obj) future = coroutine(**funcargs) if run_sync: io_loop.run_sync(lambda: future, timeout=_timeout(pyfuncitem)) else: # Run this test function as a coroutine, until the timeout. When completed, stop the IOLoop # and reraise any exceptions future_with_timeout = tornado.gen.with_timeout( datetime.timedelta(seconds=_timeout(pyfuncitem)), future) io_loop.add_future(future_with_timeout, lambda f: io_loop.stop()) io_loop.start() # This will reraise any exceptions that occurred. future_with_timeout.result() # prevent other pyfunc calls from executing return True @pytest.fixture def io_loop(request): """Create an instance of the `tornado.ioloop.IOLoop` for each test case. """ io_loop = tornado.ioloop.IOLoop() io_loop.make_current() def _close(): io_loop.clear_current() io_loop.close(all_fds=True) request.addfinalizer(_close) return io_loop @pytest.fixture def _unused_port(): return tornado.testing.bind_unused_port() @pytest.fixture def http_port(_unused_port): """Get a port used by the test server. """ return _unused_port[1] @pytest.fixture def https_port(_unused_port): """Get a port used by the test server. """ return _unused_port[1] @pytest.fixture def base_url(request): """Create an absolute base url (scheme://host:port) """ fixturenames = request.fixturenames if 'https_port' in fixturenames or 'https_client' in fixturenames or 'https_server' in fixturenames: return 'https://localhost:%s' % request.getfixturevalue('https_port') return 'http://localhost:%s' % request.getfixturevalue('http_port') @pytest.fixture def http_server(request, io_loop, _unused_port): """Start a tornado HTTP server. You must create an `app` fixture, which returns the `tornado.web.Application` to be tested. Raises: FixtureLookupError: tornado application fixture not found """ http_app = request.getfixturevalue(request.config.option.app_fixture) server = tornado.httpserver.HTTPServer(http_app) server.add_socket(_unused_port[0]) def _stop(): server.stop() if hasattr(server, 'close_all_connections'): io_loop.run_sync(server.close_all_connections, timeout=request.config.option.async_test_timeout) request.addfinalizer(_stop) return server @pytest.fixture def http_client(request, http_server): """Get an asynchronous HTTP client. """ client = tornado.httpclient.AsyncHTTPClient() def _close(): client.close() request.addfinalizer(_close) return client @pytest.fixture def https_server(request, io_loop, _unused_port): """Start a tornado HTTPS server. You must create an `app` fixture, which returns the `tornado.web.Application` to be tested. Raises: FixtureLookupError: tornado application fixture not found """ https_app = request.getfixturevalue(request.config.option.app_fixture) ssl_options = request.getfixturevalue(request.config.option.ssl_options_fixture) server = tornado.httpserver.HTTPServer(https_app, ssl_options=ssl_options) server.add_socket(_unused_port[0]) def _stop(): server.stop() if hasattr(server, 'close_all_connections'): io_loop.run_sync(server.close_all_connections, timeout=request.config.option.async_test_timeout) request.addfinalizer(_stop) return server @pytest.fixture def https_client(request, https_server): """Get an asynchronous HTTPS client. """ # How does on get ca_certs from the user client = tornado.httpclient.AsyncHTTPClient() def _close(): client.close() request.addfinalizer(_close) return client pytest-tornado-0.8.0/setup.cfg000066400000000000000000000000321346653057500163450ustar00rootroot00000000000000[bdist_wheel] universal=1 pytest-tornado-0.8.0/setup.py000066400000000000000000000027341346653057500162510ustar00rootroot00000000000000import os import io from setuptools import setup, find_packages cwd = os.path.abspath(os.path.dirname(__file__)) with io.open(os.path.join(cwd, 'README.rst'), encoding='utf-8') as fd: long_description = fd.read() setup( name='pytest-tornado', version='0.8.0', description=('A py.test plugin providing fixtures and markers ' 'to simplify testing of asynchronous tornado applications.'), long_description=long_description, url='https://github.com/eugeniy/pytest-tornado', author='Eugeniy Kalinin', author_email='burump@gmail.com', maintainer='Vidar Tonaas Fauske', maintainer_email='vidartf@gmail.com', license='Apache License, Version 2.0', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Plugins', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development', 'Topic :: Software Development :: Testing', ], keywords=('pytest py.test tornado async asynchronous ' 'testing unit tests plugin'), packages=find_packages(exclude=["tests.*", "tests"]), install_requires=['pytest>=3.6', 'tornado>=4.1'], entry_points={ 'pytest11': ['tornado = pytest_tornado.plugin'], }, ) pytest-tornado-0.8.0/test/000077500000000000000000000000001346653057500155105ustar00rootroot00000000000000pytest-tornado-0.8.0/test/conftest.py000066400000000000000000000003071346653057500177070ustar00rootroot00000000000000import sys import tornado collect_ignore = [] if sys.version_info[:2] < (3, 5) or tornado.version_info[:2] < (4, 3): collect_ignore.append("test_async_await.py") pytest_plugins = ["pytester"] pytest-tornado-0.8.0/test/create_cert.py000066400000000000000000000042341346653057500203450ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Create a cert with pyOpenSSL for tests. Heavily based on python-opsi's OPSI.Util.Task.Certificate. Source: https://github.com/opsi-org/python-opsi/blob/stable/OPSI/Util/Task/Certificate.py """ import argparse import os import random import socket from tempfile import NamedTemporaryFile from OpenSSL import crypto try: import secrets except ImportError: secrets = None def createCertificate(path): """ Creates a certificate. """ cert = crypto.X509() cert.get_subject().C = "DE" # Country cert.get_subject().ST = "HE" # State cert.get_subject().L = "Wiesbaden" # Locality cert.get_subject().O = "pytest-tornado" # Organisation cert.get_subject().OU = "Testing Department" # organisational unit cert.get_subject().CN = socket.getfqdn() # common name # As described in RFC5280 this value is required and must be a # positive and unique integer. # Source: http://tools.ietf.org/html/rfc5280#page-19 cert.set_serial_number(random.randint(0, pow(2, 16))) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(60 * 60) # Valid 1 hour k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, 2048) cert.set_issuer(cert.get_subject()) cert.set_pubkey(k) cert.set_version(2) cert.sign(k, 'sha512') certcontext = b"".join( ( crypto.dump_certificate(crypto.FILETYPE_PEM, cert), crypto.dump_privatekey(crypto.FILETYPE_PEM, k) ) ) with open(path, "wt") as certfile: certfile.write(certcontext.decode()) try: with NamedTemporaryFile(mode="wb", delete=False) as randfile: randfile.write(randomBytes(512)) command = u"openssl dhparam -rand {tempfile} 512 >> {target}".format( tempfile=randfile.name, target=path ) os.system(command) finally: os.remove(randfile.name) def randomBytes(length): """ Return _length_ random bytes. :rtype: bytes """ if secrets: return secrets.token_bytes(512) else: return os.urandom(512) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Create certificate for testing') parser.add_argument('--cert', dest='cert', default="testcert.pem", help='Name of the certificate') args = parser.parse_args() createCertificate(args.cert) pytest-tornado-0.8.0/test/test_async.py000066400000000000000000000037741346653057500202510ustar00rootroot00000000000000import functools import pytest import tornado from tornado import gen from tornado.ioloop import TimeoutError @gen.coroutine def dummy_coroutine(io_loop): yield gen.sleep(0) raise gen.Return(True) def test_explicit_start_and_stop(io_loop): future = dummy_coroutine(io_loop) future.add_done_callback(lambda *args: io_loop.stop()) io_loop.start() assert future.result() def test_run_sync(io_loop): dummy = functools.partial(dummy_coroutine, io_loop) finished = io_loop.run_sync(dummy) assert finished @pytest.mark.gen_test def test_gen_test_sync(io_loop): assert True @pytest.mark.gen_test def test_gen_test(io_loop): result = yield dummy_coroutine(io_loop) assert result @pytest.mark.gen_test(run_sync=False) def test_gen_test_run_sync_false(io_loop): result = yield dummy_coroutine(io_loop) assert result @pytest.mark.gen_test def test_gen_test_swallows_exceptions(io_loop): with pytest.raises(ZeroDivisionError): 1 / 0 @pytest.mark.gen_test def test_generator_raises(io_loop): with pytest.raises(ZeroDivisionError): yield gen.sleep(0) 1 / 0 @pytest.mark.gen_test def test_explicit_gen_test_marker(request, io_loop): yield gen.sleep(0) assert 'gen_test' in request.keywords @pytest.mark.gen_test(timeout=2.1) def test_gen_test_marker_with_params(request, io_loop): yield gen.sleep(0) assert request.node.get_closest_marker('gen_test').kwargs['timeout'] == 2.1 @pytest.mark.xfail(raises=TimeoutError) @pytest.mark.gen_test(timeout=0.1) def test_gen_test_with_timeout(io_loop): yield gen.sleep(1) def test_sync_tests_no_gen_test_marker(request): assert 'gen_test' not in request.keywords class TestClass: @pytest.mark.gen_test def test_gen_test(self, io_loop): result = yield dummy_coroutine(io_loop) assert result @pytest.mark.gen_test def test_generator_raises(self, io_loop): with pytest.raises(ZeroDivisionError): yield gen.sleep(0) 1 / 0 pytest-tornado-0.8.0/test/test_async_await.py000066400000000000000000000006571346653057500214330ustar00rootroot00000000000000import pytest from tornado import gen async def dummy_native_coroutine(io_loop): await gen.sleep(0) return True @pytest.mark.gen_test async def test_native_coroutine_gen_test(io_loop): result = await dummy_native_coroutine(io_loop) assert result @pytest.mark.gen_test(run_sync=False) async def test_native_coroutine_run_sync_false(io_loop): result = await dummy_native_coroutine(io_loop) assert result pytest-tornado-0.8.0/test/test_fixtures.py000066400000000000000000000025511346653057500207750ustar00rootroot00000000000000import pytest import sys from tornado import gen _used_fixture = False @gen.coroutine def dummy(io_loop): yield gen.sleep(0) raise gen.Return(True) @pytest.fixture(scope='module') def preparations(): global _used_fixture _used_fixture = True pytestmark = pytest.mark.usefixtures('preparations') @pytest.mark.xfail(pytest.__version__ < '2.7.0', reason='py.test 2.7 adds hookwrapper, fixes collection') @pytest.mark.gen_test def test_uses_pytestmark_fixtures(io_loop): assert (yield dummy(io_loop)) assert _used_fixture class TestClass: def beforeEach(self): global _used_fixture _used_fixture = False @pytest.mark.gen_test def test_uses_pytestmark_fixtures(self, io_loop): assert (yield dummy(io_loop)) assert _used_fixture @pytest.mark.xfail(sys.version_info < (3, 5), reason='Type hints added in Python 3.5') def test_type_annotation(testdir): testdir.makepyfile( test_type_annotation=""" import pytest from tornado.ioloop import IOLoop @pytest.mark.gen_test def test_type_attrib(io_loop: IOLoop): pass # Only check that gen_test works """, ) # Run tests result = testdir.runpytest_inprocess() # Check tests went off as they should: assert result.ret == 0 pytest-tornado-0.8.0/test/test_https_support.py000066400000000000000000000024531346653057500220630ustar00rootroot00000000000000import os import ssl import pytest import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") @pytest.fixture def ssl_options(): cert_file = os.path.join(os.path.dirname(__file__), 'testcert.pem') if not os.path.exists(cert_file): pytest.skip("Missing cert file {!r}") key_file = os.path.join(os.path.dirname(__file__), 'testcert.pem') if not os.path.exists(key_file): pytest.skip("Missing key file {!r}") ssl_context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH, cafile=None, capath=None, cadata=None) ssl_context.load_cert_chain(cert_file, keyfile=key_file) return ssl_context @pytest.fixture def app(): return tornado.web.Application([ (r"/", MainHandler), ]) @pytest.mark.gen_test def test_hello_world(https_client, base_url): response = yield https_client.fetch(base_url, validate_cert=False) assert response.code == 200 def test_base_url_is_https_with_https_client(https_client, base_url): assert base_url.startswith('https://') def test_base_url_is_https_with_https_port(https_port, base_url): assert base_url.startswith('https://') def test_base_url_is_https_with_https_server(https_server, base_url): assert base_url.startswith('https://') pytest-tornado-0.8.0/test/test_param.py000066400000000000000000000030001346653057500202120ustar00rootroot00000000000000import pytest from tornado import gen DUMMY_PARAMS = ['f00', 'bar'] @pytest.fixture(params=DUMMY_PARAMS) def _dummy(request): return request.param @pytest.mark.parametrize('input,expected', [ ('3+5', 8), ('2+4', 6), ]) def test_eval(input, expected): assert eval(input) == expected @pytest.mark.parametrize('input,expected', [ ('3+5', 8), ('2+4', 6), pytest.param("6*9", 42, marks=pytest.mark.xfail), ]) def test_eval_marking(input, expected): assert eval(input) == expected @pytest.mark.parametrize('input,expected', [ ('3+5', 8), ('2+4', 6), ]) @pytest.mark.gen_test def test_sync_eval_with_gen_test(input, expected): assert eval(input) == expected @pytest.mark.parametrize('input,expected', [ ('3+5', 8), ('2+4', 6), ]) def test_eval_with_fixtures(input, io_loop, expected): assert eval(input) == expected def test_param_fixture(_dummy): assert _dummy in DUMMY_PARAMS @pytest.mark.gen_test @pytest.mark.parametrize('input,expected', [ ('3+5', 8), ('2+4', 6), ]) def test_gen_test_parametrize(io_loop, input, expected): yield gen.sleep(0) assert eval(input) == expected @pytest.mark.parametrize('input,expected', [ ('3+5', 8), ('2+4', 6), ]) @pytest.mark.gen_test def test_gen_test_fixture_any_order(input, io_loop, expected): yield gen.sleep(0) assert eval(input) == expected @pytest.mark.gen_test def test_gen_test_param_fixture(io_loop, _dummy): yield gen.sleep(0) assert _dummy in DUMMY_PARAMS pytest-tornado-0.8.0/test/test_server.py000066400000000000000000000032451346653057500204330ustar00rootroot00000000000000import functools import pytest import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write('Hello, world') application = tornado.web.Application([ (r'/', MainHandler), (r'/f00', MainHandler), ]) @pytest.fixture(scope='module') def app(): return application def _fetch(http_client, url): return http_client.io_loop.run_sync( functools.partial(http_client.fetch, url)) def test_http_server(http_server, io_loop): status = {'done': False} def _done(): status['done'] = True io_loop.stop() io_loop.add_callback(_done) io_loop.start() assert status['done'] def test_http_client(http_client, base_url): request = http_client.fetch(base_url) request.add_done_callback(lambda future: http_client.io_loop.stop()) http_client.io_loop.start() response = request.result() assert response.code == 200 def test_http_client_with_fetch_helper(http_client, base_url): response = _fetch(http_client, base_url) assert response.code == 200 @pytest.mark.gen_test def test_http_client_with_gen_test(http_client, base_url): response = yield http_client.fetch(base_url) assert response.code == 200 @pytest.mark.gen_test def test_get_url_with_path(http_client, base_url): response = yield http_client.fetch('%s/f00' % base_url) assert response.code == 200 @pytest.mark.gen_test def test_http_client_raises_on_404(http_client, base_url): with pytest.raises(tornado.httpclient.HTTPError): yield http_client.fetch('%s/bar' % base_url) def test_base_url_default_is_http(base_url): assert base_url.startswith('http://')