Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_runner_doesnt_impact_unrised_observer_exception_while_taking_observer_result(connection_observer,
observer_runner):
from moler.runner import time_out_observer, result_for_runners
from moler.exceptions import ConnectionObserverTimeout
with observer_runner:
connection_observer.life_status.start_time = time.time() # must start observer lifetime before runner.submit()
observer_runner.submit(connection_observer)
time_out_observer(connection_observer, timeout=2.3, passed_time=2.32, runner_logger=mock.MagicMock())
timeout = connection_observer._exception
assert timeout in ConnectionObserver._not_raised_exceptions
try:
result_for_runners(connection_observer)
except ConnectionObserverTimeout as timeout:
assert timeout in ConnectionObserver._not_raised_exceptions
def test_runner_doesnt_impact_unrised_observer_exception_while_taking_observer_result(connection_observer,
observer_runner):
from moler.runner import time_out_observer, result_for_runners
from moler.exceptions import ConnectionObserverTimeout
with observer_runner:
connection_observer.life_status.start_time = time.time() # must start observer lifetime before runner.submit()
observer_runner.submit(connection_observer)
time_out_observer(connection_observer, timeout=2.3, passed_time=2.32, runner_logger=mock.MagicMock())
timeout = connection_observer._exception
assert timeout in ConnectionObserver._not_raised_exceptions
try:
result_for_runners(connection_observer)
except ConnectionObserverTimeout as timeout:
assert timeout in ConnectionObserver._not_raised_exceptions
finally:
stop_running.set()
# --------------------------- resources ---------------------------
@pytest.yield_fixture()
def observer_runner():
from moler.runner import ThreadPoolExecutorRunner
runner = ThreadPoolExecutorRunner()
yield runner
runner.shutdown()
class NetworkDownDetector(ConnectionObserver):
def __init__(self, connection=None, runner=None):
super(NetworkDownDetector, self).__init__(connection=connection, runner=runner)
self.all_data_received = []
def data_received(self, data, recv_time):
"""
Awaiting change like:
64 bytes from 10.0.2.15: icmp_req=3 ttl=64 time=0.045 ms
ping: sendmsg: Network is unreachable
"""
self.all_data_received.append(data)
if not self.done():
if "Network is unreachable" in data:
when_detected = time.time()
self.set_result(result=when_detected)
# give concurrency-of-future a chance to gain control # . |
time.sleep(0.1) # . |
assert future.running() # <- as future |
result = network_down_detector.await_done(timeout=2.0) # <- as future |
assert result == network_down_detector.result() # <- as future |
# ---------------------------------------------------------------------+
# TODO: tests of futures: cancel(), failing observer, timeouting observer
# TODO: tests for error cases
# --------------------------- resources ---------------------------
class NetworkDownDetector(ConnectionObserver):
def __init__(self, connection=None):
super(NetworkDownDetector, self).__init__(connection=connection)
def data_received(self, data, recv_time):
"""
Awaiting change like:
64 bytes from 10.0.2.15: icmp_req=3 ttl=64 time=0.045 ms
ping: sendmsg: Network is unreachable
"""
if not self.done():
if "Network is unreachable" in data:
when_detected = time.time()
self.set_result(result=when_detected)
@pytest.yield_fixture(params=['FIFO-in-memory'])
def failing_net_down_detector(fail_on_data, fail_by_raising, runner):
from moler.threaded_moler_connection import ThreadedMolerConnection
class FailingNetworkDownDetector(NetworkDownDetector):
def data_received(self, data, recv_time):
if data == fail_on_data:
raise fail_by_raising
return super(FailingNetworkDownDetector, self).data_received(data, recv_time)
moler_conn = ThreadedMolerConnection()
failing_detector = FailingNetworkDownDetector(connection=moler_conn, runner=runner)
yield failing_detector
# remove exceptions collected inside ConnectionObserver
ConnectionObserver.get_unraised_exceptions(remove=True)
con_logger = logging.getLogger('tcp-thrd-io.{}'.format(connection_name))
tcp_connection = get_connection(name=connection_name, logger=con_logger)
tcp_connection.moler_connection.name = connection_name
# client_task= asyncio.ensure_future(ping_observing_task(tcp_connection, ping_ip))
connections.append(ping_observing_task(tcp_connection, ping_ip))
# await observers job to be done
completed, pending = await asyncio.wait(connections)
# stop servers
for server in servers:
await server.wait_closed()
logger.debug('exiting main')
# ===================== Moler's connection-observer usage ======================
class NetworkToggleDetector(ConnectionObserver):
def __init__(self, net_ip, detect_pattern, detected_status,
connection=None, runner=None):
super(NetworkToggleDetector, self).__init__(connection=connection,
runner=runner)
self.net_ip = net_ip
self.detect_pattern = detect_pattern
self.detected_status = detected_status
self.logger = logging.getLogger('moler.{}'.format(self))
def data_received(self, data):
"""Awaiting ping output change"""
if not self.done():
if self.detect_pattern in data:
when_detected = time.time()
self.logger.debug("Network {} {}!".format(self.net_ip,
self.detected_status))
if old_exception:
observer._log(logging.DEBUG,
"{} has overwritten exception. From {!r} to {!r}".format(
observer,
old_exception,
new_exception,
))
if old_exception in ConnectionObserver._not_raised_exceptions:
ConnectionObserver._not_raised_exceptions.remove(old_exception)
else:
observer._log(logging.DEBUG,
"{}: cannot find exception {!r} in _not_raised_exceptions.".format(
observer,
old_exception,
))
ConnectionObserver._log_unraised_exceptions(observer)
ConnectionObserver._not_raised_exceptions.append(new_exception)
observer._exception = new_exception
__author__ = 'Grzegorz Latuszek, Marcin Usielski, Michal Ernst'
__copyright__ = 'Copyright (C) 2018-2019, Nokia'
__email__ = 'grzegorz.latuszek@nokia.com, marcin.usielski@nokia.com, michal.ernst@nokia.com'
from abc import ABCMeta
from six import add_metaclass
from moler.connection_observer import ConnectionObserver
from moler.exceptions import NoCommandStringProvided
from moler.helpers import instance_id
@add_metaclass(ABCMeta)
class Command(ConnectionObserver):
def __init__(self, connection=None, runner=None):
"""
Create instance of Command class
:param connection: connection used to start CMD and receive its output
"""
super(Command, self).__init__(connection=connection, runner=runner)
self.command_string = None
self.cmd_name = Command.observer_name
def __str__(self):
cmd_str = self.command_string if self.command_string else ''
if cmd_str[-1] == '\n':
cmd_str = cmd_str[:-1] + r'<\n>'
return '{}("{}", id:{})'.format(self.__class__.__name__, cmd_str, instance_id(self))
def _validate_start(self, *args, **kwargs):
def __init__(self, connection=None, runner=None):
"""
Create instance of ConnectionObserver class
:param connection: connection used to receive data awaited for
"""
super(ConnectionObserver, self).__init__()
self.life_status = ConnectionObserverLifeStatus()
self.connection = connection
self._result = None
self._exception = None
self.runner = runner if runner else get_runner()
self._future = None
self.device_logger = logging.getLogger('moler.{}'.format(self.get_logger_name()))
self.logger = logging.getLogger('moler.connection.{}'.format(self.get_logger_name()))
Example of connection observers catching
"network is down"/"network is up" events.
"""
__author__ = 'Grzegorz Latuszek'
__copyright__ = 'Copyright (C) 2018, Nokia'
__email__ = 'grzegorz.latuszek@nokia.com'
import logging
import time
from moler.connection_observer import ConnectionObserver
class NetworkToggleDetector(ConnectionObserver):
def __init__(self, net_ip, detect_pattern, detected_status,
connection=None, runner=None):
super(NetworkToggleDetector, self).__init__(connection=connection,
runner=runner)
self.net_ip = net_ip
self.detect_pattern = detect_pattern
self.detected_status = detected_status
self.logger = logging.getLogger('moler.{}'.format(self))
def data_received(self, data):
"""Awaiting ping output change"""
if not self.done():
if self.detect_pattern in data:
when_detected = time.time()
self.logger.debug("Network {} {}!".format(self.net_ip,
self.detected_status))