def test_with_contextmanager(): mock = Mock() @contextmanager def something(): mock.enter() try: yield mock finally: mock.exit() with something() as x: x.work() assert mock.method_calls == [ call.enter(), call.work(), call.exit() ] mock.reset_mock() with pytest.raises(Exception): with something() as x: x.work() raise Exception('omg') assert mock.method_calls == [ call.enter(), call.work(), call.exit() ]
async def test__main_loop__handle_exception_throws(self): algorithm = Mock(spec=AlgorithmBaseSync) error = ValueError('a') algorithm.next_iteration.side_effect = [0, error, 0, 0] algorithm.handle_exception.side_effect = AttributeError('side') use_algorithm = self.algo(algorithm) with self.assertLogs('btrccts') as cm: with self.assertRaises(AttributeError) as e: await main_loop(timeframe=self.timeframe, algorithm=use_algorithm) self.assertEqual(str(e.exception), 'side') self.assertEqual(algorithm.mock_calls, [ call.next_iteration(), call.next_iteration(), call.handle_exception(error), call.exit(reason=ExitReason.EXCEPTION) ]) self.assertEqual(len(cm.output), 5) self.assertEqual(cm.output[0:2], [ 'INFO:btrccts:Starting main_loop', 'ERROR:btrccts:Error occured during next_iteration' ]) self.assertTrue(cm.output[2].startswith( 'ERROR:btrccts:a\nTraceback (most recent call last):\n File')) self.assertEqual( cm.output[3], 'ERROR:btrccts:Exiting because of ' 'exception in handle_exception') self.assertTrue(cm.output[4].startswith( 'ERROR:btrccts:side\nTraceback (most recent call last):\n File'))
async def test__main_loop__successful(self): algorithm = Mock(spec=AlgorithmBaseSync) error = ValueError('a') algorithm.next_iteration.side_effect = [0, 0, error, 0] use_algorithm = self.algo(algorithm) with self.assertLogs('btrccts') as cm: result = await main_loop(timeframe=self.timeframe, algorithm=use_algorithm) self.assertEqual(result, use_algorithm) self.assertEqual(algorithm.mock_calls, [ call.next_iteration(), call.next_iteration(), call.next_iteration(), call.handle_exception(error), call.next_iteration(), call.exit(reason=ExitReason.FINISHED) ]) self.assertEqual(len(cm.output), 4) self.assertEqual(cm.output[0:2], [ 'INFO:btrccts:Starting main_loop', 'ERROR:btrccts:Error occured during next_iteration' ]) self.assertTrue(cm.output[2].startswith( 'ERROR:btrccts:a\nTraceback (most recent call last):\n File')) self.assertEqual(cm.output[3], 'INFO:btrccts:Finished main_loop')
def test_go_right_track(self): ornate, squalid = _OrnateRoom(), _SqualidRoom() ornate.add_character(G.player) self.assertIs(ornate, G.player.current_room) # Precondition direction = directions.purple description = direction.display_description ornate.add_exit(direction, squalid) next_room, _ = ornate.exit(description) self.assertIs(squalid, next_room) # Precondition with patch("sys.stdin", new_callable=io.StringIO) as fake_stdin, patch( "whimsylib.say.insayne", self._parent.say), patch( "whimsylib.room.Room.on_exit", self._parent.exit), patch( "whimsylib.globals.G.player.psyche.heal_or_harm", self._parent.heal): self._run_commands(fake_stdin, f"go {description}") # This implies that squalid.on_enter() was called. self.assertIs(squalid, G.player.current_room) self._parent.assert_has_calls([ call.pre.execute(), call.say(f"You proceed {description}."), call.exit(), call.heal(1, do_log=False), call.say(squalid.description), call.say( f"Exits are {direction.opposite.display_description}."), call.post.execute(), ])
def test_run_uses_tmpdir_lock(self, mock_volume_builder, mock_client): mock_make_tmpdir = Mock() mock_enter = Mock() mock_exit = Mock() job = self.make_job() job.make_tmpdir = mock_make_tmpdir job.populate_env_vars = Mock() job._setup = Mock() job.create_kubernetes_runtime = Mock() job.execute_kubernetes_pod = Mock() job.wait_for_kubernetes_pod = Mock() job.finish = Mock() mock_tmpdir_lock = Mock(__enter__=mock_enter, __exit__=mock_exit) manager = Mock() manager.attach_mock(mock_enter, 'enter') manager.attach_mock(mock_exit, 'exit') manager.attach_mock(mock_make_tmpdir, 'make_tmpdir') job.run(self.runtime_context, mock_tmpdir_lock) expected_calls = [ call.enter(), call.make_tmpdir(), call.exit(None, None, None) ] self.assertEqual(expected_calls, manager.mock_calls)
def test_atomiccmd__cleanup_sigterm__dead_weakrefs(): dead_ref = weakref.ref(AtomicCmd("ls")) with patch("paleomix.atomiccmd.command._PROCS", [dead_ref]): patches = Mock() with patch("os.killpg", patches.killpg): with patch("sys.exit", patches.exit): paleomix.atomiccmd.command._cleanup_children( signal.SIGTERM, None) assert patches.mock_calls == [call.exit(-signal.SIGTERM)]
def template__main_loop__exit_exception(self, exception_class, log_str): algorithm = Mock(spec=AlgorithmBase) algorithm.next_iteration.side_effect = [0, exception_class('aa'), 0, 0] with self.assertLogs('btrccts') as cm: result = main_loop(timeframe=self.timeframe, algorithm=algorithm) self.assertEqual(algorithm.mock_calls, [ call.next_iteration(), call.next_iteration(), call.exit(reason=ExitReason.STOPPED) ]) self.assertEqual(cm.output, ['INFO:btrccts:Starting main_loop', log_str]) self.assertEqual(algorithm, result)
def test_atomiccmd__cleanup_sigterm(): procs = [lambda: Mock(pid=7913), lambda: Mock(pid=12345)] with patch("paleomix.atomiccmd.command._PROCS", procs): patches = Mock() with patch("os.killpg", patches.killpg): with patch("sys.exit", patches.exit): paleomix.atomiccmd.command._cleanup_children( signal.SIGTERM, None) assert patches.mock_calls == [ call.killpg(7913, signal.SIGTERM), call.killpg(12345, signal.SIGTERM), call.exit(-signal.SIGTERM), ]
def test_atomiccmd__cleanup_sigterm__continues_on_exception(): procs = [lambda: Mock(pid=7913), lambda: Mock(pid=12345)] with patch("paleomix.atomiccmd.command._PROCS", procs): patches = Mock() with patch("os.killpg", patches.killpg): with patch("sys.exit", patches.exit): patches.killpg.side_effect = [OSError("already killed"), None] paleomix.atomiccmd.command._cleanup_children( signal.SIGTERM, None) assert patches.mock_calls == [ call.killpg(7913, signal.SIGTERM), call.killpg(12345, signal.SIGTERM), call.exit(-signal.SIGTERM), ]
def template__main_loop__exit_exception_during_sleep( self, exception_class, log_str, sleep_mock): algorithm = Mock(spec=AlgorithmBase) sleep_mock.side_effect = [exception_class('aa')] # We need to use future dates, because we are in live mode timeframe = Timeframe(pd_start_date=pd_ts('2217-01-01 1:00'), pd_end_date=pd_ts('2217-01-01 1:03'), pd_interval=pandas.Timedelta(minutes=1)) with self.assertLogs('btrccts') as cm: result = main_loop(timeframe=timeframe, algorithm=algorithm, live=True) self.assertEqual( algorithm.mock_calls, [call.next_iteration(), call.exit(reason=ExitReason.STOPPED)]) self.assertEqual(cm.output, ['INFO:btrccts:Starting main_loop', log_str]) self.assertEqual(algorithm, result)
def test_with(): mock = Mock() class Resource: def __enter__(self): mock.enter() return self def __exit__(self, exc_type, exc_val, exc_tb): mock.exit() def work(self): mock.do_something() with Resource() as r: r.work() assert mock.method_calls == [ call.enter(), call.do_something(), call.exit() ]
def test_finish(self): "finish should stop event loop" with patch("conjureup.controllers.summary.gui.EventLoop") as m_ev: self.controller.finish() m_ev.assert_has_calls([call.remove_alarms(), call.exit(0)])