美文网首页
测试异步函数的方案

测试异步函数的方案

作者: ThomasYoungK | 来源:发表于2019-11-24 12:09 被阅读0次

python异步函数需要在事件循环里跑才可以, 因此写单测会非常麻烦.
我在python源码里找到了一个简单的方案(https://github.com/python/cpython/blob/master/Lib/test/test_contextlib_async.py
), 很有意思, 推荐给大家:
_async_test装饰器, 该装饰器帮你把异步函数放到event loop里运行, 因此你只需要在单测里调用异步函数, 和同步用例一样写测试逻辑就行了. 不需要自己写eventloop.

"""测试异步函数的方案
来自python源码: https://github.com/python/cpython/blob/master/Lib/test/test_contextlib_async.py"""
import asyncio
import functools
import unittest
from contextlib import asynccontextmanager


def _async_test(func):
    """Decorator to turn an async function into a test case.
    这样就无须在测试用例里面手动触发事件循环了, 可以理解为自动把异步函数给触发运行"""

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        coro = func(*args, **kwargs)
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            return loop.run_until_complete(coro)
        finally:
            loop.close()
            asyncio.set_event_loop(None)

    return wrapper


class AsyncContextManagerTestCase(unittest.TestCase):

    @_async_test
    async def test_contextmanager_plain(self):
        state = []

        @asynccontextmanager
        async def woohoo():
            state.append(1)
            yield 42
            state.append(999)

        async with woohoo() as x:
            self.assertEqual(state, [1])
            self.assertEqual(x, 42)
            state.append(x)
        self.assertEqual(state, [1, 42, 999])

    @_async_test
    async def test_xx(self):
        assert 1 == 5

pytest的测试就更简单, 直接在异步函数上面加上装饰器即可:

@_async_test
async def test_contextmanager_plain():
    state = []

    @asynccontextmanager
    async def woohoo():
        state.append(1)
        yield 42
        state.append(999)

    async with woohoo() as x:
        assert state == [1]
        assert x == 42
        state.append(x)
    assert state == [1, 42, 999]


@_async_test
async def test_xx():
    assert 1 == 5

相关文章

  • 测试异步函数的方案

    python异步函数需要在事件循环里跑才可以, 因此写单测会非常麻烦.我在python源码里找到了一个简单的方案(...

  • 从回调函数到 async await,理清异步编程解决方案

    异步解决方案历程 1. 回调函数 回调函数是最开始的异步解决方案,在异步代码执行完后去执行回调函数 这样做有几个缺...

  • 学习笔记——Promise简单使用

    Promise 是异步编程的一种解决方案,解决了传统异步方案的弊端(回调函数和事件) 异步操作 开始说promis...

  • Async/Await 函数用法

    JavaScript编程异步操作解决方案:回调函数 => Promise对象 => Generator函数 => ...

  • Generator

    异步编程解决方案 Generator 函数、Promise 、回调函数、事件 Generator 函数有多种理解角...

  • 知识点整理之ES6

    .说说Promise Promise 是异步编程的一种解决方案,比传统的异步解决方案【回调函数】和【事件】更合理、...

  • 理解【ES6】Promise

    什么是Promise Promise是异步编程的一种解决方案,比传统的异步解决方案【回调函数】和【事件】更合理、更...

  • JS异步-解决方法简述

    介绍三种异步处理方案: 回调函数(callback)promiseasync/await 回调函数(callbac...

  • 03-JavaScript-Generator异步编程

    Generator 概念 Generator 函数是 ES6 提供的一种异步编程解决方案 Generator 函数...

  • async await promise 异步 同步的 是个什么?

    js异步编程官方介绍: Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更...

网友评论

      本文标题:测试异步函数的方案

      本文链接:https://www.haomeiwen.com/subject/gollwctx.html