How to use owner_model method in autotest

Best Python code snippet using autotest_python

compound.py

Source:compound.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2from __future__ import unicode_literals, absolute_import3import collections4from collections import Iterable, Sequence, Mapping5import itertools6from ..common import * # pylint: disable=redefined-builtin7from ..datastructures import OrderedDict8from ..exceptions import *9from ..transforms import (10 export_loop,11 get_import_context, get_export_context,12 to_native_converter, to_primitive_converter)13from .base import BaseType, get_value_in14class CompoundType(BaseType):15 def __init__(self, **kwargs):16 super(CompoundType, self).__init__(**kwargs)17 self.is_compound = True18 try:19 self.field.parent_field = self20 except AttributeError:21 pass22 def _setup(self, field_name, owner_model):23 # Recursively set up inner fields.24 if hasattr(self, 'field'):25 self.field._setup(None, owner_model)26 super(CompoundType, self)._setup(field_name, owner_model)27 def convert(self, value, context=None):28 context = context or get_import_context()29 return self._convert(value, context)30 def _convert(self, value, context):31 raise NotImplementedError32 def export(self, value, format, context=None):33 context = context or get_export_context()34 return self._export(value, format, context)35 def _export(self, value, format, context):36 raise NotImplementedError37 def to_native(self, value, context=None):38 context = context or get_export_context(to_native_converter)39 return to_native_converter(self, value, context)40 def to_primitive(self, value, context=None):41 context = context or get_export_context(to_primitive_converter)42 return to_primitive_converter(self, value, context)43 def _init_field(self, field, options):44 """45 Instantiate the inner field that represents each element within this compound type.46 In case the inner field is itself a compound type, its inner field can be provided47 as the ``nested_field`` keyword argument.48 """49 if not isinstance(field, BaseType):50 nested_field = options.pop('nested_field', None) or options.pop('compound_field', None)51 if nested_field:52 field = field(field=nested_field, **options)53 else:54 field = field(**options)55 return field56MultiType = CompoundType57class ModelType(CompoundType):58 """A field that can hold an instance of the specified model."""59 @property60 def fields(self):61 return self.model_class.fields62 def __init__(self, model_spec, **kwargs):63 if isinstance(model_spec, ModelMeta):64 self.model_class = model_spec65 self.model_name = self.model_class.__name__66 elif isinstance(model_spec, string_type):67 self.model_class = None68 self.model_name = model_spec69 else:70 raise TypeError("ModelType: Expected a model, got an argument "71 "of the type '{}'.".format(model_spec.__class__.__name__))72 super(ModelType, self).__init__(**kwargs)73 def _repr_info(self):74 return self.model_class.__name__75 def _mock(self, context=None):76 return self.model_class.get_mock_object(context)77 def _setup(self, field_name, owner_model):78 # Resolve possible name-based model reference.79 if not self.model_class:80 if self.model_name == owner_model.__name__:81 self.model_class = owner_model82 else:83 raise Exception("ModelType: Unable to resolve model '{}'.".format(self.model_name))84 super(ModelType, self)._setup(field_name, owner_model)85 def pre_setattr(self, value):86 if value is not None \87 and not isinstance(value, Model):88 value = self.model_class(value)89 return value90 def _convert(self, value, context):91 if isinstance(value, self.model_class):92 model_class = type(value)93 elif isinstance(value, dict):94 model_class = self.model_class95 else:96 raise ConversionError(97 "Input must be a mapping or '%s' instance" % self.model_class.__name__)98 if context.convert and context.oo:99 return model_class(value, context=context)100 else:101 return model_class.convert(value, context=context)102 def _export(self, value, format, context):103 if isinstance(value, Model):104 model_class = type(value)105 else:106 model_class = self.model_class107 return export_loop(model_class, value, context=context)108class ListType(CompoundType):109 """A field for storing a list of items, all of which must conform to the type110 specified by the ``field`` parameter.111 Use it like this::112 ...113 categories = ListType(StringType)114 """115 def __init__(self, field, min_size=None, max_size=None, **kwargs):116 self.field = self._init_field(field, kwargs)117 self.min_size = min_size118 self.max_size = max_size119 validators = [self.check_length] + kwargs.pop("validators", [])120 super(ListType, self).__init__(validators=validators, **kwargs)121 @property122 def model_class(self):123 return self.field.model_class124 def _repr_info(self):125 return self.field.__class__.__name__126 def _mock(self, context=None):127 min_size = self.min_size or 1128 max_size = self.max_size or 1129 if min_size > max_size:130 message = 'Minimum list size is greater than maximum list size.'131 raise MockCreationError(message)132 random_length = get_value_in(min_size, max_size)133 return [self.field._mock(context) for _ in range(random_length)]134 def _coerce(self, value):135 if isinstance(value, list):136 return value137 elif isinstance(value, (string_type, Mapping)): # unacceptable iterables138 pass139 elif isinstance(value, Sequence):140 return value141 elif isinstance(value, Iterable):142 return value143 raise ConversionError('Could not interpret the value as a list')144 def _convert(self, value, context):145 value = self._coerce(value)146 data = []147 errors = {}148 for index, item in enumerate(value):149 try:150 data.append(context.field_converter(self.field, item, context))151 except BaseError as exc:152 errors[index] = exc153 if errors:154 raise CompoundError(errors)155 return data156 def check_length(self, value, context):157 list_length = len(value) if value else 0158 if self.min_size is not None and list_length < self.min_size:159 message = ({160 True: 'Please provide at least %d item.',161 False: 'Please provide at least %d items.',162 }[self.min_size == 1]) % self.min_size163 raise ValidationError(message)164 if self.max_size is not None and list_length > self.max_size:165 message = ({166 True: 'Please provide no more than %d item.',167 False: 'Please provide no more than %d items.',168 }[self.max_size == 1]) % self.max_size169 raise ValidationError(message)170 def _export(self, list_instance, format, context):171 """Loops over each item in the model and applies either the field172 transform or the multitype transform. Essentially functions the same173 as `transforms.export_loop`.174 """175 data = []176 _export_level = self.field.get_export_level(context)177 if _export_level == DROP:178 return data179 for value in list_instance:180 shaped = self.field.export(value, format, context)181 if shaped is None:182 if _export_level <= NOT_NONE:183 continue184 elif self.field.is_compound and len(shaped) == 0:185 if _export_level <= NONEMPTY:186 continue187 data.append(shaped)188 return data189class DictType(CompoundType):190 """A field for storing a mapping of items, the values of which must conform to the type191 specified by the ``field`` parameter.192 Use it like this::193 ...194 categories = DictType(StringType)195 """196 def __init__(self, field, coerce_key=None, **kwargs):197 self.field = self._init_field(field, kwargs)198 self.coerce_key = coerce_key or str199 super(DictType, self).__init__(**kwargs)200 @property201 def model_class(self):202 return self.field.model_class203 def _repr_info(self):204 return self.field.__class__.__name__205 def _convert(self, value, context, safe=False):206 if not isinstance(value, Mapping):207 raise ConversionError('Only mappings may be used in a DictType')208 data = {}209 errors = {}210 for k, v in iteritems(value):211 try:212 data[self.coerce_key(k)] = context.field_converter(self.field, v, context)213 except BaseError as exc:214 errors[k] = exc215 if errors:216 raise CompoundError(errors)217 return data218 def _export(self, dict_instance, format, context):219 """Loops over each item in the model and applies either the field220 transform or the multitype transform. Essentially functions the same221 as `transforms.export_loop`.222 """223 data = {}224 _export_level = self.field.get_export_level(context)225 if _export_level == DROP:226 return data227 for key, value in iteritems(dict_instance):228 shaped = self.field.export(value, format, context)229 if shaped is None:230 if _export_level <= NOT_NONE:231 continue232 elif self.field.is_compound and len(shaped) == 0:233 if _export_level <= NONEMPTY:234 continue235 data[key] = shaped236 return data237class PolyModelType(CompoundType):238 """A field that accepts an instance of any of the specified models."""239 def __init__(self, model_spec, **kwargs):240 if isinstance(model_spec, (ModelMeta, string_type)):241 self.model_classes = (model_spec,)242 allow_subclasses = True243 elif isinstance(model_spec, Iterable):244 self.model_classes = tuple(model_spec)245 allow_subclasses = False246 else:247 raise Exception("The first argument to PolyModelType.__init__() "248 "must be a model or an iterable.")249 self.claim_function = kwargs.pop("claim_function", None)250 self.allow_subclasses = kwargs.pop("allow_subclasses", allow_subclasses)251 CompoundType.__init__(self, **kwargs)252 def _setup(self, field_name, owner_model):253 # Resolve possible name-based model references.254 resolved_classes = []255 for m in self.model_classes:256 if isinstance(m, string_type):257 if m == owner_model.__name__:258 resolved_classes.append(owner_model)259 else:260 raise Exception("PolyModelType: Unable to resolve model '{}'.".format(m))261 else:262 resolved_classes.append(m)263 self.model_classes = tuple(resolved_classes)264 super(PolyModelType, self)._setup(field_name, owner_model)265 def is_allowed_model(self, model_instance):266 if self.allow_subclasses:267 if isinstance(model_instance, self.model_classes):268 return True269 else:270 if model_instance.__class__ in self.model_classes:271 return True272 return False273 def _convert(self, value, context):274 if value is None:275 return None276 if self.is_allowed_model(value):277 return value278 if not isinstance(value, dict):279 if len(self.model_classes) > 1:280 instanceof_msg = 'one of: {}'.format(', '.join(281 cls.__name__ for cls in self.model_classes))282 else:283 instanceof_msg = self.model_classes[0].__name__284 raise ConversionError('Please use a mapping for this field or '285 'an instance of {}'.format(instanceof_msg))286 model_class = self.find_model(value)287 return model_class(value, context=context)288 def find_model(self, data):289 """Finds the intended type by consulting potential classes or `claim_function`."""290 chosen_class = None291 if self.claim_function:292 chosen_class = self.claim_function(self, data)293 else:294 candidates = self.model_classes295 if self.allow_subclasses:296 candidates = itertools.chain.from_iterable(297 ([m] + m._subclasses for m in candidates))298 fallback = None299 matching_classes = []300 for cls in candidates:301 match = None302 if '_claim_polymorphic' in cls.__dict__:303 match = cls._claim_polymorphic(data)304 elif not fallback: # The first model that doesn't define the hook305 fallback = cls # can be used as a default if there's no match.306 if match:307 matching_classes.append(cls)308 if not matching_classes and fallback:309 chosen_class = fallback310 elif len(matching_classes) == 1:311 chosen_class = matching_classes[0]312 else:313 raise Exception("Got ambiguous input for polymorphic field")314 if chosen_class:315 return chosen_class316 else:317 raise Exception("Input for polymorphic field did not match any model")318 def _export(self, model_instance, format, context):319 model_class = model_instance.__class__320 if not self.is_allowed_model(model_instance):321 raise Exception("Cannot export: {} is not an allowed type".format(model_class))322 return model_instance.export(context=context)...

