def test_patch_time_exceed(self): ''' check package.patched when patch time exceed ''' print 'test_patch_time_exceed' old_log_len = len(waagent.GetFileContents(log_file)) def patch_package(self): time.sleep(11) return 0 MyPatching.patch_package = patch_package # 5 minutes reserved for reboot protect_settings['installDuration'] = '00:06' with self.assertRaises(SystemExit) as cm: download() self.assertEqual(cm.exception.code, 0) with self.assertRaises(SystemExit) as cm: patch() self.assertEqual(cm.exception.code, 0) patch_list = get_patch_list(MyPatching.package_patched_path) self.assertEqual(patch_list, ['a', 'b', 'c', 'd', 'e', '1']) log_contents = waagent.GetFileContents(log_file)[old_log_len:] self.assertTrue('Patching time exceeded' in log_contents)
def main(): if len(sys.argv) == 1: unittest.main() return waagent.LoggerInit('/var/log/waagent.log', '/dev/stdout') waagent.Log("%s started to handle." %(ExtensionShortName)) global hutil hutil = Util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName) hutil.do_parse_context('TEST') global MyPatching MyPatching = FakePatching(hutil) if MyPatching == None: sys.exit(1) for a in sys.argv[1:]: if re.match("^([-/]*)(disable)", a): disable() elif re.match("^([-/]*)(uninstall)", a): uninstall() elif re.match("^([-/]*)(install)", a): install() elif re.match("^([-/]*)(enable)", a): enable() elif re.match("^([-/]*)(update)", a): update() elif re.match("^([-/]*)(download)", a): download() elif re.match("^([-/]*)(patch)", a): patch() elif re.match("^([-/]*)(oneoff)", a): oneoff()
def main(): waagent.LoggerInit("/var/log/waagent.log", "/dev/stdout") waagent.Log("%s started to handle." % (ExtensionShortName)) global hutil hutil = Util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName) global MyPatching MyPatching = GetMyPatching(hutil) if MyPatching is None: sys.exit(1) for a in sys.argv[1:]: if re.match("^([-/]*)(disable)", a): disable() elif re.match("^([-/]*)(uninstall)", a): uninstall() elif re.match("^([-/]*)(install)", a): install() elif re.match("^([-/]*)(enable)", a): enable() elif re.match("^([-/]*)(update)", a): update() elif re.match("^([-/]*)(download)", a): download() elif re.match("^([-/]*)(patch)", a): patch() elif re.match("^([-/]*)(oneoff)", a): oneoff()
def test_patch_time_exceed(self): ''' check package.patched when patch time exceed ''' print 'test_patch_time_exceed' global settings settings = { "category" : "importantandrecommended", "installDuration" : "00:06" # 5 minutes reserved for reboot } old_log_len = len(waagent.GetFileContents(log_file)) def patch_package(self): time.sleep(11) return 0 MyPatching.patch_package = patch_package with self.assertRaises(SystemExit) as cm: download() self.assertEqual(cm.exception.code, 0) with self.assertRaises(SystemExit) as cm: patch() self.assertEqual(cm.exception.code, 0) patch_list = get_patch_list(MyPatching.package_patched_path) self.assertEqual(patch_list, ['a', 'b', 'c', 'd', 'e', '1']) log_contents = waagent.GetFileContents(log_file)[old_log_len:] self.assertTrue('Patching time exceeded' in log_contents)
def test_patch(self): ''' check file package.patched when patch successful ''' print 'test_patch' with self.assertRaises(SystemExit) as cm: download() self.assertEqual(cm.exception.code, 0) with self.assertRaises(SystemExit) as cm: patch() self.assertEqual(cm.exception.code, 0) download_content = waagent.GetFileContents(MyPatching.package_downloaded_path) patch_content = waagent.GetFileContents(MyPatching.package_patched_path) self.assertEqual(download_content, patch_content)
def test_patch_failed(self): ''' check file package.patched when patch fail ''' print 'test_patch_failed' def patch_package(self): return 1 MyPatching.patch_package = patch_package old_log_len = len(waagent.GetFileContents(log_file)) with self.assertRaises(SystemExit) as cm: download() self.assertEqual(cm.exception.code, 0) with self.assertRaises(SystemExit) as cm: patch() log_contents = waagent.GetFileContents(log_file)[old_log_len:] self.assertEqual(cm.exception.code, 0) patch_content = waagent.GetFileContents(MyPatching.package_patched_path) self.assertFalse(patch_content) self.assertTrue('Failed to patch the package' in log_contents)
def test_setgroups(self, hack): with patch('os.sysconf') as sysconf: sysconf.return_value = 100 setgroups(list(range(400))) hack.assert_called_with(list(range(100)))
def test_on_decode_error(self): message = Message('foo') with patch('kombu.mixins.error') as error: self.c.on_decode_error(message, KeyError('foo')) error.assert_called() message.ack.assert_called_with()
def test_select(self, __select): ebadf = socket.error() ebadf.errno = errno.EBADF with patch('select.poll', create=True) as poller: poll = poller.return_value = Mock(name='poll.poll') poll.return_value = {3}, set(), 0 assert asynpool._select({3}, poll=poll) == ({3}, set(), 0) poll.return_value = {3}, set(), 0 assert asynpool._select({3}, None, {3}, poll=poll) == ( {3}, set(), 0, ) eintr = socket.error() eintr.errno = errno.EINTR poll.side_effect = eintr readers = {3} assert asynpool._select(readers, poll=poll) == (set(), set(), 1) assert 3 in readers with patch('select.poll', create=True) as poller: poll = poller.return_value = Mock(name='poll.poll') poll.side_effect = ebadf with patch('select.select') as selcheck: selcheck.side_effect = ebadf readers = {3} assert asynpool._select(readers, poll=poll) == ( set(), set(), 1, ) assert 3 not in readers with patch('select.poll', create=True) as poller: poll = poller.return_value = Mock(name='poll.poll') poll.side_effect = MemoryError() with pytest.raises(MemoryError): asynpool._select({1}, poll=poll) with patch('select.poll', create=True) as poller: poll = poller.return_value = Mock(name='poll.poll') with patch('select.select') as selcheck: def se(*args): selcheck.side_effect = MemoryError() raise ebadf poll.side_effect = se with pytest.raises(MemoryError): asynpool._select({3}, poll=poll) with patch('select.poll', create=True) as poller: poll = poller.return_value = Mock(name='poll.poll') with patch('select.select') as selcheck: def se2(*args): selcheck.side_effect = socket.error() selcheck.side_effect.errno = 1321 raise ebadf poll.side_effect = se2 with pytest.raises(socket.error): asynpool._select({3}, poll=poll) with patch('select.poll', create=True) as poller: poll = poller.return_value = Mock(name='poll.poll') poll.side_effect = socket.error() poll.side_effect.errno = 34134 with pytest.raises(socket.error): asynpool._select({3}, poll=poll)
def test_connect_getaddrinfo_raises_gaierror(self): with patch('socket.getaddrinfo', side_effect=socket.gaierror): with pytest.raises(socket.error): self.t.connect()
def test_when_logging_disabled(self): with patch('celery.worker.strategy.logger') as logger: logger.isEnabledFor.return_value = False with self._context(self.add.s(2, 2)) as C: C() logger.info.assert_not_called()
def test_send_task_message__with_receivers(self): from case import patch mocked_receiver = ((Mock(), Mock()), Mock()) with patch('celery.signals.task_sent.receivers', [mocked_receiver]): self.app.amqp.send_task_message(Mock(), 'foo', self.simple_message)
def test_setup_app_sets_chdir(self, app): with patch('os.chdir') as chdir: cmd = MockCommand(app=app) cmd.setup_app_from_commandline(['--workdir=/opt']) chdir.assert_called_with('/opt')
def test_move_by_taskmap(): with patch('celery.contrib.migrate.move') as move: move_by_taskmap({'add': Queue('foo')}) move.assert_called() cb = move.call_args[0][0] assert cb({'task': 'add'}, Mock())
def test_aaa_is_patched(self): with patch('eventlet.monkey_patch', create=True) as monkey_patch: from celery import maybe_patch_concurrency maybe_patch_concurrency(['x', '-P', 'eventlet']) monkey_patch.assert_called_with()
def test_maybe_close_fd(self): with patch('os.close'): _maybe_close_fd(Mock()) _maybe_close_fd(object())
def fixup_context(self, app): with patch('celery.fixups.django.DjangoWorkerFixup.validate_models'): with patch('celery.fixups.django.symbol_by_name') as symbyname: with patch('celery.fixups.django.import_module') as impmod: f = self.Fixup(app) yield f, impmod, symbyname
def test_valid_expires_with_utc_makes_aware(self): with patch('celery.worker.request.maybe_make_aware') as mma: self.get_request(self.add.s(2, 2).set(expires=10), maybe_make_aware=mma) mma.assert_called()
def test_move_task_by_id(): with patch('celery.contrib.migrate.move') as move: move_task_by_id('123f', Queue('foo')) move.assert_called() cb = move.call_args[0][0] assert cb({'id': '123f'}, Mock()) == Queue('foo')
def test_on_connection_error(self): with patch('kombu.mixins.warn') as warn: self.c.on_connection_error(KeyError('foo'), 3) warn.assert_called()
def fromfile(fdiff): return patch(fdiff)
# low-level APIs. loop = asyncio.get_event_loop() on_con_lost = loop.create_future() name, value = "@MAIN:PWR", "On" transport, protocol = await loop.create_connection( lambda: YNCAProtocol(name, value, on_con_lost, loop), 'CL-6EA47', 50000) # Wait until the protocol signals that the connection # is lost and close the transport. try: await on_con_lost finally: transport.close() def run(future): loop = asyncio.get_event_loop() result = loop.run_until_complete(future) print("result:", result) if __name__ == '__main__': patch() # asyncio.run(main2()) run(main())
def test_default_ensure_callback(self): with patch('kombu.connection.logger') as logger: c = Connection(transport=Mock) c._default_ensure_callback(KeyError(), 3) self.assertTrue(logger.error.called)
def test_setup_app_no_respect(self, app): cmd = MockCommand(app=app) cmd.respects_app_option = False with patch('celery.bin.base.Celery') as cp: cmd.setup_app_from_commandline(['--app=x.y:z']) cp.assert_called()
def test_connparams_health_check_interval_supported(self): with patch('kombu.transport.redis.Channel._create_client'): with Connection('redis+socket:///tmp/redis.sock') as conn: connparams = conn.default_channel._connparams() assert connparams['health_check_interval'] == 25
def test_get_timeout_longer(self): res = self.app.AsyncResult(self.task4['id']) # has RETRY state with patch('celery.result.time') as _time: with pytest.raises(TimeoutError): res.get(timeout=1, interval=1) _time.sleep.assert_called_with(1)
def test_calls_Queue_from_dict(self): with patch('kombu.common.Queue') as Queue: entry_to_queue('name', exchange='bar') Queue.from_dict.assert_called_with('name', exchange='bar')
def test_connect_socket_fails(self): with patch('socket.socket', side_effect=socket.error): with pytest.raises(socket.error): self.t.connect() assert self.t.sock is None and self.t.connected is False
def test_when_actual(self, getrlimit): with patch('os.sysconf') as sysconfig: sysconfig.side_effect = KeyError() getrlimit.return_value = [None, 13] assert get_fdmax(None) == 13
def test_gevent_bug_disables_connection_timeout(self): with patch('celery.worker.consumer.consumer._detect_environment') as d: d.return_value = 'gevent' self.app.conf.broker_connection_timeout = 33.33 self.get_consumer() assert self.app.conf.broker_connection_timeout is None
def test_prepare_client_options(self): with patch('pymongo.version_tuple', new=(3, 0, 3)): options = self.backend._prepare_client_options() assert options == { 'maxPoolSize': self.backend.max_pool_size }
def test_arm_alarm(self): if hasattr(signal, 'setitimer'): with patch('signal.setitimer', create=True) as seti: signals.arm_alarm(30) seti.assert_called()
def test_setgroups_sysconf_raises(self, hack): with patch('os.sysconf') as sysconf: sysconf.side_effect = ValueError() setgroups(list(range(400))) hack.assert_called_with(list(range(400)))
def test_task_not_shared(self): with patch('celery.app.base.connect_on_app_finalize') as sh: @self.app.task(shared=False) def foo(): pass sh.assert_not_called()
def test_when_infinity(self, getrlimit): with patch('os.sysconf') as sysconfig: sysconfig.side_effect = KeyError() getrlimit.return_value = [None, resource.RLIM_INFINITY] default = object() assert get_fdmax(default) is default
def test_send_worker_shutdown(self): with patch('celery.signals.worker_shutdown') as ws: self.worker._send_worker_shutdown() ws.send.assert_called_with(sender=self.worker)