我在模拟aiohttp.client.ClientSession.get上下文管理器时遇到了一些麻烦.我找到了一些文章,这里有一个似乎正在起作用的例子:第1条
所以我要测试的代码:
async_app.py
import random
from aiohttp.client import ClientSession
async def get_random_photo_url():
while True:
async with ClientSession() as session:
async with session.get('random.photos') as resp:
json = await resp.json()
photos = json['photos']
if not photos:
continue
return random.choice(photos)['img_src']
Run Code Online (Sandbox Code Playgroud)
并测试:
test_async_app.py
from asynctest import CoroutineMock, MagicMock, patch
from asynctest import TestCase as TestCaseAsync
from async_app import get_random_photo_url
class AsyncContextManagerMock(MagicMock):
async def __aenter__(self):
return self.aenter
async def __aexit__(self, *args):
pass
class TestAsyncExample(TestCaseAsync):
@patch('aiohttp.client.ClientSession.get', new_callable=AsyncContextManagerMock)
async def test_call_api_again_if_photos_not_found(self, mock_get):
mock_get.return_value.aenter.json = CoroutineMock(side_effect=[{'photos': []}, …Run Code Online (Sandbox Code Playgroud) 我想知道为什么jest.useFakeTimers与setTimeoutRxJs的延迟运算符一起工作但不是:
jest.useFakeTimers();
import {Observable} from 'rxjs/Observable';
import 'rxjs';
describe('timers', () => {
it('should resolve setTimeout synchronously', () => {
const spy = jest.fn();
setTimeout(spy, 20);
expect(spy).not.toHaveBeenCalled();
jest.runTimersToTime(20);
expect(spy).toHaveBeenCalledTimes(1);
});
it('should resolve setInterval synchronously', () => {
const spy = jest.fn();
setInterval(spy, 20);
expect(spy).not.toHaveBeenCalled();
jest.runTimersToTime(20);
expect(spy).toHaveBeenCalledTimes(1);
jest.runTimersToTime(20);
expect(spy).toHaveBeenCalledTimes(2);
});
it('should work with observables', () => {
const delay$ = Observable.of(true).delay(20);
const spy = jest.fn();
delay$.subscribe(spy);
expect(spy).not.toHaveBeenCalled();
jest.runTimersToTime(2000);
expect(spy).toHaveBeenCalledTimes(1);
});
});
Run Code Online (Sandbox Code Playgroud)
仅供参考:使用20或2000作为参数jest.runTimersToTime没有任何区别.使用jest.runAllTimers()使测试过去