code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
attrs = vars(self).copy() attrs.pop('_server_config') attrs.pop('_fields') attrs.pop('_meta') if '_path_fields' in attrs: attrs.pop('_path_fields') return attrs
def get_values(self)
Return a copy of field values on the current object. This method is almost identical to ``vars(self).copy()``. However, only instance attributes that correspond to a field are included in the returned dict. :return: A dict mapping field names to user-provided values.
4.916392
4.845102
1.014714
fields, values = self.get_fields(), self.get_values() filtered_fields = fields.items() if filter_fcn is not None: filtered_fields = ( tpl for tpl in filtered_fields if filter_fcn(tpl[0], tpl[1]) ) json_dct = {} for field_name, fiel...
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 fields. Fields can be ...
3.157491
3.063004
1.030848
if not isinstance(other, type(self)): return False if filter_fcn is None: def filter_unique(_, field): return not field.unique filter_fcn = filter_unique return self.to_json_dict(filter_fcn) == other.to_json_dict(filt...
def compare(self, other, filter_fcn=None)
Returns 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. It must return True if field's value should be included on comparis...
3.882099
3.205843
1.210945
return client.delete( self.path(which='self'), **self._server_config.get_client_kwargs() )
def delete_raw(self)
Delete the current entity. Make an HTTP DELETE call to ``self.path('base')``. Return the response. :return: A ``requests.response`` object.
18.537945
16.099415
1.151467
response = self.delete_raw() response.raise_for_status() if (synchronous is True and response.status_code == http_client.ACCEPTED): return _poll_task(response.json()['id'], self._server_config) elif (response.status_code == http_client.NO_CONTENT or...
def delete(self, synchronous=True)
Delete the current entity. Call :meth:`delete_raw` and check for an HTTP 4XX or 5XX response. Return either the JSON-decoded response or information about a completed foreman task. :param synchronous: A boolean. What should happen if the server returns an HTTP 202 (accepted...
4.30932
3.884436
1.109381
path_type = self._meta.get('read_type', 'self') return client.get( self.path(path_type), params=params, **self._server_config.get_client_kwargs() )
def read_raw(self, params=None)
Get information about the current entity. Make an HTTP GET call to ``self.path('self')``. Return the response. :return: A ``requests.response`` object.
7.920486
7.493366
1.057
response = self.read_raw(params=params) response.raise_for_status() return response.json()
def read_json(self, params=None)
Get information about the current entity. Call :meth:`read_raw`. Check the response status code, decode JSON and return the decoded JSON as a dict. :return: A dict. The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` if the response has an HTTP ...
3.938806
3.755682
1.048759
if entity is None: entity = type(self)(self._server_config) if attrs is None: attrs = self.read_json(params=params) if ignore is None: ignore = set() for field_name, field in entity.get_fields().items(): if field_name in ignore: ...
def read(self, entity=None, attrs=None, ignore=None, params=None)
Get information about the current entity. 1. Create a new entity of type ``type(self)``. 2. Call :meth:`read_json` and capture the response. 3. Populate the entity with the response. 4. Return the entity. Step one is skipped if the ``entity`` argument is specified. Step two ...
2.129193
1.942143
1.096311
for field_name, field in self.get_fields().items(): if field.required and not hasattr(self, field_name): # Most `gen_value` methods return a value such as an integer, # string or dictionary, but OneTo{One,Many}Field.gen_value # returns the ref...
def create_missing(self)
Automagically populate all required instance attributes. Iterate through the set of all required class :class:`nailgun.entity_fields.Field` defined on ``type(self)`` and create a corresponding instance attribute if none exists. Subclasses should override this method if there is some rel...
4.228458
4.137047
1.022096
if create_missing is None: create_missing = CREATE_MISSING if create_missing is True: self.create_missing() return client.post( self.path('base'), self.create_payload(), **self._server_config.get_client_kwargs() )
def create_raw(self, create_missing=None)
Create an entity. Possibly call :meth:`create_missing`. Then make an HTTP POST call to ``self.path('base')``. The request payload consists of whatever is returned by :meth:`create_payload`. Return the response. :param create_missing: Should :meth:`create_missing` be called? In ...
5.038321
3.426091
1.470574
response = self.create_raw(create_missing) response.raise_for_status() return response.json()
def create_json(self, create_missing=None)
Create an entity. Call :meth:`create_raw`. Check the response status code, decode JSON and return the decoded JSON as a dict. :return: A dict. The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` if the response has an HTTP 4XX or 5XX sta...
4.612682
3.847665
1.198826
values = self.get_values() if fields is not None: values = {field: values[field] for field in fields} return _payload(self.get_fields(), values)
def update_payload(self, fields=None)
Create a payload of values that can be sent to the server. By default, this method behaves just like :func:`_payload`. However, one can also specify a certain set of fields that should be returned. For more information, see :meth:`update`.
3.703327
3.525854
1.050335
return client.put( self.path('self'), self.update_payload(fields), **self._server_config.get_client_kwargs() )
def update_raw(self, fields=None)
Update the current entity. Make an HTTP PUT call to ``self.path('base')``. The request payload consists of whatever is returned by :meth:`update_payload`. Return the response. :param fields: See :meth:`update`. :return: A ``requests.response`` object.
9.944304
7.577148
1.312407
response = self.update_raw(fields) response.raise_for_status() return response.json()
def update_json(self, fields=None)
Update the current entity. Call :meth:`update_raw`. Check the response status code, decode JSON and return the decoded JSON as a dict. :param fields: See :meth:`update`. :return: A dict consisting of the decoded JSON in the server's response. :raises: ``requests.exc...
4.462443
4.06062
1.098956
if fields is None: fields = set(self.get_values().keys()) if query is None: query = {} payload = {} fields_dict = self.get_fields() for field in fields: value = getattr(self, field) if isinstance(fields_dict[field], OneToO...
def search_payload(self, fields=None, query=None)
Create a search query. Do the following: 1. Generate a search query. By default, all values returned by :meth:`nailgun.entity_mixins.Entity.get_values` are used. If ``fields`` is specified, only the named values are used. 2. Merge ``query`` in to the generated search quer...
2.365322
2.025482
1.167782
return client.get( self.path('base'), data=self.search_payload(fields, query), **self._server_config.get_client_kwargs() )
def search_raw(self, fields=None, query=None)
Search for entities. Make an HTTP GET call to ``self.path('base')``. Return the response. .. WARNING:: Subclasses that override this method should not alter the ``fields`` or ``query`` arguments. (However, subclasses that override this method may still alter the server's respon...
8.579811
6.915166
1.240724
response = self.search_raw(fields, query) response.raise_for_status() return response.json()
def search_json(self, fields=None, query=None)
Search for entities. Call :meth:`search_raw`. Check the response status code, decode JSON and return the decoded JSON as a dict. .. WARNING:: Subclasses that override this method should not alter the ``fields`` or ``query`` arguments. (However, subclasses that override ...
3.570166
4.044515
0.882718
fields = self.get_fields() normalized = [] for result in results: # For each field that we know about, copy the corresponding field # from the server's search result. If any extra attributes are # copied over, Entity.__init__ will raise a NoSuchFieldE...
def search_normalize(self, results)
Normalize search results so they can be used to create new entities. See :meth:`search` for an example of how to use this method. Here's a simplified example:: results = self.search_json() results = self.search_normalize(results) entity = SomeEntity(some_cfg, **resu...
5.118618
5.050902
1.013407
# Goals: # # * Be tolerant of missing values. It's reasonable for the server to # return an incomplete set of attributes for each search result. # * Use as many returned values as possible. There's no point in # letting returned data go to waste. This implies...
def search(self, fields=None, query=None, filters=None)
Search for entities. At its simplest, this method searches for all entities of a given kind. For example, to ask for all :class:`nailgun.entities.LifecycleEnvironment` entities:: LifecycleEnvironment().search() Values on an entity are used to generate a search query, and t...
10.671101
10.469107
1.019294
# Check to make sure all arguments are sane. if len(entities) == 0: return entities fields = entities[0].get_fields() # assume all entities are identical if not set(filters).issubset(fields): raise NoSuchFieldError( 'Valid filters are {0}...
def search_filter(entities, filters)
Read all ``entities`` and locally filter them. This method can be used like so:: entities = EntitySearchMixin(entities, {'name': 'foo'}) In this example, only entities where ``entity.name == 'foo'`` holds true are returned. An arbitrary number of field names and values may be ...
3.913562
3.267854
1.197594
auth = ('admin', 'changeme') base_url = 'https://sat1.example.com' organization_name = 'junk org' args = {'auth': auth, 'headers': {'content-type': 'application/json'}} response = requests.post( base_url + '/katello/api/v2/organizations', json.dumps({ 'name': organi...
def main()
Create an organization, print out its attributes and delete it.
3.084048
2.800755
1.101149
for config_dir in BaseDirectory.load_config_paths(xdg_config_dir): path = join(config_dir, xdg_config_file) if isfile(path): return path raise ConfigFileError( 'No configuration files could be located after searching for a file ' 'named "{0}" in the standard XDG ...
def _get_config_file_path(xdg_config_dir, xdg_config_file)
Search ``XDG_CONFIG_DIRS`` for a config file and return the first found. Search each of the standard XDG configuration directories for a configuration file. Return as soon as a configuration file is found. Beware that by the time client code attempts to open the file, it may be gone or otherwise inacce...
3.887163
3.581171
1.085445
if path is None: path = _get_config_file_path( cls._xdg_config_dir, cls._xdg_config_file ) cls._file_lock.acquire() try: with open(path) as config_file: config = json.load(config_file) del co...
def delete(cls, label='default', path=None)
Delete a server configuration. This method is thread safe. :param label: A string. The configuration identified by ``label`` is deleted. :param path: A string. The configuration file to be manipulated. Defaults to what is returned by :func:`nailgun.config._g...
2.110484
2.342276
0.90104
if path is None: path = _get_config_file_path( cls._xdg_config_dir, cls._xdg_config_file ) with open(path) as config_file: return cls(**json.load(config_file)[label])
def get(cls, label='default', path=None)
Read a server configuration from a configuration file. :param label: A string. The configuration identified by ``label`` is read. :param path: A string. The configuration file to be manipulated. Defaults to what is returned by :func:`nailgun.config._get_config_file_p...
3.17577
3.251267
0.976779
if path is None: path = _get_config_file_path( cls._xdg_config_dir, cls._xdg_config_file ) with open(path) as config_file: # keys() returns a list in Python 2 and a view in Python 3. return tuple(json.load(config_fi...
def get_labels(cls, path=None)
Get all server configuration labels. :param path: A string. The configuration file to be manipulated. Defaults to what is returned by :func:`nailgun.config._get_config_file_path`. :returns: Server configuration labels, where each label is a string.
4.462307
4.423465
1.008781
# What will we write out? cfg = vars(self) if 'version' in cfg: # pragma: no cover cfg['version'] = str(cfg['version']) # Where is the file we're writing to? if path is None: path = join( BaseDirectory.save_config_path(self._xdg_...
def save(self, label='default', path=None)
Save the current connection configuration to a file. This method is thread safe. :param label: A string. An identifier for the current configuration. This allows multiple configurations with unique labels to be saved in a single file. If a configuration identified by ``label`` ...
3.363168
3.45257
0.974106
config = vars(self).copy() config.pop('url') config.pop('version', None) return config
def get_client_kwargs(self)
Get kwargs for use with the methods in :mod:`nailgun.client`. This method returns a dict of attributes that can be unpacked and used as kwargs via the ``**`` operator. For example:: cfg = ServerConfig.get() client.get(cfg.url + '/api/v2', **cfg.get_client_kwargs()) Thi...
7.436101
11.356567
0.654784
config = super(ServerConfig, cls).get(label, path) if hasattr(config, 'auth') and isinstance(config.auth, list): config.auth = tuple(config.auth) return config
def get(cls, label='default', path=None)
Read a server configuration from a configuration file. This method extends :meth:`nailgun.config.BaseServerConfig.get`. Please read up on that method before trying to understand this one. The entity classes rely on the requests library to be a transport mechanism. The methods provided ...
3.41249
2.743779
1.243719
return gen_string( gen_choice(self.str_type), gen_integer(self.min_len, self.max_len) )
def gen_value(self)
Return a value suitable for a :class:`StringField`.
5.797905
5.306182
1.09267
server_config = ServerConfig( auth=('admin', 'changeme'), # Use these credentials… url='https://sat1.example.com', # …to talk to this server. ) org = Organization(server_config, name='junk org').create() pprint(org.get_values()) # e.g. {'name': 'junk org', …} org.delete()
def main()
Create an organization, print out its attributes and delete it.
9.998639
7.705307
1.29763
if 'files' in kwargs: return # requests will automatically set the content-type headers = kwargs.pop('headers', {}) headers.setdefault('content-type', 'application/json') kwargs['headers'] = headers
def _set_content_type(kwargs)
If the 'content-type' header is unset, set it to 'applcation/json'. The 'content-type' will not be set if doing a file upload as requests will automatically set it. :param kwargs: A ``dict``. The keyword args supplied to :func:`request` or one of the convenience functions like it. :return: Not...
3.982827
4.035192
0.987023
logger.debug( 'Making HTTP %s request to %s with %s, %s and %s.', method, url, 'options {0}'.format(kwargs) if len(kwargs) > 0 else 'no options', 'params {0}'.format(params) if params else 'no params', 'data {0}'.format(data) if data is not None else 'no data', ...
def _log_request(method, url, kwargs, data=None, params=None)
Log out information about the arguments given. The arguments provided to this function correspond to the arguments that one can pass to ``requests.request``. :return: Nothing is returned.
2.786044
3.150456
0.88433
message = u'Received HTTP {0} response: {1}'.format( response.status_code, response.text ) if response.status_code >= 400: # pragma: no cover logger.warning(message) else: logger.debug(message)
def _log_response(response)
Log out information about a ``Request`` object. After calling ``requests.request`` or one of its convenience methods, the object returned can be passed to this method. If done, information about the object returned is logged. :return: Nothing is returned.
2.794969
3.394449
0.823394
_set_content_type(kwargs) if _content_type_is_json(kwargs) and kwargs.get('data') is not None: kwargs['data'] = dumps(kwargs['data']) _log_request(method, url, kwargs) response = requests.request(method, url, **kwargs) _log_response(response) return response
def request(method, url, **kwargs)
A wrapper for ``requests.request``.
2.402438
2.51248
0.956202
_set_content_type(kwargs) if _content_type_is_json(kwargs) and kwargs.get('data') is not None: kwargs['data'] = dumps(kwargs['data']) _log_request('HEAD', url, kwargs) response = requests.head(url, **kwargs) _log_response(response) return response
def head(url, **kwargs)
A wrapper for ``requests.head``.
2.651797
2.752821
0.963301
_set_content_type(kwargs) if _content_type_is_json(kwargs) and data is not None: data = dumps(data) _log_request('POST', url, kwargs, data) response = requests.post(url, data, json, **kwargs) _log_response(response) return response
def post(url, data=None, json=None, **kwargs)
A wrapper for ``requests.post``.
2.965312
3.084118
0.961478
_set_content_type(kwargs) if _content_type_is_json(kwargs) and data is not None: data = dumps(data) _log_request('PUT', url, kwargs, data) response = requests.put(url, data, **kwargs) _log_response(response) return response
def put(url, data=None, **kwargs)
A wrapper for ``requests.put``. Sends a PUT request.
2.802239
2.916833
0.960713
server_configs = ServerConfig.get('sat1'), ServerConfig.get('sat2') for server_config in server_configs: org = Organization(server_config).search( query={'search': 'name="Default_Organization"'} )[0] # The LDAP authentication source with an ID of 1 is internal. It is ...
def main()
Create an identical user account on a pair of satellites.
10.425749
9.527923
1.094231
response.raise_for_status() if synchronous is True and response.status_code == ACCEPTED: return ForemanTask( server_config, id=response.json()['id']).poll(timeout=timeout) if response.status_code == NO_CONTENT: return if 'application/json' in response.headers.get('conten...
def _handle_response(response, server_config, synchronous=False, timeout=None)
Handle a server's response in a typical fashion. Do the following: 1. Check the server's response for an HTTP status code indicating an error. 2. Poll the server for a foreman task to complete if an HTTP 202 (accepted) status code is returned and ``synchronous is True``. 3. Immediately return i...
2.958675
2.723063
1.086525
organizations = Organization(server_config).search( query={u'search': u'label={0}'.format(label)} ) if len(organizations) != 1: raise APIResponseError( u'Could not find exactly one organization with label "{0}". ' u'Actual search results: {1}'.format(label, organ...
def _get_org(server_config, label)
Find an :class:`nailgun.entities.Organization` object. :param nailgun.config.ServerConfig server_config: The server that should be searched. :param label: A string. The label of the organization to find. :raises APIResponseError: If exactly one organization is not found. :returns: An :class:`na...
4.742049
4.200658
1.128883
if which in ( 'add_subscriptions', 'content_override', 'copy', 'host_collections', 'product_content', 'releases', 'remove_subscriptions', 'subscriptions'): return ...
def path(self, which=None)
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: add_subscriptions /activation_keys/<id>/add_subscriptions copy /activation_keys/<id>/copy content_override /activation_keys/<id>/content_...
7.398473
3.139365
2.356678
if which in ('download_html',): return '{0}/{1}'.format( super(ArfReport, self).path(which='self'), which ) return super(ArfReport, self).path(which)
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 /api/compliance/arf_reports/:id/download_html Otherwise, call ``super``.
7.54068
3.748351
2.011733
super(AuthSourceLDAP, self).create_missing() if getattr(self, 'onthefly_register', False) is True: for field in ( 'account_password', 'attr_firstname', 'attr_lastname', 'attr_login', ...
def create_missing(self)
Possibly set several extra instance attributes. If ``onthefly_register`` is set and is true, set the following instance attributes: * account_password * account_firstname * account_lastname * attr_login * attr_mail
5.354664
3.34205
1.60221
if attrs is None: attrs = self.update_json([]) if ignore is None: ignore = set() ignore.add('account_password') return super(AuthSourceLDAP, self).read(entity, attrs, ignore, params)
def read(self, entity=None, attrs=None, ignore=None, params=None)
Do not read the ``account_password`` attribute. Work around a bug. For more information, see `Bugzilla #1243036 <https://bugzilla.redhat.com/show_bug.cgi?id=1243036>`_.
5.369835
4.165333
1.289173
if which and which.startswith('content_'): return '{0}/content/{1}'.format( super(Capsule, self).path(which='self'), which.split('content_')[1] ) return super(Capsule, self).path(which)
def path(self, which=None)
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: content_lifecycle_environments /capsules/<id>/content/lifecycle_environments content_sync /capsules/<id>/content/sync ``super`` is called otherwise...
4.842814
3.475649
1.393355
if which == 'facts': return '{0}/{1}'.format( super(DiscoveredHost, self).path(which='base'), which ) return super(DiscoveredHost, self).path(which)
def path(self, which=None)
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: facts /discovered_hosts/facts ``super`` is called otherwise.
6.455003
4.056509
1.591271
payload = super(DiscoveryRule, self).create_payload() if 'search_' in payload: payload['search'] = payload.pop('search_') return {u'discovery_rule': payload}
def create_payload(self)
Wrap submitted data within an extra dict. For more information, see `Bugzilla #1151220 <https://bugzilla.redhat.com/show_bug.cgi?id=1151220>`_. In addition, rename the ``search_`` field to ``search``.
6.142221
4.432117
1.385844
return type(self)( self._server_config, id=self.create_json(create_missing)['id'], ).read()
def create(self, create_missing=None)
Do extra work to fetch a complete set of attributes for this entity. For more information, see `Bugzilla #1381129 <https://bugzilla.redhat.com/show_bug.cgi?id=1381129>`_.
14.321836
12.972054
1.104053
if attrs is None: attrs = self.read_json() attrs['search_'] = attrs.pop('search') # Satellite doesn't return this attribute. See BZ 1257255. attr = 'max_count' if ignore is None: ignore = set() if attr not in ignore: # We cann...
def read(self, entity=None, attrs=None, ignore=None, params=None)
Work around a bug. Rename ``search`` to ``search_``. For more information on the bug, see `Bugzilla #1257255 <https://bugzilla.redhat.com/show_bug.cgi?id=1257255>`_.
7.666526
5.802777
1.321182
payload = super(DiscoveryRule, self).update_payload(fields) if 'search_' in payload: payload['search'] = payload.pop('search_') return {u'discovery_rule': payload}
def update_payload(self, fields=None)
Wrap submitted data within an extra dict.
5.16135
4.907963
1.051628
return DockerComputeResource( self._server_config, id=self.create_json(create_missing)['id'], ).read()
def create(self, create_missing=None)
Do extra work to fetch a complete set of attributes for this entity. For more information, see `Bugzilla #1223540 <https://bugzilla.redhat.com/show_bug.cgi?id=1223540>`_.
19.515799
20.028908
0.974382
if attrs is None: attrs = self.read_json() if ignore is None: ignore = set() ignore.add('password') if 'email' not in attrs and 'email' not in ignore: response = client.put( self.path('self'), {}, ...
def read(self, entity=None, attrs=None, ignore=None, params=None)
Do extra work to fetch a complete set of attributes for this entity. For more information, see `Bugzilla #1223540 <https://bugzilla.redhat.com/show_bug.cgi?id=1223540>`_. Also, do not try to read the "password" field. No value is returned for the field, for obvious reasons.
4.039702
3.954247
1.021611
if entity is None: entity = type(self)( self._server_config, usergroup=self.usergroup, # pylint:disable=no-member ) if ignore is None: ignore = set() ignore.add('usergroup') if attrs is None: attrs ...
def read(self, entity=None, attrs=None, ignore=None, params=None)
Ignore usergroup from read and alter auth_source_ldap with auth_source
4.367484
3.36751
1.296948
if which == 'refresh': return '{0}/{1}'.format( super(ExternalUserGroup, self).path(which='self'), which ) return super(ExternalUserGroup, self).path(which)
def path(self, which=None)
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: refresh /api/usergroups/:usergroup_id/external_usergroups/:id/refresh
6.093859
4.425171
1.37709
payload = super(ConfigTemplate, self).create_payload() if 'template_combinations' in payload: payload['template_combinations_attributes'] = payload.pop( 'template_combinations') return {u'config_template': payload}
def create_payload(self)
Wrap submitted data within an extra dict. For more information, see `Bugzilla #1151220 <https://bugzilla.redhat.com/show_bug.cgi?id=1151220>`_.
4.809572
5.076892
0.947346
payload = super(ConfigTemplate, self).update_payload(fields) if 'template_combinations' in payload: payload['template_combinations_attributes'] = payload.pop( 'template_combinations') return {u'config_template': payload}
def update_payload(self, fields=None)
Wrap submitted data within an extra dict.
4.126174
4.074001
1.012806
if which in ('build_pxe_default', 'clone', 'revision'): prefix = 'self' if which == 'clone' else 'base' return '{0}/{1}'.format( super(ConfigTemplate, self).path(prefix), which ) return super(ConfigTemplate, self).path(which)
def path(self, which=None)
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: build_pxe_default /config_templates/build_pxe_default clone /config_templates/clone revision /config_templates/revision ``super`...
7.099232
3.159279
2.247105
if entity is None: entity = TemplateInput(self._server_config, template=self.template) if ignore is None: ignore = set() ignore.add('advanced') return super(TemplateInput, self).read(entity=entity, attrs=attrs, ...
def read(self, entity=None, attrs=None, ignore=None, params=None)
Create a JobTemplate object before calling read() ignore 'advanced'
3.970425
3.368095
1.178834
kwargs = kwargs.copy() # shadow the passed-in kwargs kwargs.update(self._server_config.get_client_kwargs()) if 'data' in kwargs: if 'job_template_id' not in kwargs['data'] and 'feature' not in kwargs['data']: raise KeyError('Provide either job_template_id or...
def run(self, synchronous=True, **kwargs)
Helper to run 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 ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. ...
4.539908
3.184393
1.425675
payload = super(JobTemplate, self).create_payload() effective_user = payload.pop(u'effective_user', None) if effective_user: payload[u'ssh'] = {u'effective_user': effective_user} return {u'job_template': payload}
def create_payload(self)
Wrap submitted data within an extra dict.
4.909733
4.20662
1.167145
payload = super(JobTemplate, self).update_payload(fields) effective_user = payload.pop(u'effective_user', None) if effective_user: payload[u'ssh'] = {u'effective_user': effective_user} return {u'job_template': payload}
def update_payload(self, fields=None)
Wrap submitted data within an extra dict.
4.124645
3.920811
1.051988
if attrs is None: attrs = self.read_json(params=params) if ignore is None: ignore = set() ignore.add('template_inputs') entity = super(JobTemplate, self).read(entity=entity, attrs=attrs, ignore=ignore, params...
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.
3.892404
3.222237
1.207982
super(ProvisioningTemplate, self).create_missing() if (getattr(self, 'snippet', None) is False and not hasattr(self, 'template_kind')): self.template_kind = TemplateKind(self._server_config, id=1)
def create_missing(self)
Customize the process of auto-generating instance attributes. Populate ``template_kind`` if: * this template is not a snippet, and * the ``template_kind`` instance attribute is unset.
9.511504
5.859356
1.623302
payload = super(ProvisioningTemplate, self).create_payload() if 'template_combinations' in payload: payload['template_combinations_attributes'] = payload.pop( 'template_combinations') return {u'provisioning_template': payload}
def create_payload(self)
Wrap submitted data within an extra dict. For more information, see `Bugzilla #1151220 <https://bugzilla.redhat.com/show_bug.cgi?id=1151220>`_.
5.128506
5.344171
0.959645
payload = super(ProvisioningTemplate, self).update_payload(fields) if 'template_combinations' in payload: payload['template_combinations_attributes'] = payload.pop( 'template_combinations') return {u'provisioning_template': payload}
def update_payload(self, fields=None)
Wrap submitted data within an extra dict.
4.363263
4.230746
1.031322
if which in ('build_pxe_default', 'clone', 'revision'): prefix = 'self' if which == 'clone' else 'base' return '{0}/{1}'.format( super(ProvisioningTemplate, self).path(prefix), which ) return super(ProvisioningTemplate, self).p...
def path(self, which=None)
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: build_pxe_default /provisioning_templates/build_pxe_default clone /provisioning_templates/clone revision /provisioning_templates/revision...
7.08357
3.02193
2.344056
if which in ('logs', 'power'): return '{0}/{1}'.format( super(AbstractDockerContainer, self).path(which='self'), which ) return super(AbstractDockerContainer, self).path(which)
def path(self, which=None)
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: logs /containers/<id>/logs power /containers/<id>/power ``super`` is called otherwise.
6.327016
4.30304
1.47036
# read() should not change the state of the object it's called on, but # super() alters the attributes of any entity passed in. Creating a new # object and passing it to super() lets this one avoid changing state. if entity is None: entity = type(self)( ...
def read(self, entity=None, attrs=None, ignore=None, params=None)
Provide a default value for ``entity``. By default, ``nailgun.entity_mixins.EntityReadMixin.read`` provides a default value for ``entity`` like so:: entity = type(self)() However, :class:`ContentUpload` requires that a ``repository`` be provided, so this technique will not...
6.905972
6.651003
1.038335
kwargs = kwargs.copy() # shadow the passed-in kwargs kwargs.update(self._server_config.get_client_kwargs()) # a content upload is always multipart headers = kwargs.pop('headers', {}) headers['content-type'] = 'multipart/form-data' kwargs['headers'] = headers ...
def update(self, fields=None, **kwargs)
Update the current entity. Make an HTTP PUT call to ``self.path('base')``. Return the response. :param fields: An iterable of field names. Only the fields named in this iterable will be updated. No fields are updated if an empty iterable is passed in. All fields are updated if ...
6.01168
5.888301
1.020953
base = urljoin( self._server_config.url + '/', self._meta['api_path'] # pylint:disable=no-member ) if (which == 'self' or which is None) and hasattr(self, 'upload_id'): # pylint:disable=E1101 return urljoin(base + '/', str(self.upload_id)...
def path(self, which=None)
Extend ``nailgun.entity_mixins.Entity.path``.
5.194677
4.894157
1.061404
if not filename: filename = os.path.basename(filepath) content_upload = self.create() try: offset = 0 content_chunk_size = 2 * 1024 * 1024 with open(filepath, 'rb') as contentfile: chunk = contentfile.read(content_chunk_...
def upload(self, filepath, filename=None)
Upload content. :param filepath: path to the file that should be chunked and uploaded :param filename: name of the file on the server, defaults to the last part of the ``filepath`` if not set :returns: The server's response, with all JSON decoded. :raises: ``requests.excepti...
2.510627
2.638519
0.951529
if which in ('incremental_update', 'promote'): prefix = 'base' if which == 'incremental_update' else 'self' return '{0}/{1}'.format( super(ContentViewVersion, self).path(prefix), which ) return super(ContentViewVersion, self).p...
def path(self, which=None)
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: incremental_update /content_view_versions/incremental_update promote /content_view_versions/<id>/promote ``super`` is called otherwise.
5.821222
3.383621
1.720412
if entity is None: entity = type(self)( self._server_config, # pylint:disable=no-member content_view_filter=self.content_view_filter, ) if attrs is None: attrs = self.read_json() if ignore is None: ...
def read(self, entity=None, attrs=None, ignore=None, params=None)
Do not read certain fields. Do not expect the server to return the ``content_view_filter`` attribute. This has no practical impact, as the attribute must be provided when a :class:`nailgun.entities.ContentViewFilterRule` is instantiated. Also, ignore any field that is not retur...
3.670927
3.015742
1.217255
payload = super(ContentViewFilterRule, self).create_payload() if 'errata_id' in payload: if not hasattr(self.errata, 'errata_id'): self.errata = self.errata.read() payload['errata_id'] = self.errata.errata_id return payload
def create_payload(self)
Reset ``errata_id`` from DB ID to ``errata_id``.
4.557683
3.209185
1.4202
payload = super(ContentViewFilterRule, self).update_payload(fields) if 'errata_id' in payload: if not hasattr(self.errata, 'errata_id'): self.errata = self.errata.read() payload['errata_id'] = self.errata.errata_id return payload
def update_payload(self, fields=None)
Reset ``errata_id`` from DB ID to ``errata_id``.
4.060669
3.094351
1.312285
payload = super(ContentViewFilterRule, self).search_payload( fields, query) if 'errata_id' in payload: if not hasattr(self.errata, 'errata_id'): self.errata = self.errata.read() payload['errata_id'] = self.errata.errata_id return paylo...
def search_payload(self, fields=None, query=None)
Reset ``errata_id`` from DB ID to ``errata_id``.
4.427984
3.454959
1.281631
# read() should not change the state of the object it's called on, but # super() alters the attributes of any entity passed in. Creating a new # object and passing it to super() lets this one avoid changing state. if entity is None: entity = type(self)( ...
def read(self, entity=None, attrs=None, ignore=None, params=None)
Provide a default value for ``entity``. By default, ``nailgun.entity_mixins.EntityReadMixin.read provides a default value for ``entity`` like so:: entity = type(self)() However, :class:`ContentViewPuppetModule` requires that an ``content_view`` be provided, so this techniq...
6.97928
5.850333
1.192971
if attrs is None: attrs = self.read_json() if _get_version(self._server_config) < Version('6.1'): org = _get_org(self._server_config, attrs['organization']['label']) attrs['organization'] = org.get_values() if ignore is None: ignore = set...
def read(self, entity=None, attrs=None, ignore=None, params=None)
Fetch an attribute missing from the server's response. For more information, see `Bugzilla #1237257 <https://bugzilla.redhat.com/show_bug.cgi?id=1237257>`_. Add content_view_component to the response if needed, as :meth:`nailgun.entity_mixins.EntityReadMixin.read` can't initialize ...
3.636785
3.501421
1.03866
results = self.search_json(fields, query)['results'] results = self.search_normalize(results) entities = [] for result in results: content_view_components = result.get('content_view_component') if content_view_components is not None: del r...
def search(self, fields=None, query=None, filters=None)
Search for entities. :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 an empty set, no values are used. :param query: A dict containing a raw search query. This is melded in to ...
3.329316
3.239398
1.027758
if which in ( 'available_puppet_module_names', 'available_puppet_modules', 'content_view_puppet_modules', 'content_view_versions', 'copy', 'publish'): return '{0}/{1}'.format( sup...
def path(self, which=None)
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: content_view_puppet_modules /content_views/<id>/content_view_puppet_modules content_view_versions /content_views/<id>/content_view_versions publish ...
6.374316
3.193166
1.996237
kwargs = kwargs.copy() # shadow the passed-in kwargs if 'data' in kwargs and 'id' not in kwargs['data']: kwargs['data']['id'] = self.id # pylint:disable=no-member kwargs.update(self._server_config.get_client_kwargs()) response = client.post(self.path('publish'), **...
def publish(self, synchronous=True, **kwargs)
Helper for publishing 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 ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to req...
4.719516
4.734607
0.996813
if isinstance(environment, Environment): environment_id = environment.id else: environment_id = environment response = client.delete( '{0}/environments/{1}'.format(self.path(), environment_id), **self._server_config.get_client_kwargs() ...
def delete_from_environment(self, environment, synchronous=True)
Delete this content view version from an environment. This method acts much like :meth:`nailgun.entity_mixins.EntityDeleteMixin.delete`. The documentation on that method describes how the deletion procedure works in general. This method differs only in accepting an ``environment`` ...
3.322659
4.02003
0.826526
if attrs is None: attrs = self.read_json() if ignore is None: ignore = set() if entity is None: entity = type(self)( self._server_config, composite_content_view=self.composite_content_view, ) ignore...
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.
4.448165
3.570683
1.245746
if which in ( 'add', 'remove'): return '{0}/{1}'.format( super(ContentViewComponent, self).path(which='base'), which ) return super(ContentViewComponent, self).path(which)
def path(self, which=None)
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: add /content_view_components/add remove /content_view_components/remove Otherwise, call ``super``.
6.983239
4.123192
1.693649
kwargs = kwargs.copy() # shadow the passed-in kwargs if 'data' not in kwargs: # data is required kwargs['data'] = dict() if 'component_ids' not in kwargs['data']: kwargs['data']['components'] = [_payload(self.get_fields(), self.get_values())] ...
def add(self, synchronous=True, **kwargs)
Add 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 ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. ...
5.617276
5.830322
0.963459
if not hasattr(self, 'name'): self.name = gen_alphanumeric().lower() super(Domain, self).create_missing()
def create_missing(self)
Customize the process of auto-generating instance attributes. By default, :meth:`nailgun.entity_fields.StringField.gen_value` can produce strings in both lower and upper cases, but domain name should be always in lower case due logical reason.
6.776419
5.172375
1.310117
return Domain( self._server_config, id=self.create_json(create_missing)['id'], ).read()
def create(self, create_missing=None)
Manually fetch a complete set of attributes for this entity. For more information, see `Bugzilla #1219654 <https://bugzilla.redhat.com/show_bug.cgi?id=1219654>`_.
16.590084
18.847946
0.880206
if which in ('smart_class_parameters',): return '{0}/{1}'.format( super(Environment, self).path(which='self'), which ) return super(Environment, self).path(which)
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 /api/environments/:environment_id/smart_class_parameters Otherwise, call ``super``.
7.98686
3.849059
2.075016
if which in ('compare',): return '{0}/{1}'.format(super(Errata, self).path('base'), which) return super(Errata, self).path(which)
def path(self, which=None)
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: compare /katello/api/errata/compare Otherwise, call ``super``.
6.276421
4.419281
1.420236
if attrs is None: attrs = self.read_json() attrs['override'] = attrs.pop('override?') attrs['unlimited'] = attrs.pop('unlimited?') return super(Filter, self).read(entity, attrs, ignore, params)
def read(self, entity=None, attrs=None, ignore=None, params=None)
Deal with different named data returned from the server
4.695604
4.590822
1.022824
if which in ('bulk_resume', 'bulk_search', 'summary'): return '{0}/{1}'.format( super(ForemanTask, self).path('base'), which ) return super(ForemanTask, self).path(which)
def path(self, which=None)
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: bulk_resume /foreman_tasks/api/tasks/bulk_resume bulk_search /foreman_tasks/api/tasks/bulk_search summary /foreman_tasks/api/tasks/summar...
6.457377
2.969137
2.174833
# See nailgun.entity_mixins._poll_task for an explanation of why a # private method is called. return _poll_task( self.id, # pylint:disable=no-member self._server_config, poll_rate, timeout )
def poll(self, poll_rate=None, timeout=None)
Return the status of a task or timeout. There are several API calls that trigger asynchronous tasks, such as synchronizing a repository, or publishing or promoting a content view. It is possible to check on the status of a task if you know its UUID. This method polls a task once every `...
9.529951
7.532175
1.265232
payload = super(HostCollection, self).create_payload() if 'system_ids' in payload: payload['system_uuids'] = payload.pop('system_ids') return payload
def create_payload(self)
Rename ``system_ids`` to ``system_uuids``.
4.905966
2.317676
2.116761
return HostCollection( self._server_config, id=self.create_json(create_missing)['id'], ).read()
def create(self, create_missing=None)
Manually fetch a complete set of attributes for this entity. For more information, see `Bugzilla #1654383 <https://bugzilla.redhat.com/show_bug.cgi?id=1654383>`_.
18.270117
20.170692
0.905775
payload = super(HostCollection, self).update_payload(fields) if 'system_ids' in payload: payload['system_uuids'] = payload.pop('system_ids') return payload
def update_payload(self, fields=None)
Rename ``system_ids`` to ``system_uuids``.
3.780191
2.165544
1.745608
return HostGroup( self._server_config, id=self.create_json(create_missing)['id'], ).read()
def create(self, create_missing=None)
Do extra work to fetch a complete set of attributes for this entity. For more information, see `Bugzilla #1235377 <https://bugzilla.redhat.com/show_bug.cgi?id=1235377>`_.
15.543971
17.352377
0.895783
if ignore is None: ignore = set() ignore.add('root_pass') ignore.add('kickstart_repository') if attrs is None: attrs = self.read_json() attrs['parent_id'] = attrs.pop('ancestry') # either an ID or None version = _get_version(self._server...
def read(self, entity=None, attrs=None, ignore=None, params=None)
Deal with several bugs. For more information, see: * `Bugzilla #1235377 <https://bugzilla.redhat.com/show_bug.cgi?id=1235377>`_ * `Bugzilla #1235379 <https://bugzilla.redhat.com/show_bug.cgi?id=1235379>`_ * `Bugzilla #1450379 <https://bugzilla.redhat.com/s...
6.19034
6.03952
1.024972
if which in ( 'clone', 'puppetclass_ids', 'smart_class_parameters', 'smart_variables' ): return '{0}/{1}'.format( super(HostGroup, self).path(which='self'), which ) re...
def path(self, which=None)
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: clone /api/hostgroups/:hostgroup_id/clone puppetclass_ids /api/hostgroups/:hostgroup_id/puppetclass_ids smart_class_parameters /api/hostgr...
8.031202
2.87337
2.795047
kwargs = kwargs.copy() kwargs.update(self._server_config.get_client_kwargs()) path = "{0}/{1}".format( self.path('puppetclass_ids'), kwargs['data'].pop('puppetclass_id') ) return _handle_response( client.delete(path, **kwargs), self._s...
def delete_puppetclass(self, synchronous=True, **kwargs)
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}) Constructs path: /api/hostgroups/:hostgroup_id/puppetclass_ids/:id :param synchronous: What should happen if the server...
5.494036
5.062366
1.08527
if which in ( 'add_subscriptions', 'remove_subscriptions'): return '{0}/{1}'.format( super(HostSubscription, self).path(which='base'), which ) return super(HostSubscription, self).path(which)
def path(self, which=None)
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: add_subscriptions /hosts/<id>/add_subscriptions remove_subscriptions /hosts/<id>/remove_subscriptions ``super`` is called otherwise.
6.266344
4.138085
1.51431