From 96a42134fabb32fcfd2afe5733fb9000f4c95c7b Mon Sep 17 00:00:00 2001 From: Jacob Callahan Date: Wed, 13 Sep 2023 14:00:53 -0400 Subject: [PATCH] Introduce docstring standards for Ruff Most rules are used, but a few are ignored for style. --- docs/create_user_plain.py | 1 - nailgun/client.py | 20 +- nailgun/config.py | 5 +- nailgun/entities.py | 401 +++++++++++++++++++----------------- nailgun/entity_fields.py | 25 +-- nailgun/entity_mixins.py | 51 ++--- pyproject.toml | 2 +- tests/test_client.py | 3 +- tests/test_config.py | 4 +- tests/test_entities.py | 226 ++++++++------------ tests/test_entity_fields.py | 1 - tests/test_entity_mixins.py | 50 ++--- 12 files changed, 363 insertions(+), 426 deletions(-) diff --git a/docs/create_user_plain.py b/docs/create_user_plain.py index 5df1165c..50bfd461 100755 --- a/docs/create_user_plain.py +++ b/docs/create_user_plain.py @@ -55,7 +55,6 @@ def get_organization_id(server_config, label): :param label: A string label that will be used when searching. Every organization should have a unique label. :returns: An organization ID. (Typically an integer.) - """ response = requests.get( f'{server_config["url"]}/katello/api/v2/organizations', diff --git a/nailgun/client.py b/nailgun/client.py index 3ae64d00..3bfae9f1 100644 --- a/nailgun/client.py +++ b/nailgun/client.py @@ -58,7 +58,6 @@ def _content_type_is_json(kwargs): :param kwargs: A ``dict``. The keyword args supplied to :func:`request` or one of the convenience functions like it. :returns: ``True`` or ``False`` - """ if 'headers' in kwargs and 'content-type' in kwargs['headers']: return kwargs['headers']['content-type'].lower() == 'application/json' @@ -75,7 +74,6 @@ def _set_content_type(kwargs): :param kwargs: A ``dict``. The keyword args supplied to :func:`request` or one of the convenience functions like it. :return: Nothing. ``kwargs`` is modified in-place. - """ if 'files' in kwargs: return # requests will automatically set the content-type @@ -85,7 +83,7 @@ def _set_content_type(kwargs): def _truncate_data(data, max_len=500): - """Truncate data to a max length""" + """Truncate data to a max length.""" if isinstance(data, str | bytes): if len(data) > max_len: return f"{data[:max_len - 3]}..." @@ -103,7 +101,6 @@ def _log_request(method, url, kwargs, data=None, params=None): one can pass to ``requests.request``. :return: Nothing is returned. - """ logger.debug( 'Making HTTP %s request to %s with %s, %s and %s.', @@ -123,7 +120,6 @@ def _log_response(response): the object returned is logged. :return: Nothing is returned. - """ message = f'Received HTTP {response.status_code} response: {response.text}' if not response.ok: @@ -133,7 +129,7 @@ def _log_response(response): def request(method, url, **kwargs): - """A wrapper for ``requests.request``.""" + """Wrap ``requests.request``.""" _set_content_type(kwargs) if _content_type_is_json(kwargs) and kwargs.get('data') is not None: kwargs['data'] = dumps(kwargs['data']) @@ -144,7 +140,7 @@ def request(method, url, **kwargs): def head(url, **kwargs): - """A wrapper for ``requests.head``.""" + """Wrap ``requests.head``.""" _set_content_type(kwargs) if _content_type_is_json(kwargs) and kwargs.get('data') is not None: kwargs['data'] = dumps(kwargs['data']) @@ -155,7 +151,7 @@ def head(url, **kwargs): def get(url, params=None, **kwargs): - """A wrapper for ``requests.get``.""" + """Wrap ``requests.get``.""" _set_content_type(kwargs) if _content_type_is_json(kwargs) and kwargs.get('data') is not None: kwargs['data'] = dumps(kwargs['data']) @@ -166,7 +162,7 @@ def get(url, params=None, **kwargs): def post(url, data=None, json=None, **kwargs): - """A wrapper for ``requests.post``.""" + """Wrap ``requests.post``.""" _set_content_type(kwargs) if _content_type_is_json(kwargs) and data is not None: data = dumps(data) @@ -177,7 +173,7 @@ def post(url, data=None, json=None, **kwargs): def put(url, data=None, **kwargs): - """A wrapper for ``requests.put``. Sends a PUT request.""" + """Wrap ``requests.put``. Sends a PUT request.""" _set_content_type(kwargs) if _content_type_is_json(kwargs) and data is not None: data = dumps(data) @@ -188,7 +184,7 @@ def put(url, data=None, **kwargs): def patch(url, data=None, **kwargs): - """A wrapper for ``requests.patch``. Sends a PATCH request.""" + """Wrap ``requests.patch``. Sends a PATCH request.""" _set_content_type(kwargs) if _content_type_is_json(kwargs) and data is not None: data = dumps(data) @@ -199,7 +195,7 @@ def patch(url, data=None, **kwargs): def delete(url, **kwargs): - """A wrapper for ``requests.delete``. Sends a DELETE request.""" + """Wrap ``requests.delete``. Sends a DELETE request.""" _set_content_type(kwargs) if _content_type_is_json(kwargs) and kwargs.get('data') is not None: kwargs['data'] = dumps(kwargs['data']) diff --git a/nailgun/config.py b/nailgun/config.py index ad261d30..757d048b 100644 --- a/nailgun/config.py +++ b/nailgun/config.py @@ -21,7 +21,6 @@ class ConfigFileError(Exception): .. WARNING:: This class will likely be moved to a separate Python package in a future release of NailGun. Be careful about making references to this class, as those references will likely need to be changed. - """ @@ -40,7 +39,6 @@ def _get_config_file_path(xdg_config_dir, xdg_config_file): :returns: A ``str`` path to a configuration file. :raises nailgun.config.ConfigFileError: When no configuration file can be found. - """ for config_dir in BaseDirectory.load_config_paths(xdg_config_dir): path = join(config_dir, xdg_config_file) @@ -91,7 +89,6 @@ class BaseServerConfig: .. WARNING:: This class will likely be moved to a separate Python package in a future release of NailGun. Be careful about making references to this class, as those references will likely need to be changed. - """ # Used to lock access to the configuration file when performing certain @@ -110,6 +107,7 @@ def __init__(self, url, auth=None, version=None): self.version = parse(version) def __repr__(self): + """Return a string representation of the object.""" attrs = vars(self).copy() if "version" in attrs: attrs["version"] = str(attrs.pop("version")) @@ -228,7 +226,6 @@ class ServerConfig(BaseServerConfig): :param verify: A boolean. Should SSL be verified when communicating with the server? No instance attribute is created if no value is provided. - """ # It's OK that this class has only one public method. This class is diff --git a/nailgun/entities.py b/nailgun/entities.py index 7da2f9a5..42bda690 100644 --- a/nailgun/entities.py +++ b/nailgun/entities.py @@ -1,4 +1,4 @@ -"""This module defines all entities which Foreman exposes. +"""All entities which Foreman exposes. Each class in this module allows you to work with a certain set of logically related API paths exposed by the server. For example, @@ -113,7 +113,6 @@ def _handle_response(response, server_config, synchronous=False, timeout=None): :param synchronous: Should this function poll the server? :param timeout: Maximum number of seconds to wait until timing out. Defaults to ``nailgun.entity_mixins.TASK_TIMEOUT``. - """ response.raise_for_status() if synchronous is True and response.status_code == ACCEPTED: @@ -148,7 +147,6 @@ def _check_for_value(field_name, field_values): :raises: ``TypeError`` if ``field_name`` is not present in ``field_values``. :returns: Nothing. - """ if field_name not in field_values: raise TypeError(f'A value must be provided for the "{field_name}" field.') @@ -162,7 +160,6 @@ def _get_org(server_config, label): :param label: A string. The label of the organization to find. :raises APIResponseError: If exactly one organization is not found. :returns: An :class:`nailgun.entities.Organization` object. - """ organizations = Organization(server_config).search(query={'search': f'label={label}'}) if len(organizations) != 1: @@ -189,14 +186,13 @@ def _get_version(server_config): :returns: A ``packaging.version.Version`` object. The version on ``server_config`` is returned if present, or a default version of '1!0' (epoch 1, version 0) otherwise. - """ return getattr(server_config, 'version', Version('1!0')) @lru_cache def _feature_list(server_config, smart_proxy_id=1): - """Get list of features enabled on capsule""" + """Get list of features enabled on capsule.""" smart_proxy = SmartProxy(server_config, id=smart_proxy_id).read_json() return [feature['name'] for feature in smart_proxy['features']] @@ -275,7 +271,7 @@ def path(self, which=None): return super().path(which) def add_host_collection(self, synchronous=True, timeout=None, **kwargs): - """Helper for associating host collection with activation key. + """Associate host collection with activation key. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -294,7 +290,7 @@ def add_host_collection(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def add_subscriptions(self, synchronous=True, timeout=None, **kwargs): - """Helper for adding subscriptions to activation key. + """Add subscriptions to activation key. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -334,7 +330,7 @@ def copy(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def remove_subscriptions(self, synchronous=True, timeout=None, **kwargs): - """Helper for removing subscriptions from an activation key. + """Remove subscriptions from an activation key. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -353,7 +349,7 @@ def remove_subscriptions(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def subscriptions(self, synchronous=True, timeout=None, **kwargs): - """Helper for retrieving subscriptions on an activation key. + """Retrieve subscriptions on an activation key. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -391,7 +387,7 @@ def content_override(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def product_content(self, synchronous=True, timeout=None, **kwargs): - """Helper for showing content available for activation key. + """Show content available for activation key. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -410,7 +406,7 @@ def product_content(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def remove_host_collection(self, synchronous=True, timeout=None, **kwargs): - """Helper for disassociating host collection from the activation key. + """Disassociate host collection from the activation key. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -474,7 +470,7 @@ def __init__(self, server_config=None, **kwargs): super().__init__(server_config, **kwargs) def read(self, entity=None, attrs=None, ignore=None, params=None): - """Handle read values dependencies""" + """Handle read values dependencies.""" if attrs is None: attrs = self.read_json() if ignore is None: @@ -533,7 +529,7 @@ def path(self, which=None): return super().path(which) def refresh(self, synchronous=True, timeout=None, **kwargs): - """Helper to refresh an ACS. + """Refresh an ACS. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -552,7 +548,7 @@ def refresh(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def bulk_refresh(self, synchronous=True, timeout=None, **kwargs): - """Refresh the set of ACSes + """Refresh the set of ACSes. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -570,7 +566,7 @@ def bulk_refresh(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def bulk_destroy(self, synchronous=True, timeout=None, **kwargs): - """Destroy the set of ACSes + """Destroy the set of ACSes. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -656,6 +652,7 @@ def __init__(self, server_config=None, **kwargs): def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. + The format of the returned path depends on the value of ``which``: download_html @@ -669,7 +666,7 @@ def path(self, which=None): return super().path(which) def download_html(self, synchronous=True, timeout=None, **kwargs): - """Download ARF report in HTML + """Download ARF report in HTML. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -840,7 +837,7 @@ def __init__(self, server_config=None, **kwargs): super().__init__(server_config, **kwargs) def content_add_lifecycle_environment(self, synchronous=True, timeout=None, **kwargs): - """Helper to associate lifecycle environment with capsule + """Associate lifecycle environment with capsule. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -858,7 +855,7 @@ def content_add_lifecycle_environment(self, synchronous=True, timeout=None, **kw return _handle_response(response, self._server_config, synchronous, timeout) def content_delete_lifecycle_environment(self, synchronous=True, timeout=None, **kwargs): - """Helper to disassociate lifecycle environment from capsule + """Disassociate lifecycle environment from capsule. Here is an example of how to use this method:: capsule.content_delete_lifecycle_environment(data={'environment_id': lce.id}) @@ -886,8 +883,7 @@ def content_delete_lifecycle_environment(self, synchronous=True, timeout=None, * return _handle_response(response, self._server_config, synchronous, timeout) def content_lifecycle_environments(self, synchronous=True, timeout=None, **kwargs): - """Helper to get all the lifecycle environments, associated with - capsule + """Get all lifecycle environments associated with a capsule. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -905,7 +901,7 @@ def content_lifecycle_environments(self, synchronous=True, timeout=None, **kwarg return _handle_response(response, self._server_config, synchronous, timeout) def content_sync(self, synchronous=True, timeout=None, **kwargs): - """Helper to sync content on a capsule + """Sync content on a capsule. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -923,7 +919,7 @@ def content_sync(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def content_get_sync(self, synchronous=True, timeout=None, **kwargs): - """Helper to get content sync status on capsule + """Get content sync status on capsule. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -1085,6 +1081,7 @@ def __init__(self, server_config=None, **kwargs): def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. + The format of the returned path depends on the value of ``which``: available_images @@ -1138,7 +1135,7 @@ def update(self, fields=None): return self.read() def available_images(self, synchronous=True, timeout=None, **kwargs): - """Get images available to be added to the compute resource + """Get images available to be added to the compute resource. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -1157,7 +1154,7 @@ def available_images(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def available_zones(self, synchronous=True, timeout=None, **kwargs): - """Get images available to be added to the compute resource + """Get images available to be added to the compute resource. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -1176,7 +1173,7 @@ def available_zones(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def available_flavors(self, synchronous=True, timeout=None, **kwargs): - """Get flavors available to be added to the compute resource + """Get flavors available to be added to the compute resource. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -1195,7 +1192,7 @@ def available_flavors(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def available_networks(self, synchronous=True, timeout=None, **kwargs): - """Get networks available to be selected for host provisioning + """Get networks available to be selected for host provisioning. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -1214,7 +1211,7 @@ def available_networks(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def images(self, synchronous=True, timeout=None, **kwargs): - """Get images created in a compute resource + """Get images created in a compute resource. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -1233,7 +1230,7 @@ def images(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def associate(self, synchronous=True, timeout=None, **kwargs): - """Associate the host + """Associate the host. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. @@ -1316,7 +1313,7 @@ def update_payload(self, fields=None): return {'discovered_host': super().update_payload(fields)} def facts(self, synchronous=True, timeout=None, **kwargs): - """Helper to update facts for discovered host, and create the host. + """Update facts for discovered host, and create the host. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -1335,7 +1332,7 @@ def facts(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def refresh_facts(self, synchronous=True, timeout=None, **kwargs): - """Helper to refresh facts for discovered host + """Refresh facts for discovered host. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -1354,7 +1351,7 @@ def refresh_facts(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def read(self, entity=None, attrs=None, ignore=None, params=None): - """Make sure, everything except `id` and `name` are in the ignore list for read""" + """Make sure, everything except `id` and `name` are in the ignore list for read.""" if ignore is None: ignore = set() ignore.add('ip') @@ -1367,7 +1364,7 @@ def read(self, entity=None, attrs=None, ignore=None, params=None): return super().read(entity, attrs, ignore, params) def reboot(self, synchronous=True, timeout=None, **kwargs): - """Helper to reboot the discovered host + """Reboot the discovered host. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -1386,7 +1383,7 @@ def reboot(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def reboot_all(self, synchronous=True, timeout=None, **kwargs): - """Helper for rebooting all discovered hosts + """Reboot all discovered hosts. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -1404,7 +1401,7 @@ def reboot_all(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def auto_provision(self, synchronous=True, timeout=None, **kwargs): - """Helper for auto-provisioning of the discovered host + """Auto-provision the discovered host. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -1422,7 +1419,7 @@ def auto_provision(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def auto_provision_all(self, synchronous=True, timeout=None, **kwargs): - """Helper for auto-provisioning of all discovered hosts + """Auto-provision of all discovered hosts. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -1452,7 +1449,6 @@ class DiscoveryRule( .. NOTE:: The ``search_`` field is named as such due to a naming conflict with :meth:`nailgun.entity_mixins.Entity.path`. - """ def __init__(self, server_config=None, **kwargs): @@ -1580,7 +1576,7 @@ def __init__(self, server_config=None, **kwargs): } def read(self, entity=None, attrs=None, ignore=None, params=None): - """Ignore usergroup from read and alter auth_source_ldap with auth_source""" + """Ignore usergroup from read and alter auth_source_ldap with auth_source.""" entity = entity or self.entity_with_parent() if ignore is None: ignore = set() @@ -1657,7 +1653,7 @@ def __init__(self, server_config=None, **kwargs): class OVirtComputeResource(AbstractComputeResource): - """A representation for compute resources with Ovirt provider""" + """A representation for compute resources with Ovirt provider.""" def __init__(self, server_config=None, **kwargs): self._fields = { @@ -1673,7 +1669,7 @@ def __init__(self, server_config=None, **kwargs): self._fields['provider_friendly_name'].default = 'OVirt' def read(self, entity=None, attrs=None, ignore=None, params=None): - """Make sure, ``password`` is in the ignore list for read""" + """Make sure, ``password`` is in the ignore list for read.""" if ignore is None: ignore = set() ignore.add('password') @@ -1681,7 +1677,7 @@ def read(self, entity=None, attrs=None, ignore=None, params=None): class VMWareComputeResource(AbstractComputeResource): - """A representation for compute resources with Vmware provider""" + """A representation for compute resources with Vmware provider.""" def __init__(self, server_config=None, **kwargs): self._fields = { @@ -1696,7 +1692,7 @@ def __init__(self, server_config=None, **kwargs): self._fields['provider_friendly_name'].default = 'VMware' def read(self, entity=None, attrs=None, ignore=None, params=None): - """Make sure, ``password`` is in the ignore list for read""" + """Make sure, ``password`` is in the ignore list for read.""" if ignore is None: ignore = set() ignore.add('password') @@ -1717,7 +1713,7 @@ def __init__(self, server_config=None, **kwargs): self._fields['provider_friendly_name'].default = 'GCE' def read(self, entity=None, attrs=None, ignore=None, params=None): - """Make sure, ``key_path`` is in the ignore list for read""" + """Make sure, ``key_path`` is in the ignore list for read.""" if ignore is None: ignore = set() ignore.add('key_path') @@ -1725,7 +1721,7 @@ def read(self, entity=None, attrs=None, ignore=None, params=None): class AzureRMComputeResource(AbstractComputeResource): - """A representation for compute resources with AzureRM provider""" + """A representation for compute resources with AzureRM provider.""" def __init__(self, server_config=None, **kwargs): self._fields = { @@ -1743,7 +1739,7 @@ def __init__(self, server_config=None, **kwargs): self._fields['provider_friendly_name'].default = 'Azure Resource Manager' def read(self, entity=None, attrs=None, ignore=None, params=None): - """Make sure, ``secret_key`` is in the ignore list for read""" + """Make sure, ``secret_key`` is in the ignore list for read.""" if ignore is None: ignore = set() ignore.add('secret_key') @@ -1804,9 +1800,7 @@ def __init__(self, server_config=None, **kwargs): } def read(self, entity=None, attrs=None, ignore=None, params=None): - """Create a JobTemplate object before calling read() - ignore 'advanced' - """ + """Create a JobTemplate object before calling read, ignore 'advanced'.""" entity = entity or self.entity_with_parent() if ignore is None: ignore = set() @@ -1838,7 +1832,7 @@ def __init__(self, server_config=None, **kwargs): super().__init__(server_config, **kwargs) def run(self, synchronous=True, **kwargs): - """Helper to run existing job template + """Run an existing job template. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -1911,7 +1905,6 @@ def __init__(self, server_config=None, **kwargs): def create_payload(self): """Wrap submitted data within an extra dict.""" - payload = super().create_payload() effective_user = payload.pop('effective_user', None) if effective_user: @@ -1929,8 +1922,10 @@ def update_payload(self, fields=None): def read(self, entity=None, attrs=None, ignore=None, params=None): """Ignore the template inputs when initially reading the job template. + Look up each TemplateInput entity separately - and afterwords add them to the JobTemplate entity.""" + and afterwards add them to the JobTemplate entity. + """ if attrs is None: attrs = self.read_json(params=params) if ignore is None: @@ -2048,7 +2043,7 @@ def read(self, entity=None, attrs=None, ignore=None, params=None): return super().read(entity, attrs, ignore, params) def build_pxe_default(self, synchronous=True, timeout=None, **kwargs): - """Helper to build pxe default template. + """Build pxe default template. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -2066,7 +2061,7 @@ def build_pxe_default(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def clone(self, synchronous=True, timeout=None, **kwargs): - """Helper to clone an existing provision template + """Clone an existing provision template. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -2149,7 +2144,7 @@ def path(self, which=None): return super().path(which) def clone(self, synchronous=True, timeout=None, **kwargs): - """Helper to clone an existing report template + """Clone an existing report template. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -2167,7 +2162,7 @@ def clone(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def generate(self, synchronous=True, timeout=None, **kwargs): - """Helper to generate an existing report template + """Generate an existing report template. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -2185,7 +2180,7 @@ def generate(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def schedule_report(self, synchronous=True, timeout=None, **kwargs): - """Helper to schedule an existing report template + """Schedule an existing report template. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -2203,7 +2198,7 @@ def schedule_report(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def report_data(self, synchronous=True, timeout=None, **kwargs): - """Helper to call report_data on an existing scheduled report + """Call report_data on an existing scheduled report. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -2429,7 +2424,7 @@ def path(self, which=None): return super().path(which) def incremental_update(self, synchronous=True, timeout=None, **kwargs): - """Helper for incrementally updating a content view version. + """Incrementally update a content view version. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -2448,7 +2443,7 @@ def incremental_update(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def promote(self, synchronous=True, timeout=None, **kwargs): - """Helper for promoting an existing published content view. + """Promote an existing published content view. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -2758,7 +2753,7 @@ def path(self, which=None): return super().path(which) def publish(self, synchronous=True, timeout=None, **kwargs): - """Helper for publishing an existing content view. + """Publish an existing content view. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -2842,10 +2837,9 @@ def __init__(self, server_config=None, **kwargs): } def read(self, entity=None, attrs=None, ignore=None, params=None): - """ - Add composite_content_view to the response if needed, as - :meth:`nailgun.entity_mixins.EntityReadMixin.read` can't initialize - composite_content_view. + """Add composite_content_view to the response if needed. + + :meth:`nailgun.entity_mixins.EntityReadMixin.read` can't initialize composite_content_view. """ if attrs is None: attrs = self.read_json() @@ -2858,6 +2852,7 @@ def read(self, entity=None, attrs=None, ignore=None, params=None): def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. + The format of the returned path depends on the value of ``which``: add @@ -2898,7 +2893,7 @@ def add(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def remove(self, synchronous=True, timeout=None, **kwargs): - """remove provided Content View Component. + """Remove provided Content View Component. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -3057,6 +3052,7 @@ def update_payload(self, fields=None): def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. + The format of the returned path depends on the value of ``which``: smart_class_parameters @@ -3070,7 +3066,7 @@ def path(self, which=None): return super().path(which) def list_scparams(self, synchronous=True, timeout=None, **kwargs): - """List all smart class parameters + """List all smart class parameters. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -3120,7 +3116,7 @@ def __init__(self, server_config=None, **kwargs): super().__init__(server_config, **kwargs) def compare(self, synchronous=True, timeout=None, **kwargs): - """Compare errata from different content view versions + """Compare errata from different content view versions. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -3154,9 +3150,12 @@ def path(self, which=None): return super().path(which) def read(self, entity=None, attrs=None, ignore=None, params=None): - """Following fields are only accessible for filtering search results - and are never returned by the server: ``content_view_version_id``, - ``environment_id``, ``repository_id``. + """Read errata from the server. + + Following fields are only accessible for filtering search results + and are never returned by the server: + + ``content_view_version_id``, ``environment_id``, ``repository_id``. """ if ignore is None: ignore = set() @@ -3214,7 +3213,7 @@ def create_payload(self): return {'filter': super().create_payload()} def read(self, entity=None, attrs=None, ignore=None, params=None): - """Deal with different named data returned from the server""" + """Deal with different named data returned from the server.""" if attrs is None: attrs = self.read_json() attrs['override'] = attrs.pop('override?') @@ -3317,7 +3316,7 @@ def poll(self, poll_rate=None, timeout=None, must_succeed=True): return _poll_task(self.id, self._server_config, poll_rate, timeout, must_succeed) def summary(self, synchronous=True, timeout=None, **kwargs): - """Helper to view a summary of tasks. + """View a summary of tasks. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -3336,7 +3335,7 @@ def summary(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def bulk_cancel(self, synchronous=True, timeout=None, **kwargs): - """Cancels the task(s). + """Cancel the task(s). :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -3602,6 +3601,7 @@ def update_payload(self, fields=None): def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. + The format of the returned path depends on the value of ``which``: clone @@ -3626,7 +3626,7 @@ def path(self, which=None): return super().path(which) def add_puppetclass(self, synchronous=True, timeout=None, **kwargs): - """Add a Puppet class to host group + """Add a Puppet class to host group. Here is an example of how to use this method:: hostgroup.add_puppetclass(data={'puppetclass_id': puppet.id}) @@ -3648,7 +3648,7 @@ def add_puppetclass(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def delete_puppetclass(self, synchronous=True, timeout=None, **kwargs): - """Remove a Puppet class from host group + """Remove a Puppet class from host group. Here is an example of how to use this method:: hostgroup.delete_puppetclass(data={'puppetclass_id': puppet.id}) @@ -3675,7 +3675,7 @@ def delete_puppetclass(self, synchronous=True, timeout=None, **kwargs): ) def list_scparams(self, synchronous=True, timeout=None, **kwargs): - """List all smart class parameters + """List all smart class parameters. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -3694,7 +3694,7 @@ def list_scparams(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def clone(self, synchronous=True, timeout=None, **kwargs): - """Helper to clone an existing host group + """Clone an existing host group. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -3712,7 +3712,7 @@ def clone(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def rebuild_config(self, synchronous=True, timeout=None, **kwargs): - """Helper to 'Rebuild orchestration config' of an existing host group + """Rebuild orchestration config of an existing host group. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -3780,7 +3780,7 @@ def path(self, which=None): return super().path(which) def subscriptions(self, synchronous=True, timeout=None, **kwargs): - """Helper for getting subscriptions from host + """Get subscriptions from host. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -3799,7 +3799,7 @@ def subscriptions(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def add_subscriptions(self, synchronous=True, timeout=None, **kwargs): - """Helper for adding subscriptions to host + """Add subscriptions to host. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -3818,7 +3818,7 @@ def add_subscriptions(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def remove_subscriptions(self, synchronous=True, timeout=None, **kwargs): - """Helper for removing subscriptions from host + """Remove subscriptions from host. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4101,7 +4101,7 @@ def create(self, create_missing=None): ).read() def enc(self, synchronous=True, timeout=None, **kwargs): - """Return external node classifier (ENC) information + """Return external node classifier (ENC) information. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4119,7 +4119,7 @@ def enc(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def errata(self, synchronous=True, timeout=None, **kwargs): - """List errata available for the host + """List errata available for the host. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4138,7 +4138,7 @@ def errata(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def traces(self, synchronous=True, timeout=None, **kwargs): - """List services that need restarting for the host + """List services that need restarting for the host. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4156,7 +4156,7 @@ def traces(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def bulk_traces(self, synchronous=True, timeout=None, **kwargs): - """List services that need restarting for the specified set of hosts + """List services that need restarting for the specified set of hosts. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4174,7 +4174,7 @@ def bulk_traces(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def resolve_traces(self, synchronous=True, timeout=None, **kwargs): - """Resolve traces for the host + """Resolve traces for the host. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4192,7 +4192,7 @@ def resolve_traces(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def bulk_resolve_traces(self, synchronous=True, timeout=None, **kwargs): - """Resolve traces for the specified set of hosts + """Resolve traces for the specified set of hosts. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4210,7 +4210,7 @@ def bulk_resolve_traces(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def bulk_destroy(self, synchronous=True, timeout=None, **kwargs): - """Destroy the set of hosts + """Destroy the set of hosts. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4228,7 +4228,7 @@ def bulk_destroy(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def packages(self, synchronous=True, timeout=None, **kwargs): - """List packages installed on the host + """List packages installed on the host. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4246,7 +4246,7 @@ def packages(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def module_streams(self, synchronous=True, timeout=None, **kwargs): - """List module_streams available for the host + """List module_streams available for the host. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4265,7 +4265,7 @@ def module_streams(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def errata_applicability(self, synchronous=True, timeout=None, **kwargs): - """Force regenerate errata applicability + """Force regenerate errata applicability. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4284,7 +4284,7 @@ def errata_applicability(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def errata_apply(self, synchronous=True, timeout=None, **kwargs): - """Schedule errata for installation + """Schedule errata for installation. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4303,7 +4303,7 @@ def errata_apply(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def install_content(self, synchronous=True, timeout=None, **kwargs): - """Install content on one or more hosts + """Install content on one or more hosts. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4322,7 +4322,7 @@ def install_content(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def bulk_add_subscriptions(self, synchronous=True, timeout=None, **kwargs): - """Add subscriptions to one or more hosts + """Add subscriptions to one or more hosts. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4341,7 +4341,7 @@ def bulk_add_subscriptions(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def bulk_remove_subscriptions(self, synchronous=True, timeout=None, **kwargs): - """Remove subscriptions from one or more hosts + """Remove subscriptions from one or more hosts. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4360,7 +4360,7 @@ def bulk_remove_subscriptions(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def bulk_available_incremental_updates(self, synchronous=True, timeout=None, **kwargs): - """Get available_incremental_updates for one or more hosts + """Get available_incremental_updates for one or more hosts. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4379,7 +4379,7 @@ def bulk_available_incremental_updates(self, synchronous=True, timeout=None, **k return _handle_response(response, self._server_config, synchronous, timeout) def get_facts(self, synchronous=True, timeout=None, **kwargs): - """List all fact values of a given host + """List all fact values of a given host. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4398,7 +4398,7 @@ def get_facts(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def upload_facts(self, synchronous=True, timeout=None, **kwargs): - """Upload facts for a host, creating the host if required + """Upload facts for a host, creating the host if required. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4514,6 +4514,7 @@ def update_payload(self, fields=None): def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. + The format of the returned path depends on the value of ``which``: bulk/install_content @@ -4577,7 +4578,7 @@ def path(self, which=None): return super().path(which) def add_puppetclass(self, synchronous=True, timeout=None, **kwargs): - """Add a Puppet class to host + """Add a Puppet class to host. Here is an example of how to use this method:: host.add_puppetclass(data={'puppetclass_id': puppet.id}) @@ -4599,7 +4600,7 @@ def add_puppetclass(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def delete_puppetclass(self, synchronous=True, timeout=None, **kwargs): - """Remove a Puppet class from host + """Remove a Puppet class from host. Here is an example of how to use this method:: host.delete_puppetclass(data={'puppetclass_id': puppet.id}) @@ -4626,7 +4627,7 @@ def delete_puppetclass(self, synchronous=True, timeout=None, **kwargs): ) def read_template(self, synchronous=True, timeout=None, **kwargs): - """Fetches and reads the provisioning template for given host + """Fetch and read the provisioning template for given host. Here is an example of how to use this method:: host.read_template(data={'template_kind': 'iPXE'}) @@ -4653,7 +4654,7 @@ def read_template(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def list_scparams(self, synchronous=True, timeout=None, **kwargs): - """List all smart class parameters + """List all smart class parameters. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4672,7 +4673,7 @@ def list_scparams(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def power(self, synchronous=True, timeout=None, **kwargs): - """Power the host off or on + """Power the host off or on. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. @@ -4719,7 +4720,7 @@ def search(self, fields=None, query=None, filters=None): return entities def disassociate(self, synchronous=True, timeout=None, **kwargs): - """Disassociate the host + """Disassociate the host. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. @@ -4733,7 +4734,7 @@ def disassociate(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def assign_ansible_roles(self, synchronous=True, timeout=None, **kwargs): - """Add an Ansible Role to a host + """Add an Ansible Role to a host. Here is an example of how to use this method:: host.assign_ansible_roles(data={'ansible_role_ids': @@ -4756,7 +4757,7 @@ def assign_ansible_roles(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def list_ansible_roles(self, synchronous=True, timeout=None, **kwargs): - """List all Ansible Roles assigned to a Host + """List all Ansible Roles assigned to a Host. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4775,7 +4776,7 @@ def list_ansible_roles(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def play_ansible_roles(self, synchronous=True, timeout=None, **kwargs): - """Play all assigned ansible roles on a Host + """Play all assigned ansible roles on a Host. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4794,7 +4795,7 @@ def play_ansible_roles(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout)['task_id'] def list_provisioning_templates(self, synchronous=True, timeout=None, **kwargs): - """List all Provisioning templates assigned to a Host + """List all Provisioning templates assigned to a Host. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -4981,9 +4982,7 @@ def read(self, entity=None, attrs=None, ignore=None, params=None): return super().read(entity, attrs, ignore, params) def search_normalize(self, results): - """Append host id to search results to be able to initialize found - :class:`Interface` successfully - """ + """Append host id to search results to initialize found :class:`Interface` successfully.""" for interface in results: interface['host_id'] = self.host.id return super().search_normalize(results) @@ -5083,6 +5082,7 @@ def update_payload(self, fields=None): def create_payload(self): """Wrap submitted data within an extra dict. + For more information, see `Bugzilla #1151220 `_. """ @@ -5090,6 +5090,7 @@ def create_payload(self): def read(self, entity=None, attrs=None, ignore=None, params=None): """Make sure, password, organization and location is in the ignore list for read. + For more information, see `Bugzilla #1779642 `_. """ @@ -5193,7 +5194,6 @@ class Media( .. NOTE:: The ``path_`` field is named as such due to a naming conflict with :meth:`nailgun.entity_mixins.Entity.path`. - """ def __init__(self, server_config=None, **kwargs): @@ -5348,7 +5348,6 @@ class OperatingSystemParameter(Entity, EntityCreateMixin, EntityDeleteMixin, Ent ``organization`` must be passed in when this entity is instantiated. :raises: ``TypeError`` if ``operatingsystem`` is not passed in. - """ def __init__(self, server_config=None, **kwargs): @@ -5573,7 +5572,7 @@ def sca_enable(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def repo_discover(self, synchronous=True, timeout=None, **kwargs): - """repo discovery. + """Repo discovery. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -5627,7 +5626,7 @@ def sca_eligible(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def subscriptions(self, synchronous=True, timeout=None, **kwargs): - """Helper for getting subscriptions from organization. + """Get subscriptions from organization. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -5662,7 +5661,7 @@ def rh_cloud_download_report(self, destination, **kwargs): tarfile.write(response.content) def rh_cloud_generate_report(self, synchronous=True, timeout=None, **kwargs): - """Start RHCloud Inventory report generation process + """Start RHCloud Inventory report generation process. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -5681,7 +5680,7 @@ def rh_cloud_generate_report(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def rh_cloud_inventory_sync(self, synchronous=True, timeout=None, **kwargs): - """Start inventory synchronization + """Start inventory synchronization. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -5726,6 +5725,7 @@ def __init__(self, server_config=None, **kwargs): def read(self, entity=None, attrs=None, ignore=None, params=None): """Fetch as many attributes as possible for this entity. + Since operatingsystem is needed to instanciate, prepare the entity accordingly. """ @@ -5736,8 +5736,9 @@ def read(self, entity=None, attrs=None, ignore=None, params=None): return super().read(entity, attrs, ignore, params) def update_payload(self, fields=None): - """Wrap payload in ``os_default_template`` - relates to `Redmine #21169`_. + """Wrap payload in ``os_default_template``. + + Relates to `Redmine #21169`_. .. _Redmine #21169: http://projects.theforeman.org/issues/21169 """ @@ -5771,7 +5772,7 @@ def __init__(self, server_config=None, **kwargs): } def create_payload(self): - """Remove ``smart_class_parameter_id``""" + """Remove ``smart_class_parameter_id``.""" payload = super().create_payload() if hasattr(self, 'smart_class_parameter'): del payload['smart_class_parameter_id'] @@ -5840,7 +5841,9 @@ def __init__(self, server_config=None, **kwargs): } def read(self, entity=None, attrs=None, ignore=None, params=None): - """Ignore path related fields as they're never returned by the server + """Read parameter from server. + + Ignore path related fields as they're never returned by the server and are only added to entity to be able to use proper path. """ entity = entity or self.entity_with_parent(**{self._parent_type: self._parent_id}) @@ -5950,7 +5953,7 @@ def read(self, entity=None, attrs=None, ignore=None, params=None): return result def search(self, fields=None, query=None, filters=None): - """Search for entities with missing attribute + """Search for entities with missing attribute. :param fields: A set naming which fields should be used when generating a search query. If ``None``, all values on the entity are used. If @@ -6037,7 +6040,7 @@ def path(self, which=None): return super().path(which) def destroy(self, synchronous=True, timeout=None, **kwargs): - """Helper to destroy one or more products. + """Destroy one or more products. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -6056,7 +6059,7 @@ def destroy(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def sync(self, synchronous=True, timeout=None, **kwargs): - """Helper to sync one or more products. + """Sync one or more products. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -6075,7 +6078,7 @@ def sync(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def http_proxy(self, synchronous=True, timeout=None, **kwargs): - """Helper to update the http proxy configuration on the repositories of one or more products. + """Update the http proxy configuration on the repositories of one or more products. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -6094,7 +6097,7 @@ def http_proxy(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def sync_plan(self, synchronous=True, timeout=None, **kwargs): - """Helper to sync one or more products. + """Sync one or more products. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -6129,7 +6132,6 @@ class PartitionTable( Note: Having a name length of 2 had failures again. Updating the length to 4. - """ def __init__(self, server_config=None, **kwargs): @@ -6171,7 +6173,8 @@ def __init__(self, server_config=None, **kwargs): super().__init__(server_config, **kwargs) def search_normalize(self, results): - """Flattens results. + """Flatten results. + :meth:`nailgun.entity_mixins.EntitySearchMixin.search_normalize` expects structure like list(dict_1(name: class_1), dict_2(name: class_2)), @@ -6183,6 +6186,7 @@ def search_normalize(self, results): def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. + The format of the returned path depends on the value of ``which``: smart_class_parameters @@ -6196,7 +6200,7 @@ def path(self, which=None): return super().path(which) def list_scparams(self, synchronous=True, timeout=None, **kwargs): - """List of smart class parameters for a specific Puppet class + """List of smart class parameters for a specific Puppet class. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -6373,7 +6377,7 @@ def __init__(self, server_config=None, **kwargs): super().__init__(server_config, **kwargs) def cancel(self, synchronous=True, timeout=None, **kwargs): - """Helper for canceling a recurring logic + """Cancel a recurring logic. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -6393,6 +6397,7 @@ def cancel(self, synchronous=True, timeout=None, **kwargs): def path(self, which=None): """Extend ``nailgun.entity_mixins.RecurringLogic.path``. + The format of the returned path depends on the value of ``which``: cancel @@ -6437,8 +6442,9 @@ def __init__(self, server_config=None, **kwargs): super().__init__(server_config, **kwargs) def create_payload(self): - """Wrap submitted data within an extra dict. In addition, - rename the ``activation_keys_ids`` field to ``activation_keys``. + """Wrap submitted data within an extra dict. + + In addition, rename the ``activation_keys_ids`` field to ``activation_keys``. """ payload = super().create_payload() @@ -6447,8 +6453,10 @@ def create_payload(self): return payload def read(self, entity=None, attrs=None, ignore=None, params=None): - """Override :meth:`nailgun.entity_mixins.EntityReadMixin.read` to ignore - all the fields and returns 'registration_command' output in dict + """Read registration command from server. + + Override :meth:`nailgun.entity_mixins.EntityReadMixin.read` to ignore + all the fields and returns 'registration_command' output in dict. """ if attrs is None: attrs = self.read_json() @@ -6577,7 +6585,9 @@ def path(self, which=None): return super().path(which) def read(self, entity=None, attrs=None, ignore=None, params=None): - """Ignore ``organization`` field as it's never returned by the server + """Read repository from server. + + Ignore ``organization`` field as it's never returned by the server and is only added to entity to be able to use organization path dependent helpers and also upstream_password as it is not returned for security reasons. @@ -6620,7 +6630,7 @@ def errata(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def sync(self, synchronous=True, timeout=None, **kwargs): - """Helper for syncing an existing repository. + """Sync an existing repository. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -6690,7 +6700,7 @@ def import_uploads( timeout=None, **kwargs, ): - """Import uploads into a repository + """Import uploads into a repository. It expects either a list of uploads or upload_ids (but not both). @@ -6720,7 +6730,7 @@ def import_uploads( return json def remove_content(self, synchronous=True, timeout=None, **kwargs): - """Remove content from a repository + """Remove content from a repository. It expects content/packages/docker manifests ids sent as data. Here is an example of how to use this method:: @@ -6744,7 +6754,7 @@ def remove_content(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def packages(self, synchronous=True, timeout=None, **kwargs): - """List packages associated with repository + """List packages associated with repository. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -6763,7 +6773,7 @@ def packages(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def module_streams(self, synchronous=True, timeout=None, **kwargs): - """List module_streams associated with repository + """List module_streams associated with repository. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -6782,7 +6792,7 @@ def module_streams(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def files(self, synchronous=True, timeout=None, **kwargs): - """List files associated with repository + """List files associated with repository. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -6802,7 +6812,7 @@ def files(self, synchronous=True, timeout=None, **kwargs): class RepositorySet(Entity, EntityReadMixin, EntitySearchMixin): - """A representation of a Repository Set entity""" + """A representation of a Repository Set entity.""" def __init__(self, server_config=None, **kwargs): self._fields = { @@ -6831,13 +6841,12 @@ def __init__(self, server_config=None, **kwargs): } def available_repositories(self, **kwargs): - """Lists available repositories for the repository set + """List available repositories for the repository set. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. - """ if 'data' not in kwargs: kwargs['data'] = {} @@ -6848,9 +6857,9 @@ def available_repositories(self, **kwargs): return _handle_response(response, self._server_config) def enable(self, synchronous=True, timeout=None, **kwargs): - """Enables the RedHat Repository + """Enable a RedHat Repository. - RedHat Repos needs to be enabled first, so that we can sync it. + RedHat repos needs to be enabled first, so that we can sync it. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -6872,7 +6881,7 @@ def enable(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def disable(self, synchronous=True, timeout=None, **kwargs): - """Disables the RedHat Repository + """Disables a RedHat Repository. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -7045,7 +7054,7 @@ def path(self, which=None): return super().path(which) def enable_connector(self, synchronous=True, timeout=None, **kwargs): - """Function to enable RH Cloud connector""" + """Enable RH Cloud connector.""" kwargs = kwargs.copy() kwargs.update(self._server_config.get_client_kwargs()) kwargs['data'] = {} @@ -7112,6 +7121,7 @@ def update_payload(self, fields=None): def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. + The format of the returned path depends on the value of ``which``: clone @@ -7125,7 +7135,7 @@ def path(self, which=None): return super().path(which) def clone(self, synchronous=True, timeout=None, **kwargs): - """Helper to clone an existing Role + """Clone an existing Role. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -7162,8 +7172,10 @@ def __init__(self, server_config=None, **kwargs): super().__init__(server_config, **kwargs) def read(self, entity=None, attrs=None, ignore=None, params=None): - """Override :meth:`nailgun.entity_mixins.EntityReadMixin.read` to ignore - the ``created_at and updated_at`` + """Read setting from server. + + Override :meth:`nailgun.entity_mixins.EntityReadMixin.read` to ignore + the ``created_at and updated_at``. """ if ignore is None: ignore = set() @@ -7206,6 +7218,7 @@ def __init__(self, server_config=None, **kwargs): def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. + The format of the returned path depends on the value of ``which``: refresh @@ -7219,7 +7232,7 @@ def path(self, which=None): return super().path(which) def refresh(self, synchronous=True, timeout=None, **kwargs): - """Refresh Capsule features + """Refresh Capsule features. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -7268,8 +7281,7 @@ def import_puppetclasses(self, synchronous=True, timeout=None, **kwargs): ) def read(self, entity=None, attrs=None, ignore=None, params=None): - """Ignore ``download_policy`` field as it's never returned by the - server. + """Ignore ``download_policy`` field as it's never returned by the server. For more information, see `Bugzilla #1486609 `_. @@ -7341,6 +7353,7 @@ class Snapshot( EntityUpdateMixin, ): """A representation of a Snapshot entity. + Foreman_snapshot as mentioned in the plugin: https://github.com/ATIX-AG/foreman_snapshot_management # Read Snapshot @@ -7354,7 +7367,7 @@ class Snapshot( # Revert Snapshot Snapshot(host=, id=).revert() # Delete Snapshot - Snapshot(host=, id=).delete() + Snapshot(host=, id=).delete(). """ def __init__(self, server_config=None, **kwargs): @@ -7371,8 +7384,9 @@ def __init__(self, server_config=None, **kwargs): def path(self, which=None): """Extend nailgun.entity_mixins.Entity.path. + revert - /api/v2/hosts//snapshots//revert + /api/v2/hosts//snapshots//revert. """ if which == "revert": return f'{super().path(which="self")}/{which}' @@ -7403,20 +7417,16 @@ def read(self, entity=None, attrs=None, ignore=None, params=None): return super().read(entity, attrs, ignore, params) def search_normalize(self, results): - """Append host id to search results to be able to initialize found - :class:`Snapshot` successfully - """ - + """Append host id to search results to initialize found :class:`Snapshot` successfully.""" for snapshot in results: snapshot['host_id'] = self.host.id return super().search_normalize(results) def revert(self, **kwargs): - """Rollbacks the Snapshot + """Rollback the Snapshot. Makes HTTP PUT call to revert the snapshot. """ - kwargs.update(self._server_config.get_client_kwargs()) response = client.put(self.path('revert'), **kwargs) return _handle_response(response, self._server_config) @@ -7428,7 +7438,6 @@ class SSHKey(Entity, EntityCreateMixin, EntityDeleteMixin, EntityReadMixin, Enti ``user`` must be passed in when this entity is instantiated. :raises: ``TypeError`` if ``user`` is not passed in. - """ def __init__(self, server_config=None, **kwargs): @@ -7467,9 +7476,7 @@ def read(self, entity=None, attrs=None, ignore=None, params=None): return super().read(entity, attrs, ignore, params) def search_normalize(self, results): - """Append user id to search results to be able to initialize found - :class:`User` successfully - """ + """Append user id to search results to initialize found :class:`User` successfully.""" for sshkey in results: sshkey['user_id'] = self.user.id return super().search_normalize(results) @@ -7628,7 +7635,7 @@ def path(self, which=None): return super().path(which) def _org_path(self, which, payload): - """A helper method for generating paths with organization IDs in them. + """Generate paths with organization IDs in them. :param which: A path such as "manifest_history" that has an organization ID in it. @@ -7685,7 +7692,9 @@ def manifest_history(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def read(self, entity=None, attrs=None, ignore=None, params=None): - """Ignore ``organization`` field as it's never returned by the server + """Read subscription from server. + + Ignore ``organization`` field as it's never returned by the server and is only added to entity to be able to use organization path dependent helpers. """ @@ -7763,7 +7772,6 @@ class SyncPlan( ``organization`` must be passed in when this entity is instantiated. :raises: ``TypeError`` if ``organization`` is not passed in. - """ def __init__(self, server_config=None, **kwargs): @@ -7979,7 +7987,7 @@ def path(self, which=None): return super().path(which) def imports(self, synchronous=True, timeout=None, **kwargs): - """Helper to import templates + """Import templates. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -7997,7 +8005,7 @@ def imports(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def exports(self, synchronous=True, timeout=None, **kwargs): - """Helper to export templates + """Export templates. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -8037,7 +8045,6 @@ class TemplateKind(Entity, EntityReadMixin, EntitySearchMixin): """A representation of a Template Kind entity. Unusually, the ``/api/v2/template_kinds/:id`` path is totally unsupported. - """ def __init__(self, server_config=None, **kwargs): @@ -8140,7 +8147,6 @@ class User( guaranteed to exist and be functioning. Thus, ``auth_source`` is set to "1" by default for a practical reason: it is much easier to use internal authentication than to spawn LDAP authentication servers for each new user. - """ def __init__(self, server_config=None, **kwargs): @@ -8282,19 +8288,15 @@ def path(self, which=None): return super().path(which) def create_payload(self): - """ - Wraps config in extra dict - """ + """Wrap config in extra dict.""" return {'foreman_virt_who_configure_config': super().create_payload()} def update_payload(self, fields=None): - """ - Wraps config in extra dict - """ + """Wrap config in extra dict.""" return {'foreman_virt_who_configure_config': super().update_payload(fields)} def deploy_script(self, synchronous=True, timeout=None, **kwargs): - """Helper for Config's deploy_script method. + """Deploy script for a VirtWho Config. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -8313,9 +8315,10 @@ def deploy_script(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def read(self, entity=None, attrs=None, ignore=None, params=None): - """ + """Read subscription from server. + Override :meth:`nailgun.entity_mixins.EntityReadMixin.read` to ignore - the ``hypervisor_password`` + the ``hypervisor_password``. """ if not ignore: ignore = set() @@ -8324,7 +8327,8 @@ def read(self, entity=None, attrs=None, ignore=None, params=None): return super().read(entity, attrs, ignore, params) def get_organization_configs(self, synchronous=True, timeout=None, **kwargs): - """ + """Get all virt-who configurations per organization. + Unusually, the ``/foreman_virt_who_configure/api/v2/organizations/ :organization_id/configs`` path is totally unsupported. Support to List of virt-who configurations per organization. @@ -8385,8 +8389,10 @@ def create(self, create_missing=None): ).read() def read(self, entity=None, attrs=None, ignore=None, params=None): - """Override :meth:`nailgun.entity_mixins.EntityReadMixin.read` to ignore - the ``scap_file`` + """Read subscription from server. + + Override :meth:`nailgun.entity_mixins.EntityReadMixin.read` to ignore + the ``scap_file``. """ if ignore is None: ignore = set() @@ -8395,6 +8401,7 @@ def read(self, entity=None, attrs=None, ignore=None, params=None): def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. + The format of the returned path depends on the value of ``which``: xml @@ -8413,7 +8420,7 @@ def update(self, fields=None): return self.read() def xml(self, synchronous=True, timeout=None, **kwargs): - """Download an SCAP content as XML + """Download an SCAP content as XML. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -8487,7 +8494,8 @@ def __init__(self, server_config=None, **kwargs): super().__init__(server_config, **kwargs) def create(self, create_missing=None): - """Overrides creation of Webhooks + """Override creation of Webhooks. + Before creating the Webhook, we want to call get_events to get a valid list of events to pass into our POST call. @@ -8500,8 +8508,10 @@ def create(self, create_missing=None): ).read() def read(self, entity=None, attrs=None, ignore=None, params=None): - """Override :meth:`nailgun.entity_mixins.EntityReadMixin.read` to ignore - the ``webhook_template_id``, ``password``, and ``proxy_authorization`` + """Read subscription from server. + + Override :meth:`nailgun.entity_mixins.EntityReadMixin.read` to ignore + the ``webhook_template_id``, ``password``, and ``proxy_authorization``. """ if ignore is None: ignore = set() @@ -8512,6 +8522,7 @@ def read(self, entity=None, attrs=None, ignore=None, params=None): def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. + The format of the returned path depends on the value of ``which``: events @@ -8525,7 +8536,9 @@ def path(self, which=None): return super().path(which) def get_events(self, synchronous=True, timeout=None, **kwargs): - """GET api/webhooks/events returns the list of all valid events + """Get all valid events for a Webhook. + + GET api/webhooks/events returns the list of all valid events we can use to create a Webhook. Calling this list before our create allows us to test all possible events. @@ -8556,6 +8569,7 @@ def __init__(self, server_config=None, **kwargs): def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. + The format of the returned path depends on the value of ``which``: fetch @@ -8571,7 +8585,7 @@ def path(self, which=None): return super().path(which) def fetch(self, synchronous=True, timeout=None, **kwargs): - """Helper for fetching all ansible playbooks. + """Fetch all ansible playbooks. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -8590,7 +8604,7 @@ def fetch(self, synchronous=True, timeout=None, **kwargs): return _handle_response(response, self._server_config, synchronous, timeout) def sync(self, synchronous=True, timeout=None, **kwargs): - """Helper to sync ansible playbooks. + """Sync ansible playbooks. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if @@ -8627,6 +8641,7 @@ def __init__(self, server_config=None, **kwargs): def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. + The format of the returned path depends on the value of ``which``: sync @@ -8640,7 +8655,7 @@ def path(self, which=None): return super().path(which) def sync(self, synchronous=True, timeout=None, **kwargs): - """Helper to sync ansible roles from a proxy. + """Sync ansible roles from a proxy. AnsibleRoles.sync(data={'proxy_id': "target_sat.ip", 'role_names': ["role_name"]}) diff --git a/nailgun/entity_fields.py b/nailgun/entity_fields.py index a30ae568..5276382c 100644 --- a/nailgun/entity_fields.py +++ b/nailgun/entity_fields.py @@ -51,7 +51,7 @@ class Field: - """Base class to implement other fields + """Base class to implement other fields. Record this field's attributes. @@ -76,7 +76,7 @@ def __init__(self, required=False, choices=None, default=_SENTINEL, unique=False class BooleanField(Field): - """Field that represents a boolean""" + """Field that represents a boolean.""" def gen_value(self): """Return a value suitable for a :class:`BooleanField`.""" @@ -85,7 +85,7 @@ def gen_value(self): class EmailField(Field): - """Field that represents an email""" + """Field that represents an email.""" def gen_value(self): """Return a value suitable for a :class:`EmailField`.""" @@ -94,7 +94,7 @@ def gen_value(self): class FloatField(Field): - """Field that represents a float""" + """Field that represents a float.""" def gen_value(self): """Return a value suitable for a :class:`FloatField`.""" @@ -135,7 +135,6 @@ class StringField(Field): (e.g. ``'utf8'``) or a tuple of string types. This argument is passed through to FauxFactory's ``gen_string`` method, so this method accepts all string types which that method does. - """ def __init__(self, length=(1, 30), str_type=('utf8',), *args, **kwargs): @@ -159,7 +158,7 @@ def gen_value(self): class DateField(Field): - """Field that represents a date""" + """Field that represents a date.""" def __init__(self, min_date=None, max_date=None, *args, **kwargs): # If ``None`` is passed then ``FauxFactory`` will deal with it. @@ -173,7 +172,7 @@ def gen_value(self): class DateTimeField(Field): - """Field that represents a datetime""" + """Field that represents a datetime.""" def __init__(self, min_date=None, max_date=None, *args, **kwargs): # If ``None`` is passed then ``FauxFactory`` will deal with it. @@ -196,7 +195,7 @@ def gen_value(self): class IPAddressField(StringField): - """Field that represents an IP address""" + """Field that represents an IP address.""" def gen_value(self): """Return a value suitable for a :class:`IPAddressField`.""" @@ -204,7 +203,7 @@ def gen_value(self): class NetmaskField(StringField): - """Field that represents an netmask""" + """Field that represents an netmask.""" def gen_value(self): """Return a value suitable for a :class:`NetmaskField`.""" @@ -212,11 +211,11 @@ def gen_value(self): class ListField(Field): - """Field that represents a list of strings""" + """Field that represents a list of strings.""" class MACAddressField(StringField): - """Field that represents a MAC address""" + """Field that represents a MAC address.""" def gen_value(self): """Return a value suitable for a :class:`MACAddressField`.""" @@ -230,7 +229,6 @@ class OneToOneField(Field): :param nailgun.entity_mixins.Entity entity: The entity to which this field points. - """ def __init__(self, entity, *args, **kwargs): @@ -247,7 +245,6 @@ class OneToManyField(Field): :param nailgun.entity_mixins.Entity entity: The entities to which this field points. - """ def __init__(self, entity, *args, **kwargs): @@ -260,7 +257,7 @@ def gen_value(self): class URLField(StringField): - """Field that represents an URL + """Field that represents an URL. :param str scheme: The URL scheme can be one of ['http', 'https', 'ftp'] """ diff --git a/nailgun/entity_mixins.py b/nailgun/entity_mixins.py index 5d724844..12dff93f 100644 --- a/nailgun/entity_mixins.py +++ b/nailgun/entity_mixins.py @@ -43,7 +43,7 @@ def call_entity_method_with_timeout(entity_callable, timeout=300, **kwargs): - """Call Entity callable with a custom timeout + """Call Entity callable with a custom timeout. :param entity_callable, the entity method object to call :param timeout: the time to wait for the method call to finish @@ -91,7 +91,6 @@ def _poll_task(task_id, server_config, poll_rate=None, timeout=None, must_succee import. Placing the implementation of :meth:`nailgun.entities.ForemanTask.poll` here allows both that method and the mixins in this module to use the same logic. - """ if poll_rate is None: poll_rate = TASK_POLL_RATE @@ -146,7 +145,6 @@ def _make_entity_from_id(entity_cls, entity_obj_or_id, server_config): object or an entity ID. :returns: An ``entity_cls`` object. :rtype: nailgun.entity_mixins.Entity - """ if isinstance(entity_obj_or_id, entity_cls): return entity_obj_or_id @@ -161,7 +159,6 @@ def _make_entities_from_ids(entity_cls, entity_objs_and_ids, server_config): :class:`nailgun.entity_mixins.Entity` objects and/or entity IDs. All of the entities in this iterable should be of type ``entity_cls``. :returns: A list of ``entity_cls`` objects. - """ return [ _make_entity_from_id(entity_cls, entity_or_id, server_config) @@ -200,7 +197,6 @@ def _payload(fields, values): :param values: A value like what is returned by :meth:`nailgun.entity_mixins.Entity.get_values`. :returns: A dict mapping field names to field values. - """ for field_name, field in fields.items(): if field_name in values: @@ -211,7 +207,7 @@ def _payload(fields, values): elif isinstance(field, ListField): def parse(obj): - """parse obj payload if it is an Entity""" + """Parse obj payload if it is an Entity.""" if isinstance(obj, Entity): return _payload(obj.get_fields(), obj.get_values()) return obj @@ -230,7 +226,6 @@ def _get_server_config(): ``None``, or whatever is returned by :meth:`nailgun.config.ServerConfig.get` otherwise. :rtype: nailgun.config.ServerConfig - """ if DEFAULT_SERVER_CONFIG is not None: return DEFAULT_SERVER_CONFIG @@ -253,7 +248,6 @@ def _get_entity_id(field_name, attrs): :param field_name: A string. The name of a field. :param attrs: A dict. A JSON payload as returned from a server. :returns: Either an entity ID or None. - """ field_name_id = f'{field_name}_id' if field_name in attrs: @@ -289,7 +283,6 @@ def _get_entity_ids(field_name, attrs): :param field_name: A string. The name of a field. :param attrs: A dict. A JSON payload as returned from a server. :returns: An iterable of entity IDs. - """ field_name_ids = f'{field_name}_ids' plural_field_name = pluralize(field_name) @@ -392,7 +385,6 @@ class Entity: non-existent field. :raises nailgun.entity_mixins.BadValueError: If an inappropriate value is assigned to a field. - """ def __init__(self, server_config=None, **kwargs): @@ -530,6 +522,7 @@ def get_values(self): return attrs def __repr__(self): + """Return a string representation of the current object.""" kv_pairs = ", ".join( f"{key}={value!r}" for key, value in self.get_values().items() @@ -538,7 +531,9 @@ def __repr__(self): return f'{self.__module__}.{type(self).__name__}({kv_pairs})' def to_json(self): - r"""Create a JSON encoded string with Entity properties. Ex: + r"""Create a JSON encoded string with Entity properties. + + Ex: >>> from nailgun import entities, config >>> kwargs = { @@ -555,6 +550,7 @@ def to_json(self): def to_json_dict(self, filter_fcn=None): """Create a dict with Entity properties for json encoding. + It can be overridden by subclasses for each standard serialization doesn't work. By default it call _to_json_dict on OneToOne fields and build a list calling the same method on each OneToMany object's @@ -591,8 +587,9 @@ def to_json_dict(self, filter_fcn=None): return json_dct def __eq__(self, other): - """Compare two entities based on their properties. Even nested - objects are considered for equality + """Compare two entities based on their properties. + + Even nested objects are considered for equality. :param other: entity to compare self to :return: boolean indicating if entities are equal or not @@ -602,7 +599,8 @@ def __eq__(self, other): return self.to_json_dict() == other.to_json_dict() def compare(self, other, filter_fcn=None): - """Returns True if properties can be compared in terms of eq. + """Return True if properties can be compared in terms of eq. + Entity's Fields can be filtered accordingly to 'filter_fcn'. This callable receives field's name as first parameter and field itself as second parameter. @@ -610,7 +608,7 @@ def compare(self, other, filter_fcn=None): comparison and False otherwise. If not provided field's marked as unique will not be compared by default. 'id' and 'name' are examples of unique fields commonly ignored. Check Entities fields for fields marked - with 'unique=True' + with 'unique=True'. :param other: entity to compare @@ -622,7 +620,7 @@ def compare(self, other, filter_fcn=None): if filter_fcn is None: def filter_unique(_, field): - """Filter function for unique fields""" + """Filter function for unique fields.""" return not field.unique filter_fcn = filter_unique @@ -630,7 +628,7 @@ def filter_unique(_, field): return self.to_json_dict(filter_fcn) == other.to_json_dict(filter_fcn) def entity_with_parent(self, **parent): - """Returns modified entity by adding parent entity + """Return modified entity by adding parent entity. :parent dict: optional, The key/value pair of base entity else fetch from the fields """ @@ -651,7 +649,7 @@ def entity_with_parent(self, **parent): class EntityDeleteMixin: - """This mixin provides the ability to delete an entity. + """Provide the ability to delete an entity. The methods provided by this class work together. The call tree looks like this:: @@ -664,7 +662,6 @@ class EntityDeleteMixin: Make an HTTP DELETE request to the server. :meth:`delete` Check the server's response for errors and decode the response. - """ def delete_raw(self): @@ -698,7 +695,6 @@ def delete(self, synchronous=True, timeout=None): out. """ - response = self.delete_raw() response.raise_for_status() @@ -717,7 +713,7 @@ def delete(self, synchronous=True, timeout=None): class EntityReadMixin: - """This mixin provides the ability to read an entity. + """Provide the ability to read an entity. The methods provided by this class work together. The call tree looks like this:: @@ -736,7 +732,6 @@ class EntityReadMixin: server. See the individual methods for more detailed information. - """ def read_raw(self, params=None): @@ -849,7 +844,7 @@ def read(self, entity=None, attrs=None, ignore=None, params=None): class EntityCreateMixin: - """This mixin provides the ability to create an entity. + """Provide the ability to create an entity. The methods provided by this class work together. The call tree looks like this:: @@ -878,7 +873,6 @@ class EntityCreateMixin: server. See the individual methods for more detailed information. - """ def create_missing(self): @@ -985,7 +979,7 @@ def create(self, create_missing=None): class EntityUpdateMixin: - """This mixin provides the ability to update an entity. + """Provide the ability to update an entity. The methods provided by this class work together. The call tree looks like this:: @@ -1007,7 +1001,6 @@ class EntityUpdateMixin: the created entity and populate its fields. See the individual methods for more detailed information. - """ def update_payload(self, fields=None): @@ -1084,7 +1077,7 @@ def update(self, fields=None): class EntitySearchMixin: - """This mixin provides the ability to search for entities. + """Provide the ability to search for entities. The methods provided by this class work together. The call tree looks like this:: @@ -1113,7 +1106,6 @@ class EntitySearchMixin: Read all ``entities`` and locally filter them. See the individual methods for more detailed information. - """ def search_payload(self, fields=None, query=None): @@ -1444,12 +1436,11 @@ def search_filter(entities, filters): def to_json_serializable(obj): - """Transforms obj into a json serializable object. + """Transform obj into a json serializable object. :param obj: entity or any json serializable object :return: serializable object - """ if isinstance(obj, Entity): return obj.to_json_dict() diff --git a/pyproject.toml b/pyproject.toml index 6326758f..708a464e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,7 +35,7 @@ select = [ "C", # complexity "C4", # flake8-comprehensions "COM818", # Trailing comma on bare tuple prohibited - # "D", # docstrings + "D", # docstrings "E", # pycodestyle "F", # pyflakes/autoflake "G", # flake8-logging-format diff --git a/tests/test_client.py b/tests/test_client.py index 0de36914..cd5bb2b7 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -30,7 +30,7 @@ def test_false(self): self.assertFalse(client._content_type_is_json(kwargs)) def test_false_with_no_headers(self): - """If no headers passed should return None""" + """If no headers passed should return None.""" self.assertFalse(client._content_type_is_json({})) @@ -63,6 +63,7 @@ class ClientTestCase(TestCase): """Tests for functions in :mod:`nailgun.client`.""" def setUp(self): + """Set up some common variables.""" self.bogus_url = gen_alpha() self.mock_response = mock.Mock(status_code=200) diff --git a/tests/test_config.py b/tests/test_config.py index 5ed49783..457716a5 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -44,7 +44,6 @@ def _convert_bsc_attrs(bsc_attrs): :class:`nailgun.config.BaseServerConfig`. :returns: A dict of attributes as is returned by ``vars(BaseServerConfig(bsc_attrs))``. - """ if 'version' in bsc_attrs: bsc_attrs = bsc_attrs.copy() # shadow the passed in dict @@ -69,6 +68,7 @@ def test_init(self): def test_init_invalid(self): """Test instantiating :class: `nailgun.config.BaseServerConfig`. + Assert that configs with invalid versions do not load. """ with self.assertRaises(InvalidVersion): @@ -171,7 +171,7 @@ def test_init(self): ) def test_raise_config_file_error(self): - """Should raise error if path not found""" + """Should raise error if path not found.""" with self.assertRaises(ConfigFileError): _get_config_file_path('foo', 'bar') diff --git a/tests/test_entities.py b/tests/test_entities.py index 8ca03edd..c800aaeb 100644 --- a/tests/test_entities.py +++ b/tests/test_entities.py @@ -38,7 +38,7 @@ def make_entity(cls, **kwargs): - """Helper function to create entity with dummy ServerConfig""" + """Create entity with dummy ServerConfig.""" cfg = config.ServerConfig(url='https://foo.bar', verify=False, auth=('foo', 'bar')) return cls(cfg, **kwargs) @@ -48,7 +48,6 @@ def _get_required_field_names(entity): :param nailgun.entity_mixins.Entity entity: This entity is inspected. :returns: A set in the form ``{'field_name_1', 'field_name_2', …}``. - """ return { field_name for field_name, field in entity.get_fields().items() if field.required is True @@ -69,7 +68,6 @@ class InitTestCase(TestCase): The tests in this class are a sanity check. They simply check to see if you can instantiate each entity. - """ @classmethod @@ -82,7 +80,6 @@ def test_init_succeeds(self): Assert that the returned object is an instance of the class that produced it. - """ entities_ = [ (entity, {}) @@ -224,7 +221,6 @@ def test_required_params(self): Assert that ``TypeError`` is raised if the required extra parameters are not provided. - """ for entity in ( entities.ContentViewComponent, @@ -395,7 +391,6 @@ def test_no_such_path_error(self): """Trigger :class:`nailgun.entity_mixins.NoSuchPathError` exceptions. Do this by calling ``entity().path(which=…)``. - """ for entity, which in ( (entities.ActivationKey, 'releases'), @@ -429,9 +424,10 @@ def test_no_such_path_error(self): def test_arfreport(self): """Test :meth:`nailgun.entities.ArfReport.path`. + Assert that the following return appropriate paths: * ``ArfReport(id=…).path()`` - * ``ArfReport(id=…).path('download_html')`` + * ``ArfReport(id=…).path('download_html')``. """ self.assertIn('compliance/arf_reports/1', entities.ArfReport(self.cfg, id=1).path()) for which in ['download_html']: @@ -443,7 +439,7 @@ def test_arfreport(self): self.assertRegex(path, fr'{which}$') def test_os_default_template(self): - """Test ``nailgun.entities.OSDefaultTemplate.path`` + """Test ``nailgun.entities.OSDefaultTemplate.path``. Assert that the following return appropriate paths: @@ -461,7 +457,6 @@ def test_externalusergroup(self): * ``ExternalUserGroup(id=…,usergroup=…).path()`` * ``ExternalUserGroup(id=…,usergroup=…).path('refresh')`` - """ self.assertIn( 'usergroups/1/external_usergroups/2', @@ -485,7 +480,6 @@ def test_repository_set(self): * ``RepositorySet(id=…).path('available_repositories')`` * ``RepositorySet(id=…).path('disable')`` * ``RepositorySet(id=…).path('enable')`` - """ self.assertIn( '/repository_sets/2', entities.RepositorySet(self.cfg, id=2, product=1).path() @@ -506,7 +500,6 @@ def test_snapshot(self): * ``Snapshot(id=…).path()`` * ``Snapshot(id=…).path('revert')`` - """ self.assertIn( 'hosts/1/snapshots/snapshot-2', @@ -529,7 +522,6 @@ def test_sync_plan(self): * ``SyncPlan(id=…).path()`` * ``SyncPlan(id=…).path('add_products')`` * ``SyncPlan(id=…).path('remove_products')`` - """ self.assertIn( 'organizations/1/sync_plans/2', @@ -553,7 +545,6 @@ def test_subscription(self): * ``Subscription(organization=…).path('manifest_history')`` * ``Subscription(organization=…).path('refresh_manifest')`` * ``Subscription(organization=…).path('upload')`` - """ sub = entities.Subscription(self.cfg, organization=gen_integer(1, 100)) for which in ('delete_manifest', 'manifest_history', 'refresh_manifest', 'upload'): @@ -569,7 +560,6 @@ def test_capsule(self): * ``Capsule().path('content_lifecycle_environments')`` * ``Capsule().path('content_sync')`` - """ capsule = entities.Capsule(self.cfg, id=gen_integer(1, 100)) for which in ('content_lifecycle_environments', 'content_sync'): @@ -586,7 +576,6 @@ def test_hostsubscription(self): * ``HostSubscription(host=…).path('add_subscriptions')`` * ``HostSubscription(host=…).path('remove_subscriptions')`` - """ sub = entities.HostSubscription(self.cfg, host=gen_integer(1, 100)) for which in ('add_subscriptions', 'remove_subscriptions'): @@ -647,7 +636,6 @@ class CreatePayloadTestCase(TestCase): This class attempts to find such issues by creating an entity, calling :meth:`nailgun.entity_mixins.EntityCreateMixin.create_payload` and asserting that a ``dict`` is returned. - """ @classmethod @@ -850,7 +838,7 @@ def setUpClass(cls): ) def test_auth_source_ldap_v1(self): - """Test ``AuthSourceLDAP(onthefly_register=False).create_missing()``""" + """Test ``AuthSourceLDAP(onthefly_register=False).create_missing()``.""" entity = entities.AuthSourceLDAP(self.cfg, onthefly_register=False) with mock.patch.object(EntityCreateMixin, 'create_missing'): entity.create_missing() @@ -864,7 +852,7 @@ def test_auth_source_ldap_v2(self): self.assertTrue(set(self.AS_LDAP_FIELDS).issubset(entity.get_values())) def test_auth_source_ldap_v3(self): - """Does ``AuthSourceLDAP.create_missing`` overwrite fields?""" + """Check if ``AuthSourceLDAP.create_missing`` overwrite fields.""" attrs = {field: i for i, field in enumerate(self.AS_LDAP_FIELDS)} attrs.update({'onthefly_register': True}) entity = entities.AuthSourceLDAP(self.cfg, **attrs) @@ -968,7 +956,7 @@ def test_domain_v2(self): self.assertTrue(entity.name.islower()) def test_external_usergroup(self): - """Test ``ExternalUserGroup()``""" + """Test ``ExternalUserGroup()``.""" entity = entities.ExternalUserGroup(self.cfg, usergroup=1) with mock.patch.object(EntityCreateMixin, 'create_missing'): entity.create_missing() @@ -999,7 +987,7 @@ def test_host_v1(self): ) def test_host_v2(self): - """Test ``Host()`` with providing all the optional entities unlinked""" + """Test ``Host()`` with providing all the optional entities unlinked.""" org = entities.Organization(self.cfg, id=1) loc = entities.Location(self.cfg, id=1) domain = entities.Domain( @@ -1060,6 +1048,7 @@ def test_host_v2(self): def test_host_v3(self): """Test ``Host()`` providing optional entities with id only. + Check that additional read was called for that entities. """ optional = { @@ -1107,7 +1096,7 @@ def test_lifecycle_environment_v2(self): self.assertEqual(entity.prior, search.return_value[0]) def test_lifecycle_environment_v3(self): - """What happens when the "Library" lifecycle env cannot be found?""" + """Check what happens when the "Library" lifecycle env cannot be found.""" entity = entities.LifecycleEnvironment( self.cfg, name='not Library', @@ -1150,7 +1139,6 @@ def test_entity_arg(self): for the ``entity`` argument. Assert that these entities pass their server configuration objects to the child entities that they create and pass in to the ``entity`` argument. - """ for entity in ( entities.ContentViewFilterRule( @@ -1189,7 +1177,6 @@ def test_attrs_arg_v1(self): This test is only appropriate for entities that override the ``read`` method in order to fiddle with the ``attrs`` argument. - """ for entity in ( # entities.DiscoveryRule, # see test_discovery_rule @@ -1216,7 +1203,6 @@ def test_attrs_arg_v2(self): This test is only appropriate for entities that override the ``read`` method in order to fiddle with the ``attrs`` argument. - """ # test_data is a single-use variable. We use it anyway for formatting # purposes. @@ -1238,7 +1224,6 @@ def test_entity_ids(self): Assert that the returned attributes are renamed to be more regular before calling ``read()``. - """ # test_data is a single-use variable. We use it anyway for formatting # purposes. @@ -1270,7 +1255,6 @@ def test_ignore_arg_v1(self): """Call ``read`` on a variety of entities.``. Assert that the ``ignore`` argument is correctly passed on. - """ for entity, ignored_attrs in ( (entities.AzureRMComputeResource, {'secret_key'}), @@ -1311,7 +1295,6 @@ def test_ignore_arg_v3(self): """Call :meth:`nailgun.entities.AuthSourceLDAP.read`. Assert that the entity ignores the 'account_password' field. - """ with mock.patch.object(EntityUpdateMixin, 'update_json') as u_json: with mock.patch.object(EntityReadMixin, 'read') as read: @@ -1325,7 +1308,6 @@ def test_ignore_arg_v4(self): Assert that entity`s predefined values of ``ignore`` are always correctly passed on. - """ for input_ignore, actual_ignore in ( (None, {'password'}), @@ -1475,7 +1457,6 @@ def test_discovery_rule(self): """Call :meth:`nailgun.entities.DiscoveryRule.read`. Ensure that the ``max_count`` attribute is fetched. - """ with mock.patch.object(EntityUpdateMixin, 'update_json') as u_json: u_json.return_value = {'max_count': 'max_count'} @@ -1488,11 +1469,9 @@ def test_discovery_rule(self): self.assertEqual(u_json.call_args, mock.call([])) def test_product_with_sync_plan(self): - """Call :meth:`nailgun.entities.Product.read` for a product with sync - plan assigned. + """Call :meth:`nailgun.entities.Product.read` for a product with sync plan assigned. Ensure that the sync plan entity was correctly fetched. - """ sync_plan = entities.SyncPlan(self.cfg, id=1, organization=1) product = entities.Product(self.cfg, id=1, organization=1) @@ -1511,7 +1490,6 @@ def test_hostgroup_ignore_root_pass(self): """Call :meth:`nailgun.entities.HostGroup.read`. Assert that the entity ignores the ``root_pass`` field. - """ with mock.patch.object(EntityReadMixin, 'read') as read: with mock.patch.object(EntityReadMixin, 'read_json'): @@ -1521,6 +1499,7 @@ def test_hostgroup_ignore_root_pass(self): def test_http_proxy_ignore_arg(self): """Call :meth:`nailgun.entities.HTTPProxy.read`. + Assert that the entity ignores the ``password, organization and location`` field. """ with mock.patch.object(EntityReadMixin, 'read') as read: @@ -1532,11 +1511,9 @@ def test_http_proxy_ignore_arg(self): self.assertIn('location', read.call_args[0][2]) def test_usergroup_with_external_usergroup(self): - """Call :meth:`nailgun.entities.ExternalUserGroup.read` for a usergroup with external - usergroup assigned. + """Call :meth:`nailgun.entities.ExternalUserGroup.read` with external usergroup assigned. Ensure that the external usergroup entity was correctly fetched. - """ with mock.patch.object(EntityReadMixin, 'read') as read: with mock.patch.object(EntityReadMixin, 'read_json'): @@ -1549,7 +1526,6 @@ def test_subnet(self): """Call :meth:`nailgun.entities.Subnet.read`. Ensure that the ``from_`` attribute is successfully set. - """ with mock.patch.object(EntityReadMixin, 'read_json') as read_json: read_json.return_value = {'from': 'foo'} @@ -1561,9 +1537,7 @@ def test_subnet(self): class SearchTestCase(TestCase): - """Tests for - :meth:`nailgun.entity_mixins.EntitySearchMixin.search`. - """ + """Tests for :meth:`nailgun.entity_mixins.EntitySearchMixin.search`.""" @classmethod def setUpClass(cls): @@ -1571,11 +1545,9 @@ def setUpClass(cls): cls.cfg = config.ServerConfig('http://example.com') def test_product_with_sync_plan(self): - """Call :meth:`nailgun.entities.Product.search` for a product with sync - plan assigned. + """Call :meth:`nailgun.entities.Product.search` for a product with sync plan assigned. Ensure that the sync plan entity was correctly fetched. - """ with mock.patch.object(EntitySearchMixin, 'search_json') as search_json: # Synplan set @@ -1619,11 +1591,9 @@ def test_product_with_sync_plan(self): self.assertIsNone(result[0].sync_plan) def test_host_with_image(self): - """Call :meth:`nailgun.entities.Host.search` for a host with image - assigned. + """Call :meth:`nailgun.entities.Host.search` for a host with image assigned. Ensure that the image entity was correctly fetched. - """ with mock.patch.object(EntitySearchMixin, 'search_json') as search_json: # Image is set @@ -1662,9 +1632,7 @@ def test_host_with_image(self): class SearchNormalizeTestCase(TestCase): - """Tests for - :meth:`nailgun.entity_mixins.EntitySearchMixin.search_normalize`. - """ + """Tests for :meth:`nailgun.entity_mixins.EntitySearchMixin.search_normalize`.""" @classmethod def setUpClass(cls): @@ -1729,8 +1697,7 @@ def test_interface(self): self.assertEqual(args['host_id'], 3) def test_host_with_image(self): - """Call :meth:`nailgun.entities.Host.read` for a host with image - assigned. + """Call :meth:`nailgun.entities.Host.read` for a host with image assigned. Ensure that the image entity was correctly fetched. """ @@ -1837,9 +1804,7 @@ def test_generic(self): self.assertIsInstance(entity(self.cfg, **params).search_payload(), dict) def test_content_view_filter_rule(self): - """errata_id field should be Errata ID when sent to the server, - not DB ID. - """ + """errata_id field should be Errata ID when sent to the server, not DB ID.""" errata_kwargs = { "id": 1, "uuid": "1a321570-cd30-4622-abff-2290b47ef814", @@ -1991,7 +1956,6 @@ def test_discovery_rule_search(self): The field should be renamed from ``search_`` to ``search`` when ``update_payload`` is called. - """ payload = entities.DiscoveryRule( self.cfg, @@ -2005,7 +1969,6 @@ def test_image(self): The field should be renamed from ``path_`` to ``path`` when ``update_payload`` is called. - """ payload = entities.Image( self.cfg, @@ -2018,13 +1981,13 @@ def test_media_path(self): The field should be renamed from ``path_`` to ``path`` when ``update_payload`` is called. - """ payload = entities.Media(self.cfg, path_='foo').update_payload() self.assertNotIn('path_', payload['medium']) self.assertIn('path', payload['medium']) def test_hostcollection_updatable_fields(self): + """Check whether ``HostCollection`` updates its ``updatable_fields`` field.""" org1 = entities.Organization(self.cfg, name='org1') org2 = entities.Organization(self.cfg, name='org2') host_collection = entities.HostCollection(self.cfg, name='oldname', organization=org1) @@ -2061,7 +2024,9 @@ def test_organization_rh_repo_url(self): self.assertIn('redhat_repository_url', payload) def test_os_default_template(self): - """Check, that ``os_default_template`` serves ``template_kind_id`` and + """Test ``update_payload`` for ``OSDefaultTemplate``. + + Check, that ``os_default_template`` serves ``template_kind_id`` and ``provisioning_template_id`` only wrapped in sub dict See: `Redmine #21169`_. @@ -2083,7 +2048,6 @@ def test_subnet_from(self): The field should be renamed from ``from_`` to ``from`` when ``update_payload`` is called. - """ payload = entities.Subnet( self.cfg, @@ -2111,7 +2075,6 @@ def setUpClass(cls): entity_obj3.method1, 'get', entity_obj3.method2, 'put', ) - """ cfg = config.ServerConfig('http://example.com') generic = {'server_config': cfg, 'id': 1} @@ -2227,7 +2190,6 @@ def test_generic(self): * Each method passes the right arguments to `client.*`. * Each method calls `entities._handle_response` once. * The result of `_handle_response(…)` is the return value. - """ for method, request in self.methods_requests: with self.subTest((method, request)): @@ -2251,7 +2213,6 @@ def test_intelligent(self): * Each method passes the right arguments to `client.*`. * Each method calls `entities._handle_response` once. * The result of `_handle_response(…)` is the return value. - """ for method, request, data in self.intelligent_methods_requests: with self.subTest((method, request)): @@ -2290,10 +2251,10 @@ def test_read(self): class FileTestCase(TestCase): - """Class with entity File tests""" + """Class with entity File tests.""" def test_to_json(self): - """Check json serialisation on nested entities""" + """Check json serialisation on nested entities.""" file_kwargs = { 'id': 1, 'name': 'test_file.txt', @@ -2385,7 +2346,6 @@ def test_content_upload_create(self): Make the (mock) server return a "success" status. Make the same assertions as for :meth:`tests.test_entities.GenericTestCase.test_generic`. - """ with mock.patch.object(client, 'post') as post: self.content_upload.create() @@ -2398,7 +2358,6 @@ def test_content_upload_delete(self): Make the (mock) server return a "success" status. Make the same assertions as for :meth:`tests.test_entities.GenericTestCase.test_generic`. - """ with mock.patch.object(client, 'delete') as delete: with mock.patch.object(client, 'post') as post: @@ -2415,7 +2374,6 @@ def test_content_upload_update(self): Make the (mock) server return a "success" status. Make the same assertions as for :meth:`tests.test_entities.GenericTestCase.test_generic`. - """ with mock.patch.object(client, 'post') as post: with mock.patch.object(client, 'put') as put: @@ -2434,7 +2392,6 @@ def test_content_upload_upload(self): Make the (mock) server return a "success" status. Make the same assertions as for :meth:`tests.test_entities.GenericTestCase.test_generic`. - """ filename = gen_string('alpha') filepath = os.path.join(gen_string('alpha'), filename) @@ -2459,7 +2416,6 @@ def test_content_upload_no_filename(self): Make the (mock) server return a "success" status. Make the same assertions as for :meth:`tests.test_entities.GenericTestCase.test_generic`. - """ filename = gen_string('alpha') filepath = os.path.join(gen_string('alpha'), filename) @@ -2483,6 +2439,7 @@ class ContentViewTestCase(TestCase): """Tests for :class:`nailgun.entities.ContentView`.""" def setUp(self): + """Set common attributes for all tests.""" self.server_config = config.ServerConfig('http://example.com') self.cv = entities.ContentView( self.server_config, @@ -2576,7 +2533,6 @@ class ContentViewComponentTestCase(TestCase): def setUp(self): """Set a server configuration at ``self.cfg``.""" - self.server_config = config.ServerConfig('http://example.com') self.ccv = entities.ContentView( self.server_config, @@ -2630,6 +2586,7 @@ def setUp(self): self.read_json_pacther = mock.patch.object(self.cvc, 'read_json') def test_path(self): + """Check that path is correctly constructed.""" for which in ['add', 'remove']: path = self.cvc.path(which=which) self.assertIn( @@ -2646,7 +2603,6 @@ def test_add(self): * Method calls `client.*` once. * Method calls `entities._handle_response` once. - """ self.assertEqual(inspect.getfullargspec(self.cvc.add), EXPECTED_ARGSPEC) return_dict = {'results': [self.common_return_value]} @@ -2666,7 +2622,6 @@ def test_remove(self): * Method calls `client.*` once. * Method calls `entities._handle_response` once. - """ self.assertEqual(inspect.getfullargspec(self.cvc.remove), EXPECTED_ARGSPEC) return_dict = {'results': self.common_return_value} @@ -2682,8 +2637,9 @@ class ReportTemplateTestCase(TestCase): """Tests for :class:`nailgun.entities.ReportTemplate`.""" def test_creation_and_update(self): - """Check template combinations as json or entity is set on correct - attribute template_combinations_attributes ( check #333) + """Check template combinations as json or entity is set on correct attribute. + + template_combinations_attributes ( check #333). """ cfg = config.ServerConfig(url='foo') report_template = entities.ReportTemplate(cfg, name='cfg', default=False, template='cat') @@ -2701,7 +2657,7 @@ def test_creation_and_update(self): self.assertEqual(expected_dct, report_template.update_payload()) def test_generate(self): - """Generate template""" + """Generate template.""" cfg = config.ServerConfig(url='foo') report_template = entities.ReportTemplate(cfg, id=42) with mock.patch.object(client, 'post') as post: @@ -2714,7 +2670,7 @@ def test_generate(self): self.assertEqual(post.call_args[1], {'data': {'input_values': {'hosts': 'whatever'}}}) def test_schedule(self): - """Schedule template""" + """Schedule template.""" cfg = config.ServerConfig(url='foo') report_template = entities.ReportTemplate(cfg, id=43) with mock.patch.object(client, 'post') as post: @@ -2727,7 +2683,7 @@ def test_schedule(self): self.assertEqual(post.call_args[1], {'data': {'input_values': {'hosts': 'whatever'}}}) def test_report_data(self): - """Schedule template""" + """Schedule template.""" cfg = config.ServerConfig(url='foo') report_template = entities.ReportTemplate(cfg, id=44) with mock.patch.object(client, 'get') as get_response: @@ -2746,8 +2702,9 @@ class ProvisioningTemplateTestCase(TestCase): """Tests for :class:`nailgun.entities.ProvisioningTemplate`.""" def test_creation_and_update(self): - """Check template combinations as json or entity is set on correct - attribute template_combinations_attributes ( check #333) + """Check template combinations as json or entity is set on correct attribute. + + template_combinations_attributes ( check #333). """ cfg = config.ServerConfig(url='foo') env = entities.Environment(cfg, id=2, name='env') @@ -2788,6 +2745,7 @@ class TemplateInputTestCase(TestCase): """Tests for :class:`nailgun.entities.TemplateInput`.""" def setUp(self): + """Set common attributes for all tests.""" self.cfg = config.ServerConfig('some url') self.job_template = entities.JobTemplate(self.cfg, id=2) self.entity = entities.TemplateInput(self.cfg, id=1, template=self.job_template) @@ -2810,9 +2768,11 @@ def setUp(self): del self.data['template_id'] def tearDown(self): + """Stop patching ``self.entity.read_json``.""" self.read_json_patcher.stop() def test_read(self): + """Check that ``read`` is sane.""" entity = self.entity.read() self.read_json.assert_called_once() self.assertEqual(self.data, {key: getattr(entity, key) for key in self.data}) @@ -2824,6 +2784,7 @@ class JobTemplateTestCase(TestCase): """Tests for :class:`nailgun.entities.JobTemplate`.""" def setUp(self): + """Set common attributes for all tests.""" self.cfg = config.ServerConfig('some url') self.entity = entities.JobTemplate(self.cfg, id=1) self.read_json_patcher = mock.patch.object(EntityReadMixin, 'read_json') @@ -2848,9 +2809,11 @@ def setUp(self): del self.data['template_inputs'] def tearDown(self): + """Stop patching ``self.entity.read_json``.""" self.read_json_patcher.stop() def test_read(self): + """Check that ``read`` is sane.""" entity = self.entity.read() self.read_json.assert_called_once() self.assertEqual(self.data, {key: getattr(entity, key) for key in self.data}) @@ -2866,6 +2829,7 @@ class HostGroupTestCase(TestCase): """Tests for :class:`nailgun.entities.HostGroup`.""" def setUp(self): + """Set common attributes for all tests.""" self.entity = entities.HostGroup(config.ServerConfig('some url')) self.read_json_pacther = mock.patch.object(self.entity, 'read_json') self.read_pacther = mock.patch.object(EntityReadMixin, 'read') @@ -2930,8 +2894,9 @@ def test_delete_puppetclass(self): self.assertEqual(handlr.return_value, response) def test_clone_hostgroup(self): - """Test for :meth:`nailgun.entities.HostGroup.clone` - Assert that the method is called one with correct argumets + """Test for :meth:`nailgun.entities.HostGroup.clone`. + + Assert that the method is called one with correct argumets. """ entity = self.entity entity.id = 1 @@ -2947,8 +2912,9 @@ def test_clone_hostgroup(self): self.assertEqual(handler.return_value, response) def test_rebuild_config(self): - """Test for :meth:`nailgun.entities.HostGroup.rebuild_config` - Assert that the method is called one with correct arguments + """Test for :meth:`nailgun.entities.HostGroup.rebuild_config`. + + Assert that the method is called one with correct arguments. """ entity = self.entity entity.id = 1 @@ -2972,8 +2938,7 @@ def setUp(self): self.cfg = config.ServerConfig('http://example.com') def test_init_with_owner_type(self): - """Assert ``owner`` attribute is an entity of correct type, according - to ``owner_type`` field value""" + """Assert ``owner`` attribute is type correct, according to ``owner_type`` field value.""" for owner_type, entity in (('User', entities.User), ('Usergroup', entities.UserGroup)): host = entities.Host( self.cfg, @@ -2984,9 +2949,7 @@ def test_init_with_owner_type(self): self.assertTrue(isinstance(host.owner, entity)) def test_update_owner_type(self): - """Ensure that in case ``owner_type`` value changes, ``owner`` changes - it's type accordingly. - """ + """Ensure that when ``owner_type`` value changes, ``owner`` correctly changes its type.""" host = entities.Host( self.cfg, id=gen_integer(min_value=1), @@ -3019,9 +2982,7 @@ def test_owner_type_property(self): self.assertFalse('_owner_type' in result) def test_init_with_owner(self): - """Assert that both ``id`` or ``entity`` can be passed as a value for - ``owner`` attribute. - """ + """Assert both ``id`` or ``entity`` can be passed as a value for ``owner`` attribute.""" owner_id = gen_integer(min_value=1) owner_entity = entities.UserGroup( self.cfg, @@ -3038,9 +2999,7 @@ def test_init_with_owner(self): self.assertEqual(owner_id, host.owner.id) def test_no_facet_attributes(self): - """Assert that ``content_facet_attributes`` attribute is ignored when - ``content_facet_attributes`` attribute is not returned for host - """ + """Assert that ``content_facet_attributes`` is ignored when not returned for host.""" with mock.patch.object(EntityReadMixin, 'read') as read: with mock.patch.object(entities, '_feature_list', return_value={'Puppet'}): entities.Host(self.cfg).read( @@ -3080,7 +3039,7 @@ def test_delete_puppetclass(self): self.assertEqual(handlr.return_value, response) def test_disassociate(self): - """Disassociate host""" + """Disassociate host.""" cfg = config.ServerConfig(url='foo') host = entities.Host(cfg, id=42) with mock.patch.object(client, 'put') as put: @@ -3092,7 +3051,7 @@ def test_disassociate(self): self.assertEqual(put.call_args[0][0], 'foo/api/v2/hosts/42/disassociate') def test_read_template(self): - """Read a provision template""" + """Read a provision template.""" entity = entities.Host(self.cfg, id=1) kwargs = {'data': {'template_kind': gen_alpha()}} with mock.patch.object(entities, '_handle_response') as handler: @@ -3105,7 +3064,7 @@ def test_read_template(self): self.assertEqual(handler.return_value, response) def test_play_ansible_roles(self): - """Play Ansible roles""" + """Play Ansible roles.""" cfg = config.ServerConfig(url='foo') host = entities.Host(cfg, id=42) exp_ret = mock.MagicMock() @@ -3133,6 +3092,7 @@ def setUp(self): def test_search_normalize(self): """Call :meth:`nailgun.entities.PuppetClass.search_normalize`. + Assert that returned value is a list and contains all subdictionaries. """ with mock.patch.object(EntitySearchMixin, 'search_normalize') as s_n: @@ -3163,7 +3123,6 @@ def test_upload_content_v1(self): Make the (mock) server return a "success" status. Make the same assertions as for :meth:`tests.test_entities.GenericTestCase.test_generic`. - """ kwargs = {'kwarg': gen_integer()} with mock.patch.object(client, 'post') as post, mock.patch.object( @@ -3183,7 +3142,6 @@ def test_upload_content_v2(self): Assert that :class:`nailgun.entities.APIResponseError` is raised when the (mock) server fails to return a "success" status. - """ kwargs = {'kwarg': gen_integer()} with mock.patch.object(client, 'post') as post, mock.patch.object( @@ -3198,13 +3156,11 @@ def test_upload_content_v2(self): self.assertEqual(handler.call_count, 1) def test_import_uploads_uploads(self): - """Call :meth:`nailgun.entities.Repository.import_uploads` with - the `uploads` parameter. + """Call :meth:`nailgun.entities.Repository.import_uploads` with the `uploads` parameter. Make the (mock) server return a "success" status. Make the same assertions as for :meth:`tests.test_entities.GenericTestCase.test_generic`. - """ kwargs = {'kwarg': gen_integer()} uploads = [ @@ -3228,13 +3184,11 @@ def test_import_uploads_uploads(self): self.assertEqual(handler.return_value, response) def test_import_uploads_upload_ids(self): - """Call :meth:`nailgun.entities.Repository.import_uploads` with - the `upload_ids` parameter. + """Call :meth:`nailgun.entities.Repository.import_uploads` with the `upload_ids` parameter. Make the (mock) server return a "success" status. Make the same assertions as for :meth:`tests.test_entities.GenericTestCase.test_generic`. - """ kwargs = {'kwarg': gen_integer()} upload_ids = [gen_string('numeric')] @@ -3251,8 +3205,9 @@ def test_import_uploads_upload_ids(self): self.assertEqual(handler.return_value, response) def test_files(self): - """Test for :meth:`nailgun.entities.Repository.files` - Assert that the method is called one with correct arguments + """Test for :meth:`nailgun.entities.Repository.files`. + + Assert that the method is called one with correct arguments. """ self.assertEqual(inspect.getfullargspec(self.repo.files), EXPECTED_ARGSPEC) kwargs = {'kwarg': gen_integer(), 'data': {'name': gen_string('utf8', 5)}} @@ -3293,9 +3248,10 @@ def setUp(self): def test_import_puppetclasses(self): """Call :meth:`nailgun.entities.SmartProxy.import_puppetclasses`. + Assert that * ``environment`` parameter is not sent to requests, - * proper path is built + * proper path is built. """ params = [{}, {'environment': 2}, {'environment': self.env}] for param in params: @@ -3344,7 +3300,6 @@ def test_methods(self): It would be ideal if these method could be refactored such that this unit test could be dropped. - """ cfg = config.ServerConfig('http://example.com') generic = {'server_config': cfg, 'id': 1} @@ -3404,7 +3359,7 @@ def test_api_response_error(self): self.assertEqual(search.call_count, 1) def test_to_json(self): - """json serialization""" + """Json serialization.""" kwargs = { 'id': 1, 'description': 'some description', @@ -3417,10 +3372,10 @@ def test_to_json(self): class PackageTestCase(TestCase): - """Class with entity Package tests""" + """Class with entity Package tests.""" def test_to_json(self): - """Check json serialisation on nested entities""" + """Check json serialisation on nested entities.""" package_kwargs = { 'nvrea': 'sclo-git25-1.0-2.el7.x86_64', 'checksum': ('751e639a0b8add0adc0c5cf0bf77693b3197b17533037ce2e7b9daa618898b99'), @@ -3444,10 +3399,10 @@ def test_to_json(self): class SrpmsTestCase(TestCase): - """Class with entity Srpms tests""" + """Class with entity Srpms tests.""" def test_to_json(self): - """Check json serialisation on nested entities""" + """Check json serialisation on nested entities.""" package_kwargs = { "arch": "src", "checksum": "bc69f30e1a33cff127e44c6caeabc7eb9c2f92ea21a2e6590edcf3e0ebfc87e3", @@ -3470,10 +3425,10 @@ def test_to_json(self): class PackageGroupTestCase(TestCase): - """Class with entity Package Group tests""" + """Class with entity Package Group tests.""" def test_to_json(self): - """Check json serialisation on nested entities""" + """Check json serialisation on nested entities.""" pkg_group_kwargs = { 'description': None, 'id': 3, @@ -3487,10 +3442,10 @@ def test_to_json(self): class ModuleStreamTestCase(TestCase): - """Class with entity Module Stream tests""" + """Class with entity Module Stream tests.""" def test_to_json(self): - """Check json serialisation on nested entities""" + """Check json serialisation on nested entities.""" module_stream_kwargs = { "id": 3, "name": "walrus", @@ -3526,7 +3481,7 @@ def test_default(self): ) def test_json_content(self): - """Give the response JSON content type""" + """Give the response JSON content type.""" response = mock.Mock() response.headers = {'content-type': 'application/json; charset=utf-8'} self.assertEqual( @@ -3568,7 +3523,6 @@ def test_accepted_v1(self): * Do not pass the ``synchronous`` argument. * Pass ``synchronous=False``. - """ response = mock.Mock() response.status_code = ACCEPTED @@ -3588,7 +3542,6 @@ def test_accepted_v2(self): """Give the response an HTTP "ACCEPTED" status code. Pass ``synchronous=True`` as an argument. - """ response = mock.Mock() response.status_code = ACCEPTED @@ -3619,7 +3572,6 @@ def test_missing_org_id(self): Assert that ``read_json``, ``_get_org`` and ``read`` are all called once, and that the second is called with the correct arguments. - """ for entity in (entities.ContentView, entities.Product): with self.subTest(entity): @@ -3636,15 +3588,15 @@ def test_missing_org_id(self): class JsonSerializableTestCase(TestCase): - """Test regarding Json serializable on different object""" + """Test regarding Json serializable on different object.""" def test_regular_objects(self): - """Checking regular objects transformation""" + """Checking regular objects transformation.""" lst = [[1, 0.3], {'name': 'foo'}] self.assertEqual(lst, entities.to_json_serializable(lst)) def test_entities(self): - """Testing nested entities serialization""" + """Testing nested entities serialization.""" package_kwargs = { 'nvrea': 'sclo-git25-1.0-2.el7.x86_64', 'checksum': ('751e639a0b8add0adc0c5cf0bf77693b3197b17533037ce2e7b9daa618898b99'), @@ -3679,7 +3631,7 @@ def test_entities(self): self.assertListEqual(expected, entities.to_json_serializable(to_be_transformed)) def test_nested_entities(self): - """Check nested entities serialization""" + """Check nested entities serialization.""" env_kwargs = {'id': 1, 'name': 'env'} env = make_entity(entities.Environment, **env_kwargs) @@ -3710,13 +3662,12 @@ def test_nested_entities(self): self.assertDictEqual(cfg_kwargs, entities.to_json_serializable(cfg_template)) def test_date_field(self): - """Check date field serialization""" - + """Check date field serialization.""" errata = make_entity(entities.Errata, issued=date(2016, 9, 20)) self.assertDictEqual({'issued': '2016-09-20'}, entities.to_json_serializable(errata)) def test_boolean_datetime_float(self): - """Check serialization for boolean, datetime and float fields""" + """Check serialization for boolean, datetime and float fields.""" kwargs = {'pending': True, 'progress': 0.25, 'started_at': datetime(2016, 11, 20, 1, 2, 3)} task = make_entity(entities.ForemanTask, **kwargs) kwargs['started_at'] = '2016-11-20 01:02:03' @@ -3724,16 +3675,16 @@ def test_boolean_datetime_float(self): class VirtWhoConfigTestCase(TestCase): - """ - Tests for :class:`nailgun.entities.VirtWhoConfig` - """ + """Tests for :class:`nailgun.entities.VirtWhoConfig`.""" @classmethod def setUpClass(cls): + """Set ``self.server`` and ``self.cfg``.""" cls.server = 'sat.example.com' cls.cfg = config.ServerConfig(f'http://{cls.server}/') def test_create(self): + """Test create payload.""" org = entities.Organization(self.cfg, name='vhorg', id=2) vh = entities.VirtWhoConfig( server_config=self.cfg, @@ -3770,6 +3721,7 @@ def test_create(self): self.assertDictEqual(expected_dict, vh.create_payload()) def test_update(self): + """Test update payload.""" org = entities.Organization(self.cfg, name='vhorg', id=2) vh = entities.VirtWhoConfig( server_config=self.cfg, @@ -3806,7 +3758,6 @@ def test_methods(self): slightly different set of mocks. Test the following: * :meth:`nailgun.entities.VirtWhoConfig.get_organization_configs` - """ cfg = config.ServerConfig('http://example.com') generic = {'server_config': cfg, 'id': 1} @@ -3830,10 +3781,11 @@ class JobInvocationTestCase(TestCase): @classmethod def setUpClass(cls): + """Set a common ServerConfig.""" cls.cfg = config.ServerConfig('http://example.com') def test_required_param(self): - """Check required parameters""" + """Check required parameters.""" data_list = [ {'inputs': 'ls', 'search_query': 'foo'}, {'feature': 'foo', 'inputs': 'ls'}, @@ -3846,9 +3798,7 @@ def test_required_param(self): entities.JobInvocation(self.cfg).run(data=data) def test_non_sync_run(self): - """Run job asynchronously with valid parameters and check that correct - post request is sent - """ + """Run job asynchronously with valid parameters and check that correct request is sent.""" with mock.patch.object(client, 'post') as post: entities.JobInvocation(self.cfg).run( synchronous=False, @@ -3863,7 +3813,7 @@ def test_non_sync_run(self): self.assertEqual(len(post.call_args[0]), 1) def test_sync_run(self): - """Check that sync run will result in ForemanTask poll""" + """Check that sync run will result in ForemanTask poll.""" with mock.patch.object(entities, '_poll_task') as poll_task: with mock.patch.object(client, 'post'): entities.JobInvocation(self.cfg).run( diff --git a/tests/test_entity_fields.py b/tests/test_entity_fields.py index d0496610..4a115b6e 100644 --- a/tests/test_entity_fields.py +++ b/tests/test_entity_fields.py @@ -21,7 +21,6 @@ class GenValueTestCase(TestCase): Classes with complex ``gen_value`` implementations are broken out into separate test cases. - """ def test_one_to_one_field(self): diff --git a/tests/test_entity_mixins.py b/tests/test_entity_mixins.py index c2538b93..ba46b8db 100644 --- a/tests/test_entity_mixins.py +++ b/tests/test_entity_mixins.py @@ -37,7 +37,7 @@ class SampleEntity(entity_mixins.Entity): - """Sample entity to be used in the tests""" + """Sample entity to be used in the tests.""" def __init__(self, server_config=None, **kwargs): self._fields = { @@ -54,7 +54,6 @@ class SampleEntityTwo(entity_mixins.Entity): This class has a :class:`nailgun.entity_fields.OneToManyField` called "one_to_many" pointing to :class:`tests.test_entity_mixins.SampleEntity`. - """ def __init__(self, server_config=None, **kwargs): @@ -70,7 +69,6 @@ class SampleEntityThree(entity_mixins.Entity): This class has a :class:`nailgun.entity_fields.ListField` called "list" containing instances of :class:`tests.test_entity_mixins.SampleEntity`. - """ def __init__(self, server_config=None, **kwargs): @@ -208,7 +206,7 @@ def setUp(self): self.cfg = config.ServerConfig('bogus url') def test__poll_task_failure(self): - """What happens when a foreman task completes but does not succeed? + """Check what happens when a foreman task completes but does not succeed. Assert that a :class:`nailgun.entity_mixins.TaskFailedError` exception is raised. @@ -222,7 +220,7 @@ def test__poll_task_failure(self): entity_mixins._poll_task(gen_integer(), self.cfg) def test__poll_task_success(self): - """What happens when a foreman task completes and does succeed? + """Check what happens when a foreman task completes and does succeed. Assert that the server's response is returned. @@ -237,9 +235,7 @@ def test__poll_task_success(self): ) def test__poll_task_timeout(self): - """What happens when a foreman task timesout? - Assert that the task is still running. - """ + """Assert that the task is still running after timeout.""" with self.assertRaises(entity_mixins.TaskTimedOutError): with mock.patch.object(client, 'get') as get: get.return_value.json.return_value = {'state': 'running', 'result': 'pending'} @@ -305,8 +301,9 @@ def test_entity_get_values(self): ) def test_entity_get_values_v2(self): - """Test :meth:`nailgun.entity_mixins.Entity.get_values`, ensure - ``_path_fields`` are never returned. + """Test :meth:`nailgun.entity_mixins.Entity.get_values`. + + ensure ``_path_fields`` are never returned. """ for values in ( {}, @@ -357,7 +354,7 @@ def test_bad_value_error(self): SampleEntityTwo(self.cfg, one_to_many=1) def test_eq_none(self): - """Test method ``nailgun.entity_mixins.Entity.__eq__`` against None + """Test method ``nailgun.entity_mixins.Entity.__eq__`` against None. Assert that ``__eq__`` returns False when compared to None. @@ -421,12 +418,12 @@ def test_eq(self): self.assertEqual(mary, mary_clone) def test_compare_to_null(self): - """Assert entity comparison to None""" + """Assert entity comparison to None.""" alice = SampleEntity(self.cfg, id=1, name='Alice', unique='a') self.assertFalse(alice.compare(None)) def test_compare(self): - """Assert compare take only not unique fields into account""" + """Assert compare take only not unique fields into account.""" alice = SampleEntity(self.cfg, id=1, name='Alice', unique='a') alice_2 = SampleEntity(self.cfg, id=2, name='Alice', unique='b') self.assertTrue( @@ -439,12 +436,12 @@ def test_compare(self): ) def test_compare_with_filter(self): - """Assert compare can filter fields based on callable""" + """Assert compare can filter fields based on callable.""" alice = SampleEntity(self.cfg, id=1, name='Alice', unique='a') alice_2 = SampleEntity(self.cfg, id=2, name='Alice', unique='a') def filter_example(fields_name, _): - """Filter function to avoid comparison only on id""" + """Filter function to avoid comparison only on id.""" return fields_name != 'id' self.assertTrue( @@ -575,7 +572,7 @@ def __init__(self, server_config=None, **kwargs): self.assertEqual(entity.int_default, 5) def test_create_raw_v1(self): - """What happens if the ``create_missing`` arg is not specified? + """Check what happens if the ``create_missing`` arg is not specified. :meth:`nailgun.entity_mixins.EntityCreateMixin.create_raw` should default to :data:`nailgun.entity_mixins.CREATE_MISSING`. We do not set @@ -592,7 +589,7 @@ def test_create_raw_v1(self): self.assertEqual(post.call_count, 1) def test_create_raw_v2(self): - """What happens if the ``create_missing`` arg is ``True``?""" + """Check what happens if the ``create_missing`` arg is ``True``.""" with mock.patch.object(self.entity, 'create_missing') as c_missing: with mock.patch.object(self.entity, 'create_payload') as c_payload: with mock.patch.object(client, 'post') as post: @@ -602,7 +599,7 @@ def test_create_raw_v2(self): self.assertEqual(post.call_count, 1) def test_create_raw_v3(self): - """What happens if the ``create_missing`` arg is ``False``?""" + """Check what happens if the ``create_missing`` arg is ``False``.""" with mock.patch.object(self.entity, 'create_missing') as c_missing: with mock.patch.object(self.entity, 'create_payload') as c_payload: with mock.patch.object(client, 'post') as post: @@ -958,7 +955,7 @@ def test_delete_raw(self): ) def test_delete_v1(self): - """What happens if the server returns an error HTTP status code?""" + """Check what happens if the server returns an error HTTP status code.""" response = mock.Mock() response.raise_for_status.side_effect = HTTPError('oh no!') with mock.patch.object( @@ -969,7 +966,7 @@ def test_delete_v1(self): self.entity.delete() def test_delete_v2(self): - """What happens if the server returns an HTTP ACCEPTED status code?""" + """Check what happens if the server returns an HTTP ACCEPTED status code.""" response = mock.Mock() response.status_code = http_client.ACCEPTED response.json.return_value = {'id': gen_integer()} @@ -987,7 +984,7 @@ def test_delete_v2(self): ) def test_delete_v3(self): - """What happens if the server returns an HTTP NO_CONTENT status?""" + """Check what happens if the server returns an HTTP NO_CONTENT status.""" response = mock.Mock() response.status_code = http_client.NO_CONTENT with mock.patch.object( @@ -999,7 +996,7 @@ def test_delete_v3(self): self.assertEqual(poll_task.call_count, 0) def test_delete_v4(self): - """What happens if the server returns some other stuccess status?""" + """Check what happens if the server returns some other stuccess status.""" response = mock.Mock() response.json.return_value = gen_integer() with mock.patch.object( @@ -1010,9 +1007,7 @@ def test_delete_v4(self): self.assertEqual(self.entity.delete(), response.json.return_value) def test_delete_v5(self): - """ - What happens if the server returns an HTTP OK status and empty content? - """ + """Check what happens if the server returns an HTTP OK status and empty content.""" response = mock.Mock() response.status_code = http_client.OK response.content = '' @@ -1025,10 +1020,7 @@ def test_delete_v5(self): self.assertEqual(poll_task.call_count, 0) def test_delete_v6(self): - """ - What happens if the server returns an HTTP OK status and blank only - content? - """ + """Assert delete works when receiving an OK response with no content.""" response = mock.Mock() response.status_code = http_client.OK response.content = ' '