Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
service_finished = trio.Event()
@as_service
async def RunTaskService(manager):
async def task_fn():
# this will never complete
await task_event.wait()
manager.run_task(task_fn)
# the task is set to run in the background but then the service exits.
# We want to be sure that the task is allowed to continue till
# completion unless explicitely cancelled.
service_finished.set()
async with background_service(RunTaskService()) as manager:
with trio.fail_after(0.01):
await service_finished.wait()
# show that the service hangs waiting for the task to complete.
with trio.move_on_after(0.01) as cancel_scope:
await manager.wait_stopped()
assert cancel_scope.cancelled_caught is True
# trigger cancellation and see that the service actually stops
manager.cancel()
with trio.fail_after(0.01):
await manager.wait_stopped()
# send invalid packet
await datagram_send_channel.send(IncomingDatagram(
datagram=b"not a valid packet",
sender_endpoint=EndpointFactory(),
))
# send valid packet
packet = AuthTagPacketFactory()
sender_endpoint = EndpointFactory()
await datagram_send_channel.send(IncomingDatagram(
datagram=packet.to_wire_bytes(),
sender_endpoint=sender_endpoint,
))
# ignore the invalid one, only receive the valid one
with trio.fail_after(0.5):
incoming_packet = await packet_receive_channel.receive()
assert incoming_packet.packet == packet
assert incoming_packet.sender_endpoint.ip_address == sender_endpoint.ip_address
assert incoming_packet.sender_endpoint.port == sender_endpoint.port
assert item1.completed_at == "2019-01-01T01:01:01+00:00"
assert item1.cost == 1.0
assert item1.duration == 1.0
assert item1.status_code == 200
assert item1.headers[0].key == "Server"
assert item1.headers[0].value == "FakeServer 1.0"
assert item1.headers[1].key == "X-Foo"
assert item1.headers[1].value == "Bar"
assert item1.is_success
assert item1.is_compressed
assert gzip.decompress(item1.body) == b"Test document #1"
# The subscription should time out because there are no items to send:
logger.info("Time out on next event…")
with pytest.raises(trio.TooSlowError):
with trio.fail_after(1) as cancel_scope:
data = await websocket.get_message()
# Now add second result and mark the crawl as completed:
logger.info("Add second result…")
async with db_pool.connection() as conn:
await r.table("response_body").insert(
{
"id": b"\x02" * 32,
"is_compressed": True,
"body": b"\x1f\x8b\x08\x00\xe7\x01J\\\x02\xff\x0bI-.QH\xc9O.\xcdM"
b"\xcd+QP6\x02\x00R\xda\x93\n\x10\x00\x00\x00",
}
).run(conn)
await r.table("response").insert(
{
"id": "bbbbbbbb-bbbb-bbbb-bbbb-000000000002",
assert job2.seeds[0] == 'https://job2.example'
assert job2.tags[0] == 'tag2a'
assert job2.item_count == 22
assert job2.http_success_count == 15
assert job2.http_error_count == 5
assert job2.exception_count == 2
assert job2.http_status_counts[200] == 15
assert job2.http_status_counts[404] == 5
assert job2.started_at == '2019-01-25T14:55:00+00:00'
assert job2.run_state == JobRunState.Value('RUNNING')
# Cancel the subscription and wait 2 seconds to make sure it doesn't send us
# any more events.
subscription.cancel()
with pytest.raises(trio.TooSlowError):
with trio.fail_after(2):
data = await websocket.get_message()
async def test_initial_keep_alive_timeout() -> None:
config = Config()
config.keep_alive_timeout = 0.01
client_stream, server_stream = trio.testing.memory_stream_pair()
server_stream.socket = MockSocket()
server = TCPServer(echo_framework, config, server_stream)
with trio.fail_after(2 * config.keep_alive_timeout):
await server.run()
# Only way to confirm closure is to invoke an error
with pytest.raises(trio.BrokenResourceError):
await client_stream.send_all(b"GET / HTTP/1.1\r\nHost: hypercorn\r\n")
async def wait_for_replicas_to_checkpoint(self, replica_ids, checkpoint_num):
"""
Wait for every replica in `replicas` to take a checkpoint.
Check every .5 seconds and give fail after 30 seconds.
"""
with trio.fail_after(30): # seconds
async with trio.open_nursery() as nursery:
for replica_id in replica_ids:
nursery.start_soon(self.wait_for_checkpoint, replica_id,
checkpoint_num)
def assert_max_elapsed(seconds):
'''
Fail the test if the execution of a block takes longer than ``seconds``.
'''
try:
with trio.fail_after(seconds):
yield
except trio.TooSlowError:
pytest.fail('Failed to complete within {} seconds'.format(seconds))
async def run(self) -> None:
try:
try:
with trio.fail_after(self.config.ssl_handshake_timeout):
await self.stream.do_handshake()
except (trio.BrokenResourceError, trio.TooSlowError):
return # Handshake failed
alpn_protocol = self.stream.selected_alpn_protocol()
socket = self.stream.transport_stream.socket
ssl = True
except AttributeError: # Not SSL
alpn_protocol = "http/1.1"
socket = self.stream.socket
ssl = False
try:
client = parse_socket_addr(socket.family, socket.getpeername())
server = parse_socket_addr(socket.family, socket.getsockname())
async with trio.open_nursery() as nursery:
# See https://github.com/caproto/caproto/issues/514.
self.udp_sock.bind(('', 0))
self.broadcaster.our_address = safe_getsockname(self.udp_sock)
command = self.broadcaster.register('127.0.0.1')
await self.send(ca.EPICS_CA2_PORT, command)
task_status.started()
while True:
async with self._cleanup_condition:
if self._cleanup_event.is_set():
self.udp_sock.close()
self.log.debug('Exiting broadcaster recv loop')
break
try:
with trio.fail_after(0.5):
bytes_received, address = await self.udp_sock.recvfrom(4096)
except trio.TooSlowError:
continue
if bytes_received:
if bytes_received is ca.DISCONNECTED:
break
commands = self.broadcaster.recv(bytes_received, address)
await self.command_chan.send.send(commands)
async def actually_send_batch(bq, table, template_suffix, batch, api_timeout=None):
if api_timeout is None:
api_timeout = 15
with trio.fail_after(api_timeout):
await bq.insert_all(table, batch, template_suffix)