How to use _do_properties method in Lemoncheesecake

Best Python code snippet using lemoncheesecake

glare.py

Source:glare.py Github

copy

Full Screen

...90 tags = values.pop('tags')91 artifact.tags = _do_tags(artifact, tags)92 if 'properties' in values:93 properties = values.pop('properties', {})94 artifact.properties = _do_properties(artifact, properties)95 if 'blobs' in values:96 blobs = values.pop('blobs')97 artifact.blobs = _do_blobs(artifact, blobs)98 if 'dependencies' in values:99 dependencies = values.pop('dependencies')100 _do_dependencies(artifact, dependencies, session)101 if values.get('state', None) == 'publish':102 artifact.dependencies.extend(103 _do_transitive_dependencies(artifact, session))104 artifact.update(values)105 try:106 artifact.save(session=session)107 except db_exc.DBDuplicateEntry:108 LOG.warn(_LW("Artifact with the specified type, name and version "109 "already exists"))110 raise exception.ArtifactDuplicateNameTypeVersion()111 return artifact112def get(context, artifact_id, session, type_name=None, type_version=None,113 show_level=ga.Showlevel.BASIC):114 artifact = _get(context, artifact_id, session, type_name, type_version,115 show_level)116 return _out(artifact, show_level)117def publish(context, artifact_id, session, type_name,118 type_version=None):119 """120 Because transitive dependencies are not initially created it has to be done121 manually by calling this function.122 It creates transitive dependencies for the given artifact_id and saves123 them in DB.124 :returns: artifact dict with Transitive show level125 """126 values = {'state': 'active'}127 return _out(_create_or_update(context, values, artifact_id, session,128 type_name, type_version))129def _validate_transition(source_state, target_state):130 if target_state == source_state:131 return132 try:133 source_state = State(source_state)134 target_state = State(target_state)135 except ValueError:136 raise exception.InvalidArtifactStateTransition(source=source_state,137 target=target_state)138 if (source_state not in TRANSITIONS or139 target_state not in TRANSITIONS[source_state]):140 raise exception.InvalidArtifactStateTransition(source=source_state,141 target=target_state)142def _out(artifact, show_level=ga.Showlevel.BASIC, show_text_properties=True):143 """144 Transforms sqlalchemy object into dict depending on the show level.145 :param artifact: sql146 :param show_level: constant from Showlevel class147 :param show_text_properties: for performance optimization it's possible148 to disable loading of massive text properties149 :returns: generated dict150 """151 res = artifact.to_dict(show_level=show_level,152 show_text_properties=show_text_properties)153 if show_level >= ga.Showlevel.DIRECT:154 dependencies = artifact.dependencies155 dependencies.sort(key=lambda elem: (elem.artifact_origin,156 elem.name, elem.position))157 res['dependencies'] = {}158 if show_level == ga.Showlevel.DIRECT:159 new_show_level = ga.Showlevel.BASIC160 else:161 new_show_level = ga.Showlevel.TRANSITIVE162 for dep in dependencies:163 if dep.artifact_origin == artifact.id:164 # make array165 for p in res['dependencies'].keys():166 if p == dep.name:167 # add value to array168 res['dependencies'][p].append(169 _out(dep.dest, new_show_level))170 break171 else:172 # create new array173 deparr = [_out(dep.dest, new_show_level)]174 res['dependencies'][dep.name] = deparr175 return res176def _get(context, artifact_id, session, type_name=None, type_version=None,177 show_level=ga.Showlevel.BASIC):178 values = dict(id=artifact_id)179 if type_name is not None:180 values['type_name'] = type_name181 if type_version is not None:182 values['type_version'] = type_version183 _set_version_fields(values)184 try:185 if show_level == ga.Showlevel.NONE:186 query = (187 session.query(models.Artifact).188 options(joinedload(models.Artifact.tags)).189 filter_by(**values))190 else:191 query = (192 session.query(models.Artifact).193 options(joinedload(models.Artifact.properties)).194 options(joinedload(models.Artifact.tags)).195 options(joinedload(models.Artifact.blobs).196 joinedload(models.ArtifactBlob.locations)).197 filter_by(**values))198 artifact = query.one()199 except orm.exc.NoResultFound:200 LOG.warn(_LW("Artifact with id=%s not found") % artifact_id)201 raise exception.ArtifactNotFound(id=artifact_id)202 if not _check_visibility(context, artifact):203 LOG.warn(_LW("Artifact with id=%s is not accessible") % artifact_id)204 raise exception.ArtifactForbidden(id=artifact_id)205 return artifact206def get_all(context, session, marker=None, limit=None,207 sort_keys=None, sort_dirs=None, filters=None,208 show_level=ga.Showlevel.NONE):209 """List all visible artifacts"""210 filters = filters or {}211 artifacts = _get_all(212 context, session, filters, marker,213 limit, sort_keys, sort_dirs, show_level)214 return map(lambda ns: _out(ns, show_level, show_text_properties=False),215 artifacts)216def _get_all(context, session, filters=None, marker=None,217 limit=None, sort_keys=None, sort_dirs=None,218 show_level=ga.Showlevel.NONE):219 """Get all namespaces that match zero or more filters.220 :param filters: dict of filter keys and values.221 :param marker: namespace id after which to start page222 :param limit: maximum number of namespaces to return223 :param sort_keys: namespace attributes by which results should be sorted224 :param sort_dirs: directions in which results should be sorted (asc, desc)225 """226 filters = filters or {}227 query = _do_artifacts_query(context, session, show_level)228 basic_conds, tag_conds, prop_conds = _do_query_filters(filters)229 if basic_conds:230 for basic_condition in basic_conds:231 query = query.filter(and_(*basic_condition))232 if tag_conds:233 for tag_condition in tag_conds:234 query = query.join(models.ArtifactTag, aliased=True).filter(235 and_(*tag_condition))236 if prop_conds:237 for prop_condition in prop_conds:238 query = query.join(models.ArtifactProperty, aliased=True).filter(239 and_(*prop_condition))240 marker_artifact = None241 if marker is not None:242 marker_artifact = _get(context, marker, session, None, None)243 if sort_keys is None:244 sort_keys = [('created_at', None), ('id', None)]245 sort_dirs = ['desc', 'desc']246 else:247 for key in [('created_at', None), ('id', None)]:248 if key not in sort_keys:249 sort_keys.append(key)250 sort_dirs.append('desc')251 # Note(mfedosin): Workaround to deal with situation that sqlalchemy cannot252 # work with composite keys correctly253 if ('version', None) in sort_keys:254 i = sort_keys.index(('version', None))255 version_sort_dir = sort_dirs[i]256 sort_keys[i:i + 1] = [('version_prefix', None),257 ('version_suffix', None),258 ('version_meta', None)]259 sort_dirs[i:i + 1] = [version_sort_dir] * 3260 query = _do_paginate_query(query=query,261 limit=limit,262 sort_keys=sort_keys,263 marker=marker_artifact,264 sort_dirs=sort_dirs)265 return query.all()266def _do_paginate_query(query, sort_keys=None, sort_dirs=None,267 marker=None, limit=None):268 # Default the sort direction to ascending269 sort_dir = 'asc'270 # Ensure a per-column sort direction271 if sort_dirs is None:272 sort_dirs = [sort_dir] * len(sort_keys)273 assert(len(sort_dirs) == len(sort_keys)) # nosec274 # nosec: This function runs safely if the assertion fails.275 if len(sort_dirs) < len(sort_keys):276 sort_dirs += [sort_dir] * (len(sort_keys) - len(sort_dirs))277 # Add sorting278 for current_sort_key, current_sort_dir in zip(sort_keys, sort_dirs):279 try:280 sort_dir_func = {281 'asc': sqlalchemy.asc,282 'desc': sqlalchemy.desc,283 }[current_sort_dir]284 except KeyError:285 raise ValueError(_LE("Unknown sort direction, "286 "must be 'desc' or 'asc'"))287 if current_sort_key[1] is None:288 # sort by generic property289 query = query.order_by(sort_dir_func(getattr(290 models.Artifact,291 current_sort_key[0])))292 else:293 # sort by custom property294 prop_type = current_sort_key[1] + "_value"295 query = (296 query.join(models.ArtifactProperty).297 filter(models.ArtifactProperty.name == current_sort_key[0]).298 order_by(sort_dir_func(getattr(models.ArtifactProperty,299 prop_type))))300 default = ''301 # Add pagination302 if marker is not None:303 marker_values = []304 for sort_key in sort_keys:305 v = getattr(marker, sort_key[0])306 if v is None:307 v = default308 marker_values.append(v)309 # Build up an array of sort criteria as in the docstring310 criteria_list = []311 for i in range(len(sort_keys)):312 crit_attrs = []313 if marker_values[i] is None:314 continue315 for j in range(i):316 if sort_keys[j][1] is None:317 model_attr = getattr(models.Artifact, sort_keys[j][0])318 else:319 model_attr = getattr(models.ArtifactProperty,320 sort_keys[j][1] + "_value")321 default = None if isinstance(322 model_attr.property.columns[0].type,323 sqlalchemy.DateTime) else ''324 attr = case([(model_attr != None,325 model_attr), ],326 else_=default)327 crit_attrs.append((attr == marker_values[j]))328 if sort_keys[i][1] is None:329 model_attr = getattr(models.Artifact, sort_keys[i][0])330 else:331 model_attr = getattr(models.ArtifactProperty,332 sort_keys[i][1] + "_value")333 default = None if isinstance(model_attr.property.columns[0].type,334 sqlalchemy.DateTime) else ''335 attr = case([(model_attr != None,336 model_attr), ],337 else_=default)338 if sort_dirs[i] == 'desc':339 crit_attrs.append((attr < marker_values[i]))340 else:341 crit_attrs.append((attr > marker_values[i]))342 criteria = and_(*crit_attrs)343 criteria_list.append(criteria)344 f = or_(*criteria_list)345 query = query.filter(f)346 if limit is not None:347 query = query.limit(limit)348 return query349def _do_artifacts_query(context, session, show_level=ga.Showlevel.NONE):350 """Build the query to get all artifacts based on the context"""351 LOG.debug("context.is_admin=%(is_admin)s; context.owner=%(owner)s",352 {'is_admin': context.is_admin, 'owner': context.owner})353 if show_level == ga.Showlevel.NONE:354 query = session.query(models.Artifact).options(355 joinedload(models.Artifact.tags))356 elif show_level == ga.Showlevel.BASIC:357 query = (358 session.query(models.Artifact).359 options(joinedload(360 models.Artifact.properties).361 defer(models.ArtifactProperty.text_value)).362 options(joinedload(models.Artifact.tags)).363 options(joinedload(models.Artifact.blobs).364 joinedload(models.ArtifactBlob.locations)))365 else:366 # other show_levels aren't supported367 msg = _LW("Show level %s is not supported in this "368 "operation") % ga.Showlevel.to_str(show_level)369 LOG.warn(msg)370 raise exception.ArtifactUnsupportedShowLevel(shl=show_level)371 # If admin, return everything.372 if context.is_admin:373 return query374 else:375 # If regular user, return only public artifacts.376 # However, if context.owner has a value, return both377 # public and private artifacts of the context.owner.378 if context.owner is not None:379 query = query.filter(380 or_(models.Artifact.owner == context.owner,381 models.Artifact.visibility == 'public'))382 else:383 query = query.filter(384 models.Artifact.visibility == 'public')385 return query386op_mappings = {387 'EQ': operator.eq,388 'GT': operator.gt,389 'GE': operator.ge,390 'LT': operator.lt,391 'LE': operator.le,392 'NE': operator.ne,393 'IN': operator.eq # it must be eq394}395def _do_query_filters(filters):396 basic_conds = []397 tag_conds = []398 prop_conds = []399 # don't show deleted artifacts400 basic_conds.append([models.Artifact.state != 'deleted'])401 visibility = filters.pop('visibility', None)402 if visibility is not None:403 # ignore operator. always consider it EQ404 basic_conds.append(405 [models.Artifact.visibility == visibility[0]['value']])406 type_name = filters.pop('type_name', None)407 if type_name is not None:408 # ignore operator. always consider it EQ409 basic_conds.append([models.Artifact.type_name == type_name['value']])410 type_version = filters.pop('type_version', None)411 if type_version is not None:412 # ignore operator. always consider it EQ413 # TODO(mfedosin) add support of LIKE operator414 type_version = semver_db.parse(type_version['value'])415 basic_conds.append([models.Artifact.type_version == type_version])416 name = filters.pop('name', None)417 if name is not None:418 # ignore operator. always consider it EQ419 basic_conds.append([models.Artifact.name == name[0]['value']])420 versions = filters.pop('version', None)421 if versions is not None:422 for version in versions:423 value = semver_db.parse(version['value'])424 op = version['operator']425 fn = op_mappings[op]426 basic_conds.append([fn(models.Artifact.version, value)])427 state = filters.pop('state', None)428 if state is not None:429 # ignore operator. always consider it EQ430 basic_conds.append([models.Artifact.state == state['value']])431 owner = filters.pop('owner', None)432 if owner is not None:433 # ignore operator. always consider it EQ434 basic_conds.append([models.Artifact.owner == owner[0]['value']])435 id_list = filters.pop('id_list', None)436 if id_list is not None:437 basic_conds.append([models.Artifact.id.in_(id_list['value'])])438 name_list = filters.pop('name_list', None)439 if name_list is not None:440 basic_conds.append([models.Artifact.name.in_(name_list['value'])])441 tags = filters.pop('tags', None)442 if tags is not None:443 for tag in tags:444 tag_conds.append([models.ArtifactTag.value == tag['value']])445 # process remaining filters446 for filtername, filtervalues in filters.items():447 for filtervalue in filtervalues:448 db_prop_op = filtervalue['operator']449 db_prop_value = filtervalue['value']450 db_prop_type = filtervalue['type'] + "_value"451 db_prop_position = filtervalue.get('position')452 conds = [models.ArtifactProperty.name == filtername]453 if db_prop_op in op_mappings:454 fn = op_mappings[db_prop_op]455 result = fn(getattr(models.ArtifactProperty, db_prop_type),456 db_prop_value)457 cond = [result]458 if db_prop_position is not 'any':459 cond.append(460 models.ArtifactProperty.position == db_prop_position)461 if db_prop_op == 'IN':462 if (db_prop_position is not None and463 db_prop_position is not 'any'):464 msg = _LE("Cannot use this parameter with "465 "the operator IN")466 LOG.error(msg)467 raise exception.ArtifactInvalidPropertyParameter(468 op='IN')469 cond = [result,470 models.ArtifactProperty.position >= 0]471 else:472 msg = _LE("Operator %s is not supported") % db_prop_op473 LOG.error(msg)474 raise exception.ArtifactUnsupportedPropertyOperator(475 op=db_prop_op)476 conds.extend(cond)477 prop_conds.append(conds)478 return basic_conds, tag_conds, prop_conds479def _do_tags(artifact, new_tags):480 tags_to_update = []481 # don't touch existing tags482 for tag in artifact.tags:483 if tag.value in new_tags:484 tags_to_update.append(tag)485 new_tags.remove(tag.value)486 # add new tags487 for tag in new_tags:488 db_tag = models.ArtifactTag()489 db_tag.value = tag490 tags_to_update.append(db_tag)491 return tags_to_update492def _do_property(propname, prop, position=None):493 db_prop = models.ArtifactProperty()494 db_prop.name = propname495 setattr(db_prop,496 (prop['type'] + "_value"),497 prop['value'])498 db_prop.position = position499 return db_prop500def _do_properties(artifact, new_properties):501 props_to_update = []502 # don't touch existing properties503 for prop in artifact.properties:504 if prop.name not in new_properties:505 props_to_update.append(prop)506 for propname, prop in new_properties.items():507 if prop['type'] == 'array':508 for pos, arrprop in enumerate(prop['value']):509 props_to_update.append(510 _do_property(propname, arrprop, pos)511 )512 else:513 props_to_update.append(514 _do_property(propname, prop)...

