pytest导致asyncio循环失败

时间:2017-06-14 19:09:45

标签: python python-3.x pytest

因此,在任何带有循环的文件上运行pytest会产生错误

test_post.py:6: in <module>
loop = asyncio.get_event_loop()
/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/events.py:678: in get_event_loop
    return get_event_loop_policy().get_event_loop()
/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/events.py:584: in get_event_loop
    % threading.current_thread().name)
E   RuntimeError: There is no current event loop in thread 'MainThread'.

代码如下......

import pytest
#from handlers import request_handler
import json

import asyncio
loop = asyncio.get_event_loop()
async def compute(x, y):
  print("Compute %s + %s ..." % (x, y))
  await asyncio.sleep(1.0)
  return x + y

async def print_sum(x, y):
  result = await compute(x, y)
  print("%s + %s = %s" % (x, y, result))
loop.run_until_complete( print_sum(1, 2) )
loop.close()

这些不是我想写的实际测试,但我需要首先使用循环...有关如何修复的任何想法?

1 个答案:

答案 0 :(得分:0)

Add a __main__ entry point and put loop = asyncio.get_event_loop() beneath that.