summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests')
-rw-r--r--tests/common/osutil/test_default.py151
-rw-r--r--tests/common/test_version.py36
-rw-r--r--tests/daemon/test_daemon.py4
-rw-r--r--tests/data/ga/WALinuxAgent-2.2.0.zipbin357277 -> 0 bytes
-rw-r--r--tests/data/ga/WALinuxAgent-2.2.4.zipbin0 -> 403507 bytes
-rw-r--r--tests/distro/test_resourceDisk.py1
-rw-r--r--tests/ga/test_monitor.py50
-rw-r--r--tests/ga/test_update.py72
-rw-r--r--tests/pa/test_provision.py13
-rw-r--r--tests/protocol/test_hostplugin.py4
-rw-r--r--tests/protocol/test_wire.py34
-rw-r--r--tests/tools.py4
-rw-r--r--tests/utils/test_file_util.py70
-rw-r--r--tests/utils/test_passwords.txt4
-rw-r--r--tests/utils/test_text_util.py12
15 files changed, 379 insertions, 76 deletions
diff --git a/tests/common/osutil/test_default.py b/tests/common/osutil/test_default.py
index d982b7e..933787b 100644
--- a/tests/common/osutil/test_default.py
+++ b/tests/common/osutil/test_default.py
@@ -21,6 +21,7 @@ import mock
import azurelinuxagent.common.osutil.default as osutil
import azurelinuxagent.common.utils.shellutil as shellutil
from azurelinuxagent.common.osutil import get_osutil
+from azurelinuxagent.common.utils import fileutil
from tests.tools import *
@@ -164,5 +165,155 @@ class TestOSUtil(AgentTestCase):
else:
self.fail("Cannot retrieve number of process cores using shell command.")
+ def test_conf_sshd(self):
+ new_file = "\
+Port 22\n\
+Protocol 2\n\
+ChallengeResponseAuthentication yes\n\
+#PasswordAuthentication yes\n\
+UsePAM yes\n\
+"
+ expected_output = "\
+Port 22\n\
+Protocol 2\n\
+ChallengeResponseAuthentication no\n\
+#PasswordAuthentication yes\n\
+UsePAM yes\n\
+PasswordAuthentication no\n\
+ClientAliveInterval 180\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_conf_sshd_with_match(self):
+ new_file = "\
+Port 22\n\
+ChallengeResponseAuthentication yes\n\
+Match host 192.168.1.1\n\
+ ChallengeResponseAuthentication yes\n\
+"
+ expected_output = "\
+Port 22\n\
+ChallengeResponseAuthentication no\n\
+PasswordAuthentication 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_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_conf_sshd_with_match_middle(self):
+ new_file = "\
+Port 22\n\
+match host 192.168.1.1\n\
+ ChallengeResponseAuthentication yes\n\
+match all\n\
+#Other config\n\
+"
+ expected_output = "\
+Port 22\n\
+match host 192.168.1.1\n\
+ ChallengeResponseAuthentication yes\n\
+match all\n\
+#Other config\n\
+PasswordAuthentication no\n\
+ChallengeResponseAuthentication no\n\
+ClientAliveInterval 180\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_conf_sshd_with_match_multiple(self):
+ new_file = "\
+Port 22\n\
+Match host 192.168.1.1\n\
+ ChallengeResponseAuthentication yes\n\
+Match host 192.168.1.2\n\
+ ChallengeResponseAuthentication yes\n\
+Match all\n\
+#Other config\n\
+"
+ expected_output = "\
+Port 22\n\
+Match host 192.168.1.1\n\
+ ChallengeResponseAuthentication yes\n\
+Match host 192.168.1.2\n\
+ ChallengeResponseAuthentication yes\n\
+Match all\n\
+#Other config\n\
+PasswordAuthentication no\n\
+ChallengeResponseAuthentication no\n\
+ClientAliveInterval 180\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_conf_sshd_with_match_multiple_first_last(self):
+ new_file = "\
+Match host 192.168.1.1\n\
+ ChallengeResponseAuthentication yes\n\
+Match host 192.168.1.2\n\
+ ChallengeResponseAuthentication yes\n\
+"
+ expected_output = "\
+PasswordAuthentication no\n\
+ChallengeResponseAuthentication no\n\
+ClientAliveInterval 180\n\
+Match host 192.168.1.1\n\
+ ChallengeResponseAuthentication yes\n\
+Match host 192.168.1.2\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)
+
if __name__ == '__main__':
unittest.main()
diff --git a/tests/common/test_version.py b/tests/common/test_version.py
index 306ea16..df4f0e3 100644
--- a/tests/common/test_version.py
+++ b/tests/common/test_version.py
@@ -17,29 +17,13 @@
from __future__ import print_function
-import copy
-import glob
-import json
-import mock
-import os
-import platform
-import random
-import subprocess
-import sys
-import tempfile
import textwrap
-import zipfile
-from tests.protocol.mockwiredata import *
-from tests.tools import *
+import mock
-import azurelinuxagent.common.conf as conf
-import azurelinuxagent.common.logger as logger
-import azurelinuxagent.common.utils.fileutil as fileutil
import azurelinuxagent.common.version as version
-
-from azurelinuxagent.common.utils.flexible_version import FlexibleVersion
from azurelinuxagent.common.version import *
+from tests.tools import *
class TestCurrentAgentName(AgentTestCase):
@@ -54,6 +38,22 @@ class TestCurrentAgentName(AgentTestCase):
self.assertEqual(AGENT_VERSION, str(current_version))
return
+ @patch("os.getcwd", return_value="/")
+ def test_extract_name_root_finds_installed(self, mock_cwd):
+ current_agent, current_version = set_current_agent()
+ self.assertEqual(AGENT_LONG_VERSION, current_agent)
+ self.assertEqual(AGENT_VERSION, str(current_version))
+ return
+
+ @patch("os.getcwd")
+ def test_extract_name_in_path_finds_installed(self, mock_cwd):
+ path = os.path.join(conf.get_lib_dir(), "events")
+ mock_cwd.return_value = path
+ current_agent, current_version = set_current_agent()
+ self.assertEqual(AGENT_LONG_VERSION, current_agent)
+ self.assertEqual(AGENT_VERSION, str(current_version))
+ return
+
@patch("os.getcwd")
def test_extract_name_finds_latest_agent(self, mock_cwd):
path = os.path.join(conf.get_lib_dir(), "{0}-{1}".format(
diff --git a/tests/daemon/test_daemon.py b/tests/daemon/test_daemon.py
index 263af49..77b4e3e 100644
--- a/tests/daemon/test_daemon.py
+++ b/tests/daemon/test_daemon.py
@@ -15,9 +15,9 @@
# Requires Python 2.4+ and Openssl 1.0+
#
-from tests.tools import *
-from azurelinuxagent.common.exception import *
from azurelinuxagent.daemon import *
+from tests.tools import *
+
class MockDaemonCall(object):
def __init__(self, daemon_handler, count):
diff --git a/tests/data/ga/WALinuxAgent-2.2.0.zip b/tests/data/ga/WALinuxAgent-2.2.0.zip
deleted file mode 100644
index 4f28a83..0000000
--- a/tests/data/ga/WALinuxAgent-2.2.0.zip
+++ /dev/null
Binary files differ
diff --git a/tests/data/ga/WALinuxAgent-2.2.4.zip b/tests/data/ga/WALinuxAgent-2.2.4.zip
new file mode 100644
index 0000000..fd48991
--- /dev/null
+++ b/tests/data/ga/WALinuxAgent-2.2.4.zip
Binary files differ
diff --git a/tests/distro/test_resourceDisk.py b/tests/distro/test_resourceDisk.py
index 1bd79fe..3d39d31 100644
--- a/tests/distro/test_resourceDisk.py
+++ b/tests/distro/test_resourceDisk.py
@@ -18,6 +18,7 @@
# http://msdn.microsoft.com/en-us/library/cc227282%28PROT.10%29.aspx
# http://msdn.microsoft.com/en-us/library/cc227259%28PROT.13%29.aspx
+import sys
from azurelinuxagent.common.utils import shellutil
from azurelinuxagent.daemon.resourcedisk import get_resourcedisk_handler
from tests.tools import *
diff --git a/tests/ga/test_monitor.py b/tests/ga/test_monitor.py
index 838d037..c646cef 100644
--- a/tests/ga/test_monitor.py
+++ b/tests/ga/test_monitor.py
@@ -16,7 +16,6 @@
#
from tests.tools import *
-from azurelinuxagent.common.exception import *
from azurelinuxagent.ga.monitor import *
class TestMonitor(AgentTestCase):
@@ -27,3 +26,52 @@ class TestMonitor(AgentTestCase):
self.assertNotEquals(0, event.parameters)
self.assertNotEquals(None, event.parameters[0])
+ @patch('azurelinuxagent.common.osutil.get_osutil')
+ @patch('azurelinuxagent.common.protocol.get_protocol_util')
+ def test_add_sysinfo(self, _, __):
+ data_str = load_data('ext/event.xml')
+ event = parse_xml_event(data_str)
+ monitor_handler = get_monitor_handler()
+
+ vm_name = 'dummy_vm'
+ tenant_name = 'dummy_tenant'
+ role_name = 'dummy_role'
+ role_instance_name = 'dummy_role_instance'
+ container_id = 'dummy_container_id'
+
+ vm_name_param = "VMName"
+ tenant_name_param = "TenantName"
+ role_name_param = "RoleName"
+ role_instance_name_param = "RoleInstanceName"
+ container_id_param = "ContainerId"
+
+ sysinfo = [TelemetryEventParam(vm_name_param, vm_name),
+ TelemetryEventParam(tenant_name_param, tenant_name),
+ TelemetryEventParam(role_name_param, role_name),
+ TelemetryEventParam(role_instance_name_param, role_instance_name),
+ TelemetryEventParam(container_id_param, container_id)]
+ monitor_handler.sysinfo = sysinfo
+ monitor_handler.add_sysinfo(event)
+
+ self.assertNotEquals(None, event)
+ self.assertNotEquals(0, event.parameters)
+ self.assertNotEquals(None, event.parameters[0])
+ counter = 0
+ for p in event.parameters:
+ if p.name == vm_name_param:
+ self.assertEquals(vm_name, p.value)
+ counter += 1
+ elif p.name == tenant_name_param:
+ self.assertEquals(tenant_name, p.value)
+ counter += 1
+ elif p.name == role_name_param:
+ self.assertEquals(role_name, p.value)
+ counter += 1
+ elif p.name == role_instance_name_param:
+ self.assertEquals(role_instance_name, p.value)
+ counter += 1
+ elif p.name == container_id_param:
+ self.assertEquals(container_id, p.value)
+ counter += 1
+
+ self.assertEquals(5, counter)
diff --git a/tests/ga/test_update.py b/tests/ga/test_update.py
index a431a9b..5277e59 100644
--- a/tests/ga/test_update.py
+++ b/tests/ga/test_update.py
@@ -17,30 +17,10 @@
from __future__ import print_function
-import copy
-import glob
-import json
-import os
-import platform
-import random
-import re
-import subprocess
-import sys
-import tempfile
-import zipfile
-
-from tests.protocol.mockwiredata import *
-from tests.tools import *
-
-import azurelinuxagent.common.logger as logger
-import azurelinuxagent.common.utils.fileutil as fileutil
-
-from azurelinuxagent.common.exception import UpdateError
-from azurelinuxagent.common.protocol.restapi import *
+from azurelinuxagent.common.protocol.hostplugin import *
from azurelinuxagent.common.protocol.wire import *
-from azurelinuxagent.common.utils.flexible_version import FlexibleVersion
-from azurelinuxagent.common.version import AGENT_NAME, AGENT_VERSION
from azurelinuxagent.ga.update import *
+from tests.tools import *
NO_ERROR = {
"last_failure" : 0.0,
@@ -194,7 +174,7 @@ class UpdateTestCase(AgentTestCase):
self.copy_agents(get_agent_pkgs()[0])
self.expand_agents()
count -= 1
-
+
# Determine the most recent agent version
versions = self.agent_versions()
src_v = FlexibleVersion(str(versions[0]))
@@ -290,11 +270,11 @@ class TestGuestAgentError(UpdateTestCase):
for i in range(0, MAX_FAILURE):
err.mark_failure()
-
+
# Agent failed >= MAX_FAILURE, it should be blacklisted
self.assertTrue(err.is_blacklisted)
self.assertEqual(MAX_FAILURE, err.failure_count)
-
+
# Clear old failure does not clear recent failure
err.clear_old_failure()
self.assertTrue(err.is_blacklisted)
@@ -396,7 +376,7 @@ class TestGuestAgent(UpdateTestCase):
self.assertFalse(agent.is_available)
agent._unpack()
self.assertTrue(agent.is_available)
-
+
agent.mark_failure(is_fatal=True)
self.assertFalse(agent.is_available)
return
@@ -409,7 +389,7 @@ class TestGuestAgent(UpdateTestCase):
agent._unpack()
self.assertFalse(agent.is_blacklisted)
self.assertEqual(agent.is_blacklisted, agent.error.is_blacklisted)
-
+
agent.mark_failure(is_fatal=True)
self.assertTrue(agent.is_blacklisted)
self.assertEqual(agent.is_blacklisted, agent.error.is_blacklisted)
@@ -525,7 +505,7 @@ class TestGuestAgent(UpdateTestCase):
self.assertFalse(os.path.isdir(self.agent_path))
mock_http_get.return_value= ResponseMock(status=restutil.httpclient.SERVICE_UNAVAILABLE)
-
+
pkg = ExtHandlerPackage(version=str(get_agent_version()))
pkg.uris.append(ExtHandlerPackageUri())
agent = GuestAgent(pkg=pkg)
@@ -546,6 +526,8 @@ class TestGuestAgent(UpdateTestCase):
ext_uri = 'ext_uri'
host_uri = 'host_uri'
+ api_uri = URI_FORMAT_GET_API_VERSIONS.format(host_uri, HOST_PLUGIN_PORT)
+ art_uri = URI_FORMAT_GET_EXTENSION_ARTIFACT.format(host_uri, HOST_PLUGIN_PORT)
mock_host = HostPluginProtocol(host_uri,
'container_id',
'role_config')
@@ -555,13 +537,29 @@ class TestGuestAgent(UpdateTestCase):
agent = GuestAgent(pkg=pkg)
agent.host = mock_host
+ # ensure fallback fails gracefully, no http
+ self.assertRaises(UpdateError, agent._download)
+ self.assertEqual(mock_http_get.call_count, 2)
+ self.assertEqual(mock_http_get.call_args_list[0][0][0], ext_uri)
+ self.assertEqual(mock_http_get.call_args_list[1][0][0], api_uri)
+
+ # ensure fallback fails gracefully, artifact api failure
with patch.object(HostPluginProtocol,
- "get_artifact_request",
- return_value=[host_uri, {}]):
+ "ensure_initialized",
+ return_value=True):
self.assertRaises(UpdateError, agent._download)
- self.assertEqual(mock_http_get.call_count, 2)
- self.assertEqual(mock_http_get.call_args_list[0][0][0], ext_uri)
- self.assertEqual(mock_http_get.call_args_list[1][0][0], host_uri)
+ self.assertEqual(mock_http_get.call_count, 4)
+ self.assertEqual(mock_http_get.call_args_list[2][0][0], ext_uri)
+ self.assertEqual(mock_http_get.call_args_list[3][0][0], art_uri)
+
+ # ensure fallback works as expected
+ with patch.object(HostPluginProtocol,
+ "get_artifact_request",
+ return_value=[art_uri, {}]):
+ self.assertRaises(UpdateError, agent._download)
+ self.assertEqual(mock_http_get.call_count, 6)
+ self.assertEqual(mock_http_get.call_args_list[4][0][0], ext_uri)
+ self.assertEqual(mock_http_get.call_args_list[5][0][0], art_uri)
@patch("azurelinuxagent.ga.update.restutil.http_get")
def test_ensure_downloaded(self, mock_http_get):
@@ -688,7 +686,7 @@ class TestUpdate(UpdateTestCase):
protocol=None,
versions=None,
count=5):
-
+
latest_version = self.prepare_agents(count=count)
if versions is None or len(versions) <= 0:
versions = [latest_version]
@@ -741,7 +739,7 @@ class TestUpdate(UpdateTestCase):
self.prepare_agents()
agent_count = self.agent_count()
self.assertEqual(5, agent_count)
-
+
agent_versions = self.agent_versions()[:3]
self.assertTrue(self._test_upgrade_available(versions=agent_versions))
self.assertEqual(len(agent_versions), len(self.update_handler.agents))
@@ -793,7 +791,7 @@ class TestUpdate(UpdateTestCase):
return iterations[0] < invocations
mock_util.check_pid_alive = Mock(side_effect=iterator)
-
+
with patch('os.getpid', return_value=42):
with patch('time.sleep', return_value=None) as mock_sleep:
self.update_handler._ensure_no_orphans(orphan_wait_interval=interval)
@@ -1178,7 +1176,7 @@ class TestUpdate(UpdateTestCase):
# reference. Incrementing an item of a list changes an item to
# which the code has a reference.
# See http://stackoverflow.com/questions/26408941/python-nested-functions-and-variable-scope
- iterations = [0]
+ iterations = [0]
def iterator(*args, **kwargs):
iterations[0] += 1
if iterations[0] >= invocations:
diff --git a/tests/pa/test_provision.py b/tests/pa/test_provision.py
index 6508017..a98eacd 100644
--- a/tests/pa/test_provision.py
+++ b/tests/pa/test_provision.py
@@ -15,11 +15,12 @@
# Requires Python 2.4+ and Openssl 1.0+
#
-from tests.tools import *
-import azurelinuxagent.common.conf as conf
-from azurelinuxagent.common.protocol import OVF_FILE_NAME
import azurelinuxagent.common.utils.fileutil as fileutil
+from azurelinuxagent.common.osutil.default import DefaultOSUtil
+from azurelinuxagent.common.protocol import OVF_FILE_NAME
from azurelinuxagent.pa.provision import get_provision_handler
+from tests.tools import *
+
class TestProvision(AgentTestCase):
@@ -42,6 +43,12 @@ class TestProvision(AgentTestCase):
provision_handler.run()
+ def test_customdata(self):
+ base64data = 'Q3VzdG9tRGF0YQ=='
+ data = DefaultOSUtil().decode_customdata(base64data)
+ fileutil.write_file(tempfile.mktemp(), data)
+
+
if __name__ == '__main__':
unittest.main()
diff --git a/tests/protocol/test_hostplugin.py b/tests/protocol/test_hostplugin.py
index 3b99050..1298fdc 100644
--- a/tests/protocol/test_hostplugin.py
+++ b/tests/protocol/test_hostplugin.py
@@ -65,7 +65,7 @@ class TestHostPlugin(AgentTestCase):
wire_protocol_client.get_goal_state = Mock(return_value=test_goal_state)
plugin = wire_protocol_client.get_host_plugin()
blob = wire_protocol_client.status_blob
- blob.vm_status = restapi.VMStatus()
+ blob.vm_status = restapi.VMStatus(message="Ready", status="Ready")
blob.data = '{"dummy": "data"}'
with patch.object(plugin, 'get_api_versions') as patch_api:
patch_api.return_value = API_VERSION
@@ -117,7 +117,7 @@ class TestHostPlugin(AgentTestCase):
self.assertFalse(host_client.is_initialized)
self.assertTrue(host_client.api_versions is None)
status_blob = wire.StatusBlob(None)
- status_blob.vm_status = restapi.VMStatus()
+ status_blob.vm_status = restapi.VMStatus(message="Ready", status="Ready")
status_blob.data = '{"dummy": "data"}'
status_blob.type = "BlockBlob"
with patch.object(wire.HostPluginProtocol,
diff --git a/tests/protocol/test_wire.py b/tests/protocol/test_wire.py
index 8c9cc02..e083678 100644
--- a/tests/protocol/test_wire.py
+++ b/tests/protocol/test_wire.py
@@ -270,6 +270,40 @@ class TestWireProtocolGetters(AgentTestCase):
self.assertTrue(in_vm_artifacts_profile.is_on_hold())
artifact_request.assert_called_once_with(testurl)
+ @patch("socket.gethostname", return_value="hostname")
+ @patch("time.gmtime", return_value=time.localtime(1485543256))
+ def test_report_vm_status(self, *args):
+ status = 'status'
+ message = 'message'
+
+ client = WireProtocol(wireserver_url).client
+ actual = StatusBlob(client=client)
+ actual.set_vm_status(VMStatus(status=status, message=message))
+ timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+
+ formatted_msg = {
+ 'lang': 'en-US',
+ 'message': message
+ }
+ v1_ga_status = {
+ 'version': str(CURRENT_VERSION),
+ 'status': status,
+ 'osversion': DISTRO_VERSION,
+ 'osname': DISTRO_NAME,
+ 'hostname': socket.gethostname(),
+ 'formattedMessage': formatted_msg
+ }
+ v1_agg_status = {
+ 'guestAgentStatus': v1_ga_status,
+ 'handlerAggregateStatus': []
+ }
+ v1_vm_status = {
+ 'version': '1.1',
+ 'timestampUTC': timestamp,
+ 'aggregateStatus': v1_agg_status
+ }
+ self.assertEqual(json.dumps(v1_vm_status), actual.to_json())
+
class MockResponse:
def __init__(self, body, status_code):
diff --git a/tests/tools.py b/tests/tools.py
index 8801a0c..a505700 100644
--- a/tests/tools.py
+++ b/tests/tools.py
@@ -19,18 +19,14 @@
Define util functions for unit test
"""
-import json
import os
import re
import shutil
-import sys
import tempfile
import unittest
-
from functools import wraps
import azurelinuxagent.common.conf as conf
-import azurelinuxagent.common.event as event
import azurelinuxagent.common.logger as logger
from azurelinuxagent.common.version import PY_VERSION_MAJOR
diff --git a/tests/utils/test_file_util.py b/tests/utils/test_file_util.py
index f16f409..76fb15b 100644
--- a/tests/utils/test_file_util.py
+++ b/tests/utils/test_file_util.py
@@ -15,13 +15,12 @@
# Requires Python 2.4+ and Openssl 1.0+
#
-from tests.tools import *
import uuid
-import unittest
-import os
-import sys
-from azurelinuxagent.common.future import ustr
+
import azurelinuxagent.common.utils.fileutil as fileutil
+from azurelinuxagent.common.future import ustr
+from tests.tools import *
+
class TestFileOperations(AgentTestCase):
@@ -117,5 +116,66 @@ class TestFileOperations(AgentTestCase):
self.assertEqual(set(expected_files), set(actual_files))
+ @patch('os.path.isfile')
+ 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)
+
if __name__ == '__main__':
unittest.main()
diff --git a/tests/utils/test_passwords.txt b/tests/utils/test_passwords.txt
new file mode 100644
index 0000000..0d995ef
--- /dev/null
+++ b/tests/utils/test_passwords.txt
@@ -0,0 +1,4 @@
+김치
+करी
+hamburger
+café \ No newline at end of file
diff --git a/tests/utils/test_text_util.py b/tests/utils/test_text_util.py
index dc3de85..6f204c7 100644
--- a/tests/utils/test_text_util.py
+++ b/tests/utils/test_text_util.py
@@ -23,12 +23,16 @@ from azurelinuxagent.common.future import ustr
import azurelinuxagent.common.utils.textutil as textutil
from azurelinuxagent.common.utils.textutil import Version
+
class TestTextUtil(AgentTestCase):
def test_get_password_hash(self):
- password_hash = textutil.gen_password_hash("asdf", 6, 10)
- self.assertNotEquals(None, password_hash)
- password_hash = textutil.gen_password_hash("asdf", 6, 0)
- self.assertNotEquals(None, password_hash)
+ with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test_passwords.txt'), 'rb') as in_file:
+ for data in in_file:
+ # Remove bom on bytes data before it is converted into string.
+ data = textutil.remove_bom(data)
+ data = ustr(data, encoding='utf-8')
+ password_hash = textutil.gen_password_hash(data, 6, 10)
+ self.assertNotEquals(None, password_hash)
def test_remove_bom(self):
#Test bom could be removed