summaryrefslogtreecommitdiff
path: root/cloudinit/tests/helpers.py
AgeCommit message (Collapse)Author
2020-04-24cloudinit: drop dependencies on unittest2 and contextlib2 (#322)Daniel Watkins
These libraries provide backports of Python 3's stdlib components to Python 2. As we only support Python 3, we can simply use the stdlib now. This pull request does the following: * removes some unneeded compatibility code for the old spelling of `assertRaisesRegex` * replaces invocations of the Python 2-only `assertItemsEqual` with its new name, `assertCountEqual` * replaces all usage of `unittest2` with `unittest` * replaces all usage of `contextlib2` with `contextlib` * drops `unittest2` and `contextlib2` from requirements files and tox.ini It also rewrites some `test_azure` helpers to use bare asserts. We were seeing a strange error in xenial builds of this branch which appear to be stemming from the AssertionError that pytest produces being _different_ from the standard AssertionError. This means that the modified helpers weren't behaving correctly, because they weren't catching AssertionErrors as one would expect. (I believe this is related, in some way, to https://github.com/pytest-dev/pytest/issues/645, but the only version of pytest where we're affected is so far in the past that it's not worth pursuing it any further as we have a workaround.)
2020-03-31CiTestCase: stop using and remove sys_exit helper (#283)Daniel Watkins
This shim was required to support Python 2.6, so we no longer need it.
2020-03-27CiTestCase: remove now-unneeded parse_and_read helper method (#286)Daniel Watkins
(And sort some imports where I was changing them.)
2020-03-12Add Netbsd support (#62)Gonéri Le Bouder
Add support for the NetBSD Operating System. Features in this branch: * Add BSD distro parent class from which NetBSD and FreeBSD can specialize * Add *bsd util functions to cloudinit.net and cloudinit.net.bsd_utils * subclass cloudinit.distro.freebsd.Distro from bsd.Distro * Add new cloudinit.distro.netbsd and cloudinit.net.renderer for netbsd * Add lru_cached util.is_NetBSD functions * Add NetBSD detection for ConfigDrive and NoCloud datasources This branch has been tested with: - NoCloud and OpenStack (with and without config-drive) - NetBSD 8.1. and 9.0 - FreeBSD 11.2 and 12.1 - Python 3.7 only, because of the dependency oncrypt.METHOD_BLOWFISH. This version is available in NetBSD 7, 8 and 9 anyway
2020-01-29Replace mock library with unittest.mock (#186)Daniel Watkins
* cloudinit: replace "import mock" with "from unittest import mock" * test-requirements.txt: drop mock Co-authored-by: Chad Smith <chad.smith@canonical.com>
2020-01-21Drop most of the remaining use of six (#179)Daniel Watkins
2019-09-09net,Oracle: Add support for netfailover detectionRyan Harper
Add support for detecting netfailover[1] device 3-tuple in networking layer. In the Oracle datasource ensure that if a provided network config, either fallback or provided config includes a netfailover master to remove any MAC address value as this can break under 3-netdev as the other two devices have the same MAC. 1. https://www.kernel.org/doc/html/latest/networking/net_failover.html
2019-08-22ubuntu-drivers: call db_x_loadtemplatefile to accept NVIDIA EULAChad Smith
Emit a script allowing cloud-init to set linux/nvidia/latelink debconf selection to true. This avoids having to call debconf-set-selections and allows cloud-init to pre-confgure linux-restricted-modules to link NVIDIA drivers to the running kernel. Cloud-init loads this debconf template and sets the value to true in the debconf database by sourcing debconf's /usr/share/debconf/confmodule and uses db_x_loadtemplatefile to register cloud-init's setting for linux/nvidia/latelink. LP: #1840080
2019-03-04drop Python 2.6 support and our NIH version detectionDaniel Watkins
- Remove the last few places that use `if PY26` - Replace our Python version detection logic with six's (which we were already using in most places)
2019-02-26tests: fix some slow tests and some leaking stateDaniel Watkins
In test_ds_identify, don't mutate otherwise-static test data. When running tests in a random order, this was causing failures due to breaking preconditions for other tests. In tests/helpers, reset logging level in tearDown. Some of the CLI tests set the level of the root logger in a way that isn't correctly reset. For test_poll_imds_re_dhcp_on_timeout and test_dhcp_discovery_run_in_sandbox_warns_invalid_pid, mock out time.sleep; this saves ~11 seconds (or ~40% of previous test time!).
2018-09-11user-data: jinja template to render instance-data.json in cloud-configChad Smith
Allow users to provide '## template: jinja' as the first line or their #cloud-config or custom script user-data parts. When this header exists, the cloud-config or script will be rendered as a jinja template. All instance metadata keys and values present in /run/cloud-init/instance-data.json will be available as jinja variables for the template. This means any cloud-config module or script can reference any standardized instance data in templates and scripts. Additionally, any standardized instance-data.json keys scoped below a '<v#>' key will be promoted as a top-level key for ease of reference in templates. This means that '{{ local_hostname }}' is the same as using the latest '{{ v#.local_hostname }}'. Since instance-data is written to /run/cloud-init/instance-data.json, make sure it is persisted across reboots when the cached datasource opject is reloaded. LP: #1791781
2018-09-05tests: print failed testname instead of docstring upon failureChad Smith
2018-09-05tests: Disallow use of util.subp except for where needed.Scott Moser
In many cases, cloud-init uses 'util.subp' to run a subprocess. This is not really desirable in our unit tests as it makes the tests dependent upon existance of those utilities. The change here is to modify the base test case class (CiTestCase) to raise exception any time subp is called. Then, fix all callers. For cases where subp is necessary or actually desired, we can use it via   a.) context hander CiTestCase.allow_subp(value)   b.) class level self.allowed_subp = value Both cases the value is a list of acceptable executable names that will be called (essentially argv[0]). Some cleanups in AltCloud were done as the code was being updated.
2018-09-05sysconfig: refactor sysconfig to accept distro specific templates pathsRyan Harper
Multiple distros use sysconfig format but have different content and paths to certain files. Update distros to specify these template paths in their renderer_configs dictionary.
2018-09-01Add unit tests for config/cc_ssh.pyFrancis Ginther
These tests focus on the apply_credentials method and the ssh setup for root and a distro default user.
2018-08-31Fix the built-in cloudinit/tests/helpers:skipIfScott Moser
this version uses unittest2 skipIf which is present in our python 2.6 environment.
2018-05-23tests: Avoid using https in httpretty, improve HttPretty test case.Scott Moser
On OpenSuSE 42.3, we would get errors running tests/unittests/test_handler/test_handler_chef.py  - test_myhttps_nonet raises a UnmockedError    No mocking was registered, and real connections are not allowed  - test_myhttps_net raises SSLError    ("bad handshake: SysCallError(32, 'EPIPE')",) This fixes the errors by just using http instead of https. Also it modifies the HttprettyTestCase to do the httpretty activate and deactivate itself in setUp and tearDown. Then we don't have to decorate individual test_ methods. Also, we set    httpretty.HTTPretty.allow_net_connect = False Test cases here should not reach out to a network resource. LP: #1771659
2018-05-22cc_mounts: Do not add devices to fstab that are already present.Lars Kellogg-Stedman
Do not add new entries to /etc/fstab for devices that already have an existing fstab entry. Resolves: rhbz#1542578
2018-04-26IBMCloud: recognize provisioning environment during debug boots.Scott Moser
When images are deployed from template in a production environment the artifacts of the provisioning stage (provisioningConfiguration.cfg) that cloud-init referenced are cleaned up. However, when provisioned in "debug" mode (internal to IBM) the artifacts are left. This changes the 'is_ibm_provisioning' implementations in both ds-identify and in the IBM datasource to identify the provisioning stage more correctly. The change is to consider provisioning only if the provisioing file existed and there was no log file or the log file was older than this boot. LP: #1767166
2018-04-20schema: in validation, raise ImportError if strict but no jsonschema.Scott Moser
validate_cloudconfig_schema with strict=True would not actually validate if there was no jsonschema available. That seems kind of strange. The change here is to make it raise an exception if strict was passed in. And then to fix the one test that needed a skipIfJsonSchema wrapper.
2018-04-19pylint: pay attention to unused variable warnings.Scott Moser
This enables warnings produced by pylint for unused variables (W0612), and fixes the existing errors.
2018-04-18net: Depend on iproute2's ip instead of net-tools ifconfig or routeChad Smith
The net-tools package is deprecated and will eventually be dropped. Use "ip route", "link" or "address" instead of "ifconfig" or "route" calls. Cloud-init can now run in an environment that no longer has net-tools. This affects the network and route printing emitted to cloud-config-output.log as well as the cc_disable_ec2_metadata module. Additional changes:  - separate readResource and resourceLocation into standalone test    functions  - Fix ipv4 address rows to report scopes represented by ip addr show  - Formatted route/address ouput now handles multiple ipv4 and ipv6    addresses on a single interface Co-authored-by: James Hogarth <james.hogarth@gmail.com> Co-authored-by: Robert Schweikert <rjschwei@suse.com>
2018-03-16net: recognize iscsi root cases without ip= on kernel command line.Scott Moser
When 'ip=' or 'ip6=' is found on the kernel command line, cloud-init will consider read network config from /run/net-*.conf files. There are some iscsi-root scenarios where initramfs configures networking but the ip= parameter is not present. 2 such cases are:  a.) static config in /etc/iscsi/iscsi.initramfs (copied into the initramfs)  b.) iBft This changes cloud-init to consider initramfs provided networking information if:  * there are /run/net-* files and  * (ip= or ip6 is on the command line) or open-iscsi.interface file exists. LP: #1752391
2018-03-16tests: Make pylint happy and fix python2.6 uses of assertRaisesRegex.Scott Moser
Older unittest2.TestCase (as seen in CentOS 6) do not have an assertRaisesRegex method. They only have the now-deprecated assertRaisesRegexp. We need our unit tests to work there and on newer python (3.6). Simply making assertRaisesRegex = assertRaisesRegexp makes pylint complain as described in https://github.com/PyCQA/pylint/issues/1946 . What was here before this commit was actually broken. This commit makes assertRaisesRegex functional in CentOS 6 and works around the invalid Deprecated warning from pylint. To prove this, we use assertRaisesRegex in a unit test which will be exectued in py27, py3 and py26.
2018-03-14tests: Centralize and re-use skipTest based on json schema presense.Scott Moser
This just centralizes a hunk of duplicated code and uses it from the new location.
2018-02-12tests: run nosetests in cloudinit/ directory, fix py26 fallout.Scott Moser
When we moved some tests to live under cloudinit/ we inadvertantly failed to change all things that would run nose to include that directory. This changes all the 'nose' invocations to consistently run with tests/unittests and cloudinit/. Also, it works around, more correctly this time, a python2.6-ism with the following code: with assertRaises(SystemExit) as cm: sys.exit(2)
2017-12-07pylint: Update pylint to 1.7.1, run on tests/ and tools and fix complaints.Ryan Harper
The motivation for this is that a.) 1.7.1 runs with python 3.6 (bionic) b.) we want to run pylint on tests/ and tools for the same reasons that we want to run it on cloudinit/ The changes are described below. - Update tox.ini to invoke pylint v1.7.1. - Modify .pylintrc generated-members ignore mocked object members (m_.*) - Replace "dangerous" params defaulting to {} - Fix up cloud_tests use of platforms - Cast some instance objects to with dict() - Handle python2.7 vs 3+ ConfigParser use of readfp (deprecated) - Update use of assertEqual(<boolean>, value) to assert<Boolean>(value) - replace depricated assertRegexp -> assertRegex - Remove useless test-class calls to super class - Assign class property accessors a result and use it - Fix missing class member in CepkoResultTests - Fix Cheetah test import
2017-12-05Datasources: Formalize DataSource get_data and related properties.Chad Smith
Each DataSource subclass must define its own get_data method. This branch formalizes our DataSource class to require that subclasses define an explicit dsname for sourcing cloud-config datasource configuration. Subclasses must also override the _get_data method or a NotImplementedError is raised. The branch also writes /run/cloud-init/instance-data.json. This file contains all meta-data, user-data and vendor-data and a standardized set of metadata keys in a json blob which other utilities with root-access could make use of. Because some meta-data or user-data is potentially sensitive the file is only readable by root. Generally most metadata content types should be json serializable. If specific keys or values are not serializable, those specific values will be base64encoded and the key path will be listed under the top-level key 'base64-encoded-keys' in instance-data.json. If json writing fails due to other TypeErrors or UnicodeDecodeErrors, a warning log will be emitted to /var/log/cloud-init.log and no instance-data.json will be created.
2017-09-22DataSourceOVF: use util.find_devs_with(TYPE=iso9660)Ryan Harper
DataSourceOVF attempts to find iso files via walking os.listdir('/dev/') which is far too wide. This approach is too invasive and can sometimes race with systemd attempting to fsck and mount devices. Instead, utilize cloudinit.util.find_devs_with to filter devices by criteria (which uses blkid under the covers). This results in fewer attempts to mount block devices which do not contain iso filesystems. Unittest changes include: - cloudinit.tests.helpers; introduce add_patch() helper - Add unittest coverage for DataSourceOVF use of transport_iso9660 LP: #1718287
2017-09-05relocate tests/unittests/helpers.py to cloudinit/testsLars Kellogg-Stedman
This moves the base test case classes into into cloudinit/tests and updates all the corresponding imports.