Full Screen

Full Screen

treemodel.py

Source:treemodel.py Github

copy

Full Screen

1from __future__ import annotations2from unicodedata import normalize3from gi.repository import Gio, GObject, Pango4from gaphor import UML5from gaphor.core.format import format6from gaphor.core.modeling import Diagram, Element7from gaphor.diagram.iconname import get_icon_name8from gaphor.i18n import gettext9_no_value = object()10class TreeItem(GObject.Object):11 def __init__(self, element):12 super().__init__()13 self.element = element14 if element:15 self.sync()16 text = GObject.Property(type=str)17 icon = GObject.Property(type=str)18 icon_visible = GObject.Property(type=bool, default=False)19 attributes = GObject.Property(type=Pango.AttrList)20 visible_child_name = GObject.Property(type=str, default="default")21 @GObject.Property(type=str)22 def read_only(self):23 return not self.element or not hasattr(self.element, "name")24 @GObject.Property(type=str)25 def edit_text(self):26 return "" if self.read_only else (self.element.name or "")27 @edit_text.setter # type: ignore[no-redef]28 def edit_text(self, text):29 if not self.read_only:30 self.element.name = text or ""31 def sync(self) -> None:32 if element := self.element:33 self.text = format(element) or gettext("<None>")34 self.notify("edit-text")35 self.icon = get_icon_name(element)36 self.icon_visible = bool(37 self.icon38 and not isinstance(39 element, (UML.Parameter, UML.Property, UML.Operation)40 )41 )42 self.attributes = pango_attributes(element)43 def start_editing(self):44 self.visible_child_name = "editing"45class RelationshipItem(TreeItem):46 def __init__(self):47 super().__init__(None)48 self.text = gettext("<Relationships>")49 def start_editing(self):50 pass51def visible(element):52 return isinstance(53 element, (UML.Relationship, UML.NamedElement, Diagram)54 ) and not isinstance(55 element, (UML.InstanceSpecification, UML.OccurrenceSpecification)56 )57def tree_item_sort(a, b, _user_data=None):58 if isinstance(a, RelationshipItem):59 return -160 if isinstance(b, RelationshipItem):61 return 162 na = normalize("NFC", a.text).casefold()63 nb = normalize("NFC", b.text).casefold()64 return (na > nb) - (na < nb)65class TreeModel:66 def __init__(self):67 super().__init__()68 self.branches: dict[TreeItem | None, Gio.ListStore] = {69 None: Gio.ListStore.new(TreeItem.__gtype__)70 }71 @property72 def root(self):73 return self.branches[None]74 def sync(self, element):75 if visible(element) and (tree_item := self.tree_item_for_element(element)):76 tree_item.sync()77 def child_model(self, item: TreeItem, _user_data=None):78 """This method will create branches on demand (lazy)."""79 branches = self.branches80 if item in branches:81 return branches[item]82 elif not item.element:83 return None84 elif owned_elements := [85 e86 for e in item.element.ownedElement87 if e.owner is item.element and visible(e)88 ]:89 new_branch = Gio.ListStore.new(TreeItem.__gtype__)90 self.branches[item] = new_branch91 for e in owned_elements:92 self._maybe_relationships_model(e, new_branch, create=True).append(93 TreeItem(e)94 )95 return new_branch96 return None97 def _maybe_relationships_model(98 self, element: Element, owner_model: Gio.ListStore, create: bool99 ) -> Gio.ListStore:100 """Return `owner_model`, or the model to hold relationships."""101 if not isinstance(element, UML.Relationship):102 return owner_model103 if isinstance(owner_model.get_item(0), RelationshipItem):104 return self.branches[owner_model.get_item(0)]105 if create:106 relationship_item = RelationshipItem()107 relationship_branch = Gio.ListStore.new(TreeItem.__gtype__)108 self.branches[relationship_item] = relationship_branch109 # Add item after branch, so it is seen as expandable110 owner_model.insert(0, relationship_item)111 return relationship_branch112 return owner_model113 def list_model_for_element(114 self, element: Element, former_owner=_no_value, create=False115 ) -> Gio.ListStore | None:116 if (117 owner := element.owner if former_owner is _no_value else former_owner118 ) is None:119 return self.root120 if (121 owner_model := next(122 (m for ti, m in self.branches.items() if ti and ti.element is owner),123 None,124 )125 ) is not None:126 return self._maybe_relationships_model(element, owner_model, create)127 return None128 def tree_item_for_element(self, element: Element | None) -> TreeItem | None:129 if element is None:130 return None131 if owner_model := self.list_model_for_element(element):132 return next((ti for ti in owner_model if ti.element is element), None)133 return None134 def add_element(self, element: Element) -> None:135 if (not visible(element)) or self.tree_item_for_element(element):136 return137 if (138 owner_model := self.list_model_for_element(element, create=True)139 ) is not None:140 owner_model.append(TreeItem(element))141 elif element.owner:142 self.notify_child_model(element.owner)143 def remove_element(self, element: Element, former_owner=_no_value) -> None:144 for child in element.ownedElement:145 self.remove_element(child)146 if (147 owner_model := self.list_model_for_element(148 element, former_owner=former_owner149 )150 ) is not None:151 index = next(152 (i for i, ti in enumerate(owner_model) if ti.element is element), None153 )154 if index is not None:155 owner_model.remove(index)156 if not len(owner_model):157 self.remove_branch(158 owner_model,159 element.owner if former_owner is _no_value else former_owner,160 )161 # TODO: if relationship, remove Relationships node if empty162 def remove_branch(self, branch: Gio.ListStore, owner) -> None:163 tree_item = next(ti for ti, b in self.branches.items() if b is branch)164 if tree_item is None:165 # Do never remove the root branch166 return167 del self.branches[tree_item]168 if tree_item.element:169 self.notify_child_model(tree_item.element)170 elif isinstance(tree_item, RelationshipItem):171 owner_item = self.tree_item_for_element(owner)172 if owner_model := self.branches.get(owner_item):173 if owner_model.get_item(0) is tree_item:174 owner_model.remove(0)175 else:176 raise NotImplementedError()177 def notify_child_model(self, element):178 # Only notify the change, the branch is created in child_model()179 if not (tree_item := self.tree_item_for_element(element)):180 return181 if self.branches.get(tree_item):182 return183 owner_tree_item = self.tree_item_for_element(element.owner)184 if (owner_model := self.branches.get(owner_tree_item)) is not None:185 found, index = owner_model.find(tree_item)186 if found:187 owner_model.items_changed(index, 1, 1)188 def clear(self) -> None:189 root = self.root190 root.remove_all()191 self.branches.clear()192 self.branches[None] = root193def pango_attributes(element):194 attrs = Pango.AttrList.new()195 attrs.insert(196 Pango.attr_weight_new(197 Pango.Weight.BOLD if isinstance(element, Diagram) else Pango.Weight.NORMAL198 )199 )200 attrs.insert(201 Pango.attr_style_new(202 Pango.Style.ITALIC203 if isinstance(element, (UML.Classifier, UML.BehavioralFeature))204 and element.isAbstract205 else Pango.Style.NORMAL206 )207 )...