Full Screen

Full Screen

filter.py

Source:filter.py Github

copy

Full Screen

...85 def _do_descriptions(self, node):86 return all(self._match_values(node.hierarchy_descriptions, descs) for descs in self.descriptions)87 def _do_tags(self, node):88 return all(self._match_values(node.hierarchy_tags, tags) for tags in self.tags)89 def _do_properties(self, node):90 return all(self._match_key_values(node.hierarchy_properties, props) for props in self.properties)91 def _do_links(self, node):92 return all(self._match_values_lists(node.hierarchy_links, links) for links in self.links)93 @staticmethod94 def _apply_criteria(obj, *criteria):95 return all(criterion(obj) for criterion in criteria)96 def __call__(self, node):97 assert isinstance(node, (BaseTest, BaseSuite))98 return self._apply_criteria(99 node, self._do_paths, self._do_descriptions, self._do_tags, self._do_properties, self._do_links100 )101class TestFilter(BaseTreeNodeFilter):102 def __init__(self, enabled=False, disabled=False, **kwargs):103 BaseTreeNodeFilter.__init__(self, **kwargs)...

Full Screen

Full Screen

ukriss.py

Source:ukriss.py Github

copy

Full Screen

...44 classes.append(self._do_class(child))45 elif self._is_rel(rawname, child):46 relations.append(self._do_relations(child))47 else:48 properties.append(self._do_properties(child))49 50 if len(classes) > 0:51 nodetree["children"].append({"name" : "CLASSES", "children" : classes})52 if len(relations) > 0:53 nodetree["children"].append({"name" : "RELATIONS", "children" : relations})54 if len(properties) > 0:55 nodetree["children"].append({"name" : "PROPERTIES", "children" : properties})56 57 return nodetree58 59 def _do_class(self, node):60 class_id = node.find(self.NS + "cfClassId")61 class_scheme = node.find(self.NS + "cfClassSchemeId")62 return {"name" : class_scheme.text, "children" : [{"name" : class_id.text}]}63 # return {"name" : "Scheme: " + class_scheme.text + ", ID: " + class_id.text}64 65 def _do_relations(self, node):66 class_id = node.find(self.NS + "cfClassId")67 class_scheme = node.find(self.NS + "cfClassSchemeId")68 obj = {"name" : class_scheme.text + "/" + class_id.text, "children" : []}69 for child in node:70 if not isinstance(child.tag, str):71 continue72 73 if not child.tag.startswith("{urn:xmlns:org:eurocris:cerif-1.6-2}"):74 continue75 76 if (not child.tag.endswith("cfClassId") and 77 not child.tag.endswith("cfClassSchemeId")):78 obj["children"].append({"name" : child.tag[36:]})79 # return {"name" : child.tag[36:] + ": " + obj.get("name", "")}80 return obj81 82 def _do_properties(self, node):83 if len(node.getchildren()) > 0:84 return self._do_nodes(node)85 return {"name" : node.tag[36:], "children" : [{"name" : str(node.text)}]}86 # return {"name" : node.tag[36:] + ": " + str(node.text)} # FIXME: need to deal with attributes somewhere87 88 def _is_class(self, rawname, child):89 return child.tag.endswith("cf" + rawname + "_Class")90 91 def _is_rel(self, rawname, child):92 p1 = "cf" + rawname + "_"93 p2 = "_" + rawname94 return p1 in child.tag or p2 in child.tag95 96 ...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Lemoncheesecake automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful