Test python asyncio-based code with ease.

Overview

aiounittest

image0 image1

Info

The aiounittest is a helper library to ease of your pain (and boilerplate), when writing a test of the asynchronous code (asyncio). You can test:

  • synchronous code (same as the unittest.TestCase)
  • asynchronous code, it supports syntax with async/await (Python 3.5+) and asyncio.coroutine/yield from (Python 3.4)

In the Python 3.8 (release note) and newer consider to use the unittest.IsolatedAsyncioTestCase. Builtin unittest module is now asyncio-featured.

Installation

Use pip:

pip install aiounittest

Usage

It's as simple as use of unittest.TestCase. Full docs at http://aiounittest.readthedocs.io.

import asyncio
import aiounittest


async def add(x, y):
    await asyncio.sleep(0.1)
    return x + y

class MyTest(aiounittest.AsyncTestCase):

    async def test_async_add(self):
        ret = await add(5, 6)
        self.assertEqual(ret, 11)

    # or 3.4 way
    @asyncio.coroutine
    def test_sleep(self):
        ret = yield from add(5, 6)
        self.assertEqual(ret, 11)

    # some regular test code
    def test_something(self):
        self.assertTrue(True)

Library provides some additional tooling:

License

MIT

Comments
  • test_sync_async_add: After closing the default event loop, set a new one

    test_sync_async_add: After closing the default event loop, set a new one

    TestAsyncCase.test_sync_async_add leaves the default loop closed. If TestAsyncCaseWithCustomLoop.test_await_async_add runs right after it, it will fail. As far as I can see from the other test methods, the default loop should be reset if it's closed.

    Usually, this issue is masked by tests that run in between these two and re-set the default event loop as a side effect. It can be reproduced with pytest -k 'test_await_async_add or test_sync_async_add', or on Python 3.11 with #21 merged (cc @hroncok).

    opened by encukou 1
  • Re-export top-level imports to satisfy Mypy

    Re-export top-level imports to satisfy Mypy

    Using Mypy (at least in strict mode) with the library as it currently is causes errors.

    import aiounittest
    
    
    class ExampleTest(aiounittest.AsyncTestCase):
        def test_example(self) -> None:
            self.assertEqual(1, 2 - 1)
    
    tests/test_example.py:4: error: Name "aiounittest.AsyncTestCase" is not defined
    tests/test_example.py:4: error: Class cannot subclass "AsyncTestCase" (has type "Any")
    

    It seems to be good practice to 're-export' (using __all__) all the things that you import into a module and wish to allow others to use as an import. I don't think this is actually functionally different, but just a convention. IDEs (auto-import feature) and Mypy pick up on this, at the very least.

    Signed-off-by: Olivier Wilkinson (reivilibre) [email protected] I am happy for these changes to be available under the project's licence (MIT).

    opened by reivilibre 1
  • patch on method/class level

    patch on method/class level

    Hi :)

    class Test(AsyncTestCase):
        @patch('some_path.features_topic.send', new=AsyncMock())
        async def test_smoke(self, mocked_topic):
            ...
    

    I get a TypeError: test_smoke() missing 1 required positional argument: 'mocked_topic'

    If I patch within the test with a with patch(..) as patched_object: it works fine.

    opened by jorotenev 1
  • Event loop is closed after a test but new default event loop is not created

    Event loop is closed after a test but new default event loop is not created

    When running multiple test cases using aiounittest under Python 3.8, the second and all the following unit test cases fail because there is no default event loop set in the MainThread. The following exception is raised when the unit tests are executed.

    Traceback (most recent call last):
      File "lib\site-packages\aiounittest\helpers.py", line 130, in wrapper
        loop = get_brand_new_default_event_loop()
      File "lib\site-packages\aiounittest\helpers.py", line 117, in get_brand_new_default_event_loop
        old_loop = asyncio.get_event_loop()
      File "lib\asyncio\events.py", line 639, in get_event_loop
        raise RuntimeError('There is no current event loop in thread %r.'
    RuntimeError: There is no current event loop in thread 'MainThread'.
    

    This exception occurs because get_brand_new_default_event_loop tries to get the default event loop after it has been closed in the decorator.

    opened by tmaila 1
  • Latest version isn't published to PyPI

    Latest version isn't published to PyPI

    The PyPI version does not check if a test case method is a coroutine, only that it is a callable. This differs from what's in this repo, which I think is the more correct behavior:

        def __getattribute__(self, name):
            attr = super().__getattribute__(name)
            if name.startswith('test_') and callable(attr):
                return async_test(attr, loop=self.get_event_loop())
            else:
                return attr
    
    opened by jcmcken 1
  • setUp and tearDown can't be async

    setUp and tearDown can't be async

    The AsyncTestCase assumes that only methods named test_* can be async, which isn't necessarily a valid assumption. This restriction should be removed, since you already test if the given function is a coroutine.

    opened by jcmcken 1
  • Can't call python -m unittest my_test_module.MyTestCase.test_my_async_test

    Can't call python -m unittest my_test_module.MyTestCase.test_my_async_test

    Can't call one test method directly:

    $ python -m unittest my_test_module.MyTestCase.test_my_async_test
      File ".../unittest/loader.py", line 205, in loadTestsFromName
        test = obj()
    TypeError: test_my_async_test() missing 1 required positional argument: 'self'
    
    

    The reason is that the object given by __getattribute__ is tested against type.MethodType, but async_test(...) is not.

    opened by Alcolo47 0
  • Fixed an issue where RuntimeError was thrown when running multiple tests

    Fixed an issue where RuntimeError was thrown when running multiple tests

    Fixes issue #10: RuntimeError was thrown the decorator trying to get the default event loop after the old event loop was closed. No default event loop existed and the asyncio threw a RuntimeErroe exception.

    opened by tmaila 0
  • mypy / static typing support

    mypy / static typing support

    Right now mypy is not aware that aiounittest subclasses TestCase, which is a bummer for static typing. One has to

    import aiounittest  # type: ignore
    

    which gives it the Any type. Apart from disabling type checking, this also prevents us from turning on mypy --strict mode which includes disallow_subclassing_any = True or the following error ensues:

    tests/test_case.py:15: error: Class cannot subclass 'AsyncTestCase' (has type 'Any')
    

    It seems like we only need to add an empty py.typed marker file as described in https://www.python.org/dev/peps/pep-0561/

    opened by vbraun 0
  • Initial Update

    Initial Update

    The bot created this issue to inform you that pyup.io has been set up on this repo. Once you have closed it, the bot will open pull requests for updates as soon as they are available.

    opened by pyup-bot 0
  • 1.4.1: pytest warnings

    1.4.1: pytest warnings

    Looks like latest pytest shows some warnings

    ============================================================================= warnings summary =============================================================================
    tests/test_asynctestcase.py:41
      /home/tkloczko/rpmbuild/BUILD/aiounittest-1.4.1/tests/test_asynctestcase.py:41: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead
        def test_yield_async_add(self):
    
    tests/test_asynctestcase.py:56
      /home/tkloczko/rpmbuild/BUILD/aiounittest-1.4.1/tests/test_asynctestcase.py:56: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead
        def test_yield_async_add(self):
    
    tests/test_asynctestcase_get_event_loop.py:38
      /home/tkloczko/rpmbuild/BUILD/aiounittest-1.4.1/tests/test_asynctestcase_get_event_loop.py:38: DeprecationWarning: "@coroutine" decorator is deprecated since Python 3.8, use "async def" instead
        def test_yield_async_add(self):
    
    -- Docs: https://docs.pytest.org/en/stable/warnings.html
    
    opened by kloczek 0
Releases(1.4.2)
  • 1.4.2(Jun 13, 2022)

    What's Changed

    • Don't run @asyncio.coroutine tests with Python 3.11 by @hroncok in https://github.com/kwarunek/aiounittest/pull/21
    • test_sync_async_add: After closing the default event loop, set a new one by @encukou in https://github.com/kwarunek/aiounittest/pull/22
    • Fixed deps for travis-ci py3.7

    New Contributors

    • @hroncok made their first contribution in https://github.com/kwarunek/aiounittest/pull/21
    • @encukou made their first contribution in https://github.com/kwarunek/aiounittest/pull/22

    Full Changelog: https://github.com/kwarunek/aiounittest/compare/1.4.1...1.4.2

    Source code(tar.gz)
    Source code(zip)
  • 1.4.1(Oct 22, 2021)

    What's Changed

    • Fix typo in documentation by @svisser in https://github.com/kwarunek/aiounittest/pull/17
    • Fix main example by @Zeskbest in https://github.com/kwarunek/aiounittest/pull/18
    • Re-export top-level imports to satisfy Mypy by @reivilibre in https://github.com/kwarunek/aiounittest/pull/19

    New Contributors

    • @svisser made their first contribution in https://github.com/kwarunek/aiounittest/pull/17
    • @Zeskbest made their first contribution in https://github.com/kwarunek/aiounittest/pull/18
    • @reivilibre made their first contribution in https://github.com/kwarunek/aiounittest/pull/19

    Full Changelog: https://github.com/kwarunek/aiounittest/compare/1.4.0...1.4.1

    Source code(tar.gz)
    Source code(zip)
Generates realistic traffic for load testing tile servers

Generates realistic traffic for load testing tile servers. Useful for: Measuring throughput, latency and concurrency of your tile serving stack. Ident

Brandon Liu 23 Dec 05, 2022
Asyncio http mocking. Similar to the responses library used for 'requests'

aresponses an asyncio testing server for mocking external services Features Fast mocks using actual network connections allows mocking some types of n

93 Nov 16, 2022
A pytest plugin, that enables you to test your code that relies on a running PostgreSQL Database

This is a pytest plugin, that enables you to test your code that relies on a running PostgreSQL Database. It allows you to specify fixtures for PostgreSQL process and client.

Clearcode 252 Dec 21, 2022
Fail tests that take too long to run

GitHub | PyPI | Issues pytest-fail-slow is a pytest plugin for making tests fail that take too long to run. It adds a --fail-slow DURATION command-lin

John T. Wodder II 4 Nov 27, 2022
Mypy static type checker plugin for Pytest

pytest-mypy Mypy static type checker plugin for pytest Features Runs the mypy static type checker on your source files as part of your pytest test run

Dan Bader 218 Jan 03, 2023
Airspeed Velocity: A simple Python benchmarking tool with web-based reporting

airspeed velocity airspeed velocity (asv) is a tool for benchmarking Python packages over their lifetime. It is primarily designed to benchmark a sing

745 Dec 28, 2022
MongoDB panel for the Flask Debug Toolbar

Flask Debug Toolbar MongoDB Panel Info: An extension panel for Rob Hudson's Django Debug Toolbar that adds MongoDB debugging information Author: Harry

Cenk Altı 4 Dec 11, 2019
Akulaku Create NewProduct Automation using Selenium Python

Akulaku-Create-NewProduct-Automation Akulaku Create NewProduct Automation using Selenium Python Usage: 1. Install Python 3.9 2. Open CMD on Bot Folde

Rahul Joshua Damanik 1 Nov 22, 2021
A set of pytest fixtures to test Flask applications

pytest-flask An extension of pytest test runner which provides a set of useful tools to simplify testing and development of the Flask extensions and a

pytest-dev 433 Dec 23, 2022
Photostudio是一款能进行自动化检测网页存活并实时给网页拍照的工具,通过调用Fofa/Zoomeye/360qua/shodan等 Api快速准确查询资产并进行网页截图,从而实施进一步的信息筛查。

Photostudio-红队快速爬取网页快照工具 一、简介: 正如其名:这是一款能进行自动化检测,实时给网页拍照的工具 信息收集要求所收集到的信息要真实可靠。 当然,这个原则是信息收集工作的最基本的要求。为达到这样的要求,信息收集者就必须对收集到的信息反复核实,不断检验,力求把误差减少到最低限度。我

s7ck Team 41 Dec 11, 2022
Python script to automatically download from Zippyshare

Zippyshare downloader and Links Extractor Python script to automatically download from Zippyshare using Selenium package and Internet Download Manager

Daksh Khurana 2 Oct 31, 2022
Scalable user load testing tool written in Python

Locust Locust is an easy to use, scriptable and scalable performance testing tool. You define the behaviour of your users in regular Python code, inst

Locust.io 20.4k Jan 04, 2023
Python Testing Crawler 🐍 🩺 🕷️ A crawler for automated functional testing of a web application

Python Testing Crawler 🐍 🩺 🕷️ A crawler for automated functional testing of a web application Crawling a server-side-rendered web application is a

70 Aug 07, 2022
Avocado is a set of tools and libraries to help with automated testing.

Welcome to Avocado Avocado is a set of tools and libraries to help with automated testing. One can call it a test framework with benefits. Native test

Ana Guerrero Lopez 1 Nov 19, 2021
Generate random test credit card numbers for testing, validation and/or verification purposes.

Generate random test credit card numbers for testing, validation and/or verification purposes.

Dark Hunter 141 5 Nov 14, 2022
PacketPy is an open-source solution for stress testing network devices using different testing methods

PacketPy About PacketPy is an open-source solution for stress testing network devices using different testing methods. Currently, there are only two c

4 Sep 22, 2022
This is a pytest plugin, that enables you to test your code that relies on a running MongoDB database

This is a pytest plugin, that enables you to test your code that relies on a running MongoDB database. It allows you to specify fixtures for MongoDB process and client.

Clearcode 19 Oct 21, 2022
AutoExploitSwagger is an automated API security testing exploit tool that can be combined with xray, BurpSuite and other scanners.

AutoExploitSwagger is an automated API security testing exploit tool that can be combined with xray, BurpSuite and other scanners.

6 Jan 28, 2022
Automates hiketop+ crystal earning using python and appium

hikepy Works on poco x3 idk about your device deponds on resolution Prerquests Android sdk java adb Setup Go to https://appium.io/ Download and instal

4 Aug 26, 2022
pytest splinter and selenium integration for anyone interested in browser interaction in tests

Splinter plugin for the pytest runner Install pytest-splinter pip install pytest-splinter Features The plugin provides a set of fixtures to use splin

pytest-dev 238 Nov 14, 2022