def test_propagate_work_on(self): """ Check custom attributes and their propagation """ registry = ComponentRegistry() work = WorkContext( model_name='res.partner', collection=self.collection, # we can customize the lookup registry, but used mostly for tests components_registry=registry, # we can pass our own keyword args that will set as attributes test_keyword='value', ) self.assertIs(registry, work.components_registry) # check that our custom keyword is set as attribute self.assertEqual('value', work.test_keyword) # when we want to work on another model, work_on() create # another instance and propagate the attributes to it work2 = work.work_on('res.users') self.assertNotEqual(work, work2) self.assertEqual(self.env, work2.env) self.assertEqual(self.collection, work2.collection) self.assertEqual('res.users', work2.model_name) self.assertIs(registry, work2.components_registry) # test_keyword has been propagated to the new WorkContext instance self.assertEqual('value', work2.test_keyword)
def matches(self, query, mode=MATCH_MODE_NORMAL, stop_on_first=False, threshold=None): """ Given an query find recordset that is strongly similar @TODO implement threshold """ matches = self.env['openg2p.beneficiary'] work = WorkContext(model_name=self._name, collection=self.with_context(active_test=False)) matchers = [ matcher for matcher in work.many_components(usage='beneficiary.matcher') if matcher.mode <= mode ] matchers.sort(key=lambda r: r.sequence) for matcher in matchers: res = matcher.match(query) if res: matches += res if stop_on_first: break return matches if len(matches) else False
def _get_services(self, collection_name): collection = _PseudoCollection(collection_name, self.env) work = WorkContext(model_name="rest.service.registration", collection=collection) component_classes = work._lookup_components(usage=None, model_name=None) # removes component without collection that are not a rest service component_classes = [c for c in component_classes if self._filter_service_component(c)] return [comp(work) for comp in component_classes]
def _get_provider(self, provider_name=None): if not provider_name: if self: provider_name = self.payment_mode_id.provider else: raise UserError(_('Provider name is missing')) work = WorkContext(model_name=self._name, collection=self) yield work.component_by_name('payment.service.%s' % provider_name)
def _get_service_component(self, usage): collection = _PseudoCollection(self._collection_name, self.env) work = WorkContext( model_name="rest.service.registration", collection=collection, components_registry=self.comp_registry, ) return work.component(usage=usage)
def _get_service_component(class_or_instance, usage): collection = _PseudoCollection(class_or_instance._collection_name, class_or_instance.env) work = WorkContext( model_name="rest.service.registration", collection=collection, components_registry=class_or_instance.comp_registry, ) return work.component(usage=usage)
def test_public_service(self): collection = _PseudoCollection("emc.services", self.env) emc_services_env = WorkContext(model_name="rest.service.registration", collection=collection) service = emc_services_env.component(usage="ping") result = service.test() self.assertTrue("message" in result)
def setUp(self): res = super().setUp() collection = _PseudoCollection("emc.services", self.env) emc_services_env = WorkContext(model_name="rest.service.registration", collection=collection) self.ap_service = emc_services_env.component(usage="payment") self.ai_service = emc_services_env.component(usage="invoice") self.demo_request_1 = self.browse_ref( "easy_my_coop.subscription_request_1_demo") return res
def setUp(self): res = super().setUp() collection = _PseudoCollection("emc.services", self.env) emc_services_env = WorkContext(model_name="rest.service.registration", collection=collection) self.ai_service = emc_services_env.component(usage="invoice") self.share_type_A = self.browse_ref( "easy_my_coop.product_template_share_type_1_demo") self._capital_release_create() today = Date.to_string(Date.today()) self.demo_invoice_dict = { "id": 1, "name": "Capital Release Example", "partner": { "id": 1, "name": "Catherine des Champs" }, "account": { "id": 1, "name": "Cooperators" }, "journal": { "id": 1, "name": "Subscription Journal" }, "subscription_request": {}, "state": "open", "date": today, "date_invoice": today, "date_due": today, "type": "out_invoice", "invoice_lines": [{ "name": "Share Type A", "product": { "id": 1, "name": "Part A - Founder" }, "price_unit": 100.0, "quantity": 2.0, "account": { "id": 2, "name": "Equity" }, }], } return res
def setUpClass(cls): super(CommonCase, cls).setUpClass() collection = _PseudoCollection("base.rest.demo.private.services", cls.env) cls.private_services_env = WorkContext( model_name="rest.service.registration", collection=collection) collection = _PseudoCollection("base.rest.demo.public.services", cls.env) cls.public_services_env = WorkContext( model_name="rest.service.registration", collection=collection)
def setUp(self): super().setUp() # As the env.user is superuser anyways for our controllers, # for now we neglect it for tests superuser = self.env["res.users"].browse([SUPERUSER_ID]) self.env = self.env(user=superuser) self.cr = self.env.cr self.api_key = "ASecureKeyEbay" collection = _PseudoCollection("sale.import.rest.services", self.env) self.sale_import_service_env = WorkContext(model_name="sale.order", collection=collection) self.service = self.sale_import_service_env.component(usage="sale") self.api_key = "ASecureKeyEbay"
def _get_component_context(self, collection=None): """ This method can be inherited to add parameter into the component context :return: dict of key value. """ work = WorkContext( model_name="rest.service.registration", collection=collection or self.default_collection, request=request, controller=self, ) provider = work.component(usage=self._component_context_provider) return provider._get_component_context()
def work_on(self, model_name=None, collection=None): """ Create a new work context for another model keeping attributes Used when one need to lookup components for another model. Used on an EventWorkContext, it switch back to a normal WorkContext. It means we are inside an event listener, and we want to get a component. We need to set a collection to be able to get components. """ if self._collection is None and collection is None: raise ValueError('you must provide a collection to work with') if collection is not None: if self.env is not collection.env: raise ValueError('the Odoo env of the collection must be ' 'the same than the current one') kwargs = { attr_name: getattr(self, attr_name) for attr_name in self._propagate_kwargs } kwargs.pop('env', None) if collection is not None: kwargs['collection'] = collection if model_name is not None: kwargs['model_name'] = model_name return WorkContext(**kwargs)
def work_on_services(self, **params): params = params or {} if 'shopinvader_backend' not in params: params['shopinvader_backend'] = self.backend if 'shopinvader_session' not in params: params['shopinvader_session'] = {} collection = _PseudoCollection('shopinvader.backend', self.env) yield WorkContext(model_name='rest.service.registration', collection=collection, **params)
def work_on_component(self, collection_name): """ Return the all the components implementing REST services :param collection_name: :return: a WorkContext instance """ collection = _PseudoCollection(collection_name, request.env) yield WorkContext(model_name="rest.service.registration", collection=collection)
def setUp(self): super(TestMapperRecordsets, self).setUp() self.comp_registry.load_components('connector') backend_record = mock.Mock() backend_record.env = self.env self.work = WorkContext(model_name='res.partner', collection=backend_record, components_registry=self.comp_registry)
def work_on_services(self, **params): params = params or {} if "shopinvader_backend" not in params: params["shopinvader_backend"] = self.backend if "shopinvader_session" not in params: params["shopinvader_session"] = {} collection = _PseudoCollection("shopinvader.backend", self.env) yield WorkContext(model_name="rest.service.registration", collection=collection, **params)
def setUp(self, *args, **kwargs): super(TestTask, self).setUp(*args, **kwargs) self.env.user.image = self._get_image('partner-support-image.png') self.project = self.env.ref('project_api.project_project_1') self.partner = self.env.ref('project_api.partner_customer_help_desk') self.partner.help_desk_project_id = self.project collection = _PseudoCollection('project.project', self.env) self.work = WorkContext(model_name='rest.service.registration', collection=collection, partner=self.partner)
def work_on_services(cls, **params): params = params or {} if "shopinvader_backend" not in params: params["shopinvader_backend"] = cls.backend if "shopinvader_session" not in params: params["shopinvader_session"] = {} if not params.get("partner_user") and params.get("partner"): params["partner_user"] = params["partner"] collection = _PseudoCollection("shopinvader.backend", cls.env) yield WorkContext(model_name="rest.service.registration", collection=collection, **params)
def work_on_component(self): """ Return the component that implements the methods of the requested service. :param service_name: :return: an instance of base.rest.service component """ collection = self.collection params = self._get_component_context() yield WorkContext(model_name="rest.service.registration", collection=collection, **params)
def test_concurrent_import_lock(self): """ A 2nd concurrent transaction must retry """ # the lock is based on a string, a second transaction trying # to acquire the same lock won't be able to acquire it lock = 'import_record({}, {}, {}, {})'.format( 'backend.name', 1, 'res.partner', '999999', ) backend = mock.MagicMock() backend.env = self.env work = WorkContext(model_name='res.partner', collection=backend) # we test the function through a Component instance component = work.component_by_name('base.connector') # acquire the lock component.advisory_lock_or_retry(lock) # instanciate another component using a different odoo env # hence another PG transaction backend2 = mock.MagicMock() backend2.env = self.env2 work2 = WorkContext(model_name='res.partner', collection=backend2) component2 = work2.component_by_name('base.connector') with self.assertRaises(RetryableJobError) as cm: component2.advisory_lock_or_retry(lock, retry_seconds=3) self.assertEqual(cm.exception.seconds, 3)
def test_lock(self): """Lock a record""" main_partner = self.env.ref("base.main_partner") work = WorkContext(model_name="res.partner", collection=self.backend) work.component("record.locker").lock(main_partner) main_partner2 = self.env2.ref("base.main_partner") work2 = WorkContext(model_name="res.partner", collection=self.backend2) locker2 = work2.component("record.locker") with self.assertRaises(RetryableJobError): locker2.lock(main_partner2)
def setUp(self): super().setUp() collection = _PseudoCollection("emc.services", self.env) emc_services_env = WorkContext(model_name="rest.service.registration", collection=collection) self.sr_service = emc_services_env.component( usage="subscription-request") self.demo_request_1 = self.browse_ref( "easy_my_coop.subscription_request_1_demo") self.demo_request_2 = self.browse_ref( "easy_my_coop.subscription_request_waiting_demo") self.demo_share_product = ( self.demo_request_1.share_product_id.product_tmpl_id) date = Date.to_string(self.demo_request_1.date) self.demo_request_1_dict = { "id": self.demo_request_1.get_api_external_id(), "name": "Manuel Dublues", "email": "*****@*****.**", "date": date, "state": "draft", "ordered_parts": 3, "share_product": { "id": self.demo_share_product.get_api_external_id(), "name": self.demo_share_product.name, }, "address": { "street": "schaerbeekstraat", "zip_code": "1111", "city": "Brussels", "country": "BE", }, "lang": "en_US", "capital_release_request": [], }
def work_on_component(self, collection=None): """ Return the component that implements the methods of the requested service. :param service_name: :return: an instance of base.rest.service component """ collection = collection or self.default_collection component_ctx = self._get_component_context(collection=collection) env = collection.env collection.env = env(context=dict( env.context, authenticated_partner_id=component_ctx.get( "authenticated_partner_id"), )) yield WorkContext(model_name="rest.service.registration", **component_ctx)
def setUp(self): super(TestMapperBinding, self).setUp() self.comp_registry.load_components('connector') backend_record = mock.Mock() backend_record.env = self.env backend_record._name = 'my.collection' self.work = WorkContext(model_name='res.partner', collection=backend_record, components_registry=self.comp_registry) self.country_binder = mock.MagicMock(name='country_binder') self.country_binder.return_value = self.country_binder self.country_binder._name = 'test.binder' self.country_binder._inherit = 'base.binder' self.country_binder.apply_on_models = ['res.country'] self.country_binder._usage = 'binder' self.country_binder._collection = 'my.collection' self.country_binder._abstract = False self.comp_registry['test.binder'] = self.country_binder
def setUp(self): super(TestMapperBinding, self).setUp() self.comp_registry.load_components("connector") backend_record = mock.Mock() backend_record.env = self.env backend_record._name = "my.collection" self.work = WorkContext( model_name="res.partner", collection=backend_record, components_registry=self.comp_registry, ) self.country_binder = mock.MagicMock(name="country_binder") self.country_binder.return_value = self.country_binder self.country_binder._name = "test.binder" self.country_binder._inherit = "base.binder" self.country_binder.apply_on_models = ["res.country"] self.country_binder._usage = "binder" self.country_binder._collection = "my.collection" self.country_binder._abstract = False self.comp_registry["test.binder"] = self.country_binder
def test_concurrent_import(self): api_client = mock.MagicMock(name='Magento API') api_client.call.return_value = { 'name': 'Root', 'description': '', 'level': '1', } work = WorkContext(model_name='magento.product.category', collection=self.backend, magento_api=api_client) importer = work.component_by_name('magento.product.category.importer') importer.run(1) work2 = WorkContext(model_name='magento.product.category', collection=self.backend2, magento_api=api_client) importer2 = work2.component_by_name( 'magento.product.category.importer') with self.assertRaises(RetryableJobError): importer2.run(1)
def _get_all_provider(self): work = WorkContext(model_name=self._name, collection=self) return [ provider for provider in work.many_components(usage='gateway.provider') ]
class TestSaleOrderImport(SaleImportCase): @property def payload_multi_sale(self): chunks_data = [ self.get_chunk_vals("all")["data_str"], self.get_chunk_vals("all")["data_str"], ] chunks_data[1]["payment"]["reference"] = "PMT-EXAMPLE-002" return {"sale_orders": chunks_data} def setUp(self): super().setUp() # As the env.user is superuser anyways for our controllers, # for now we neglect it for tests superuser = self.env["res.users"].browse([SUPERUSER_ID]) self.env = self.env(user=superuser) self.cr = self.env.cr self.api_key = "ASecureKeyEbay" collection = _PseudoCollection("sale.import.rest.services", self.env) self.sale_import_service_env = WorkContext(model_name="sale.order", collection=collection) self.service = self.sale_import_service_env.component(usage="sale") self.api_key = "ASecureKeyEbay" def _service_create(self, vals): with patch( "odoo.addons.sale_import_rest.components.sale_import_service." "SaleImportService._get_api_key", return_value=self.api_key, ): return self.service.dispatch("create", params=vals) def _service_cancel(self, params): with patch( "odoo.addons.sale_import_rest.components.sale_import_service." "SaleImportService._get_api_key", return_value=self.api_key, ): return self.service.dispatch("cancel", params=params) def test_chunks_created(self): chunk_count_initial = self.env["queue.job.chunk"].search_count([]) self._service_create(self.payload_multi_sale) chunk_count_after = self.env["queue.job.chunk"].search_count([]) self.assertEqual(chunk_count_initial + 2, chunk_count_after) def test_wrong_key(self): self.api_key = "WrongKey" with self.assertRaises(ValidationError): return self._service_create(self.payload_multi_sale) def test_key_not_mapped_to_channel(self): self.env["auth.api.key"].create({ "name": "aName", "key": "ASecureKey", "user_id": 1 }) self.api_key = "ASecureKey" with self.assertRaises(ValidationError): return self._service_create(self.payload_multi_sale) def test_cancel_sale(self): sale = self.env.ref("sale.sale_order_1") sale.sale_channel_id = self.sale_channel_ebay sale.client_order_ref = "CLIENTREF" res = self._service_cancel({"sale_name": "CLIENTREF"}) self.assertEqual(sale.state, "cancel") self.assertEqual(res, {"success": True}) def test_cancel_sale_missing(self): with self.assertRaises(MissingError): self._service_cancel({"sale_name": "does not exist"})
def work_on_service(env, **params): """Work on a shopinvader service.""" collection = _PseudoCollection("shopinvader.backend", env) yield WorkContext(model_name="rest.service.registration", collection=collection, **params)