def __setup__(cls): super(Model, cls).__setup__() cls.__rpc__ = { 'default_get': RPC(), 'fields_get': RPC(), 'pre_validate': RPC(instantiate=0), } cls._error_messages = {} # Copy fields and update depends for attr in dir(cls): if attr.startswith('_'): continue if not isinstance(getattr(cls, attr), fields.Field): continue field_name = attr field = getattr(cls, field_name) # Copy the original field definition to prevent side-effect with # the mutable attributes for parent_cls in cls.__mro__: parent_field = getattr(parent_cls, field_name, None) if isinstance(parent_field, fields.Field): field = parent_field field = copy.deepcopy(field) setattr(cls, field_name, field)
def __setup__(cls): super(UserView, cls).__setup__() cls.__rpc__['user_views_get'] = RPC(cache=dict(days=1)) cls.__rpc__['user_view_fields_get'] = RPC(cache=dict(days=1)) cls.__rpc__['user_view_set'] = RPC(readonly=False) cls.__rpc__['user_view_set_default_view'] = RPC(readonly=False) cls.__rpc__['user_view_manager_access'] = RPC(cache=dict(days=1))
def __post_setup__(cls): super(ModelView, cls).__post_setup__() # Update __rpc__ for field_name, field in cls._fields.iteritems(): field.set_rpc(cls) for button in cls._buttons: if not is_instance_method(cls, button): cls.__rpc__.setdefault(button, RPC(readonly=False, instantiate=0)) else: cls.__rpc__.setdefault( button, RPC(instantiate=0, result=on_change_result)) # Update depend on methods for (field_name, attribute), others in (cls.__depend_methods.iteritems()): field = getattr(cls, field_name) for other in others: other_field = getattr(cls, other) setattr( field, attribute, getattr(field, attribute) | getattr(other_field, attribute)) # JMO : work around BUG#8723 func = getattr(cls, attribute + '_' + field_name, None) if func: if not hasattr(func, 'depends'): setattr(func, 'depends', set()) deps = getattr(func, 'depends') deps |= getattr(other_field, attribute, set())
def __setup__(cls): super(ModelInfo, cls).__setup__() cls.__rpc__.update({ 'raw_model_infos': RPC(), 'raw_module_infos': RPC(), 'raw_field_infos': RPC(), })
def __post_setup__(cls): super(ModelView, cls).__post_setup__() # Update __rpc__ for field_name, field in cls._fields.iteritems(): field.set_rpc(cls) for button in cls._buttons: if not is_instance_method(cls, button): cls.__rpc__.setdefault(button, RPC(readonly=False, instantiate=0)) else: cls.__rpc__.setdefault( button, RPC(instantiate=0, result=on_change_result)) # Update depend on methods for (field_name, attribute), others in (cls.__depend_methods.iteritems()): field = getattr(cls, field_name) for other in others: other_field = getattr(cls, other) setattr( field, attribute, getattr(field, attribute) | getattr(other_field, attribute))
def __post_setup__(cls): super(ModelView, cls).__post_setup__() # Update __rpc__ for field_name, field in cls._fields.items(): field.set_rpc(cls) for button in cls._buttons: if not is_instance_method(cls, button): cls.__rpc__.setdefault(button, RPC(readonly=False, instantiate=0)) else: cls.__rpc__.setdefault(button, RPC(instantiate=0, result=on_change_result)) for parent_cls in cls.__mro__: parent_meth = getattr(parent_cls, button, None) if not parent_meth: continue cls.__change_buttons[button] |= getattr( parent_meth, 'change', set()) for method_name, rpc in cls.__rpc__.items(): if not rpc.cache: continue cache_name = 'rpc.%s.%s' % (cls.__name__, method_name) cache_duration = config.getint('cache', cache_name, default=None) if cache_duration is not None: rpc.cache.duration = datetime.timedelta(seconds=cache_duration)
def __setup__(cls): super(ShipmentOut, cls).__setup__() # There can be cases when people might want to use a different # shipment carrier after the shipment is marked as done cls.carrier.states = { 'readonly': ~Eval('state').in_(['packed', 'done']), } cls._error_messages.update({ 'warehouse_address_required': 'Warehouse address is required.', 'mailclass_missing': 'Select a mailclass to ship using Endicia [USPS].', 'error_label': 'Error in generating label "%s"', 'tracking_number_already_present': 'Tracking Number is already present for this shipment.', 'invalid_state': 'Labels can only be generated when the ' 'shipment is in Packed or Done states only', 'wrong_carrier': 'Carrier for selected shipment is not Endicia', }) cls.__rpc__.update({ 'make_endicia_labels': RPC(readonly=False, instantiate=0), 'get_endicia_shipping_cost': RPC(readonly=False, instantiate=0), })
def __setup__(cls): super(UIMenuFavorite, cls).__setup__() cls.__rpc__.update({ 'get': RPC(), 'set': RPC(readonly=False), 'unset': RPC(readonly=False), })
def __setup__(cls): super(ShipmentOut, cls).__setup__() # There can be cases when people might want to use a different # shipment carrier at any state except `done`. cls.carrier.states = STATES cls._error_messages.update({ 'ups_wrong_carrier': 'Carrier for selected shipment is not UPS', 'ups_service_type_missing': 'UPS service type missing.', 'tracking_number_already_present': 'Tracking Number is already present for this shipment.', 'invalid_state': 'Labels can only be generated when the ' 'shipment is in Packed or Done states only', 'no_packages': 'Shipment %s has no packages', }) cls.__rpc__.update({ 'make_ups_labels': RPC(readonly=False, instantiate=0), 'get_ups_shipping_cost': RPC(readonly=False, instantiate=0), 'get_worldship_xml': RPC(instantiate=0, readonly=True), })
def __setup__(cls): super(Address, cls).__setup__() cls._order.insert(0, ('party', 'ASC')) cls.__rpc__.update( autocomplete_zip=RPC(instantiate=0, cache=dict(days=1)), autocomplete_city=RPC(instantiate=0, cache=dict(days=1)), )
def __setup__(cls): super(ModelView, cls).__setup__() cls.__rpc__['fields_view_get'] = RPC() cls.__rpc__['view_toolbar_get'] = RPC() cls.__rpc__['on_change'] = RPC(instantiate=0) cls.__rpc__['on_change_with'] = RPC(instantiate=0) cls._buttons = {} if hasattr(cls, '__depend_methods'): cls.__depend_methods = cls.__depend_methods.copy() else: cls.__depend_methods = collections.defaultdict(set) if hasattr(cls, '__change_buttons'): cls.__change_buttons = cls.__change_buttons.copy() else: cls.__change_buttons = collections.defaultdict(set) def setup_field(field, field_name): for attribute in ('on_change', 'on_change_with', 'autocomplete', 'selection_change_with'): if attribute == 'selection_change_with': if isinstance(getattr(field, 'selection', None), basestring): function_name = field.selection else: continue else: function_name = '%s_%s' % (attribute, field_name) if not getattr(cls, function_name, None): continue # Search depends on all parent class because field has been # copied with the original definition for parent_cls in cls.__mro__: function = getattr(parent_cls, function_name, None) if not function: continue if getattr(function, 'depends', None): setattr(field, attribute, getattr(field, attribute) | function.depends) if getattr(function, 'depend_methods', None): cls.__depend_methods[(field_name, attribute)] |= \ function.depend_methods function = getattr(cls, function_name, None) if (attribute == 'on_change' and not getattr(function, 'on_change', None)): # Decorate on_change to always return self setattr(cls, function_name, on_change(function)) def setup_callable(function, name): if hasattr(function, 'change'): cls.__change_buttons[name] |= function.change for name in dir(cls): attr = getattr(cls, name) if isinstance(attr, fields.Field): setup_field(attr, name) elif isinstance(attr, collections.Callable): setup_callable(attr, name)
def __setup__(cls): super().__setup__() cls._order.insert(0, ('create_date', 'DESC')) cls.__rpc__.update({ 'send': RPC(readonly=False, result=int), 'complete': RPC(check_access=False), }) del cls.__rpc__['create']
def __setup__(cls): super(PaymentProfile, cls).__setup__() cls.__rpc__.update({ 'create_profile_using_stripe_token': RPC(instantiate=0, readonly=True), 'update_stripe': RPC(instantiate=0, readonly=False), })
def __setup__(cls): super(ModelInfo, cls).__setup__() cls.__rpc__.update({ 'raw_model_infos': RPC(), 'raw_module_infos': RPC(), 'raw_field_infos': RPC(), }) cls._buttons.update({ 'follow_link': {}, })
def test_check_access(self): "Test check_access" rpc_no_access = RPC(check_access=False) self.assertEqual(rpc_no_access.convert(None, {}), ([], {}, {}, None)) rpc_with_access = RPC(check_access=True) self.assertEqual(rpc_with_access.convert(None, {}), ([], {}, { '_check_access': True }, None))
def __setup__(cls): super(UIMenuFavorite, cls).__setup__() cls.__rpc__.update({ 'get': RPC(), 'set': RPC(readonly=False), 'unset': RPC(readonly=False), }) cls._order = [ ('sequence', 'ASC'), ('id', 'DESC'), ]
def __setup__(cls): super(Wizard, cls).__setup__() cls.__rpc__ = { 'create': RPC(readonly=False), 'delete': RPC(readonly=False), 'execute': RPC(readonly=False, check_access=False), } # Copy states for attr in dir(cls): if isinstance(getattr(cls, attr), State): setattr(cls, attr, copy.deepcopy(getattr(cls, attr)))
def __post_setup__(cls): super(ModelView, cls).__post_setup__() # Update __rpc__ for field_name, field in cls._fields.items(): field.set_rpc(cls) for button in cls._buttons: if not is_instance_method(cls, button): cls.__rpc__.setdefault(button, RPC(readonly=False, instantiate=0)) else: cls.__rpc__.setdefault( button, RPC(instantiate=0, result=on_change_result))
def __setup__(cls): super(Bench, cls).__setup__() cls.__rpc__['list'] = RPC(readonly=False) cls.__rpc__['setup'] = RPC(readonly=False) cls.__rpc__['teardown'] = RPC(readonly=False) cls.__rpc__['test_latency'] = RPC(readonly=True) cls.__rpc__['test_cpu'] = RPC(readonly=True) cls.__rpc__['test_memory'] = RPC(readonly=True) cls.__rpc__['test_db_latency'] = RPC(readonly=False) cls.__rpc__['test_db_write'] = RPC(readonly=False) cls.__rpc__['test_db_read'] = RPC(readonly=False)
def __setup__(cls): super(ModelView, cls).__setup__() cls.__rpc__['fields_view_get'] = RPC(cache=dict(days=1)) cls.__rpc__['view_toolbar_get'] = RPC(cache=dict(days=1)) cls.__rpc__['on_change'] = RPC(instantiate=0) cls.__rpc__['on_change_with'] = RPC(instantiate=0) cls._buttons = {} fields_ = {} for name in dir(cls): if name.startswith('__'): continue attr = getattr(cls, name) if isinstance(attr, fields.Field): fields_[name] = attr
def set_rpc(self, model): super(Char, self).set_rpc(model) if self.autocomplete: func_name = 'autocomplete_%s' % self.name assert hasattr(model, func_name), \ 'Missing %s on model %s' % (func_name, model.__name__) model.__rpc__.setdefault(func_name, RPC(instantiate=0))
def test_missing_context(self): "Test missing context" rpc = RPC() with self.assertRaises(ValueError) as cm: rpc.convert(None) self.assertEqual(str(cm.exception), "Missing context argument")
def test_wrong_context_type(self): "Test wrong context type" rpc = RPC() with self.assertRaises(TypeError) as cm: rpc.convert(None, context=None) self.assertEqual(str(cm.exception), "context must be a dictionary")
def __setup__(cls): super(FiscalYear, cls).__setup__() cls._order.insert(0, ('start_date', 'ASC')) cls._transitions |= set(( ('open', 'close'), ('close', 'locked'), ('close', 'open'), )) cls._buttons.update({ 'create_periods': { 'invisible': ((Eval('state') != 'open') | Eval('periods', [0])), 'depends': ['state'], }, 'close': { 'invisible': Eval('state') != 'open', 'depends': ['state'], }, 'reopen': { 'invisible': Eval('state') != 'close', 'depends': ['state'], }, 'lock': { 'invisible': Eval('state') != 'close', 'depends': ['state'], }, }) cls.__rpc__.update({ 'create_period': RPC(readonly=False, instantiate=0), })
def __setup__(cls, *a, **k): super(RemoteParty, cls).__setup__(*a, **k) cls.__rpc__['fetch_remote_party'] = RPC(readonly=False) # if not hasattr(cls, '_xcache'): # cls._xcache = LRUDict(RECORD_CACHE_SIZE) # # _zcache stores the records to be import # if not hasattr(cls, '_zcache'): # cls._zcache = LRUDict(RECORD_CACHE_SIZE) # if not hasattr(cls, '_post_import_cache'): # cls._post_import_cache = LRUDict(RECORD_CACHE_SIZE) pool = Pool() cls._target_model = pool.get('party.party') cache_server = config.get('synchronisation', 'cache_server', '127.0.0.1:11211') cls._sync_id_local = config.get('synchronisation', 'id', '511') cls._cache_client = memcache.Client([cache_server]) # cls._cache_model = pool.get('party.party.remote_cache') cls._cache_field_names = ['searched', 'to_import', 'imported'] cls._buttons.update({ 'mark_for_import': { 'readonly': Eval('marked_for_import', False) }, 'unmark_import': { 'readonly': ~Eval('marked_for_import', False) } })
def test_instantiate(self): "Test instantiate" def side_effect(*args, **kwargs): self.assertEqual(Transaction().context, {'test': True}) return DEFAULT rpc = RPC(instantiate=0, check_access=True) obj = Mock() obj.return_value = instance = Mock() obj.side_effect = side_effect # Integer self.assertEqual( rpc.convert(obj, 1, {'test': True}), ([instance], {}, {'test': True, '_check_access': True}, None)) obj.assert_called_once_with(1) obj.reset_mock() # Dictionary self.assertEqual( rpc.convert(obj, {'foo': 'bar'}, {'test': True}), ([instance], {}, {'test': True, '_check_access': True}, None)) obj.assert_called_once_with(foo='bar') obj.reset_mock() obj.browse.return_value = instances = Mock() # List self.assertEqual( rpc.convert(obj, [1, 2, 3], {'test': True}), ([instances], {}, {'test': True, '_check_access': True}, None)) obj.browse.assert_called_once_with([1, 2, 3])
def __setup__(cls): super().__setup__() t = cls.__table__() cls.__rpc__.update({ 'read': RPC(), 'search': RPC(), 'search_count': RPC(), 'search_read': RPC(), }) cls.index.domain = [ ('index', '>=', cls._min_index), ('index', '<=', cls._max_index), ] cls._order = [('index', 'ASC')] cls._sql_constraints = [('index_unique', Unique(t, t.index), "The index must by unique.")]
def __setup__(cls): """ Setup the class before adding to pool """ super(SaleChannel, cls).__setup__() cls._buttons.update({ 'import_data_button': {}, 'export_data_button': {}, 'import_order_states_button': {}, 'import_shipping_carriers': {}, }) cls.__rpc__.update({ 'get_listings_updated_after': RPC(instantiate=0, readonly=True), }) cls._error_messages.update({ "no_carriers_found": "Shipping carrier is not configured for code: %s", "no_tax_found": "%s (tax) of rate %f was not found.", "no_order_states_to_import": "No importable order state found\n" "HINT: Import order states from Order States tab in Channel" }) cls._order.insert(0, ('sequence', 'ASC'))
def __call__(self, *args): from trytond.transaction import Transaction from trytond.rpc import RPC if self._name in self._object.__rpc__: rpc = self._object.__rpc__[self._name] elif self._name in getattr(self._object, '_buttons', {}): rpc = RPC(readonly=False, instantiate=0) else: raise TypeError('%s is not callable' % self._name) with Transaction().start(self._config.database_name, self._config.user, readonly=rpc.readonly) as transaction: args, kwargs, transaction.context, transaction.timestamp = \ rpc.convert(self._object, *args) meth = getattr(self._object, self._name) if not hasattr(meth, 'im_self') or meth.im_self: result = rpc.result(meth(*args, **kwargs)) else: assert rpc.instantiate == 0 inst = args.pop(0) if hasattr(inst, self._name): result = rpc.result(meth(inst, *args, **kwargs)) else: result = [rpc.result(meth(i, *args, **kwargs)) for i in inst] if not rpc.readonly: transaction.commit() return result
def test_keyword_argument(self): "Test keyword argument" rpc = RPC(check_access=False) self.assertEqual(rpc.convert(None, 'foo', bar=True, context={}), (['foo'], { 'bar': True }, {}, None))