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)
Simple frontend TypeScript testing utility

TSFTest Simple frontend TypeScript testing utility. Installation Install webpack in your project directory: npm install --save-dev webpack webpack-cli

2 Nov 09, 2021
The (Python-based) mining software required for the Game Boy mining project.

ntgbtminer - Game Boy edition This is a version of ntgbtminer that works with the Game Boy bitcoin miner. ntgbtminer ntgbtminer is a no thrills getblo

Ghidra Ninja 31 Nov 04, 2022
PoC getting concret intel with chardet and charset-normalizer

aiohttp with charset-normalizer Context aiohttp.TCPConnector(limit=16) alpine linux nginx 1.21 python 3.9 aiohttp dev-master chardet 4.0.0 (aiohttp-ch

TAHRI Ahmed R. 2 Nov 30, 2022
Find index entries in $INDEX_ALLOCATION attributes

INDXRipper Find index entries in $INDEX_ALLOCATION attributes Timeline created using mactime.pl on the combined output of INDXRipper and fls. See: sle

32 Nov 05, 2022
Test scripts etc. for experimental rollup testing

rollup node experiments Test scripts etc. for experimental rollup testing. untested, work in progress python -m venv venv source venv/bin/activate #

Diederik Loerakker 14 Jan 25, 2022
ApiPy was created for api testing with Python pytest framework which has also requests, assertpy and pytest-html-reporter libraries.

ApiPy was created for api testing with Python pytest framework which has also requests, assertpy and pytest-html-reporter libraries. With this f

Mustafa 1 Jul 11, 2022
pywinauto is a set of python modules to automate the Microsoft Windows GUI

pywinauto is a set of python modules to automate the Microsoft Windows GUI. At its simplest it allows you to send mouse and keyboard actions to windows dialogs and controls, but it has support for mo

3.8k Jan 06, 2023
A collection of benchmarking tools.

Benchmark Utilities About A collection of benchmarking tools. PYPI Package Table of Contents Using the library Installing and using the library Manual

Kostas Georgiou 2 Jan 28, 2022
Python wrapper of Android uiautomator test tool.

uiautomator This module is a Python wrapper of Android uiautomator testing framework. It works on Android 4.1+ (API Level 16~30) simply with Android d

xiaocong 1.9k Dec 30, 2022
Python package to easily work with selenium and manage tabs effectively.

Simple Selenium The aim of this package is to quickly get started with working with selenium for simple browser automation tasks. Installation Install

Vishal Kumar Mishra 1 Oct 27, 2021
Minimal example of getting Django + PyTest running on GitHub Actions

Minimal Django + Pytest + GitHub Actions example This minimal example shows you how you can runs pytest on your Django app on every commit using GitHu

Matt Segal 5 Sep 19, 2022
Percy visual testing for Python Selenium

percy-selenium-python Percy visual testing for Python Selenium. Installation npm install @percy/cli: $ npm install --save-dev @percy/cli pip install P

Percy 9 Mar 24, 2022
Python tools for penetration testing

pyTools_PT python tools for penetration testing Please don't use these tool for illegal purposes. These tools is meant for penetration testing for leg

Gourab 1 Dec 01, 2021
MultiPy lets you conveniently keep track of your python scripts for personal use or showcase by loading and grouping them into categories. It allows you to either run each script individually or together with just one click.

MultiPy About MultiPy is a graphical user interface built using Dear PyGui Python GUI Framework that lets you conveniently keep track of your python s

56 Oct 29, 2022
Mixer -- Is a fixtures replacement. Supported Django, Flask, SqlAlchemy and custom python objects.

The Mixer is a helper to generate instances of Django or SQLAlchemy models. It's useful for testing and fixture replacement. Fast and convenient test-

Kirill Klenov 871 Dec 25, 2022
API mocking with Python.

apyr apyr (all lowercase) is a simple & easy to use mock API server. It's great for front-end development when your API is not ready, or when you are

Umut Seven 55 Nov 25, 2022
It's a simple script to generate a mush on code forces, the script will accept the public problem urls only or polygon problems.

Codeforces-Sheet-Generator It's a simple script to generate a mushup on code forces, the script will accept the public problem urls only or polygon pr

Ahmed Hossam 10 Aug 02, 2022
Aplikasi otomasi klik di situs popcat.click menggunakan Python dan Selenium

popthe-popcat Aplikasi Otomasi Klik di situs popcat.click. aplikasi ini akan secara otomatis melakukan click pada kucing viral itu, sehingga anda tida

cndrw_ 2 Oct 07, 2022
Bayesian A/B testing

bayesian_testing is a small package for a quick evaluation of A/B (or A/B/C/...) tests using Bayesian approach.

Matus Baniar 35 Dec 15, 2022
This file will contain a series of Python functions that use the Selenium library to search for elements in a web page while logging everything into a file

element_search with Selenium (Now With docstrings 😎 ) Just to mention, I'm a beginner to all this, so it it's very possible to make some mistakes The

2 Aug 12, 2021