Full Screen

Full Screen

importer.py

Source:importer.py Github

copy

Full Screen

1from odoo.addons.component.core import Component2from odoo.addons.connector.components.mapper import mapping3from odoo.addons.connector.exception import MappingError4class ImageBatchImporter(Component):5 """ Import the distant Odoo Images.6 For every Images in the list, a delayed job is created.7 """8 _name = 'odoo.base_multi_image.image.batch.importer'9 _inherit = 'odoo.delayed.batch.importer'10 _apply_on = ['odoo.base_multi_image.image']11 def _import_record(self, external_id, job_options=None):12 """ Delay the job for the import"""13 super(ImageBatchImporter, self)._import_record(14 external_id, job_options=job_options,15 )16 def run(self, filters=[]):17 """ Run the synchronization"""18 updated_ids = self.backend_adapter.search(filters)19 for updated in updated_ids:20 self._import_record(updated)21class ImageImporter(Component):22 _name = 'odoo.base_multi_image.image.importer'23 _inherit = 'odoo.importer'24 _apply_on = ['odoo.base_multi_image.image']25 def _import_dependencies(self):26 """ Import the attribute dependencies for the record"""27 record = self.odoo_record28 # import product attribute29 if record.get('product_variant_ids'):30 for variant_id in record.get('product_variant_ids'):31 self._import_dependency(variant_id, 'odoo.product.product')32class ImageImportMapper(Component):33 _name = 'odoo.base_multi_image.image.import.mapper'34 _inherit = 'odoo.import.mapper'35 _apply_on = 'odoo.base_multi_image.image'36 direct = [37 ('owner_model', 'owner_model'),38 ('storage', 'storage'),39 ('filename', 'filename'),40 ('comments', 'comments'),41 ('sequence', 'sequence'),42 ('name', 'name'),43 ('file_db_store', 'file_db_store'),44 ]45 @mapping46 def backend_id(self, record):47 return {'backend_id': self.backend_record.id}48 @mapping49 def product_variant_ids(self, record):50 if not record.get('product_variant_ids'):51 return52 binder = self.binder_for('odoo.product.product')53 variant_ids = []54 for variant in record.get('product_variant_ids'):55 variant_binding = binder.to_internal(variant)56 if not variant_binding:57 raise MappingError("The product with "58 "distant Odoo id %s is not import." %59 variant)60 variant_ids.append(variant_binding.odoo_id)61 return {62 'product_variant_ids': [(6, 0, variant_ids)]63 }64 @mapping65 def owner_id(self, record):66 if not record.get('owner_model') or not record.get('owner_id'):67 return68 binding_model = record.get('owner_model')69 binding_id = record.get('owner_id')70 binder = self.binder_for('odoo.%s' % binding_model)71 if not binder:72 return73 record_binding = binder.to_internal(binding_id)74 if not record_binding:75 raise MappingError("The %s with "76 "distant Odoo id %s is not import." % (77 binding_model,78 binding_id,79 )80 )81 return {82 'owner_id': record_binding.odoo_id.id,83 }84 @mapping85 def owner_ref_id(self, record):86 if not record.get('owner_model') or not record.get('owner_id'):87 return88 return {89 'owner_ref_id': '%s,%s' % (90 record.get('owner_model'),91 self.owner_id(record).get('owner_id'),92 )...

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 autotest 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