<p>我认为您可以通过更改此方法来修复错误:</p>
<pre class="lang-py prettyprint-override"><code>@app.listener('after_server_stop')
async def finish(app, loop):
await app.aiohttp_session.close()
</code></pre>
<p>关闭循环不是您的责任,您应该使用这样一个事实,即<code>finish</code>是从异步上下文调用的(不需要启动事件循环,它已经在运行)。在</p>
<p>如果这不是唯一的问题,那么也许从一个简单的例子开始,添加一些东西,直到它再次崩溃。Sanic似乎有一个很好的文档<a href="https://sanic.readthedocs.io/en/latest/sanic/testing.html#testing" rel="nofollow noreferrer">test section</a>,他们建议使用<a href="https://github.com/yunstanford/pytest-sanic" rel="nofollow noreferrer">pytest-sanic</a>。使用pytest的一个简单示例如下:</p>
^{pr2}$
<pre class="lang-py prettyprint-override"><code># file: server_test.py
import pytest
from server import app
@pytest.yield_fixture
def sanic_app():
yield app
@pytest.fixture
def test_cli(loop, sanic_app, sanic_client):
return loop.run_until_complete(sanic_client(app))
async def test_index(test_cli):
resp = await test_cli.get('/')
assert resp.status == 200
json = await resp.json()
assert json == {'hello': 'world'}
async def test_index_fail(test_cli):
resp = await test_cli.get('/')
assert resp.status == 200
json = await resp.json()
assert json == {'bonjour': 'monde'}
</code></pre>
<p>您需要安装一些软件包:</p>
<pre><code>pip install sanic pytest pytest-sanic
</code></pre>
<p>然后可以运行<code>pytest</code>,第一个测试通过,第二个测试失败。在</p>
<p>一般来说,您不必自己启动事件循环,始终尝试摆脱<code>loop.run_...</code>。在</p>