def test_no_primary_does_not_throw(self): with patch.object(osutil.DefaultOSUtil, 'get_primary_interface') \ as patch_primary: exception = False patch_primary.return_value = '' try: osutil.DefaultOSUtil().get_first_if()[0] except Exception as e: print(traceback.format_exc()) exception = True self.assertFalse(exception)
def test_no_routes(self): route_table = """Routing tables Internet: Destination Gateway Flags Netif Expire """ with patch.object(shellutil, 'run_command', return_value=route_table): raw_route_list = FreeBSDOSUtil().read_route_table() self.assertEqual(len(FreeBSDOSUtil().get_list_of_routes(raw_route_list)), 0)
def test_no_primary_does_not_throw(self): with patch.object(osutil.DefaultOSUtil, 'get_primary_interface') \ as patch_primary: exception = False patch_primary.return_value = '' try: osutil.DefaultOSUtil().get_first_if()[0] except Exception as e: # pylint: disable=unused-variable print(textutil.format_exception(e)) exception = True self.assertFalse(exception)
def test_validate_block_blob(self): with mock_wire_protocol(DATA_FILE) as protocol: test_goal_state = protocol.client._goal_state host_client = wire.HostPluginProtocol(wireserver_url, test_goal_state.container_id, test_goal_state.role_config_name) self.assertFalse(host_client.is_initialized) self.assertTrue(host_client.api_versions is None) self.assertTrue(host_client.health_service is not None) status_blob = protocol.client.status_blob status_blob.data = faux_status status_blob.type = block_blob_type status_blob.vm_status = restapi.VMStatus(message="Ready", status="Ready") exp_method = 'PUT' exp_url = hostplugin_status_url exp_data = self._hostplugin_data( status_blob.get_block_blob_headers(len(faux_status)), bytearray(faux_status, encoding='utf-8')) with patch.object(restutil, "http_request") as patch_http: patch_http.return_value = Mock(status=httpclient.OK) with patch.object(wire.HostPluginProtocol, "get_api_versions") as patch_get: patch_get.return_value = api_versions host_client.put_vm_status(status_blob, sas_url) self.assertTrue(patch_http.call_count == 2) # first call is to host plugin self._validate_hostplugin_args( patch_http.call_args_list[0], test_goal_state, exp_method, exp_url, exp_data) # second call is to health service self.assertEqual('POST', patch_http.call_args_list[1][0][0]) self.assertEqual(health_service_url, patch_http.call_args_list[1][0][1])
def test_no_primary_does_not_throw(self): freebsdosutil = FreeBSDOSUtil() with patch.object(freebsdosutil, '_get_net_info', return_value=('em0', '10.0.0.1', 'e5:f0:38:aa:da:52')): try: freebsdosutil.get_first_if()[0] except Exception as e: print(traceback.format_exc()) exception = True
def test_conf_sshd_with_match_last(self): new_file = "\ Port 22\n\ Match host 192.168.1.1\n\ ChallengeResponseAuthentication yes\n\ " expected_output = "\ Port 22\n\ PasswordAuthentication no\n\ ChallengeResponseAuthentication no\n\ ClientAliveInterval 180\n\ Match host 192.168.1.1\n\ ChallengeResponseAuthentication yes\n\ " with patch.object(fileutil, 'write_file') as patch_write: with patch.object(fileutil, 'read_file', return_value=new_file): osutil.DefaultOSUtil().conf_sshd(disable_password=True) patch_write.assert_called_once_with( conf.get_sshd_conf_file_path(), expected_output)
def test_rm_ext_handler_dir_should_not_report_an_event_if_a_child_is_removed_asynchronously_while_deleting_the_extension_directory(self): os.mkdir(self.extension_directory) os.mknod(os.path.join(self.extension_directory, "extension_file1")) os.mknod(os.path.join(self.extension_directory, "extension_file2")) os.mknod(os.path.join(self.extension_directory, "extension_file3")) # # Some extensions uninstall asynchronously and the files we are trying to remove may be removed # while shutil.rmtree is traversing the extension's directory. Mock this by deleting a file # twice (the second call will produce "[Errno 2] No such file or directory", which should not be # reported as a telemetry event. # In order to mock this, we need to know that remove_ext_handler invokes Pyhon's shutil.rmtree, # which in turn invokes os.unlink (Python 3) or os.remove (Python 2) # remove_api_name = "unlink" if sys.version_info >= (3, 0) else "remove" original_remove_api = getattr(shutil.os, remove_api_name) extension_directory = self.extension_directory def mock_remove(path, dir_fd=None): if dir_fd is not None: # path is relative, make it absolute path = os.path.join(extension_directory, path) if path.endswith("extension_file2"): original_remove_api(path) mock_remove.file_deleted_asynchronously = True original_remove_api(path) mock_remove.file_deleted_asynchronously = False with patch.object(shutil.os, remove_api_name, mock_remove): with patch.object(self.ext_handler_instance, "report_event") as mock_report_event: self.ext_handler_instance.remove_ext_handler() mock_report_event.assert_not_called() # The next 2 asserts are checks on the mock itself, in case the implementation of remove_ext_handler changes (mocks may need to be updated then) self.assertTrue(mock_remove.file_deleted_asynchronously) # verify the mock was actually called self.assertFalse(os.path.exists(self.extension_directory)) # verify the error produced by the mock did not prevent the deletion
def test_validate_http_request(self): """Validate correct set of data is sent to HostGAPlugin when reporting VM status""" wire_protocol_client = wire.WireProtocol(wireserver_url).client test_goal_state = wire.GoalState( WireProtocolData(DATA_FILE).goal_state) status_blob = wire_protocol_client.status_blob status_blob.data = faux_status status_blob.vm_status = restapi.VMStatus(message="Ready", status="Ready") exp_method = 'PUT' exp_url = hostplugin_status_url exp_data = self._hostplugin_data( status_blob.get_block_blob_headers(len(faux_status)), bytearray(faux_status, encoding='utf-8')) with patch.object(restutil, "http_request") as patch_http: patch_http.return_value = Mock(status=httpclient.OK) wire_protocol_client.get_goal_state = Mock( return_value=test_goal_state) plugin = wire_protocol_client.get_host_plugin() with patch.object(plugin, 'get_api_versions') as patch_api: patch_api.return_value = API_VERSION plugin.put_vm_status(status_blob, sas_url, block_blob_type) self.assertTrue(patch_http.call_count == 2) # first call is to host plugin self._validate_hostplugin_args(patch_http.call_args_list[0], test_goal_state, exp_method, exp_url, exp_data) # second call is to health service self.assertEqual('POST', patch_http.call_args_list[1][0][0]) self.assertEqual(health_service_url, patch_http.call_args_list[1][0][1])
def test_it_should_be_a_pass_thru_to_run_get_output(self): with patch.object(shellutil, "run_get_output", return_value=(0, "")) as mock_run_get_output: shellutil.run("echo hello word!", chk_err=False, expected_errors=[1, 2, 3]) self.assertEqual(mock_run_get_output.call_count, 1) args, kwargs = mock_run_get_output.call_args self.assertEqual(args[0], "echo hello word!") self.assertEqual(kwargs["chk_err"], False) self.assertEqual(kwargs["expected_errors"], [1, 2, 3])
def test_update_conf_file(self, _): new_file = "\ DEVICE=eth0\n\ ONBOOT=yes\n\ BOOTPROTO=dhcp\n\ TYPE=Ethernet\n\ USERCTL=no\n\ PEERDNS=yes\n\ IPV6INIT=no\n\ NM_CONTROLLED=yes\n" existing_file = "\ DEVICE=eth0\n\ ONBOOT=yes\n\ BOOTPROTO=dhcp\n\ TYPE=Ethernet\n\ DHCP_HOSTNAME=existing\n\ USERCTL=no\n\ PEERDNS=yes\n\ IPV6INIT=no\n\ NM_CONTROLLED=yes\n" bad_file = "\ DEVICE=eth0\n\ ONBOOT=yes\n\ BOOTPROTO=dhcp\n\ TYPE=Ethernet\n\ USERCTL=no\n\ PEERDNS=yes\n\ IPV6INIT=no\n\ NM_CONTROLLED=yes\n\ DHCP_HOSTNAME=no_new_line" updated_file = "\ DEVICE=eth0\n\ ONBOOT=yes\n\ BOOTPROTO=dhcp\n\ TYPE=Ethernet\n\ USERCTL=no\n\ PEERDNS=yes\n\ IPV6INIT=no\n\ NM_CONTROLLED=yes\n\ DHCP_HOSTNAME=test\n" path = 'path' with patch.object(fileutil, 'write_file') as patch_write: with patch.object(fileutil, 'read_file', return_value=new_file): fileutil.update_conf_file(path, 'DHCP_HOSTNAME', 'DHCP_HOSTNAME=test') patch_write.assert_called_once_with(path, updated_file) with patch.object(fileutil, 'write_file') as patch_write: with patch.object(fileutil, 'read_file', return_value=existing_file): fileutil.update_conf_file(path, 'DHCP_HOSTNAME', 'DHCP_HOSTNAME=test') patch_write.assert_called_once_with(path, updated_file) with patch.object(fileutil, 'write_file') as patch_write: with patch.object(fileutil, 'read_file', return_value=bad_file): fileutil.update_conf_file(path, 'DHCP_HOSTNAME', 'DHCP_HOSTNAME=test') patch_write.assert_called_once_with(path, updated_file)
def test_restart(self): # setup retries = 3 ifname = 'dummy' with patch.object(shellutil, "run") as run_patch: run_patch.return_value = 1 # execute osutil.DefaultOSUtil.restart_if(osutil.DefaultOSUtil(), ifname=ifname, retries=retries, wait=0) # assert self.assertEqual(run_patch.call_count, retries) self.assertEqual(run_patch.call_args_list[0][0][0], 'ifdown {0} && ifup {0}'.format(ifname))
def test_change_partition_type(self): resource_handler = get_resourcedisk_handler() # test when sfdisk --part-type does not exist with patch.object(shellutil, "run_get_output", side_effect=[[1, ''], [0, '']]) as run_patch: resource_handler.change_partition_type( suppress_message=True, option_str='') # assert assert run_patch.call_count == 2 assert "sfdisk --part-type" in run_patch.call_args_list[0][0][0] assert "sfdisk -c" in run_patch.call_args_list[1][0][0] # test when sfdisk --part-type exists with patch.object(shellutil, "run_get_output", side_effect=[[0, '']]) as run_patch: resource_handler.change_partition_type( suppress_message=True, option_str='') # assert assert run_patch.call_count == 1 assert "sfdisk --part-type" in run_patch.call_args_list[0][0][0]
def test_dhcp_skip_cache(self): handler = dhcp.get_dhcp_handler() handler.osutil = osutil.DefaultOSUtil() open_file_mock = mock.mock_open(read_data=TestDHCP.DEFAULT_ROUTING_TABLE) with patch('os.path.exists', return_value=False): with patch.object(osutil.DefaultOSUtil, 'get_dhcp_lease_endpoint')\ as patch_dhcp_cache: with patch.object(dhcp.DhcpHandler, 'send_dhcp_req') \ as patch_dhcp_send: endpoint = 'foo' patch_dhcp_cache.return_value = endpoint # endpoint comes from cache self.assertFalse(handler.skip_cache) with patch("os.path.exists", return_value=True): with patch(open_patch(), open_file_mock): handler.run() self.assertTrue(patch_dhcp_cache.call_count == 1) self.assertTrue(patch_dhcp_send.call_count == 0) self.assertTrue(handler.endpoint == endpoint) # reset handler.skip_cache = True handler.endpoint = None # endpoint comes from dhcp request self.assertTrue(handler.skip_cache) with patch("os.path.exists", return_value=True): with patch(open_patch(), open_file_mock): handler.run() self.assertTrue(patch_dhcp_cache.call_count == 1) self.assertTrue(patch_dhcp_send.call_count == 1)
def test_it_should_reset_service_unit_files_if_version_changed(self): with self._get_persist_firewall_rules_handler() as handler: # 1st step - Setup the service with old Version test_ver = str(uuid.uuid4()) with patch.object(handler, "_UNIT_VERSION", test_ver): self.__setup_and_assert_network_service_setup_scenario(handler) self.assertIn(test_ver, fileutil.read_file(handler.get_service_file_path()), "Test version not found") # 2nd step - Re-run the setup and ensure the service file set up again even if service enabled self.__executed_commands = [] self.__setup_and_assert_network_service_setup_scenario(handler, mock_popen=self.__mock_network_setup_service_enabled) self.assertNotIn(test_ver, fileutil.read_file(handler.get_service_file_path()), "Test version found incorrectly")
def test_dhcp_lease_ubuntu(self): with patch.object(glob, "glob", return_value=['/var/lib/dhcp/dhclient.eth0.leases']): with patch(open_patch(), mock.mock_open(read_data=load_data("dhcp.leases"))): endpoint = get_osutil(distro_name='ubuntu', distro_version='12.04').get_dhcp_lease_endpoint() # pylint: disable=assignment-from-none self.assertTrue(endpoint is not None) self.assertEqual(endpoint, "168.63.129.16") endpoint = get_osutil(distro_name='ubuntu', distro_version='12.04').get_dhcp_lease_endpoint() # pylint: disable=assignment-from-none self.assertTrue(endpoint is not None) self.assertEqual(endpoint, "168.63.129.16") endpoint = get_osutil(distro_name='ubuntu', distro_version='14.04').get_dhcp_lease_endpoint() # pylint: disable=assignment-from-none self.assertTrue(endpoint is not None) self.assertEqual(endpoint, "168.63.129.16")
def test_rm_ext_handler_dir_should_report_an_event_if_an_error_occurs_while_deleting_the_extension_directory(self): os.mkdir(self.extension_directory) os.mknod(os.path.join(self.extension_directory, "extension_file1")) os.mknod(os.path.join(self.extension_directory, "extension_file2")) os.mknod(os.path.join(self.extension_directory, "extension_file3")) # The mock below relies on the knowledge that remove_ext_handler invokes Pyhon's shutil.rmtree, # which in turn invokes os.unlink (Python 3) or os.remove (Python 2) remove_api_name = "unlink" if sys.version_info >= (3, 0) else "remove" original_remove_api = getattr(shutil.os, remove_api_name) def mock_remove(path, dir_fd=None): # pylint: disable=unused-argument if path.endswith("extension_file2"): raise IOError("A mocked error") original_remove_api(path) with patch.object(shutil.os, remove_api_name, mock_remove): with patch.object(self.ext_handler_instance, "report_event") as mock_report_event: self.ext_handler_instance.remove_ext_handler() args, kwargs = mock_report_event.call_args # pylint: disable=unused-variable self.assertTrue("A mocked error" in kwargs["message"])
def test_it_should_invoke_all_periodic_operations(self): invoked_operations = [] with _create_collect_logs_handler() as collect_logs_handler: def mock_run(self): invoked_operations.append(self._name) with patch.object(PeriodicOperation, "run", side_effect=mock_run, spec=CollectLogsHandler.run): collect_logs_handler.run_and_wait() expected_operations = ["collect_and_send_logs"] self.assertEqual(invoked_operations.sort(), expected_operations.sort(), "The collect logs thread did not invoke the expected operations")
def test_put_status_error_reporting(self, patch_add_event): """ Validate the telemetry when uploading status fails """ wire.HostPluginProtocol.set_default_channel(False) with patch.object(wire.StatusBlob, "upload", return_value=False): with self.create_mock_protocol() as wire_protocol: wire_protocol_client = wire_protocol.client put_error = wire.HttpError("put status http error") with patch.object(restutil, "http_put", side_effect=put_error): with patch.object(wire.HostPluginProtocol, "ensure_initialized", return_value=True): self.assertRaises( wire.ProtocolError, wire_protocol_client.upload_status_blob) # The agent tries to upload via HostPlugin and that fails due to # http_put having a side effect of "put_error" # # The agent tries to upload using a direct connection, and that succeeds. self.assertEqual( 1, wire_protocol_client.status_blob.upload.call_count) # pylint: disable=no-member # The agent never touches the default protocol is this code path, so no change. self.assertFalse( wire.HostPluginProtocol.is_default_channel()) # The agent never logs telemetry event for direct fallback self.assertEqual(1, patch_add_event.call_count) self.assertEqual('ReportStatus', patch_add_event.call_args[1]['op']) self.assertTrue( 'Falling back to direct' in patch_add_event.call_args[1]['message']) self.assertEqual( True, patch_add_event.call_args[1]['is_success'])
def test_get_first_if(self): """ Validate that the agent can find the first active non-loopback interface. This test case used to run live, but not all developers have an eth* interface. It is perfectly valid to have a br*, but this test does not account for that. """ freebsdosutil = FreeBSDOSUtil() with patch.object(freebsdosutil, '_get_net_info', return_value=('em0', '10.0.0.1', 'e5:f0:38:aa:da:52')): ifname, ipaddr = freebsdosutil.get_first_if() self.assertEqual(ifname, 'em0') self.assertEqual(ipaddr, '10.0.0.1')
def test_cgroup_operations_should_log_a_warning_when_the_cgroup_api_raises_an_exception( self): configurator = CGroupConfigurator.get_instance() # cleanup_legacy_cgroups disables cgroups on error, so make disable() a no-op with patch.object(configurator, "disable"): # List of operations to test, and the functions to mock in order to raise exceptions operations = [ [ lambda: configurator.create_agent_cgroups(track_cgroups= False), "azurelinuxagent.common.cgroupapi.FileSystemCgroupsApi.create_agent_cgroups" ], [ lambda: configurator.cleanup_legacy_cgroups(), "azurelinuxagent.common.cgroupapi.FileSystemCgroupsApi.cleanup_legacy_cgroups" ], [ lambda: configurator.create_extension_cgroups_root(), "azurelinuxagent.common.cgroupapi.FileSystemCgroupsApi.create_extension_cgroups_root" ], [ lambda: configurator.create_extension_cgroups("A.B.C-1.0.0" ), "azurelinuxagent.common.cgroupapi.FileSystemCgroupsApi.create_extension_cgroups" ], [ lambda: configurator.remove_extension_cgroups("A.B.C-1.0.0" ), "azurelinuxagent.common.cgroupapi.FileSystemCgroupsApi.remove_extension_cgroups" ] ] def raise_exception(*_): raise Exception("A TEST EXCEPTION") for op in operations: with patch( "azurelinuxagent.common.cgroupconfigurator.logger.warn" ) as mock_logger_warn: with patch(op[1], raise_exception): op[0]() self.assertEquals(mock_logger_warn.call_count, 1) args, kwargs = mock_logger_warn.call_args message = args[0] self.assertIn("A TEST EXCEPTION", message)
def test_check_cgroups_should_disable_cgroups_when_a_check_fails(self): with self._get_cgroup_configurator() as configurator: checks = [ "_check_processes_in_agent_cgroup", "_check_agent_throttled_time" ] for method_to_fail in checks: patchers = [] try: # mock 'method_to_fail' to raise an exception and the rest to do nothing for method_to_mock in checks: side_effect = CGroupsException( method_to_fail ) if method_to_mock == method_to_fail else lambda *_: None p = patch.object(configurator, method_to_mock, side_effect=side_effect) patchers.append(p) p.start() with patch( "azurelinuxagent.common.cgroupconfigurator.add_event" ) as add_event: configurator.enable() configurator.check_cgroups([]) self.assertFalse( configurator.enabled(), "An error in {0} should have disabled cgroups". format(method_to_fail)) disable_events = [ kwargs for _, kwargs in add_event.call_args_list if kwargs["op"] == WALAEventOperation.CGroupsDisabled ] self.assertTrue( len(disable_events) == 1, "Exactly 1 event should have been emitted when {0} fails. Got: {1}" .format(method_to_fail, disable_events)) self.assertIn( "[CGroupsException] {0}".format(method_to_fail), disable_events[0]["message"], "The error message is not correct when {0} failed". format(method_to_fail)) finally: for p in patchers: p.stop()
def enable_invocations(*emulators): """ Allows ExtHandlersHandler objects to call the specified emulators and keeps track of the order of those invocations. Returns the invocation record. Note that this method patches subprocess.Popen and ExtHandlerInstance.load_manifest. """ invocation_record = InvocationRecord() patched_popen = generate_patched_popen(invocation_record, *emulators) patched_load_manifest = generate_mock_load_manifest(*emulators) with patch.object(ExtHandlerInstance, "load_manifest", patched_load_manifest): with patch("subprocess.Popen", patched_popen): yield invocation_record
def test_read_response_error(self): """ Validate the read_response_error method handles encoding correctly """ responses = ['message', b'message', '\x80message\x80'] response = MagicMock() response.status = 'status' response.reason = 'reason' with patch.object(response, 'read') as patch_response: for s in responses: patch_response.return_value = s result = restutil.read_response_error(response) print("RESPONSE: {0}".format(s)) print("RESULT: {0}".format(result)) print("PRESENT: {0}".format('[status: reason]' in result)) self.assertTrue('[status: reason]' in result) self.assertTrue('message' in result)
def setUp(self): AgentTestCase.setUp(self) ext_handler_properties = ExtHandlerProperties() ext_handler_properties.version = "1.2.3" ext_handler = ExtHandler(name='foo') ext_handler.properties = ext_handler_properties self.ext_handler_instance = ExtHandlerInstance(ext_handler=ext_handler, protocol=None) pkg_uri = ExtHandlerVersionUri() pkg_uri.uri = "http://bar/foo__1.2.3" self.ext_handler_instance.pkg = ExtHandlerPackage(ext_handler_properties.version) self.ext_handler_instance.pkg.uris.append(pkg_uri) self.base_dir = self.tmp_dir self.extension_directory = os.path.join(self.tmp_dir, "extension_directory") self.mock_get_base_dir = patch.object(self.ext_handler_instance, "get_base_dir", return_value=self.extension_directory) self.mock_get_base_dir.start()
def test_it_should_invoke_all_periodic_operations(self): def periodic_operation_run(self): invoked_operations.append(self.__class__.__name__) with _mock_wire_protocol(): with patch("azurelinuxagent.ga.monitor.MonitorHandler.stopped", side_effect=[False, True, False, True]): with patch("time.sleep"): with patch.object(PeriodicOperation, "run", side_effect=periodic_operation_run, autospec=True): with patch( "azurelinuxagent.common.conf.get_monitor_network_configuration_changes" ) as monitor_network_changes: for network_changes in [True, False]: monitor_network_changes.return_value = network_changes invoked_operations = [] monitor_handler = get_monitor_handler() monitor_handler.run() monitor_handler.join() expected_operations = [ PollResourceUsage.__name__, ReportNetworkErrors.__name__, ResetPeriodicLogMessages.__name__, SendHostPluginHeartbeat.__name__, SendImdsHeartbeat.__name__, ] if network_changes: expected_operations.append( ReportNetworkConfigurationChanges. __name__) invoked_operations.sort() expected_operations.sort() self.assertEqual( invoked_operations, expected_operations, "The monitor thread did not invoke the expected operations" )
def _get_cgroup_configurator(self, initialize=True, enable=True, mock_commands=None): CGroupConfigurator._instance = None configurator = CGroupConfigurator.get_instance() CGroupsTelemetry.reset() with mock_cgroup_environment(self.tmp_dir) as mock_environment: if mock_commands is not None: for command in mock_commands: mock_environment.add_command(command) configurator.mocks = mock_environment if initialize: if not enable: with patch.object(configurator, "enable"): configurator.initialize() else: configurator.initialize() yield configurator
def test_mkfile_dd_fallback(self): with patch.object(shellutil, "run") as run_patch: # setup run_patch.return_value = 1 test_file = os.path.join(self.tmp_dir, 'test_file') file_size = 1024 * 128 # execute if sys.version_info >= (3, 3): with patch("os.posix_fallocate", side_effect=Exception('failure')): get_resourcedisk_handler().mkfile(test_file, file_size) else: get_resourcedisk_handler().mkfile(test_file, file_size) # assert assert run_patch.call_count > 1 assert "fallocate" in run_patch.call_args_list[0][0][0] assert "dd if" in run_patch.call_args_list[-1][0][0]
def _create_collect_logs_handler(iterations=1, cgroups_enabled=True, collect_logs_conf=True): """ Creates an instance of CollectLogsHandler that * Uses a mock_wire_protocol for network requests, * Runs its main loop only the number of times given in the 'iterations' parameter, and * Does not sleep at the end of each iteration The returned CollectLogsHandler is augmented with 2 methods: * get_mock_wire_protocol() - returns the mock protocol * run_and_wait() - invokes run() and wait() on the CollectLogsHandler """ with mock_wire_protocol(DATA_FILE) as protocol: protocol_util = MagicMock() protocol_util.get_protocol = Mock(return_value=protocol) with patch("azurelinuxagent.ga.collect_logs.get_protocol_util", return_value=protocol_util): with patch( "azurelinuxagent.ga.collect_logs.CollectLogsHandler.stopped", side_effect=[False] * iterations + [True]): with patch("time.sleep"): # Grab the singleton to patch it cgroups_configurator_singleton = CGroupConfigurator.get_instance( ) with patch.object(cgroups_configurator_singleton, "enabled", return_value=cgroups_enabled): with patch( "azurelinuxagent.ga.collect_logs.conf.get_collect_logs", return_value=collect_logs_conf): def run_and_wait(): collect_logs_handler.run() collect_logs_handler.join() collect_logs_handler = get_collect_logs_handler() collect_logs_handler.get_mock_wire_protocol = lambda: protocol collect_logs_handler.run_and_wait = run_and_wait yield collect_logs_handler
def setUp(self): AgentTestCase.setUp(self) prefix = "UnitTest" logger.DEFAULT_LOGGER = Logger(prefix=prefix) self.archive_path = os.path.join(self.tmp_dir, "logs.zip") self.mock_archive_path = patch( "azurelinuxagent.ga.collect_logs.COMPRESSED_ARCHIVE_PATH", self.archive_path) self.mock_archive_path.start() self.logger_path = os.path.join(self.tmp_dir, "waagent.log") self.mock_logger_path = patch.object(conf, "get_agent_log_file", return_value=self.logger_path) self.mock_logger_path.start() # Since ProtocolUtil is a singleton per thread, we need to clear it to ensure that the test cases do not # reuse a previous state clear_singleton_instances(ProtocolUtil)
def test_get_dhcp_pid_should_return_an_empty_list_when_the_dhcp_client_is_not_running( self): with patch.object( NSBSDOSUtil, "resolver"): # instantiating NSBSDOSUtil requires a resolver # # PID file does not exist # original_isfile = path.isfile def mock_isfile(path): # pylint: disable=redefined-outer-name return False if path == self.dhclient_pid_file else original_isfile( path) with patch("os.path.isfile", mock_isfile): pid_list = NSBSDOSUtil().get_dhcp_pid() self.assertEqual(pid_list, []) # # PID file is empty # original_isfile = path.isfile def mock_isfile(path): # pylint: disable=redefined-outer-name,function-redefined return True if path == self.dhclient_pid_file else original_isfile( path) original_read_file = read_file def mock_read_file(file, *args, **kwargs): # pylint: disable=redefined-builtin return "" if file == self.dhclient_pid_file else original_read_file( file, *args, **kwargs) with patch("os.path.isfile", mock_isfile): with patch( "azurelinuxagent.common.osutil.nsbsd.fileutil.read_file", mock_read_file): pid_list = NSBSDOSUtil().get_dhcp_pid() self.assertEqual(pid_list, [])