[python/asyncio] explicitly close client session via async context manager (#5621)

This commit is contained in:
Tomasz Prus
2020-03-25 15:59:27 +01:00
committed by GitHub
parent 928d065bbf
commit 625c734cfe
7 changed files with 58 additions and 22 deletions

View File

@@ -0,0 +1,27 @@
# coding: utf-8
# flake8: noqa
import unittest
import weakref
from tests.util import async_test
import petstore_api
class TestApiClient(unittest.TestCase):
@async_test
async def test_context_manager_closes_client(self):
async with petstore_api.ApiClient() as client:
# thread pool
self.assertIsNotNone(client.pool)
pool_ref = weakref.ref(client._pool)
self.assertIsNotNone(pool_ref())
# pool_manager
self.assertFalse(client.rest_client.pool_manager.closed)
rest_pool_ref = client.rest_client.pool_manager
self.assertIsNone(pool_ref())
self.assertTrue(rest_pool_ref.closed)

View File

@@ -18,7 +18,7 @@ import petstore_api
from petstore_api import Configuration
from petstore_api.rest import ApiException
from .util import id_gen
from .util import id_gen, async_test
import json
@@ -27,15 +27,6 @@ import urllib3
HOST = 'http://localhost:80/v2'
def async_test(f):
def wrapper(*args, **kwargs):
coro = asyncio.coroutine(f)
future = coro(*args, **kwargs)
loop = asyncio.get_event_loop()
loop.run_until_complete(future)
return wrapper
class TestPetApiTests(unittest.TestCase):
def setUp(self):

View File

@@ -1,5 +1,6 @@
# flake8: noqa
import asyncio
import random
@@ -8,4 +9,10 @@ def id_gen(bits=32):
return int(random.getrandbits(bits))
def async_test(f):
def wrapper(*args, **kwargs):
coro = asyncio.coroutine(f)
future = coro(*args, **kwargs)
loop = asyncio.get_event_loop()
loop.run_until_complete(future)
return wrapper