![](/img/trans.png)
[英]How do I make parallel async HTTP requests using httpx (versus aiohttp) in Python?
[英]How to run a async http test in python using pytest aiohttp
我想測試對我不擁有的 api 的 http 調用(集成測試)。 我創建了一個帶有異步函數的類,該函數使用 aiohttp 進行 http 調用。 然后我做了一個測試用例來運行這個函數並斷言它的狀態。
測試/test_coinbase.py :
import json
import os
from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from src.coinbase import CoinbaseService
class CoinbaseTestCase():
async def test_get_current_user(self):
coinbase_service = CoinbaseService(os.getenv('COINBASE_APIURL'), os.getenv('COINBASE_APIKEY'), os.getenv('COINBASE_APISECRET'))
status, user = await coinbase_service.show_current_user()
assert status == 200
src/coinbase.py :
import json, hmac, hashlib, time
import aiohttp
class CoinbaseService:
def __init__(self, API_URL, API_KEY, API_SECRET):
self.API_URL = API_URL
self.API_KEY = API_KEY
self.API_SECRET = API_SECRET
def generateHeaders(self, method, path_url, body = ''):
timestamp = str(int(time.time()))
message = timestamp + method + path_url + body
signature = hmac.new(self.API_SECRET, message, hashlib.sha256).hexdigest()
headers = {
'CB-ACCESS-SIGN': signature,
'CB-ACCESS-TIMESTAMP': timestamp,
'CB-ACCESS-KEY': self.API_KEY
}
return headers
async def show_current_user(self):
path_url = 'user'
headers = self.generateHeaders('GET', path_url)
async with aiohttp.ClientSession() as session:
async with session.get(path_url, headers=headers) as response:
status = response.status
user = await response.json()
return status, user
當我在我的根項目中運行以下命令時,我得到以下信息。
平台達爾文 -- Python 3.7.4, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 rootdir: /Users/helloworld/Krypto plugins: aiohttp-0.3.0 收集了 0 項
套餐
[packages]
aiohttp = "*"
backoff = "*"
requests = "*"
asyncio = "*"
vadersentiment = "*"
python-dateutil = "*"
pytest = "*"
pytest-aiohttp = "*"
CoinbaseTestCase
不匹配被視為測試類的默認pytest
命名規則,請參閱Python 測試發現的約定。 要么將該類重命名為TestCoinbase
之類的TestCoinbase
,要么定義您自己的命名約定。
vanilla pytest
不支持運行異步測試。 安裝pytest-asyncio
:
$ pip install pytest-asyncio
並使用asyncio
標記標記異步測試:
class TestCoinbase: @pytest.mark.asyncio async def test_get_current_user(self): await coinbase_service.show_current_user() ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.