首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异步协程的单元测试

异步协程的单元测试
EN

Stack Overflow用户
提问于 2020-04-08 21:01:55
回答 1查看 89关注 0票数 1

我想使用nosetests来测试类中的协程。我的第一个想法是用asyncio.run()调用每个协程。不幸的是,在第一次测试之后,我开始收到运行时异常。这是一个显示问题的最小示例:

代码语言:javascript
复制
import asyncio

class MyClass:

    def __init__(self):
        self.event = asyncio.Event()

    async def hello(self):
        print("Hello from MyClass")

class TestMyClass:

    def setup(self):
        self.my_class = MyClass()

    def test1(self):
        asyncio.run(self.my_class.hello())

    def test2(self):
        asyncio.run(self.my_class.hello())

当使用nosetests运行此脚本时,将为test2引发一个RuntimeError: There is no current event loop in thread 'MainThread'.。令人不快的一行是在MyClass中创建Event。我不完全理解这个问题。documentation for asyncio.run()声明该函数“应该用作异步程序的主要入口点,并且理想情况下应该只调用一次。”对我来说,这听起来似乎可以在一个程序中多次调用asyncio.run(),尽管不推荐这样做。

无论如何,当错误指向一个不存在的事件循环时,我决定手动管理事件循环,并提出了以下解决方法:

代码语言:javascript
复制
import asyncio

class MyClass:

    def __init__(self):
        self.event = asyncio.Event()

    async def hello(self):
        print("Hello from MyClass")

class TestMyClass:

    def __init__(self):
        try:
            self.loop = asyncio.get_event_loop()
        except RuntimeError:
            self.loop = asyncio.new_event_loop()

    def setup(self):
        asyncio.set_event_loop(self.loop)
        self.my_class = MyClass()

    def test1(self):
        asyncio.run(self.my_class.hello())

    def test2(self):
        asyncio.run(self.my_class.hello())

当多个测试脚本顺序运行时,初始化中的try...except是必需的。我使用的是Python 3.7.6。

我的解决方案在我看来不是很干净,我想知道是否有更好的方法。

EN

回答 1

Stack Overflow用户

发布于 2020-04-09 01:40:14

由于我使用的是asyncio低级API,一个潜在的更干净的解决方法可能是:

代码语言:javascript
复制
import asyncio

class MyClass:

    def __init__(self):
        self.event = asyncio.Event()

    async def hello(self):
        print("Hello from MyClass")

class TestMyClass:

    def __init__(self):
        self.loop = asyncio.get_event_loop()

    def setup(self):
        self.my_class = MyClass()

    def test1(self):
        self.loop.run_until_complete(self.my_class.hello())

    def test2(self):
        self.loop.run_until_complete(self.my_class.hello())

这种方法是否存在任何可能的问题?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61101328

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档