Here are the examples of the python api pytest.mark.asyncio taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
157 Examples
3
Example 1
Project: irc3 Source File: test_async.py
@pytest.mark.asyncio
def test_no_topic(irc3_bot_factory):
bot = irc3_bot_factory(includes=['irc3.plugins.async'])
assert len(bot.registry.events_re['in']) == 0
task = bot.async_cmds.topic('#chan', timeout=.1)
assert len(bot.registry.events_re['in']) > 0
bot.dispatch(':localhost 331 me #chan :Not topic')
result = yield from task
assert result['timeout'] is False
assert result['topic'] is None
3
Example 2
@pytest.mark.asyncio
def test_decorator_exc(self, fo, patch_timer):
"""
Does not swallow exceptions.
"""
v = ValueError("foo")
@aio.time(fo)
@asyncio.coroutine
def func():
yield from asyncio.sleep(0)
raise v
with pytest.raises(ValueError) as e:
yield from func()
assert v is e.value
assert [1] == fo._observed
3
Example 3
Project: elasticsearch-py-async Source File: test_client.py
@mark.asyncio
def test_custom_body(server, client):
server.register_response('/', {'custom': 'body'})
data = yield from client.info()
assert [('GET', '/', '', {})] == server.calls
assert {'custom': 'body'} == data
3
Example 4
Project: irc3 Source File: test_async.py
@pytest.mark.asyncio
def test_whois_timeout(irc3_bot_factory):
bot = irc3_bot_factory(includes=['irc3.plugins.async'])
assert len(bot.registry.events_re['in']) == 0
task = bot.async_cmds.whois(nick='GaWel', timeout=.1)
assert len(bot.registry.events_re['in']) > 2
result = yield from task
assert result['timeout'] is True
3
Example 5
@mark.asyncio
def test_info(connection):
status, headers, data = yield from connection.perform_request('GET', '/')
data = json.loads(data)
assert status == 200
assert {'body': '', 'method': 'GET', 'params': {}, 'path': '/'} == data
3
Example 6
@pytest.mark.asyncio
@pytest.mark.parametrize('mode', ['w', 'r', 'r+', 'w+', 'a', 'a+'])
def test_simple_close(mode, tmpdir):
"""Open a file, read a byte, and close it."""
filename = 'bigfile.bin'
content = '0' * 4 * io.DEFAULT_BUFFER_SIZE
full_file = tmpdir.join(filename)
full_file.write(content)
file = yield from aioopen(str(full_file), mode=mode)
assert not file.closed
assert not file._file.closed
yield from file.close()
assert file.closed
assert file._file.closed
3
Example 7
@pytest.mark.asyncio
def test_login_ok(manager):
manager = manager(username='xx', secret='xx', stream='login_ok.yaml')
authenticated = yield from manager.authenticated_future
assert authenticated.success is True
assert manager.login(manager.authenticated_future) is True
3
Example 8
@pytest.mark.asyncio
@pytest.mark.parametrize('mode', ['rb', 'rb+', 'ab+'])
@pytest.mark.parametrize('buffering', [-1, 0])
def test_simple_read(mode, buffering):
"""Just read some bytes from a test file."""
filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt')
file = yield from aioopen(filename, mode=mode, buffering=buffering)
yield from file.seek(0) # Needed for the append mode.
actual = yield from file.read()
assert b'' == (yield from file.read())
assert actual == open(filename, mode='rb').read()
yield from file.close()
3
Example 9
Project: prometheus_async Source File: test_aio.py
@pytest.mark.asyncio
def test_decorator_no_exc(self, fc, event_loop):
"""
If no exception is raised, the counter does not change.
"""
@aio.count_exceptions(fc)
def func():
yield from asyncio.sleep(0.0)
return 42
assert 42 == (yield from func())
assert 0 == fc._val
3
Example 10
@pytest.mark.asyncio
@pytest.mark.parametrize('mode', ['rb', 'rb+', 'ab+'])
@pytest.mark.parametrize('buffering', [-1, 0])
def test_simple_readinto(mode, buffering):
"""Test the readinto functionality."""
filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt')
file = yield from aioopen(filename, mode=mode, buffering=buffering)
yield from file.seek(0) # Needed for the append mode.
array = bytearray(4)
bytes_read = yield from file.readinto(array)
assert bytes_read == 4
assert array == open(filename, mode='rb').read(4)
yield from file.close()
3
Example 11
Project: irc3 Source File: test_async.py
@pytest.mark.asyncio
def test_whois_fail(irc3_bot_factory):
bot = irc3_bot_factory(includes=['irc3.plugins.async'])
assert len(bot.registry.events_re['in']) == 0
task = bot.async_cmds.whois(nick='gawel')
assert len(bot.registry.events_re['in']) > 2
bot.dispatch(':localhost 401 me gawel :No such nick')
result = yield from task
assert result['success'] is False
assert len(bot.registry.events_re['in']) == 0
3
Example 12
Project: elasticsearch-py-async Source File: test_connection.py
@mark.asyncio
def test_error_is_properly_logged(connection, caplog, port, server):
server.register_response('/i', status=404)
with raises(NotFoundError):
yield from connection.perform_request('GET', '/i', params={'some': 'data'})
for logger, level, message in caplog.record_tuples:
if logger == 'elasticsearch' and level == logging.WARNING:
assert message.startswith('GET http://localhost:%s/i?some=data [status:404 request:' % port)
break
else:
assert False, "Log not received"
3
Example 13
@pytest.mark.asyncio
@pytest.mark.parametrize('mode', ['r', 'r+', 'a+'])
def test_simple_read(mode):
"""Just read some bytes from a test file."""
filename = join(dirname(__file__), '..', 'resources', 'test_file1.txt')
file = yield from aioopen(filename, mode=mode)
yield from file.seek(0) # Needed for the append mode.
actual = yield from file.read()
assert '' == (yield from file.read())
assert actual == open(filename, mode='r').read()
yield from file.close()
3
Example 14
Project: irc3 Source File: test_async.py
@pytest.mark.asyncio
def test_who_nick(irc3_bot_factory):
bot = irc3_bot_factory(includes=['irc3.plugins.async'])
assert len(bot.registry.events_re['in']) == 0
task = bot.async_cmds.who('irc3')
assert len(bot.registry.events_re['in']) == 2
bot.dispatch(
':card.freenode.net 352 nick * ~irc3 host1 serv1 irc3 H :0 bot')
bot.dispatch(':card.freenode.net 315 nick irc3 :End of /WHO list.')
result = yield from task
assert result['timeout'] is False
assert result['hopcount'] == '0'
3
Example 15
Project: with Source File: test_prompt.py
@pytest.mark.asyncio
def it_shows_prompt_again_on_keyboard_interrupt(self):
with mock.patch('withtool.prompt.prompt_async') as mock_prompt_async:
mock_prompt_async.side_effect = (
KeyboardInterrupt,
''
)
try:
yield from prompt.get_prompt('cmd')
except Exception as e:
pytest.fail('It should not have raised: {}'.format(e))
assert mock_prompt_async.call_count == 2
3
Example 16
@pytest.mark.asyncio
def test_names(irc3_bot_factory):
bot = irc3_bot_factory(includes=['irc3.plugins.async'])
assert len(bot.registry.events_re['in']) == 0
task = bot.async_cmds.names('#irc3')
assert len(bot.registry.events_re['in']) == 2
bot.dispatch(
':card.freenode.net 353 nick @ #irc3 :irc3 @gawel')
bot.dispatch(
':card.freenode.net 353 nick @ #irc3 :+panoramisk')
bot.dispatch(
':card.freenode.net 366 nick #irc3 :End of /NAMES list.')
result = yield from task
assert result['timeout'] is False
assert len(result['names']) == 3
3
Example 17
@pytest.mark.asyncio
def test_simple_detach(tmpdir):
"""Test detaching for buffered streams."""
filename = 'file.bin'
full_file = tmpdir.join(filename)
full_file.write('0123456789')
file = yield from aioopen(str(full_file), mode='r')
raw_file = file.detach()
assert raw_file
with pytest.raises(ValueError):
yield from file.read()
assert b'0123456789' == raw_file.read(10)
3
Example 18
@pytest.mark.asyncio
def test_decorator_sync(self, fo, patch_timer):
"""
time works with sync results functions.
"""
@aio.time(fo)
@asyncio.coroutine
def func():
if True:
return 42
else:
yield from asyncio.sleep(0)
assert 42 == (yield from func())
assert [1] == fo._observed
3
Example 19
Project: pytest-asyncio Source File: test_simple.py
@pytest.mark.asyncio
def test_unused_port_fixture(unused_tcp_port, event_loop):
"""Test the unused TCP port fixture."""
@asyncio.coroutine
def closer(_, writer):
writer.close()
server1 = yield from asyncio.start_server(closer, host='localhost',
port=unused_tcp_port,
loop=event_loop)
with pytest.raises(IOError):
yield from asyncio.start_server(closer, host='localhost',
port=unused_tcp_port,
loop=event_loop)
server1.close()
yield from server1.wait_closed()
3
Example 20
Project: prometheus_async Source File: test_aio.py
@pytest.mark.asyncio
def test_future_exc(self, fo, patch_timer, event_loop):
"""
Does not swallow exceptions.
"""
fut = asyncio.Future(loop=event_loop)
coro = aio.time(fo, fut)
v = ValueError("foo")
assert [] == fo._observed
fut.set_exception(v)
with pytest.raises(ValueError) as e:
yield from coro
assert [1] == fo._observed
assert v is e.value
3
Example 21
Project: elasticsearch-py-async Source File: test_client.py
@mark.asyncio
def test_ping_works(server, client):
data = yield from client.ping()
assert [('HEAD', '/', '', {})] == server.calls
assert data is True
3
Example 22
Project: elasticsearch-py-async Source File: test_client.py
@mark.asyncio
def test_exists_with_404_returns_false(server, client):
server.register_response('/not-there', status=404)
data = yield from client.indices.exists(index='not-there')
assert data is False
3
Example 23
Project: with Source File: test_main.py
@pytest.mark.asyncio
def it_prints_the_current_version_and_exits(self):
with mock.patch.object(sys, 'argv', ['/tmp/with', '--version']), \
mock.patch('builtins.print') as mock_print:
with pytest.raises(SystemExit):
yield from main()
version_pattern = re.compile(r'with \d+\.\d+\.\d+')
assert mock_print.called
assert version_pattern.match(mock_print.call_args[0][0])
3
Example 24
Project: elasticsearch-py-async Source File: test_connection.py
@mark.asyncio
def test_request_is_properly_logged(connection, caplog, port, server):
server.register_response('/_cat/indices', {'cat': 'indices'})
yield from connection.perform_request('GET', '/_cat/indices', body=b'{}', params={"format": "json"})
for logger, level, message in caplog.record_tuples:
if logger == 'elasticsearch' and level == logging.INFO:
assert message.startswith('GET http://localhost:%s/_cat/indices?format=json [status:200 request:' % port)
break
else:
assert False, 'Message not found'
assert ('elasticsearch', logging.DEBUG, '> {}') in caplog.record_tuples
assert ('elasticsearch', logging.DEBUG, '< {"cat": "indices"}') in caplog.record_tuples
3
Example 25
@pytest.mark.asyncio
def test_simple_detach(tmpdir):
"""Test detaching for buffered streams."""
filename = 'file.bin'
full_file = tmpdir.join(filename)
full_file.write_binary(b'0123456789')
file = yield from aioopen(str(full_file), mode='rb')
raw_file = file.detach()
assert raw_file
with pytest.raises(ValueError):
yield from file.read()
assert b'0123456789' == raw_file.read(10)
3
Example 26
Project: elasticsearch-py-async Source File: test_transport.py
@mark.asyncio
def test_retry_will_work(port, server, event_loop):
client = AsyncElasticsearch(hosts=['not-an-es-host', 'localhost'], port=port, loop=event_loop, randomize_hosts=False)
data = yield from client.info()
assert {'body': '', 'method': 'GET', 'params': {}, 'path': '/'} == data
client.transport.close()
3
Example 27
Project: elasticsearch-py-async Source File: test_connection.py
@mark.asyncio
def test_timeout_is_properly_raised(connection, server):
@asyncio.coroutine
def slow_request():
yield from asyncio.sleep(0.01)
return {}
server.register_response('/_search', slow_request())
with raises(ConnectionTimeout):
yield from connection.perform_request('GET', '/_search', timeout=0.0001)
3
Example 28
@pytest.mark.asyncio
@pytest.mark.parametrize('mode', ['r', 'r+', 'a+'])
def test_simple_readlines(mode):
"""Test the readlines functionality."""
filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt')
with open(filename, mode='r') as f:
expected = f.readlines()
file = yield from aioopen(filename, mode=mode)
# Append mode needs us to seek.
yield from file.seek(0)
actual = yield from file.readlines()
yield from file.close()
assert actual == expected
3
Example 29
Project: irc3 Source File: test_async.py
@pytest.mark.asyncio
def test_whois_success(irc3_bot_factory):
bot = irc3_bot_factory(includes=['irc3.plugins.async'])
assert len(bot.registry.events_re['in']) == 0
task = bot.async_cmds.whois(nick='GaWel')
assert len(bot.registry.events_re['in']) > 2
bot.dispatch(':localhost 311 me gawel username localhost * :realname')
bot.dispatch(':localhost 319 me gawel :@#irc3')
bot.dispatch(':localhost 312 me gawel localhost :Paris, FR')
bot.dispatch(':localhost 671 me gawel :is using a secure connection')
bot.dispatch(':localhost 330 me gawel gawel :is logged in as')
bot.dispatch(':localhost 318 me gawel :End')
result = yield from task
assert len(bot.registry.events_re['in']) == 0
assert result['success']
assert result['timeout'] is False
assert result['username'] == 'username'
assert result['realname'] == 'realname'
3
Example 30
Project: with Source File: test_prompt.py
@pytest.mark.asyncio
def it_exits_on_EOF_error(self):
with mock.patch('withtool.prompt.prompt_async') as mock_prompt_async:
mock_prompt_async.side_effect = EOFError
with pytest.raises(SystemExit):
yield from prompt.get_prompt('cmd')
3
Example 31
Project: irc3 Source File: test_async.py
@pytest.mark.asyncio
def test_who_channel(irc3_bot_factory):
bot = irc3_bot_factory(includes=['irc3.plugins.async'])
assert len(bot.registry.events_re['in']) == 0
task = bot.async_cmds.who('#irc3')
assert len(bot.registry.events_re['in']) == 2
bot.dispatch(
':card.freenode.net 352 nick #irc3 ~irc3 host1 srv1 irc3 H :0 bot')
bot.dispatch(
':card.freenode.net 352 nick #irc3 ~gael host2 srv2 gawel H@ :1 g')
bot.dispatch(':card.freenode.net 315 nick #irc3 :End of /WHO list.')
result = yield from task
assert result['timeout'] is False
assert len(result['users']) == 2
3
Example 32
@pytest.mark.asyncio
@pytest.mark.parametrize('mode', ['r', 'r+', 'a+'])
def test_simple_seek(mode, tmpdir):
"""Test seeking and then reading."""
filename = 'bigfile.bin'
content = '0123456789' * 4 * io.DEFAULT_BUFFER_SIZE
full_file = tmpdir.join(filename)
full_file.write(content)
file = yield from aioopen(str(full_file), mode=mode)
yield from file.seek(4)
assert '4' == (yield from file.read(1))
yield from file.close()
3
Example 33
@pytest.mark.asyncio
def test_topic(irc3_bot_factory):
bot = irc3_bot_factory(includes=['irc3.plugins.async'])
assert len(bot.registry.events_re['in']) == 0
task = bot.async_cmds.topic('#chan', topic='test', timeout=.1)
assert len(bot.registry.events_re['in']) > 0
bot.dispatch(':localhost TOPIC #chan :test')
result = yield from task
assert result['timeout'] is False
assert result['topic'] == 'test'
3
Example 34
Project: pytest-asyncio Source File: test_alternative_loops.py
@pytest.mark.asyncio(forbid_global_loop=True)
def test_forbid_global_loop(event_loop):
"""Test forbidding fetching the global loop using get_event_loop."""
yield from asyncio.sleep(0.01, loop=event_loop)
with pytest.raises(Exception):
asyncio.get_event_loop()
3
Example 35
@pytest.mark.asyncio
def test_ison(irc3_bot_factory):
bot = irc3_bot_factory(includes=['irc3.plugins.async'])
assert len(bot.registry.events_re['in']) == 0
task = bot.async_cmds.ison('GaWel', timeout=.1)
assert len(bot.registry.events_re['in']) > 0
bot.dispatch(':localhost 303 me :gawel')
result = yield from task
assert result['timeout'] is False
assert result['names'] == ['gawel']
3
Example 36
@pytest.mark.asyncio
@pytest.mark.parametrize('mode', ['w', 'r+', 'w+', 'a', 'a+'])
def test_simple_write(mode, tmpdir):
"""Test writing into a file."""
filename = 'bigfile.bin'
content = '0' * 4 * io.DEFAULT_BUFFER_SIZE
full_file = tmpdir.join(filename)
if 'r' in mode:
full_file.ensure() # Read modes want it to already exist.
file = yield from aioopen(str(full_file), mode=mode)
bytes_written = yield from file.write(content)
yield from file.close()
assert bytes_written == len(content)
assert content == full_file.read()
3
Example 37
Project: panoramisk Source File: test_fast_agi.py
@pytest.mark.asyncio
def test_fast_agi_application(event_loop, unused_tcp_port):
fa_app = Application(loop=event_loop)
fa_app.add_route('call_waiting', call_waiting)
server = yield from asyncio.start_server(fa_app.handler, '127.0.0.1',
unused_tcp_port, loop=event_loop)
msg_back = yield from fake_asterisk_client(event_loop,
unused_tcp_port)
assert b'ANSWER\n' == msg_back
server.close()
yield from server.wait_closed()
yield from asyncio.sleep(1) # Wait the end of endpoint
3
Example 38
@pytest.mark.asyncio
def test_stat():
"""Test the stat call."""
filename = join(dirname(__file__), 'resources', 'test_file1.txt')
stat_res = yield from aiofiles.os.stat(filename)
assert stat_res.st_size == 10
3
Example 39
@pytest.mark.asyncio
def test_login_failed(manager):
manager = manager(username='xx', secret='xx', stream='login_failed.yaml')
authenticated = yield from manager.authenticated_future
assert authenticated.success is False
assert manager.login(manager.authenticated_future) is False
3
Example 40
Project: asyncpgsa Source File: conftest.py
def pytest_pycollect_makeitem(collector, name, obj):
"""
Fix pytest collecting for coroutines.
"""
if collector.funcnamefilter(name) and asyncio.iscoroutinefunction(obj):
obj = pytest.mark.asyncio(obj)
return list(collector._genfunctions(name, obj))
3
Example 41
@pytest.mark.asyncio
def test_decorator(self, fo, patch_timer):
"""
time works with asyncio results functions.
"""
@aio.time(fo)
@asyncio.coroutine
def func():
yield from asyncio.sleep(0)
return 42
rv = func()
assert asyncio.iscoroutine(rv)
assert [] == fo._observed
rv = yield from rv
assert [1] == fo._observed
assert 42 == rv
3
Example 42
Project: Growler Source File: test_event_emitter.py
@pytest.mark.asyncio
def test_events_on():
e = Events('foo')
m = mock.MagicMock()
e.on('foo', m)
yield from e.emit('foo')
assert m.called
3
Example 43
Project: prometheus_async Source File: test_aio.py
@pytest.mark.asyncio
def test_future(self, fo, patch_timer, event_loop):
"""
time works with a asyncio.Future.
"""
fut = asyncio.Future(loop=event_loop)
coro = aio.time(fo, fut)
assert [] == fo._observed
fut.set_result(42)
assert 42 == (yield from coro)
assert [1] == fo._observed
3
Example 44
Project: elasticsearch-py-async Source File: test_client.py
@mark.asyncio
def test_info_works(server, client):
data = yield from client.info()
assert [('GET', '/', '', {})] == server.calls
assert {'body': '', 'method': 'GET', 'params': {}, 'path': '/'} == data
3
Example 45
@pytest.mark.asyncio
@pytest.mark.parametrize('mode', ['rb', 'rb+', 'ab+'])
@pytest.mark.parametrize('buffering', [-1, 0])
def test_simple_seek(mode, buffering, tmpdir):
"""Test seeking and then reading."""
filename = 'bigfile.bin'
content = b'0123456789' * 4 * io.DEFAULT_BUFFER_SIZE
full_file = tmpdir.join(filename)
full_file.write_binary(content)
file = yield from aioopen(str(full_file), mode=mode,
buffering=buffering)
yield from file.seek(4)
assert b'4' == (yield from file.read(1))
yield from file.close()
3
Example 46
Project: Growler Source File: test_event_emitter.py
@pytest.mark.asyncio
def test_events_on_decorator():
e = Events('foo')
m = mock.MagicMock()
@e.on("foo")
def doit():
m()
yield from e.emit("foo")
assert m.called
3
Example 47
Project: Growler Source File: test_event_emitter.py
@pytest.mark.asyncio
def test_events_on_async():
e = Events('foo')
m = mock.MagicMock()
@asyncio.coroutine
def foo():
m()
e.on('foo', foo())
yield from e.emit('foo')
assert m.called
3
Example 48
Project: with Source File: test_prompt.py
@pytest.mark.asyncio
def it_calls_an_async_prompt(self):
with mock.patch('withtool.prompt.prompt_async') as mock_prompt_async:
yield from prompt.get_prompt('cmd')
assert mock_prompt_async.called
3
Example 49
@pytest.mark.asyncio
def test_simple_readall(tmpdir):
"""Test the readall function by reading a large file in.
Only RawIOBase supports readall().
"""
filename = 'bigfile.bin'
content = b'0' * 4 * io.DEFAULT_BUFFER_SIZE # Hopefully several reads.
sync_file = tmpdir.join(filename)
sync_file.write_binary(content)
file = yield from aioopen(str(sync_file), mode='rb', buffering=0)
actual = yield from file.readall()
assert actual == content
yield from file.close()
3
Example 50
Project: elasticsearch-py-async Source File: test_transport.py
@mark.asyncio
def test_sniff_on_start_sniffs(server, event_loop, port, sniff_data):
server.register_response('/_nodes/_all/clear', sniff_data)
client = AsyncElasticsearch(port=port, sniff_on_start=True, loop=event_loop)
# sniff has been called in the background
assert client.transport.sniffing_task is not None
yield from client.transport.sniffing_task
assert [('GET', '/_nodes/_all/clear', '', {})] == server.calls
connections = client.transport.connection_pool.connections
assert 1 == len(connections)
assert 'http://node1:9200' == connections[0].host