Python fixtures.FakeLogger() Examples
The following are 30
code examples of fixtures.FakeLogger().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
fixtures
, or try the search function
.
Example #1
Source File: base.py From senlin with Apache License 2.0 | 6 votes |
def setup_logging(self): # Assign default logs to self.LOG so we can still # assert on senlin logs. default_level = logging.INFO if os.environ.get('OS_DEBUG') in _TRUE_VALUES: default_level = logging.DEBUG self.LOG = self.useFixture( fixtures.FakeLogger(level=default_level, format=_LOG_FORMAT)) base_list = set([nlog.split('.')[0] for nlog in logging.getLogger().logger.manager.loggerDict]) for base in base_list: if base in TEST_DEFAULT_LOGLEVELS: self.useFixture(fixtures.FakeLogger( level=TEST_DEFAULT_LOGLEVELS[base], name=base, format=_LOG_FORMAT)) elif base != 'senlin': self.useFixture(fixtures.FakeLogger( name=base, format=_LOG_FORMAT))
Example #2
Source File: test_hooks.py From maas with GNU Affero General Public License v3.0 | 6 votes |
def test_non_zero_exit_status(self): node = factory.make_Node() Interface.objects.filter(node_id=node.id).delete() nic = factory.make_Interface(node=node) node.boot_interface = None node.save() kernel_cmdline = KERNEL_CMDLINE_OUTPUT.format( mac_address=str(nic.mac_address).replace(":", "-") ) logger = self.useFixture(FakeLogger()) self.hook(node, kernel_cmdline.encode("utf-8"), 1) node = reload_object(node) self.assertIsNone(node.boot_interface) self.assertIn("kernel-cmdline failed with status: 1", logger.output)
Example #3
Source File: test_node_power_monitor_service.py From maas with GNU Affero General Public License v3.0 | 6 votes |
def test_try_query_nodes_logs_other_errors(self): service = self.make_monitor_service() self.patch(npms, "getRegionClient").return_value = sentinel.client sentinel.client.localIdent = factory.make_UUID() query_nodes = self.patch(service, "query_nodes") query_nodes.return_value = fail( ZeroDivisionError("Such a shame I can't divide by zero") ) with FakeLogger("maas") as maaslog, TwistedLoggerFixture(): d = service.try_query_nodes() self.assertEqual(None, extract_result(d)) self.assertDocTestMatches( "Failed to query nodes' power status: " "Such a shame I can't divide by zero", maaslog.output, )
Example #4
Source File: test_power.py From maas with GNU Affero General Public License v3.0 | 6 votes |
def test_query_all_nodes_swallows_PowerActionFail(self): node1, node2 = self.make_nodes(2) new_state_2 = self.pick_alternate_state(node2["power_state"]) get_power_state = self.patch(power, "get_power_state") error_msg = factory.make_name("error") get_power_state.side_effect = [ fail(exceptions.PowerActionFail(error_msg)), succeed(new_state_2), ] suppress_reporting(self) with FakeLogger("maas.power", level=logging.DEBUG) as maaslog: yield power.query_all_nodes([node1, node2]) self.assertDocTestMatches( """\ hostname-...: Could not query power state: %s. hostname-...: Power state has changed from ... to ... """ % error_msg, maaslog.output, )
Example #5
Source File: test_download_descriptions.py From maas with GNU Affero General Public License v3.0 | 6 votes |
def test_sync_does_propagate_ioerror(self): io_error = factory.make_exception_type(bases=(IOError,)) mock_sync = self.patch(download_descriptions.BasicMirrorWriter, "sync") mock_sync.side_effect = io_error() boot_images_dict = BootImageMapping() dumper = RepoDumper(boot_images_dict) with FakeLogger("maas.import-images", level=logging.INFO) as maaslog: self.assertRaises( io_error, dumper.sync, sentinel.reader, sentinel.path ) self.assertDocTestMatches( "...error...syncing boot images...", maaslog.output )
Example #6
Source File: test_service_monitor.py From maas with GNU Affero General Public License v3.0 | 6 votes |
def test_ensureService_logs_warning_in_mismatch_process_state(self): service = make_fake_service(SERVICE_STATE.ON) service_monitor = self.make_service_monitor([service]) invalid_process_state = factory.make_name("invalid_state") mock_getServiceState = self.patch(service_monitor, "getServiceState") mock_getServiceState.return_value = succeed( ServiceState(SERVICE_STATE.ON, invalid_process_state) ) with FakeLogger( "maas.service_monitor", level=logging.WARNING ) as maaslog: yield service_monitor._ensureService(service) self.assertDocTestMatches( "Service '%s' is %s but not in the expected state of " "'%s', its current state is '%s'." % ( service.service_name, SERVICE_STATE.ON.value, service_monitor.PROCESS_STATE[SERVICE_STATE.ON], invalid_process_state, ), maaslog.output, )
Example #7
Source File: test_node_power_monitor_service.py From maas with GNU Affero General Public License v3.0 | 6 votes |
def test_query_nodes_copes_with_NoSuchCluster(self): service = self.make_monitor_service() rpc_fixture = self.useFixture(MockClusterToRegionRPCFixture()) proto_region, io = rpc_fixture.makeEventLoop( region.ListNodePowerParameters ) client = getRegionClient() proto_region.ListNodePowerParameters.return_value = fail( exceptions.NoSuchCluster.from_uuid(client.localIdent) ) d = service.query_nodes(client) d.addErrback(service.query_nodes_failed, client.localIdent) with FakeLogger("maas") as maaslog: io.flush() self.assertEqual(None, extract_result(d)) self.assertDocTestMatches( "Rack controller '...' is not recognised.", maaslog.output )
Example #8
Source File: test_config.py From maas with GNU Affero General Public License v3.0 | 6 votes |
def test_logs_resolution_failures(self): # Some ISPs configure their DNS to resolve to an ads page when a domain # doesn't exist. This ensures resolving fails so the test passes. exception = socket.gaierror() exception.errno = random.choice( list(config._gen_addresses_where_possible_suppress) ) exception.strerror = "[Errno ...] ..." self.patch(config, "_gen_addresses").side_effect = exception with FakeLogger(config.__name__) as logger: config._get_addresses("no-way-this-exists.maas.io") self.assertThat( logger.output.strip(), DocTestMatches( "Could not resolve no-way-this-exists.maas.io: [Errno ...] ..." ), )
Example #9
Source File: test_vpn_gateway.py From ec2-api with Apache License 2.0 | 6 votes |
def test_safe_delete_vpnservice(self): vpn_gateway_api._safe_delete_vpnservice( self.neutron, fakes.ID_OS_VPNSERVICE_1, fakes.ID_EC2_SUBNET_1) self.neutron.delete_vpnservice.assert_called_once_with( fakes.ID_OS_VPNSERVICE_1) self.neutron.delete_vpnservice.side_effect = ( neutron_exception.NotFound()) with fixtures.FakeLogger() as log: vpn_gateway_api._safe_delete_vpnservice( self.neutron, fakes.ID_OS_VPNSERVICE_1, fakes.ID_EC2_SUBNET_1) self.assertEqual(0, len(log.output)) self.neutron.delete_vpnservice.side_effect = ( neutron_exception.Conflict()) with fixtures.FakeLogger() as log: vpn_gateway_api._safe_delete_vpnservice( self.neutron, fakes.ID_OS_VPNSERVICE_1, fakes.ID_EC2_SUBNET_1) self.assertIn(fakes.ID_EC2_SUBNET_1, log.output) self.assertIn(fakes.ID_OS_VPNSERVICE_1, log.output)
Example #10
Source File: test_dhcp.py From maas with GNU Affero General Public License v3.0 | 6 votes |
def test_does_log_other_exceptions_when_restarting(self): self.patch_sudo_write_file() self.patch_restartService().side_effect = factory.make_exception( "DHCP is on strike today" ) failover_peers = [make_failover_peer_config()] shared_networks = fix_shared_networks_failover( [make_shared_network()], failover_peers ) with FakeLogger("maas") as logger: with ExpectedException(exceptions.CannotConfigureDHCP): yield self.configure( factory.make_name("key"), failover_peers, shared_networks, [make_host()], [make_interface()], make_global_dhcp_snippets(), ) self.assertDocTestMatches( "DHCPv... server failed to restart: " "DHCP is on strike today", logger.output, )
Example #11
Source File: test_rackcontrollers.py From maas with GNU Affero General Public License v3.0 | 6 votes |
def test_logs_warning_for_external_dhcp_on_interface_no_vlan(self): rack_controller = factory.make_RackController(interface=False) interface = factory.make_Interface( INTERFACE_TYPE.PHYSICAL, node=rack_controller ) dhcp_ip = factory.make_ip_address() interface.vlan = None interface.save() logger = self.useFixture(FakeLogger()) update_foreign_dhcp(rack_controller.system_id, interface.name, dhcp_ip) self.assertThat( logger.output, DocTestMatches( "...DHCP server on an interface with no VLAN defined..." ), )
Example #12
Source File: test_power.py From maas with GNU Affero General Public License v3.0 | 6 votes |
def test_query_all_nodes_swallows_NoSuchNode(self): node1, node2 = self.make_nodes(2) new_state_2 = self.pick_alternate_state(node2["power_state"]) get_power_state = self.patch(power, "get_power_state") get_power_state.side_effect = [ fail(exceptions.NoSuchNode()), succeed(new_state_2), ] suppress_reporting(self) with FakeLogger("maas.power", level=logging.DEBUG) as maaslog: yield power.query_all_nodes([node1, node2]) self.assertDocTestMatches( """\ hostname-...: Power state has changed from ... to ... """, maaslog.output, )
Example #13
Source File: base.py From DLRN with Apache License 2.0 | 6 votes |
def setUp(self): "Run before each test method to initialize test environment." super(TestCase, self).setUp() test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0) try: test_timeout = int(test_timeout) except ValueError: # If timeout value is invalid do not set a timeout. test_timeout = 0 if test_timeout > 0: self.useFixture(fixtures.Timeout(test_timeout, gentle=True)) self.useFixture(fixtures.NestedTempfile()) self.useFixture(fixtures.TempHomeDir()) if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES: stdout = self.useFixture(fixtures.StringStream('stdout')).stream self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES: stderr = self.useFixture(fixtures.StringStream('stderr')).stream self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) self.log_fixture = self.useFixture(fixtures.FakeLogger())
Example #14
Source File: base.py From python-tripleoclient with Apache License 2.0 | 6 votes |
def setUp(self): """Run before each test method to initialize test environment.""" super(TestCase, self).setUp() test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0) try: test_timeout = int(test_timeout) except ValueError: # If timeout value is invalid do not set a timeout. test_timeout = 0 if test_timeout > 0: self.useFixture(fixtures.Timeout(test_timeout, gentle=True)) self.useFixture(fixtures.NestedTempfile()) self.temp_homedir = self.useFixture(fixtures.TempHomeDir()).path if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES: stdout = self.useFixture(fixtures.StringStream('stdout')).stream self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES: stderr = self.useFixture(fixtures.StringStream('stderr')).stream self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) self.log_fixture = self.useFixture(fixtures.FakeLogger())
Example #15
Source File: base.py From tosca-parser with Apache License 2.0 | 6 votes |
def setUp(self): """Run before each test method to initialize test environment.""" super(TestCase, self).setUp() test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0) try: test_timeout = int(test_timeout) except ValueError: # If timeout value is invalid do not set a timeout. test_timeout = 0 if test_timeout > 0: self.useFixture(fixtures.Timeout(test_timeout, gentle=True)) self.useFixture(fixtures.NestedTempfile()) self.useFixture(fixtures.TempHomeDir()) if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES: stdout = self.useFixture(fixtures.StringStream('stdout')).stream self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES: stderr = self.useFixture(fixtures.StringStream('stderr')).stream self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) self.log_fixture = self.useFixture(fixtures.FakeLogger())
Example #16
Source File: test_catch_errors.py From oslo.middleware with Apache License 2.0 | 6 votes |
def test_filter_tokens_from_log(self): logger = self.useFixture(fixtures.FakeLogger(nuke_handlers=False)) @webob.dec.wsgify def application(req): raise Exception() app = catch_errors.CatchErrors(application) req = webob.Request.blank('/test', text=u'test data', method='POST', headers={'X-Auth-Token': 'secret1', 'X-Service-Token': 'secret2', 'X-Other-Token': 'secret3'}) res = req.get_response(app) self.assertEqual(500, res.status_int) output = logger.output self.assertIn('X-Auth-Token: *****', output) self.assertIn('X-Service-Token: *****', output) self.assertIn('X-Other-Token: *****', output) self.assertIn('test data', output)
Example #17
Source File: base.py From heat-translator with Apache License 2.0 | 6 votes |
def setUp(self): """Run before each test method to initialize test environment.""" super(TestCase, self).setUp() test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0) try: test_timeout = int(test_timeout) except ValueError: # If timeout value is invalid do not set a timeout. test_timeout = 0 if test_timeout > 0: self.useFixture(fixtures.Timeout(test_timeout, gentle=True)) self.useFixture(fixtures.NestedTempfile()) self.useFixture(fixtures.TempHomeDir()) if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES: stdout = self.useFixture(fixtures.StringStream('stdout')).stream self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES: stderr = self.useFixture(fixtures.StringStream('stderr')).stream self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) self.log_fixture = self.useFixture(fixtures.FakeLogger())
Example #18
Source File: test_service_monitor.py From maas with GNU Affero General Public License v3.0 | 6 votes |
def test_ensureService_logs_mismatch_for_dead_process_state(self): service = make_fake_service(SERVICE_STATE.OFF) service_monitor = self.make_service_monitor([service]) invalid_process_state = factory.make_name("invalid") mock_getServiceState = self.patch(service_monitor, "getServiceState") mock_getServiceState.return_value = succeed( ServiceState(SERVICE_STATE.DEAD, invalid_process_state) ) with FakeLogger( "maas.service_monitor", level=logging.WARNING ) as maaslog: yield service_monitor._ensureService(service) self.assertDocTestMatches( "Service '%s' is %s but not in the expected state of " "'%s', its current state is '%s'." % ( service.service_name, SERVICE_STATE.DEAD.value, service_monitor.PROCESS_STATE[SERVICE_STATE.DEAD], invalid_process_state, ), maaslog.output, )
Example #19
Source File: test_scanner.py From reno with Apache License 2.0 | 6 votes |
def setUp(self): super(Base, self).setUp() self.fake_logger = self.useFixture( fixtures.FakeLogger( format='%(levelname)8s %(name)s %(message)s', level=logging.DEBUG, nuke_handlers=True, ) ) # Older git does not have config --local, so create a temporary home # directory to permit using git config --global without stepping on # developer configuration. self.useFixture(fixtures.TempHomeDir()) self.useFixture(fixtures.NestedTempfile()) self.temp_dir = self.useFixture(fixtures.TempDir()).path self.reporoot = os.path.join(self.temp_dir, 'reporoot') self.repo = self.useFixture(GitRepoFixture(self.reporoot)) self.c = config.Config(self.reporoot) self._counter = itertools.count(1) self.get_note_num = lambda: next(self._counter)
Example #20
Source File: base.py From oslo.vmware with Apache License 2.0 | 6 votes |
def setUp(self): """Run before each test method to initialize test environment.""" super(TestCase, self).setUp() test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0) try: test_timeout = int(test_timeout) except ValueError: # If timeout value is invalid do not set a timeout. test_timeout = 0 if test_timeout > 0: self.useFixture(fixtures.Timeout(test_timeout, gentle=True)) self.useFixture(fixtures.NestedTempfile()) self.useFixture(fixtures.TempHomeDir()) if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES: stdout = self.useFixture(fixtures.StringStream('stdout')).stream self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES: stderr = self.useFixture(fixtures.StringStream('stderr')).stream self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) self.log_fixture = self.useFixture(fixtures.FakeLogger())
Example #21
Source File: test_enginefacade.py From oslo.db with Apache License 2.0 | 6 votes |
def test_save_and_reraise_when_rollback_exception(self, rollback_patch, commit_patch): context = oslo_context.RequestContext() log = self.useFixture(fixtures.FakeLogger()) class RollbackException(Exception): pass class CommitException(Exception): pass commit_patch.side_effect = CommitException() rollback_patch.side_effect = RollbackException() @enginefacade.writer def go_session(context): context.session.add(self.User(name="u1")) self.assertRaises(RollbackException, go_session, context) self.assertIn('CommitException', log.output)
Example #22
Source File: test_utils.py From oslo.db with Apache License 2.0 | 6 votes |
def test_ensure_backend_available_no_connection_raises(self): log = self.useFixture(fixtures.FakeLogger()) err = OperationalError("Can't connect to database", None, None) with mock.patch.object( sqlalchemy.engine.base.Engine, 'connect') as mock_connect: mock_connect.side_effect = err exc = self.assertRaises( exception.BackendNotAvailable, provision.Backend._ensure_backend_available, self.connect_string) self.assertEqual( "Backend 'postgresql' is unavailable: " "Could not connect", str(exc)) self.assertEqual( "The postgresql backend is unavailable: %s" % err, log.output.strip())
Example #23
Source File: test_utils.py From oslo.db with Apache License 2.0 | 6 votes |
def test_ensure_backend_available_no_dbapi_raises(self): log = self.useFixture(fixtures.FakeLogger()) with mock.patch.object(sqlalchemy, 'create_engine') as mock_create: mock_create.side_effect = ImportError( "Can't import DBAPI module foobar") exc = self.assertRaises( exception.BackendNotAvailable, provision.Backend._ensure_backend_available, self.connect_string) mock_create.assert_called_once_with( sa_url.make_url(self.connect_string)) self.assertEqual( "Backend 'postgresql' is unavailable: " "No DBAPI installed", str(exc)) self.assertEqual( "The postgresql backend is unavailable: Can't import " "DBAPI module foobar", log.output.strip())
Example #24
Source File: base.py From oslo.db with Apache License 2.0 | 6 votes |
def setUp(self): """Run before each test method to initialize test environment.""" super(TestCase, self).setUp() test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0) try: test_timeout = int(test_timeout) except ValueError: # If timeout value is invalid do not set a timeout. test_timeout = 0 if test_timeout > 0: self.useFixture(fixtures.Timeout(test_timeout, gentle=True)) self.useFixture(fixtures.NestedTempfile()) self.useFixture(fixtures.TempHomeDir()) if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES: stdout = self.useFixture(fixtures.StringStream('stdout')).stream self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES: stderr = self.useFixture(fixtures.StringStream('stderr')).stream self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) self.log_fixture = self.useFixture(fixtures.FakeLogger())
Example #25
Source File: test_processutils.py From oslo.concurrency with Apache License 2.0 | 6 votes |
def _test_and_check_logging_communicate_errors(self, log_errors=None, attempts=None): mock = self.useFixture(fixtures.MockPatch( 'subprocess.Popen.communicate', side_effect=OSError(errno.EAGAIN, 'fake-test'))) fixture = self.useFixture(fixtures.FakeLogger(level=logging.DEBUG)) kwargs = {} if log_errors: kwargs.update({"log_errors": log_errors}) if attempts: kwargs.update({"attempts": attempts}) self.assertRaises(OSError, processutils.execute, '/usr/bin/env', 'false', **kwargs) self.assertEqual(attempts if attempts else 1, mock.mock.call_count) self.assertIn('Got an OSError', fixture.output) self.assertIn('errno: %d' % errno.EAGAIN, fixture.output) self.assertIn("'/usr/bin/env false'", fixture.output)
Example #26
Source File: test_processutils.py From oslo.concurrency with Apache License 2.0 | 6 votes |
def _test_and_check(self, log_errors=None, attempts=None): fixture = self.useFixture(fixtures.FakeLogger(level=logging.DEBUG)) kwargs = {} if log_errors: kwargs.update({"log_errors": log_errors}) if attempts: kwargs.update({"attempts": attempts}) err = self.assertRaises(processutils.ProcessExecutionError, processutils.execute, self.tmpfilename, **kwargs) self.assertEqual(41, err.exit_code) self.assertIn(self.tmpfilename, fixture.output)
Example #27
Source File: base.py From bashate with Apache License 2.0 | 6 votes |
def setUp(self): """Run before each test method to initialize test environment.""" super(TestCase, self).setUp() test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0) try: test_timeout = int(test_timeout) except ValueError: # If timeout value is invalid do not set a timeout. test_timeout = 0 if test_timeout > 0: self.useFixture(fixtures.Timeout(test_timeout, gentle=True)) self.useFixture(fixtures.NestedTempfile()) self.useFixture(fixtures.TempHomeDir()) if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES: stdout = self.useFixture(fixtures.StringStream('stdout')).stream self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES: stderr = self.useFixture(fixtures.StringStream('stderr')).stream self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) self.log_fixture = self.useFixture(fixtures.FakeLogger())
Example #28
Source File: test_dhcp.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def test_does_log_other_exceptions(self): self.patch_sudo_write_file() self.patch_sudo_delete_file() self.patch_ensureService().side_effect = factory.make_exception( "DHCP is on strike today" ) with FakeLogger("maas") as logger: with ExpectedException(exceptions.CannotConfigureDHCP): yield self.configure( factory.make_name("key"), [], [], [], [], [] ) self.assertDocTestMatches( "DHCPv... server failed to stop: DHCP is on strike today", logger.output, )
Example #29
Source File: test_xpath.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def setUp(self): super().setUp() self.logger = self.useFixture(FakeLogger())
Example #30
Source File: test_loader.py From reno with Apache License 2.0 | 5 votes |
def setUp(self): super(TestValidate, self).setUp() self.logger = self.useFixture( fixtures.FakeLogger( format='%(message)s', level=logging.WARNING, ) ) self.c = config.Config('reporoot')