def test_runner_secures_observer_against_additional_data_after_observer_is_done( observer_runner): """Done observer should not get data even before unsubscribe from moler-connection""" # correctly written observer looks like: # # def data_received(self, data): # if not self.done(): # parse(data) # # This test checks if runners secure wrong-written-observers with missing 'if not self.done():' from moler.connection import ObservableConnection with disabled_logging(): for n in range( 20 ): # need to test multiple times to ensure there are no thread races moler_conn = ObservableConnection() net_down_detector = NetworkDownDetector(connection=moler_conn, runner=observer_runner) net_down_detector.start_time = time.time( ) # must start observer lifetime before runner.submit() connection = net_down_detector.connection net_down_detector.start_time = time.time() observer_runner.submit(net_down_detector) connection.data_received("61 bytes") connection.data_received("ping: Network is unreachable") connection.data_received("62 bytes") assert net_down_detector.all_data_received == [ "61 bytes", "ping: Network is unreachable" ]
async def test_observer_gets_all_data_of_connection_after_it_is_submitted_to_background( observer_runner): # another words: after returning from runner.submit() no data can be lost, no races # Raw 'def' usage note: # This functionality works as well when runner is used inside raw def function # since it only uses runner.submit() + awaiting time # another words - runner is running over some time period # The only difference is that raw def function may use only standalone_runner (which is subset of observer_runner) # and inside test you exchange 'await asyncio.sleep()' with 'time.sleep()' from moler.connection import ObservableConnection with disabled_logging(): durations = [] for n in range( 20 ): # need to test multiple times to ensure there are no thread races moler_conn = ObservableConnection() net_down_detector = NetworkDownDetector(connection=moler_conn, runner=observer_runner) connection = net_down_detector.connection start_time = net_down_detector.start_time = time.time() observer_runner.submit(net_down_detector) durations.append(time.time() - start_time) connection.data_received("61 bytes") connection.data_received("62 bytes") connection.data_received("ping: Network is unreachable") assert net_down_detector.all_data_received == [ "61 bytes", "62 bytes", "ping: Network is unreachable" ] print("\n{}.submit() duration == {}".format( observer_runner.__class__.__name__, float(sum(durations)) / len(durations)))