From 6cf8db906f595a0e579f9b0fd93e789c54c17fd4 Mon Sep 17 00:00:00 2001 From: Raphael Collet Date: Tue, 29 Mar 2022 11:31:39 +0000 Subject: [PATCH] [REF] *: adapt code to new flush API closes odoo/odoo#87527 Related: odoo/upgrade#3497 Related: odoo/enterprise#26939 Signed-off-by: Raphael Collet --- addons/account/models/account_account.py | 39 +++--- .../account/models/account_analytic_line.py | 6 +- addons/account/models/account_journal.py | 20 +-- .../models/account_journal_dashboard.py | 2 +- addons/account/models/account_move.py | 38 +++--- addons/account/models/account_payment.py | 6 +- .../account/models/account_payment_method.py | 3 +- .../account/models/account_reconcile_model.py | 2 +- addons/account/models/account_tax.py | 3 +- addons/account/models/account_tax_report.py | 4 +- addons/account/models/sequence_mixin.py | 2 +- addons/account/tests/common.py | 4 +- addons/account/tests/test_account_account.py | 6 +- .../account/tests/test_account_move_entry.py | 6 +- .../account/tests/test_invoice_tax_totals.py | 6 +- .../account/tests/test_portal_attachment.py | 8 +- addons/account/tests/test_sequence_mixin.py | 2 +- addons/account/tests/test_settings.py | 6 +- addons/account/wizard/accrued_orders.py | 2 +- .../models/account_payment.py | 2 +- .../account_edi/models/account_edi_format.py | 1 + .../tests/test_import_vendor_bill.py | 1 - .../models/account_edi_proxy_user.py | 4 +- addons/auth_ldap/models/res_users.py | 10 +- addons/auth_oauth/models/auth_oauth.py | 4 +- addons/auth_totp/models/res_users.py | 4 +- .../tests/test_barcode_nomenclature.py | 6 +- .../calendar/models/calendar_alarm_manager.py | 2 +- addons/calendar/tests/test_access_rights.py | 2 +- addons/calendar/tests/test_calendar.py | 1 - .../tests/test_calendar_controller.py | 4 +- .../tests/test_event_notifications.py | 2 +- addons/crm/models/crm_lead.py | 10 +- addons/crm/models/ir_config_parameter.py | 6 +- addons/crm/tests/common.py | 6 +- addons/crm/tests/test_crm_activity.py | 2 +- addons/crm/tests/test_crm_lead_assignment.py | 40 +++--- addons/crm/tests/test_crm_pls.py | 8 -- addons/crm/tests/test_performances.py | 18 +-- .../crm_iap_enrich/tests/test_lead_enrich.py | 4 +- .../data_recycle/models/data_recycle_model.py | 2 +- addons/delivery/models/delivery_carrier.py | 6 +- addons/delivery/tests/test_delivery_cost.py | 4 +- addons/digest/models/digest.py | 4 +- addons/digest/tests/test_digest.py | 20 +-- addons/event/models/event_event.py | 4 +- addons/event/models/event_mail.py | 2 +- addons/event/models/event_ticket.py | 2 +- addons/event_crm/models/event_registration.py | 2 +- addons/hr/tests/test_multi_company.py | 4 +- .../tests/test_expenses_access_rights.py | 2 +- .../hr_holidays/models/hr_leave_allocation.py | 2 +- addons/hr_holidays/models/res_users.py | 4 +- .../hr_holidays/tests/test_access_rights.py | 8 +- .../hr_holidays/tests/test_holidays_flow.py | 4 +- .../hr_holidays/tests/test_leave_requests.py | 4 +- .../hr_recruitment/models/hr_recruitment.py | 2 +- addons/hr_work_entry/models/hr_work_entry.py | 2 +- .../models/hr_work_entry.py | 4 +- addons/iap/models/iap_account.py | 6 +- .../im_livechat/models/chatbot_script_step.py | 2 +- .../tests/test_chatbot_internals.py | 2 +- addons/knowledge/models/knowledge_article.py | 9 +- addons/knowledge/tests/common.py | 4 +- .../tests/test_knowledge_article_business.py | 14 ++- .../test_knowledge_article_permissions.py | 4 +- .../tests/test_knowledge_article_sequence.py | 2 +- .../tests/test_knowledge_performance.py | 2 +- addons/l10n_es_edi_sii/models/res_company.py | 4 +- addons/l10n_in_edi/models/res_company.py | 4 +- addons/l10n_it_stock_ddt/tests/test_ddt.py | 6 +- addons/lunch/models/lunch_order.py | 4 +- addons/lunch/tests/test_supplier.py | 2 +- addons/mail/models/ir_model.py | 2 +- addons/mail/models/mail_activity.py | 2 +- addons/mail/models/mail_activity_mixin.py | 4 +- addons/mail/models/mail_channel.py | 9 +- addons/mail/models/mail_channel_partner.py | 3 +- addons/mail/models/mail_followers.py | 10 +- addons/mail/models/mail_mail.py | 2 +- addons/mail/models/mail_message.py | 15 +-- addons/mail/models/mail_template.py | 4 +- addons/mail/models/mail_thread.py | 4 +- addons/mail/models/mail_thread_blacklist.py | 4 +- addons/mail/models/res_partner.py | 2 +- addons/mail/tests/common.py | 2 +- addons/mail/tests/test_mail_channel.py | 2 +- addons/mail/tests/test_rtc.py | 4 +- addons/mail/wizard/mail_compose_message.py | 2 +- addons/mail/wizard/mail_template_preview.py | 2 +- .../tests/test_mail_group_message.py | 8 +- .../tests/test_mail_group_moderation.py | 1 - addons/mail_plugin/tests/test_controller.py | 2 +- .../mail_plugin/tests/test_res_partner_iap.py | 8 +- addons/mass_mailing/models/mailing.py | 3 +- addons/mass_mailing/models/mailing_list.py | 6 +- .../tests/test_mailing_ab_testing.py | 17 +-- .../tests/test_mailing_internals.py | 6 +- addons/mrp/models/mrp_workorder.py | 2 +- addons/mrp/tests/test_bom.py | 4 +- addons/mrp/tests/test_order.py | 4 +- .../test_warehouse_multistep_manufacturing.py | 4 +- addons/payment/models/account_journal.py | 6 +- addons/payment/models/payment_acquirer.py | 8 +- addons/payment/models/payment_transaction.py | 4 +- addons/payment/tests/test_flows.py | 2 +- addons/portal/tests/test_portal_wizard.py | 4 - addons/pos_sale/models/pos_order.py | 2 +- .../wizard/privacy_lookup_wizard.py | 2 +- addons/product/models/product_attribute.py | 20 +-- addons/product/models/product_template.py | 10 +- addons/product/tests/test_variants.py | 10 +- .../product_margin/models/product_product.py | 6 +- addons/project/tests/test_access_rights.py | 29 +++-- addons/project/tests/test_burndown_chart.py | 2 +- addons/project/tests/test_personal_stages.py | 2 +- addons/project/tests/test_project_flow.py | 8 +- .../project/tests/test_project_recurrence.py | 2 +- .../project/tests/test_task_dependencies.py | 2 +- addons/project/tests/test_task_tracking.py | 2 +- addons/purchase/tests/test_access_rights.py | 2 +- .../tests/test_purchase_order_report.py | 4 +- .../tests/test_purchase_matrix.py | 2 +- .../tests/test_purchase_order.py | 2 +- .../tests/test_reordering_rule.py | 6 +- addons/rating/models/rating_mixin.py | 2 +- addons/sale/models/sale_order.py | 2 +- addons/sale/models/sale_order_line.py | 2 +- addons/sale/models/utm_campaign.py | 4 +- addons/sale/tests/test_reinvoice.py | 2 +- addons/sale/tests/test_sale_order.py | 2 +- addons/sale/tests/test_sale_to_invoice.py | 2 +- .../tests/test_program_numbers.py | 4 +- addons/sale_margin/models/sale_order.py | 1 - addons/sale_mrp/tests/test_sale_mrp_flow.py | 4 +- .../sale_purchase/tests/test_sale_purchase.py | 2 +- addons/sale_stock/tests/test_create_perf.py | 2 +- addons/sale_stock/tests/test_sale_stock.py | 4 +- addons/sale_timesheet/tests/test_project.py | 6 +- addons/sales_team/tests/test_sales_team.py | 2 +- .../tests/test_sales_team_internals.py | 2 +- .../tests/test_sales_team_membership.py | 11 +- addons/stock/models/stock_location.py | 4 +- addons/stock/models/stock_quant.py | 2 +- addons/stock/tests/test_proc_rule.py | 2 +- addons/stock/tests/test_quant.py | 2 +- addons/stock/tests/test_report.py | 20 +-- .../stock/tests/test_report_stock_quantity.py | 6 +- addons/survey/models/survey_survey.py | 2 +- addons/survey/models/survey_user_input.py | 2 +- .../survey/tests/test_certification_badge.py | 1 - .../survey/tests/test_certification_flow.py | 2 +- addons/survey/tests/test_survey_flow.py | 4 +- .../tests/test_survey_flow_with_conditions.py | 2 +- addons/survey/tests/test_survey_invite.py | 2 +- .../test_base_automation/tests/test_flow.py | 4 +- .../test_crm_full/tests/test_performance.py | 2 +- .../tests/test_performance.py | 4 +- addons/test_event_full/tests/common.py | 2 +- .../test_event_full/tests/test_event_event.py | 4 +- .../test_event_full/tests/test_performance.py | 2 +- addons/test_mail/tests/test_mail_activity.py | 14 +-- addons/test_mail/tests/test_mail_followers.py | 10 +- addons/test_mail/tests/test_mail_gateway.py | 4 +- addons/test_mail/tests/test_mail_mail.py | 6 +- addons/test_mail/tests/test_mail_message.py | 4 +- addons/test_mail/tests/test_mail_template.py | 2 +- addons/test_mail/tests/test_message_post.py | 2 +- addons/test_mail/tests/test_message_track.py | 2 +- addons/test_mail/tests/test_performance.py | 15 +-- .../tests/test_phone_blacklist.py | 10 +- addons/test_mail_full/tests/test_rating.py | 4 +- .../test_mail_full/tests/test_sms_composer.py | 2 +- .../test_mass_mailing/tests/test_mailing.py | 8 +- .../tests/test_performance.py | 2 +- .../tests/test_sale_product_matrix.py | 2 +- .../tests/test_ui_wslides.py | 1 - addons/website/models/ir_ui_view.py | 4 +- addons/website/models/res_users.py | 2 +- addons/website/models/website.py | 4 +- addons/website/tests/test_menu.py | 4 +- addons/website/tests/test_views.py | 10 +- .../tests/test_website_reset_password.py | 6 +- addons/website/tests/test_website_visitor.py | 4 +- addons/website_crm/models/crm_lead.py | 3 +- addons/website_crm/models/website_visitor.py | 1 - .../models/crm_reveal_rule.py | 4 +- .../website_event/models/website_visitor.py | 1 - .../tests/test_sponsor_internals.py | 26 ++-- .../tests/test_frontend_buy_tickets.py | 3 +- .../tests/test_track_internals.py | 2 +- .../tests/test_knowledge_security.py | 4 +- .../tests/test_livechat_request.py | 2 +- addons/website_livechat/tests/test_ui.py | 2 +- .../tests/test_website_sale_pricelist.py | 4 +- .../tests/test_shop_sale_coupon.py | 5 +- addons/website_slides/models/slide_slide.py | 2 +- addons/website_slides/tests/test_security.py | 56 ++++----- .../tests/test_slide_channel.py | 8 +- .../website_slides/tests/test_statistics.py | 12 +- .../website_slides/tests/test_ui_wslides.py | 7 -- .../test_course_certification_failure.py | 10 +- .../tests/test_access_monetary_related.py | 2 +- .../tests/test_check_access.py | 4 +- .../test_access_rights/tests/test_feedback.py | 8 +- .../test_access_rights/tests/test_ir_rules.py | 14 +-- .../tests/test_assetsbundle.py | 6 +- .../test_auth_custom/tests/test_endpoints.py | 4 +- odoo/addons/test_impex/tests/test_export.py | 14 +-- .../test_inherits/tests/test_inherits.py | 8 +- .../test_new_api/models/test_new_api.py | 2 +- .../test_new_api/tests/test_new_fields.py | 114 +++++++++--------- .../test_new_api/tests/test_onchange.py | 8 +- .../test_new_api/tests/test_one2many.py | 8 +- .../tests/test_performance.py | 82 ++++++------- 215 files changed, 692 insertions(+), 703 deletions(-) diff --git a/addons/account/models/account_account.py b/addons/account/models/account_account.py index ddf13bbd094..7c54a743afd 100644 --- a/addons/account/models/account_account.py +++ b/addons/account/models/account_account.py @@ -113,8 +113,8 @@ class AccountAccount(models.Model): @api.constrains('allowed_journal_ids') def _constrains_allowed_journal_ids(self): - self.env['account.move.line'].flush(['account_id', 'journal_id']) - self.flush(['allowed_journal_ids']) + self.env['account.move.line'].flush_model(['account_id', 'journal_id']) + self.flush_recordset(['allowed_journal_ids']) self._cr.execute(""" SELECT aml.id FROM account_move_line aml @@ -134,14 +134,14 @@ class AccountAccount(models.Model): if not self: return - self.env['account.account'].flush(['currency_id']) - self.env['account.journal'].flush([ + self.env['account.account'].flush_model(['currency_id']) + self.env['account.journal'].flush_model([ 'currency_id', 'default_account_id', 'suspense_account_id', ]) - self.env['account.payment.method'].flush(['payment_type']) - self.env['account.payment.method.line'].flush(['payment_method_id', 'payment_account_id']) + self.env['account.payment.method'].flush_model(['payment_type']) + self.env['account.payment.method.line'].flush_model(['payment_method_id', 'payment_account_id']) self._cr.execute(''' SELECT @@ -204,7 +204,8 @@ class AccountAccount(models.Model): if not self: return - self.flush(['company_id']) + self.env['account.move.line'].flush_model(['account_id', 'company_id']) + self.flush_recordset(['company_id']) self._cr.execute(''' SELECT line.id FROM account_move_line line @@ -220,7 +221,9 @@ class AccountAccount(models.Model): if not self: return - self.flush(['user_type_id']) + self.flush_recordset(['user_type_id']) + self.env['account.account.type'].flush_model(['type']) + self.env['account.journal'].flush_model(['type', 'default_account_id']) self._cr.execute(''' SELECT account.id FROM account_account account @@ -241,8 +244,10 @@ class AccountAccount(models.Model): if not accounts: return - self.flush(['reconcile']) - self.env['account.payment.method.line'].flush(['journal_id', 'payment_account_id']) + self.flush_recordset(['reconcile']) + self.env['account.journal'].flush_model(['company_id', 'default_account_id']) + self.env['res.company'].flush_model(['account_journal_payment_credit_account_id', 'account_journal_payment_debit_account_id']) + self.env['account.payment.method.line'].flush_model(['journal_id', 'payment_account_id']) self._cr.execute(''' SELECT journal.id @@ -670,7 +675,7 @@ class AccountGroup(models.Model): @api.constrains('code_prefix_start', 'code_prefix_end') def _constraint_prefix_overlap(self): - self.env['account.group'].flush() + self.flush_model() query = """ SELECT other.id FROM account_group this JOIN account_group other @@ -726,8 +731,8 @@ class AccountGroup(models.Model): account_ids = account_ids.ids if account_ids else [] if not company_ids and not account_ids: return - self.env['account.group'].flush(self.env['account.group']._fields) - self.env['account.account'].flush(self.env['account.account']._fields) + self.flush_model() + self.env['account.account'].flush_model() account_where_clause = '' where_params = [tuple(company_ids)] @@ -753,7 +758,7 @@ class AccountGroup(models.Model): FROM candidates_account_groups rel WHERE account_account.id = rel.account_id ''', where_params) - self.env['account.account'].invalidate_cache(fnames=['group_id']) + self.env['account.account'].invalidate_model(['group_id']) def _adapt_parent_account_group(self): """Ensure consistency of the hierarchy of account groups. @@ -764,7 +769,7 @@ class AccountGroup(models.Model): """ if not self: return - self.env['account.group'].flush(self.env['account.group']._fields) + self.flush_model() query = """ WITH relation AS ( SELECT DISTINCT FIRST_VALUE(parent.id) OVER (PARTITION BY child.id ORDER BY child.id, char_length(parent.code_prefix_start) DESC) AS parent_id, @@ -784,8 +789,8 @@ class AccountGroup(models.Model): WHERE child.id = relation.child_id; """ self.env.cr.execute(query, {'company_ids': tuple(self.company_id.ids)}) - self.env['account.group'].invalidate_cache(fnames=['parent_id']) - self.env['account.group'].search([('company_id', 'in', self.company_id.ids)])._parent_store_update() + self.invalidate_model(['parent_id']) + self.search([('company_id', 'in', self.company_id.ids)])._parent_store_update() class AccountRoot(models.Model): diff --git a/addons/account/models/account_analytic_line.py b/addons/account/models/account_analytic_line.py index 9f67e339d8a..503949b3917 100644 --- a/addons/account/models/account_analytic_line.py +++ b/addons/account/models/account_analytic_line.py @@ -17,7 +17,8 @@ class AccountAnalyticAccount(models.Model): if not analytic_accounts: return - self.flush(['company_id']) + self.flush_recordset(['company_id']) + self.env['account.move.line'].flush_model(['analytic_account_id', 'company_id']) self._cr.execute(''' SELECT line.id FROM account_move_line line @@ -89,7 +90,8 @@ class AccountAnalyticTag(models.Model): if not analytic_tags: return - self.flush(['company_id']) + self.flush_recordset(['company_id']) + self.env['account.move.line'].flush_model(['company_id']) self._cr.execute(''' SELECT line.id FROM account_analytic_tag_account_move_line_rel tag_rel diff --git a/addons/account/models/account_journal.py b/addons/account/models/account_journal.py index e45dadc039e..55190d787ec 100644 --- a/addons/account/models/account_journal.py +++ b/addons/account/models/account_journal.py @@ -371,7 +371,7 @@ class AccountJournal(models.Model): alias_values['alias_model_id'] = self.env['ir.model']._get('account.move').id alias_values['alias_parent_model_id'] = self.env['ir.model']._get('account.journal').id journal.alias_id = self.env['mail.alias'].sudo().create(alias_values) - self.invalidate_cache(['alias_name'], self.ids) + self.invalidate_recordset(['alias_name']) @api.depends('name') def _compute_alias_domain(self): @@ -384,8 +384,9 @@ class AccountJournal(models.Model): @api.constrains('type_control_ids') def _constrains_type_control_ids(self): - self.env['account.move.line'].flush(['account_id', 'journal_id']) - self.flush(['type_control_ids']) + self.env['account.move.line'].flush_model(['account_id', 'journal_id']) + self.env['account.account'].flush_model(['user_type_id']) + self.flush_recordset(['type_control_ids']) self._cr.execute(""" SELECT aml.id FROM account_move_line aml @@ -400,8 +401,8 @@ class AccountJournal(models.Model): @api.constrains('account_control_ids') def _constrains_account_control_ids(self): - self.env['account.move.line'].flush(['account_id', 'journal_id']) - self.flush(['account_control_ids']) + self.env['account.move.line'].flush_model(['account_id', 'journal_id', 'display_type']) + self.flush_recordset(['account_control_ids']) self._cr.execute(""" SELECT aml.id FROM account_move_line aml @@ -429,7 +430,8 @@ class AccountJournal(models.Model): if not self: return - self.flush(['company_id']) + self.env['account.move'].flush_model(['company_id', 'journal_id']) + self.flush_recordset(['company_id']) self._cr.execute(''' SELECT move.id FROM account_move move @@ -457,9 +459,9 @@ class AccountJournal(models.Model): if not unique_codes: return - self.flush(['inbound_payment_method_line_ids', 'outbound_payment_method_line_ids', 'company_id']) - self.env['account.payment.method.line'].flush(['payment_method_id', 'journal_id']) - self.env['account.payment.method'].flush(['code']) + self.flush_model(['inbound_payment_method_line_ids', 'outbound_payment_method_line_ids', 'company_id']) + self.env['account.payment.method.line'].flush_model(['payment_method_id', 'journal_id']) + self.env['account.payment.method'].flush_model(['code']) if unique_codes: self._cr.execute(''' diff --git a/addons/account/models/account_journal_dashboard.py b/addons/account/models/account_journal_dashboard.py index a30224b514f..d018737f089 100644 --- a/addons/account/models/account_journal_dashboard.py +++ b/addons/account/models/account_journal_dashboard.py @@ -286,7 +286,7 @@ class account_journal(models.Model): #TODO need to check if all invoices are in the same currency than the journal!!!! elif self.type in ['sale', 'purchase']: title = _('Bills to pay') if self.type == 'purchase' else _('Invoices owed to you') - self.env['account.move'].flush(['amount_residual', 'currency_id', 'move_type', 'invoice_date', 'company_id', 'journal_id', 'date', 'state', 'payment_state']) + self.env['account.move'].flush_model() (query, query_args) = self._get_open_bills_to_pay_query() self.env.cr.execute(query, query_args) diff --git a/addons/account/models/account_move.py b/addons/account/models/account_move.py index ee78676cbe8..6c116dc523f 100644 --- a/addons/account/models/account_move.py +++ b/addons/account/models/account_move.py @@ -1373,8 +1373,8 @@ class AccountMove(models.Model): def _compute_amount(self): stored_ids = tuple(self.ids) if stored_ids: - self.env['account.partial.reconcile'].flush(self.env['account.partial.reconcile']._fields) - self.env['account.payment'].flush(fnames=['is_matched']) + self.env['account.partial.reconcile'].flush_model() + self.env['account.payment'].flush_model(['is_matched']) queries = [] for source_field, counterpart_field in (('debit', 'credit'), ('credit', 'debit')): @@ -1825,7 +1825,7 @@ class AccountMove(models.Model): if not moves: return - self.flush(['name', 'journal_id', 'move_type', 'state']) + self.flush_model(['name', 'journal_id', 'move_type', 'state']) # /!\ Computed stored fields are not yet inside the database. self._cr.execute(''' @@ -1849,12 +1849,12 @@ class AccountMove(models.Model): if not moves: return - self.env["account.move"].flush([ + self.env["account.move"].flush_model([ "ref", "move_type", "invoice_date", "journal_id", "company_id", "partner_id", "commercial_partner_id", ]) - self.env["account.journal"].flush(["company_id"]) - self.env["res.partner"].flush(["commercial_partner_id"]) + self.env["account.journal"].flush_model(["company_id"]) + self.env["res.partner"].flush_model(["commercial_partner_id"]) # /!\ Computed stored fields are not yet inside the database. self._cr.execute(''' @@ -1892,8 +1892,8 @@ class AccountMove(models.Model): # /!\ As this method is called in create / write, we can't make the assumption the computed stored fields # are already done. Then, this query MUST NOT depend of computed stored fields (e.g. balance). # It happens as the ORM makes the create with the 'no_recompute' statement. - self.env['account.move.line'].flush(self.env['account.move.line']._fields) - self.env['account.move'].flush(['journal_id']) + self.env['account.move.line'].flush_model() + self.env['account.move'].flush_model(['journal_id']) self._cr.execute(''' WITH error_moves AS ( SELECT line.move_id, @@ -4172,8 +4172,8 @@ class AccountMoveLine(models.Model): stored_lines = need_residual_lines.filtered('id') if stored_lines: - self.env['account.partial.reconcile'].flush(self.env['account.partial.reconcile']._fields) - self.env['res.currency'].flush(['decimal_places']) + self.env['account.partial.reconcile'].flush_model() + self.env['res.currency'].flush_model(['decimal_places']) aml_ids = tuple(stored_lines.ids) self._cr.execute(''' @@ -4698,16 +4698,24 @@ class AccountMoveLine(models.Model): result.append((line.id, name)) return result - @api.model - def invalidate_cache(self, fnames=None, ids=None): + def invalidate_model(self, fnames=None): # Invalidate cache of related moves if fnames is None or 'move_id' in fnames: field = self._fields['move_id'] - lines = self.env.cache.get_records(self, field) if ids is None else self.browse(ids) + lines = self.env.cache.get_records(self, field) move_ids = {id_ for id_ in self.env.cache.get_values(lines, field) if id_} if move_ids: - self.env['account.move'].invalidate_cache(ids=move_ids) - return super().invalidate_cache(fnames=fnames, ids=ids) + self.env['account.move'].browse(move_ids).invalidate_recordset() + return super().invalidate_model(fnames) + + def invalidate_recordset(self, fnames=None): + # Invalidate cache of related moves + if fnames is None or 'move_id' in fnames: + field = self._fields['move_id'] + move_ids = {id_ for id_ in self.env.cache.get_values(self, field) if id_} + if move_ids: + self.env['account.move'].browse(move_ids).invalidate_recordset() + return super().invalidate_recordset(fnames) # ------------------------------------------------------------------------- # TRACKING METHODS diff --git a/addons/account/models/account_payment.py b/addons/account/models/account_payment.py index 389bc028ed0..b7c67ed5413 100644 --- a/addons/account/models/account_payment.py +++ b/addons/account/models/account_payment.py @@ -548,9 +548,9 @@ class AccountPayment(models.Model): self.reconciled_statements_count = 0 return - self.env['account.move'].flush() - self.env['account.move.line'].flush() - self.env['account.partial.reconcile'].flush() + self.env['account.move'].flush_model() + self.env['account.move.line'].flush_model() + self.env['account.partial.reconcile'].flush_model() self._cr.execute(''' SELECT diff --git a/addons/account/models/account_payment_method.py b/addons/account/models/account_payment_method.py index 3bd0b248dd8..2e421dd5bd5 100644 --- a/addons/account/models/account_payment_method.py +++ b/addons/account/models/account_payment_method.py @@ -121,7 +121,8 @@ class AccountPaymentMethodLine(models.Model): @api.constrains('name') def _ensure_unique_name_for_journal(self): - self.flush(['name']) + self.flush_model(['name', 'journal_id', 'payment_method_id']) + self.env['account.payment.method'].flush_model(['payment_type']) self._cr.execute(''' SELECT apml.name, apm.payment_type FROM account_payment_method_line apml diff --git a/addons/account/models/account_reconcile_model.py b/addons/account/models/account_reconcile_model.py index c9db411c72a..e30097a53a9 100644 --- a/addons/account/models/account_reconcile_model.py +++ b/addons/account/models/account_reconcile_model.py @@ -466,7 +466,7 @@ class AccountReconcileModel(models.Model): ''' # This functions uses SQL to compute its results. We need to flush before doing anything more. for model_name in ('account.bank.statement', 'account.bank.statement.line', 'account.move', 'account.move.line', 'res.company', 'account.journal', 'account.account'): - self.env[model_name].flush(self.env[model_name]._fields) + self.env[model_name].flush_model() results = {line.id: {'aml_ids': []} for line in st_lines} diff --git a/addons/account/models/account_tax.py b/addons/account/models/account_tax.py index 905ae23e089..501382bc237 100644 --- a/addons/account/models/account_tax.py +++ b/addons/account/models/account_tax.py @@ -218,7 +218,8 @@ class AccountTax(models.Model): if not self: return - self.flush(['company_id']) + self.env['account.move.line'].flush_model(['company_id', 'tax_line_id']) + self.flush_recordset(['company_id']) self._cr.execute(''' SELECT line.id FROM account_move_line line diff --git a/addons/account/models/account_tax_report.py b/addons/account/models/account_tax_report.py index 51a94471cf2..8825c004971 100644 --- a/addons/account/models/account_tax_report.py +++ b/addons/account/models/account_tax_report.py @@ -356,8 +356,8 @@ class AccountTaxReportLine(models.Model): where account_account_tag_id in %(tag_ids_to_delete)s; """, {'tag_ids_to_delete': tuple(tag_ids_to_delete)}) - self.env['account.move.line'].invalidate_cache(fnames=['tax_tag_ids']) - self.env['account.tax.repartition.line'].invalidate_cache(fnames=['tag_ids']) + self.env['account.move.line'].invalidate_model(['tax_tag_ids']) + self.env['account.tax.repartition.line'].invalidate_model(['tag_ids']) self.env['account.account.tag'].browse(tag_ids_to_delete).unlink() diff --git a/addons/account/models/sequence_mixin.py b/addons/account/models/sequence_mixin.py index 78071774086..0425f34c6a0 100644 --- a/addons/account/models/sequence_mixin.py +++ b/addons/account/models/sequence_mixin.py @@ -180,7 +180,7 @@ class SequenceMixin(models.AbstractModel): field=self._sequence_field, ) - self.flush([self._sequence_field, 'sequence_number', 'sequence_prefix']) + self.flush_model([self._sequence_field, 'sequence_number', 'sequence_prefix']) self.env.cr.execute(query, param) return (self.env.cr.fetchone() or [None])[0] diff --git a/addons/account/tests/common.py b/addons/account/tests/common.py index 3e486cd595a..2f8af2578be 100644 --- a/addons/account/tests/common.py +++ b/addons/account/tests/common.py @@ -421,7 +421,7 @@ class AccountTestInvoicingCommon(TransactionCase): :param invoice: An invoice. :param expected_amounts: A map -> """ - invoice.invalidate_cache(['invoice_outstanding_credits_debits_widget']) + invoice.invalidate_recordset(['invoice_outstanding_credits_debits_widget']) widget_vals = json.loads(invoice.invoice_outstanding_credits_debits_widget) if widget_vals: @@ -435,7 +435,7 @@ class AccountTestInvoicingCommon(TransactionCase): :param invoice: An invoice. :param expected_amounts: A map -> """ - invoice.invalidate_cache(['invoice_payments_widget']) + invoice.invalidate_recordset(['invoice_payments_widget']) widget_vals = json.loads(invoice.invoice_payments_widget) if widget_vals: diff --git a/addons/account/tests/test_account_account.py b/addons/account/tests/test_account_account.py index f4666e17974..5b88a14a82f 100644 --- a/addons/account/tests/test_account_account.py +++ b/addons/account/tests/test_account_account.py @@ -61,7 +61,7 @@ class TestAccountAccount(AccountTestInvoicingCommon): # Set the account as reconcile and fully reconcile something. account.reconcile = True - self.env['account.move.line'].invalidate_cache() + self.env['account.move.line'].invalidate_model() self.assertRecordValues(move.line_ids, [ {'reconciled': False, 'amount_residual': 100.0, 'amount_residual_currency': 200.0}, @@ -77,7 +77,7 @@ class TestAccountAccount(AccountTestInvoicingCommon): # Set back to a not reconcile account and check the journal items. move.line_ids.remove_move_reconcile() account.reconcile = False - self.env['account.move.line'].invalidate_cache() + self.env['account.move.line'].invalidate_model() self.assertRecordValues(move.line_ids, [ {'reconciled': False, 'amount_residual': 0.0, 'amount_residual_currency': 0.0}, @@ -119,7 +119,7 @@ class TestAccountAccount(AccountTestInvoicingCommon): # Set the account as reconcile and partially reconcile something. account.reconcile = True - self.env['account.move.line'].invalidate_cache() + self.env['account.move.line'].invalidate_model() move.line_ids.filtered(lambda line: line.account_id == account).reconcile() diff --git a/addons/account/tests/test_account_move_entry.py b/addons/account/tests/test_account_move_entry.py index ce484d123f2..03ca4707e95 100644 --- a/addons/account/tests/test_account_move_entry.py +++ b/addons/account/tests/test_account_move_entry.py @@ -358,7 +358,7 @@ class TestAccountMove(AccountTestInvoicingCommon): def test_add_followers_on_post(self): # Add some existing partners, some from another company company = self.env['res.company'].create({'name': 'Oopo'}) - company.flush() + company.flush_recordset() existing_partners = self.env['res.partner'].create([{ 'name': 'Jean', 'company_id': company.id, @@ -722,13 +722,13 @@ class TestAccountMove(AccountTestInvoicingCommon): return len(self.env.cache.get_records(model, field)) def test_cache_invalidation(self): - self.env['account.move'].invalidate_cache() + self.env.invalidate_all() lines = self.test_move.line_ids # prefetch lines.mapped('move_id.name') # check account.move cache self.assertEqual(self._get_cache_count(), 1) - self.env['account.move.line'].invalidate_cache(ids=lines.ids) + lines.invalidate_recordset() self.assertEqual(self._get_cache_count(), 0) def test_misc_prevent_edit_tax_on_posted_moves(self): diff --git a/addons/account/tests/test_invoice_tax_totals.py b/addons/account/tests/test_invoice_tax_totals.py index 08f97a442d2..6a0fb13b3c7 100644 --- a/addons/account/tests/test_invoice_tax_totals.py +++ b/addons/account/tests/test_invoice_tax_totals.py @@ -140,7 +140,7 @@ class TestTaxTotals(AccountTestInvoicingCommon): # Same but both are sharing the same tax group. tax_20.tax_group_id = self.tax_group1 - document.invalidate_cache(['tax_totals_json']) + document.invalidate_model(['tax_totals_json']) self.assertTaxTotals(document, { 'amount_total': 3600, @@ -252,7 +252,7 @@ class TestTaxTotals(AccountTestInvoicingCommon): # Same but both are sharing the same tax group. tax_20.tax_group_id = self.tax_group1 - document.invalidate_cache(['tax_totals_json']) + document.invalidate_model(['tax_totals_json']) self.assertTaxTotals(document, { 'amount_total': 3620, @@ -337,7 +337,7 @@ class TestTaxTotals(AccountTestInvoicingCommon): # Same but both are sharing the same tax group. tax_30.tax_group_id = self.tax_group1 - document.invalidate_cache(['tax_totals_json']) + document.invalidate_model(['tax_totals_json']) self.assertTaxTotals(document, { 'amount_total': 2750, diff --git a/addons/account/tests/test_portal_attachment.py b/addons/account/tests/test_portal_attachment.py index f8f093232f8..e6f559052ad 100644 --- a/addons/account/tests/test_portal_attachment.py +++ b/addons/account/tests/test_portal_attachment.py @@ -148,7 +148,7 @@ class TestPortalAttachment(AccountTestInvoicingHttpCommon): 'res_model': 'mail.compose.message', 'res_id': 0, }) - attachment.flush() + attachment.flush_recordset() message = self.env['mail.message'].create({ 'attachment_ids': [(6, 0, attachment.ids)], }) @@ -218,7 +218,7 @@ class TestPortalAttachment(AccountTestInvoicingHttpCommon): }, ) self.assertEqual(res.status_code, 200) - self.out_invoice.invalidate_cache(fnames=['message_ids'], ids=self.out_invoice.ids) + self.out_invoice.invalidate_recordset(['message_ids']) self.assertEqual(len(self.out_invoice.message_ids), 1) self.assertEqual(self.out_invoice.message_ids.body, "

test message 1

") self.assertFalse(self.out_invoice.message_ids.attachment_ids) @@ -240,7 +240,7 @@ class TestPortalAttachment(AccountTestInvoicingHttpCommon): }, ) self.assertEqual(res.status_code, 200) - self.out_invoice.invalidate_cache(fnames=['message_ids'], ids=self.out_invoice.ids) + self.out_invoice.invalidate_recordset(['message_ids']) self.assertEqual(len(self.out_invoice.message_ids), 2) self.assertEqual(self.out_invoice.message_ids[0].body, "

test message 2

") self.assertFalse(self.out_invoice.message_ids.attachment_ids) @@ -276,7 +276,7 @@ class TestPortalAttachment(AccountTestInvoicingHttpCommon): }, ) self.assertEqual(res.status_code, 200) - self.out_invoice.invalidate_cache(fnames=['message_ids'], ids=self.out_invoice.ids) + self.out_invoice.invalidate_recordset(['message_ids']) self.assertEqual(len(self.out_invoice.message_ids), 3) self.assertEqual(self.out_invoice.message_ids[0].body, "

test message 3

") self.assertEqual(len(self.out_invoice.message_ids[0].attachment_ids), 1) diff --git a/addons/account/tests/test_sequence_mixin.py b/addons/account/tests/test_sequence_mixin.py index 1a5f3d8d98a..a42d1381811 100644 --- a/addons/account/tests/test_sequence_mixin.py +++ b/addons/account/tests/test_sequence_mixin.py @@ -214,7 +214,7 @@ class TestSequenceMixin(TestSequenceMixinCommon): ) journals[0].code = 'OLD' - journals.flush() + journals.flush_recordset() journal_same_code = self.env['account.journal'].create([{ 'name': 'Journal0', 'code': 'J0', diff --git a/addons/account/tests/test_settings.py b/addons/account/tests/test_settings.py index 595ff571405..ecd4870025f 100644 --- a/addons/account/tests/test_settings.py +++ b/addons/account/tests/test_settings.py @@ -19,19 +19,19 @@ class TestSettings(AccountTestInvoicingCommon): def switch_tax_settings(self, config): config.show_line_subtotals_tax_selection = "tax_excluded" - config.flush() + config.flush_recordset() config.execute() self.assertEqual(self.env.user.has_group('account.group_show_line_subtotals_tax_excluded'), True) self.assertEqual(self.env.user.has_group('account.group_show_line_subtotals_tax_included'), False) config.show_line_subtotals_tax_selection = "tax_included" - config.flush() + config.flush_recordset() config.execute() self.assertEqual(self.env.user.has_group('account.group_show_line_subtotals_tax_excluded'), False) self.assertEqual(self.env.user.has_group('account.group_show_line_subtotals_tax_included'), True) config.show_line_subtotals_tax_selection = "tax_excluded" - config.flush() + config.flush_recordset() config.execute() self.assertEqual(self.env.user.has_group('account.group_show_line_subtotals_tax_excluded'), True) self.assertEqual(self.env.user.has_group('account.group_show_line_subtotals_tax_included'), False) diff --git a/addons/account/wizard/accrued_orders.py b/addons/account/wizard/accrued_orders.py index ad7c3fc714c..cf2df277233 100644 --- a/addons/account/wizard/accrued_orders.py +++ b/addons/account/wizard/accrued_orders.py @@ -183,7 +183,7 @@ class AccruedExpenseRevenue(models.TransientModel): move_lines.append(Command.create(values)) total_balance += amount # must invalidate cache or o can mess when _create_invoices().action_post() of original order after this - order.order_line.invalidate_cache(fnames=fnames) + order.order_line.invalidate_model(fnames) if not self.company_id.currency_id.is_zero(total_balance): # globalized counterpart for the whole orders selection diff --git a/addons/account_check_printing/models/account_payment.py b/addons/account_check_printing/models/account_payment.py index 5ba561288bf..1b78fc609d9 100644 --- a/addons/account_check_printing/models/account_payment.py +++ b/addons/account_check_printing/models/account_payment.py @@ -52,7 +52,7 @@ class AccountPayment(models.Model): for payment_check in payment_checks: if not payment_check.check_number.isdecimal(): raise ValidationError(_('Check numbers can only consist of digits')) - self.flush() + self.env.flush_all() self.env.cr.execute(""" SELECT payment.check_number, move.journal_id FROM account_payment payment diff --git a/addons/account_edi/models/account_edi_format.py b/addons/account_edi/models/account_edi_format.py index 975f7859148..7a1fa3747da 100644 --- a/addons/account_edi/models/account_edi_format.py +++ b/addons/account_edi/models/account_edi_format.py @@ -503,6 +503,7 @@ class AccountEdiFormat(models.Model): vat_only_numeric = None if vat_only_numeric: + self.env['res.partner'].flush_model() query = self.env['res.partner']._where_calc(extra_domain + [('active', '=', True)]) tables, where_clause, where_params = query.get_sql() diff --git a/addons/account_edi/tests/test_import_vendor_bill.py b/addons/account_edi/tests/test_import_vendor_bill.py index 8d4cc288d6d..ba2b476df8e 100644 --- a/addons/account_edi/tests/test_import_vendor_bill.py +++ b/addons/account_edi/tests/test_import_vendor_bill.py @@ -10,7 +10,6 @@ class TestImportVendorBill(AccountTestInvoicingCommon): def retrieve_partner(vat, import_vat): self.partner_a.with_context(no_vat_validation=True).vat = vat - self.partner_a.flush() return self.env['account.edi.format']._retrieve_partner(vat=import_vat) self.assertEqual(self.partner_a, retrieve_partner('BE0477472701', 'BE0477472701')) diff --git a/addons/account_edi_proxy_client/models/account_edi_proxy_user.py b/addons/account_edi_proxy_client/models/account_edi_proxy_user.py index d071b54ccfe..c41837627b3 100644 --- a/addons/account_edi_proxy_client/models/account_edi_proxy_user.py +++ b/addons/account_edi_proxy_client/models/account_edi_proxy_user.py @@ -209,8 +209,8 @@ class AccountEdiProxyClientUser(models.Model): def _neutralize(self): super()._neutralize() - self.flush() - self.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() self.env.cr.execute(""" INSERT INTO ir_config_parameter(key, value) VALUES ('account_edi_proxy_client.demo', true) diff --git a/addons/auth_ldap/models/res_users.py b/addons/auth_ldap/models/res_users.py index a153221763d..59ea08ae5c4 100644 --- a/addons/auth_ldap/models/res_users.py +++ b/addons/auth_ldap/models/res_users.py @@ -47,14 +47,14 @@ class Users(models.Model): for conf in Ldap._get_ldap_dicts(): changed = Ldap._change_password(conf, self.env.user.login, old_passwd, new_passwd) if changed: - uid = self.env.user.id - self._set_empty_password(uid) - self.invalidate_cache(['password'], [uid]) + self.env.user._set_empty_password() return True return super(Users, self).change_password(old_passwd, new_passwd) - def _set_empty_password(self, uid): + def _set_empty_password(self): + self.flush_recordset(['password']) self.env.cr.execute( 'UPDATE res_users SET password=NULL WHERE id=%s', - (uid,) + (self.id,) ) + self.invalidate_recordset(['password']) diff --git a/addons/auth_oauth/models/auth_oauth.py b/addons/auth_oauth/models/auth_oauth.py index 6efb044b7ed..40cc66ab89e 100644 --- a/addons/auth_oauth/models/auth_oauth.py +++ b/addons/auth_oauth/models/auth_oauth.py @@ -23,6 +23,6 @@ class AuthOAuthProvider(models.Model): def _neutralize(self): super()._neutralize() - self.flush() - self.invalidate_cache() + self.flush_model(['enabled']) self.env.cr.execute("UPDATE auth_oauth_provider SET enabled = false") + self.invalidate_model(['enabled']) diff --git a/addons/auth_totp/models/res_users.py b/addons/auth_totp/models/res_users.py index f7b1227d860..1b0b0e34003 100644 --- a/addons/auth_totp/models/res_users.py +++ b/addons/auth_totp/models/res_users.py @@ -77,7 +77,7 @@ class Users(models.Model): self.sudo().totp_secret = secret if request: - self.flush() + self.env.flush_all() # update session token so the user does not get logged out (cache cleared by change) new_token = self.env.user._compute_session_token(request.session.sid) request.session.session_token = new_token @@ -96,7 +96,7 @@ class Users(models.Model): self.sudo().write({'totp_secret': False}) if request and self == self.env.user: - self.flush() + self.env.flush_all() # update session token so the user does not get logged out (cache cleared by change) new_token = self.env.user._compute_session_token(request.session.sid) request.session.session_token = new_token diff --git a/addons/barcodes/tests/test_barcode_nomenclature.py b/addons/barcodes/tests/test_barcode_nomenclature.py index 98f7a555473..1bdf20c050e 100644 --- a/addons/barcodes/tests/test_barcode_nomenclature.py +++ b/addons/barcodes/tests/test_barcode_nomenclature.py @@ -225,7 +225,7 @@ class TestBarcodeNomenclature(common.TransactionCase): }) # Invalids the cache to reset the nomenclature barcode rules' order. - self.env['barcode.nomenclature'].invalidate_cache() + self.nomenclature.invalidate_recordset(['rule_ids']) # Only fits the second barcode rule. res = self.nomenclature.parse_barcode('2012345610255') @@ -243,9 +243,9 @@ class TestBarcodeNomenclature(common.TransactionCase): self.assertEqual(res['base_code'], '2212345600007') self.assertEqual(res['value'], 10.25) - # Invalids the cache to reset the nomenclature barcode rules' order. first_created_rule.sequence = 1 - self.env['barcode.nomenclature'].invalidate_cache() + # Invalids the cache to reset the nomenclature barcode rules' order. + self.nomenclature.invalidate_recordset(['rule_ids']) # Should take the first one now (lower sequence). res = self.nomenclature.parse_barcode('2212345610259') diff --git a/addons/calendar/models/calendar_alarm_manager.py b/addons/calendar/models/calendar_alarm_manager.py index b2927a37c13..40d1318c16e 100644 --- a/addons/calendar/models/calendar_alarm_manager.py +++ b/addons/calendar/models/calendar_alarm_manager.py @@ -75,7 +75,7 @@ class AlarmManager(models.AbstractModel): first_alarm_max_value = "(now() at time zone 'utc' + interval '%s' second )" tuple_params += (seconds,) - self.flush() + self.env.flush_all() self._cr.execute(""" WITH calcul_delta AS (%s) SELECT * diff --git a/addons/calendar/tests/test_access_rights.py b/addons/calendar/tests/test_access_rights.py index acbf9a30c30..b36de6c87eb 100644 --- a/addons/calendar/tests/test_access_rights.py +++ b/addons/calendar/tests/test_access_rights.py @@ -73,7 +73,7 @@ class TestAccessRights(TransactionCase): (self.raoul, 'partner_ids', self.env['res.partner'], None), (self.portal, 'partner_ids', None, AccessError), ]: - event.invalidate_cache() + self.env.invalidate_all() with self.subTest("private read", user=user.display_name, field=field, error=error): e = event.with_user(user) if error: diff --git a/addons/calendar/tests/test_calendar.py b/addons/calendar/tests/test_calendar.py index e1d44e04291..a26aecbbc1a 100644 --- a/addons/calendar/tests/test_calendar.py +++ b/addons/calendar/tests/test_calendar.py @@ -161,7 +161,6 @@ class TestCalendar(SavepointCaseWithUserDemo): 'stop_date': "2018-10-18", 'allday': True, }) - event.invalidate_cache() self.assertEqual(str(event.start), '2018-10-16 08:00:00') self.assertEqual(str(event.stop), '2018-10-18 18:00:00') diff --git a/addons/calendar/tests/test_calendar_controller.py b/addons/calendar/tests/test_calendar_controller.py index abdc9e961ee..4eb3e778b2e 100644 --- a/addons/calendar/tests/test_calendar_controller.py +++ b/addons/calendar/tests/test_calendar_controller.py @@ -33,7 +33,7 @@ class TestCalendarController(HttpCase): res = self.url_open(url) self.assertEqual(res.status_code, 200, "Response should = OK") - attendee.invalidate_cache() + self.env.invalidate_all() self.assertEqual(attendee.state, "accepted", "Attendee should have accepted") def test_accept_meeting_authenticated(self): @@ -45,5 +45,5 @@ class TestCalendarController(HttpCase): res = self.url_open(url) self.assertEqual(res.status_code, 200, "Response should = OK") - attendee.invalidate_cache() + self.env.invalidate_all() self.assertEqual(attendee.state, "accepted", "Attendee should have accepted") diff --git a/addons/calendar/tests/test_event_notifications.py b/addons/calendar/tests/test_event_notifications.py index b7833f00342..3b76faa2cbd 100644 --- a/addons/calendar/tests/test_event_notifications.py +++ b/addons/calendar/tests/test_event_notifications.py @@ -160,7 +160,7 @@ class TestEventNotifications(TransactionCase, MailCase, CronMixinCase): 'partner_ids': [fields.Command.link(self.partner.id)], 'alarm_ids': [fields.Command.link(alarm.id)], }) - self.event.flush() # flush is required to make partner_ids be present in the event + self.env.flush_all() # flush is required to make partner_ids be present in the event capt.records.ensure_one() self.assertLessEqual(capt.records.call_at, now) diff --git a/addons/crm/models/crm_lead.py b/addons/crm/models/crm_lead.py index 249c007a77d..bb1203711bf 100644 --- a/addons/crm/models/crm_lead.py +++ b/addons/crm/models/crm_lead.py @@ -1008,7 +1008,7 @@ class Lead(models.Model): return _('Go, go, go! Congrats for your first deal.') return False - self.flush() # flush fields to make sure DB is up to date + self.flush_model() # flush fields to make sure DB is up to date query = """ SELECT SUM(CASE WHEN user_id = %(user_id)s THEN 1 ELSE 0 END) as total_won, @@ -1480,8 +1480,8 @@ class Lead(models.Model): """ self.ensure_one() - self.env['mail.message'].flush() - self.env['mail.followers'].flush() + self.env['mail.message'].flush_model() + self.env['mail.followers'].flush_model() # Get the active followers (followers whose partner post a message on the # leads in the last 30 days) which should be moved on the destination lead @@ -2157,6 +2157,7 @@ class Lead(models.Model): transactions_count, transactions_failed_count = 0, 0 cron_update_lead_start_date = datetime.now() auto_commit = not getattr(threading.current_thread(), 'testing', False) + self.flush_model() for probability, probability_lead_ids in probability_leads.items(): for lead_ids_current in tools.split_every(PLS_UPDATE_BATCH_STEP, probability_lead_ids): transactions_count += 1 @@ -2168,6 +2169,7 @@ class Lead(models.Model): except Exception as e: _logger.warning("Predictive Lead Scoring : update transaction failed. Error: %s" % e) transactions_failed_count += 1 + self.invalidate_model() _logger.info( "Predictive Lead Scoring : All automated probabilities updated (%d leads / %d transactions (%d failed) / %d seconds)" % ( @@ -2446,7 +2448,7 @@ class Lead(models.Model): args = [sql.Identifier(field) for field in pls_fields] # Get leads values - self.flush(['probability']) + self.flush_model() query = """SELECT id, probability, %s FROM %s WHERE %s order by team_id asc""" diff --git a/addons/crm/models/ir_config_parameter.py b/addons/crm/models/ir_config_parameter.py index af74a83e272..975d048dfde 100644 --- a/addons/crm/models/ir_config_parameter.py +++ b/addons/crm/models/ir_config_parameter.py @@ -10,7 +10,7 @@ class IrConfigParameter(models.Model): def write(self, vals): result = super(IrConfigParameter, self).write(vals) if any(record.key == "crm.pls_fields" for record in self): - self.flush() + self.env.flush_all() self.env.registry.setup_models(self.env.cr) return result @@ -18,7 +18,7 @@ class IrConfigParameter(models.Model): def create(self, vals_list): records = super(IrConfigParameter, self).create(vals_list) if any(record.key == "crm.pls_fields" for record in records): - self.flush() + self.env.flush_all() self.env.registry.setup_models(self.env.cr) return records @@ -26,6 +26,6 @@ class IrConfigParameter(models.Model): pls_emptied = any(record.key == "crm.pls_fields" for record in self) result = super(IrConfigParameter, self).unlink() if pls_emptied: - self.flush() + self.env.flush_all() self.env.registry.setup_models(self.env.cr) return pls_emptied diff --git a/addons/crm/tests/common.py b/addons/crm/tests/common.py index 8da73db8597..23babc0843d 100644 --- a/addons/crm/tests/common.py +++ b/addons/crm/tests/common.py @@ -164,7 +164,7 @@ class TestCrmCommon(TestSalesCommon, MailCase): 'team_id': cls.sales_team_1.id, }) cls.lead_team_1_lost.action_set_lost() - (cls.lead_team_1_won + cls.lead_team_1_lost).flush() + (cls.lead_team_1_won + cls.lead_team_1_lost).flush_recordset() # email / phone data cls.test_email_data = [ @@ -434,7 +434,7 @@ class TestCrmCommon(TestSalesCommon, MailCase): opp_lost = self.env['crm.lead'] new_leads = lead_email_from + lead_email_normalized + lead_partner + opp_lost - new_leads.flush() # compute notably probability + new_leads.flush_recordset() # compute notably probability return customer, new_leads @contextmanager @@ -722,4 +722,4 @@ class TestLeadConvertMassCommon(TestLeadConvertCommon): 'stage_id': cls.stage_team1_2.id, 'active': False, }) - (cls.lead_w_partner + cls.lead_w_partner_company + cls.lead_w_contact + cls.lead_w_email + cls.lead_w_email_lost).flush() + cls.env.flush_all() diff --git a/addons/crm/tests/test_crm_activity.py b/addons/crm/tests/test_crm_activity.py index f5f669e8641..2e7b72b7800 100644 --- a/addons/crm/tests/test_crm_activity.py +++ b/addons/crm/tests/test_crm_activity.py @@ -74,7 +74,7 @@ class TestCrmMailActivity(TestCrmCommon): test_leads[5].activity_schedule(act_type_xmlid='crm.initial_contact', date_deadline=deadline_in2d) (test_leads[1] | test_leads[3]).activity_schedule(act_type_xmlid='crm.initial_contact', date_deadline=deadline_was1d) (test_leads[2] | test_leads[4]).activity_schedule(act_type_xmlid='crm.call_for_demo', date_deadline=deadline_was2d) - test_leads.invalidate_cache() + test_leads.invalidate_recordset() expected_ids_asc = [2, 4, 1, 3, 5, 0, 8, 7, 9, 6] expected_leads_asc = self.env['crm.lead'].browse([test_leads[lid].id for lid in expected_ids_asc]) diff --git a/addons/crm/tests/test_crm_lead_assignment.py b/addons/crm/tests/test_crm_lead_assignment.py index 31cfc7875e8..e308eb5ea00 100644 --- a/addons/crm/tests/test_crm_lead_assignment.py +++ b/addons/crm/tests/test_crm_lead_assignment.py @@ -120,7 +120,7 @@ class TestLeadAssign(TestLeadAssignCommon): suffix='Initial', ) # commit probability and related fields - leads.flush() + leads.flush_recordset() self.assertInitialData() # archived members should not be taken into account @@ -133,7 +133,7 @@ class TestLeadAssign(TestLeadAssignCommon): for idx, lead in enumerate(leads): lead.probability = idx * 10 # commit probability and related fields - leads.flush() + leads.flush_recordset() self.assertEqual(leads[0].probability, 0) # create exiting leads for user_sales_salesman (sales_team_1_m3, sales_team_convert_m1) @@ -146,17 +146,17 @@ class TestLeadAssign(TestLeadAssignCommon): existing_leads[0].active = False # lost existing_leads[1].probability = 100 # not won existing_leads[2].probability = 0 # not lost - existing_leads.flush() + existing_leads.flush_recordset() - self.members.invalidate_cache(fnames=['lead_month_count']) + self.members.invalidate_model(['lead_month_count']) self.assertEqual(self.sales_team_1_m3.lead_month_count, 14) self.assertEqual(self.sales_team_convert_m1.lead_month_count, 0) # re-assign existing leads, check monthly count is updated existing_leads[-2:]._handle_salesmen_assignment(user_ids=self.user_sales_manager.ids) # commit probability and related fields - leads.flush() - self.members.invalidate_cache(fnames=['lead_month_count']) + leads.flush_recordset() + self.members.invalidate_model(['lead_month_count']) self.assertEqual(self.sales_team_1_m3.lead_month_count, 12) # sales_team_1_m2 is opt-out (new field in 14.3) -> even with max, no lead assigned @@ -184,7 +184,7 @@ class TestLeadAssign(TestLeadAssignCommon): ) # salespersons assign - self.members.invalidate_cache(fnames=['lead_month_count']) + self.members.invalidate_model(['lead_month_count']) self.assertEqual(self.sales_team_1_m1.lead_month_count, 0) # archived do not get leads self.assertEqual(self.sales_team_1_m2.lead_month_count, 0) # opt-out through assignment_max = 0 self.assertEqual(self.sales_team_1_m3.lead_month_count, 14) # 15 max on 4 days (2) + existing 12 @@ -193,7 +193,7 @@ class TestLeadAssign(TestLeadAssignCommon): self.env['crm.team'].browse(self.sales_team_1.ids)._action_assign_leads(work_days=4) # salespersons assign - self.members.invalidate_cache(fnames=['lead_month_count']) + self.members.invalidate_model(['lead_month_count']) self.assertEqual(self.sales_team_1_m1.lead_month_count, 0) # archived do not get leads self.assertEqual(self.sales_team_1_m2.lead_month_count, 0) # opt-out through assignment_max = 0 self.assertEqual(self.sales_team_1_m3.lead_month_count, 16) # 15 max on 4 days (2) + existing 14 and not capped anymore @@ -212,7 +212,7 @@ class TestLeadAssign(TestLeadAssignCommon): count=200 ) # commit probability and related fields - leads.flush() + leads.flush_recordset() self.assertInitialData() # assign probability to leads (bypass auto probability as purpose is not to test pls) @@ -222,7 +222,7 @@ class TestLeadAssign(TestLeadAssignCommon): for lead in sliced_leads: lead.probability = (idx + 1) * 10 * ((int(lead.priority) + 1) / 2) # commit probability and related fields - leads.flush() + leads.flush_recordset() with self.with_user('user_sales_manager'): self.env['crm.team'].browse(self.sales_teams.ids)._action_assign_leads(work_days=2) @@ -239,7 +239,7 @@ class TestLeadAssign(TestLeadAssignCommon): self.assertEqual(len(leads_st1) + len(leads_stc), len(leads)) # Make sure all lead are assigned # salespersons assign - self.members.invalidate_cache(fnames=['lead_month_count']) + self.members.invalidate_model(['lead_month_count']) self.assertMemberAssign(self.sales_team_1_m1, 11) # 45 max on 2 days (3) + compensation (8.4) self.assertMemberAssign(self.sales_team_1_m2, 4) # 15 max on 2 days (1) + compensation (2.8) self.assertMemberAssign(self.sales_team_1_m3, 4) # 15 max on 2 days (1) + compensation (2.8) @@ -269,7 +269,7 @@ class TestLeadAssign(TestLeadAssignCommon): count=150 ) # commit probability and related fields - leads.flush() + leads.flush_recordset() self.assertInitialData() # assign probability to leads (bypass auto probability as purpose is not to test pls) @@ -279,7 +279,7 @@ class TestLeadAssign(TestLeadAssignCommon): for lead in sliced_leads: lead.probability = (idx + 1) * 10 * ((int(lead.priority) + 1) / 2) # commit probability and related fields - leads.flush() + leads.flush_recordset() with self.with_user('user_sales_manager'): self.env['crm.team'].browse(self.sales_teams.ids)._action_assign_leads(work_days=2) @@ -296,7 +296,7 @@ class TestLeadAssign(TestLeadAssignCommon): self.assertEqual(len(leads_st1) + len(leads_stc), len(leads)) # Make sure all lead are assigned # salespersons assign - self.members.invalidate_cache(fnames=['lead_month_count']) + self.members.invalidate_model(['lead_month_count']) self.assertMemberAssign(self.sales_team_1_m1, 11) # 45 max on 2 days (3) + compensation (8.4) self.assertMemberAssign(self.sales_team_1_m2, 4) # 15 max on 2 days (1) + compensation (2.8) self.assertMemberAssign(self.sales_team_1_m3, 4) # 15 max on 2 days (1) + compensation (2.8) @@ -320,7 +320,7 @@ class TestLeadAssign(TestLeadAssignCommon): count=_lead_count, email_dup_count=_email_dup_count) # commit probability and related fields - leads.flush() + leads.flush_recordset() self.assertInitialData() # assign for one month, aka a lot @@ -365,7 +365,7 @@ class TestLeadAssign(TestLeadAssignCommon): for lead in sliced_leads: lead.probability = (idx + 1) * 10 * ((int(lead.priority) + 1) / 2) # commit probability and related fields - leads.flush() + leads.flush_recordset() with self.with_user('user_sales_manager'): self.env['crm.team'].browse(sales_teams.ids)._action_assign_leads(work_days=30) @@ -388,7 +388,7 @@ class TestLeadAssign(TestLeadAssignCommon): self.assertGreaterEqual(len(leads_st3), 135) # 135 * 600 / 300 * 0.5 (because random) # salespersons assign - self.members.invalidate_cache(fnames=['lead_month_count']) + self.members.invalidate_model(['lead_month_count']) self.assertMemberAssign(self.sales_team_1_m1, 45) # 45 max on one month self.assertMemberAssign(self.sales_team_1_m2, 15) # 15 max on one month self.assertMemberAssign(self.sales_team_1_m3, 15) # 15 max on one month @@ -432,9 +432,9 @@ class TestLeadAssign(TestLeadAssignCommon): probabilities=[10], count=30) self.assertEqual(existing_leads.team_id, self.sales_team_1, "Team should have lower sequence") - existing_leads.flush() + existing_leads.flush_recordset() - self.sales_team_1_m1.invalidate_cache(fnames=['lead_month_count']) + self.sales_team_1_m1.invalidate_model(['lead_month_count']) self.assertEqual(self.sales_team_1_m1.lead_month_count, 30) # quota computation with existing leads @@ -479,7 +479,7 @@ class TestLeadAssign(TestLeadAssignCommon): leads[5].update({'team_id': self.sales_team_convert.id, 'user_id': self.user_sales_manager.id}) # assigned lead should not be re-assigned # commit probability and related fields - leads.flush() + leads.flush_recordset() with self.with_user('user_sales_manager'): self.env['crm.team'].browse(self.sales_team_1.ids)._action_assign_leads(work_days=4) diff --git a/addons/crm/tests/test_crm_pls.py b/addons/crm/tests/test_crm_pls.py index d51ccb89df8..98e54f11e33 100644 --- a/addons/crm/tests/test_crm_pls.py +++ b/addons/crm/tests/test_crm_pls.py @@ -191,9 +191,6 @@ class TestCRMPLS(TransactionCase): # rebuild frequencies table and recompute automated_probability for all leads. Lead._cron_update_automated_probabilities() - # As the cron is computing and writing in SQL queries, we need to invalidate the cache - leads.invalidate_cache() - self.assertEqual(tools.float_compare(leads[3].automated_probability, 33.49, 2), 0) self.assertEqual(tools.float_compare(leads[8].automated_probability, 7.74, 2), 0) lead_13_team_3_proba = leads[13].automated_probability @@ -204,7 +201,6 @@ class TestCRMPLS(TransactionCase): # Proba should be different as "no team" is not considered as a separated team. leads_with_no_team.write({'team_id': False}) Lead._cron_update_automated_probabilities() - leads.invalidate_cache() lead_13_no_team_proba = leads[13].automated_probability self.assertTrue(lead_13_team_3_proba != leads[13].automated_probability, "Probability for leads with no team should be different than if they where in their own team.") self.assertEqual(tools.float_compare(lead_13_no_team_proba, 36.65, 2), 0) @@ -407,7 +403,6 @@ class TestCRMPLS(TransactionCase): # Force recompute - A priori, no need to do this as, for each won / lost, we increment tag frequency. Lead._cron_update_automated_probabilities() - leads_with_tags.invalidate_cache() lead_tag_1 = leads_with_tags[30] lead_tag_2 = leads_with_tags[90] @@ -445,7 +440,6 @@ class TestCRMPLS(TransactionCase): leads.filtered(lambda lead: lead.id % 2 == 0).email_state = 'correct' leads.filtered(lambda lead: lead.id % 2 == 1).email_state = 'incorrect' Lead._cron_update_automated_probabilities() - leads_with_tags.invalidate_cache() self.assertEqual(tools.float_compare(leads[3].automated_probability, 4.21, 2), 0) self.assertEqual(tools.float_compare(leads[8].automated_probability, 0.23, 2), 0) @@ -453,7 +447,6 @@ class TestCRMPLS(TransactionCase): # remove all pls fields self.env['ir.config_parameter'].sudo().set_param("crm.pls_fields", False) Lead._cron_update_automated_probabilities() - leads_with_tags.invalidate_cache() self.assertEqual(tools.float_compare(leads[3].automated_probability, 34.38, 2), 0) self.assertEqual(tools.float_compare(leads[8].automated_probability, 50.0, 2), 0) @@ -461,7 +454,6 @@ class TestCRMPLS(TransactionCase): # check if the probabilities are the same with the old param self.env['ir.config_parameter'].sudo().set_param("crm.pls_fields", "country_id,state_id,email_state,phone_state,source_id") Lead._cron_update_automated_probabilities() - leads_with_tags.invalidate_cache() self.assertEqual(tools.float_compare(leads[3].automated_probability, 4.21, 2), 0) self.assertEqual(tools.float_compare(leads[8].automated_probability, 0.23, 2), 0) diff --git a/addons/crm/tests/test_performances.py b/addons/crm/tests/test_performances.py index dd4b58b8227..f949e126e2a 100644 --- a/addons/crm/tests/test_performances.py +++ b/addons/crm/tests/test_performances.py @@ -35,7 +35,7 @@ class TestLeadAssignPerf(TestLeadAssignCommon): count=200 ) # commit probability and related fields - leads.flush() + leads.flush_recordset() self.assertInitialData() # assign probability to leads (bypass auto probability as purpose is not to test pls) @@ -45,7 +45,7 @@ class TestLeadAssignPerf(TestLeadAssignCommon): for lead in sliced_leads: lead.probability = (idx + 1) * 10 * ((int(lead.priority) + 1) / 2) # commit probability and related fields - leads.flush() + leads.flush_recordset() with self.with_user('user_sales_manager'): self.env['res.users'].has_group('base.group_user') # warmup the cache to avoid inconsistency between community an enterprise @@ -61,7 +61,7 @@ class TestLeadAssignPerf(TestLeadAssignCommon): self.assertEqual(len(leads_st1) + len(leads_stc), len(leads)) # Make sure all lead are assigned # salespersons assign - self.members.invalidate_cache(fnames=['lead_month_count']) + self.members.invalidate_model(['lead_month_count']) self.assertMemberAssign(self.sales_team_1_m1, 11) # 45 max on 2 days (3) + compensation (8.4) self.assertMemberAssign(self.sales_team_1_m2, 4) # 15 max on 2 days (1) + compensation (2.8) self.assertMemberAssign(self.sales_team_1_m3, 4) # 15 max on 2 days (1) + compensation (2.8) @@ -80,7 +80,7 @@ class TestLeadAssignPerf(TestLeadAssignCommon): count=100 ) # commit probability and related fields - leads.flush() + leads.flush_recordset() self.assertInitialData() # assign probability to leads (bypass auto probability as purpose is not to test pls) @@ -90,7 +90,7 @@ class TestLeadAssignPerf(TestLeadAssignCommon): for lead in sliced_leads: lead.probability = (idx + 1) * 10 * ((int(lead.priority) + 1) / 2) # commit probability and related fields - leads.flush() + leads.flush_recordset() with self.with_user('user_sales_manager'): with self.assertQueryCount(user_sales_manager=584): @@ -103,7 +103,7 @@ class TestLeadAssignPerf(TestLeadAssignCommon): self.assertEqual(len(leads_st1) + len(leads_stc), 100) # salespersons assign - self.members.invalidate_cache(fnames=['lead_month_count']) + self.members.invalidate_model(['lead_month_count']) self.assertMemberAssign(self.sales_team_1_m1, 11) # 45 max on 2 days (3) + compensation (8.4) self.assertMemberAssign(self.sales_team_1_m2, 4) # 15 max on 2 days (1) + compensation (2.8) self.assertMemberAssign(self.sales_team_1_m3, 4) # 15 max on 2 days (1) + compensation (2.8) @@ -127,7 +127,7 @@ class TestLeadAssignPerf(TestLeadAssignCommon): count=_lead_count, email_dup_count=_email_dup_count) # commit probability and related fields - leads.flush() + leads.flush_recordset() self.assertInitialData() # assign for one month, aka a lot @@ -172,7 +172,7 @@ class TestLeadAssignPerf(TestLeadAssignCommon): for lead in sliced_leads: lead.probability = (idx + 1) * 10 * ((int(lead.priority) + 1) / 2) # commit probability and related fields - leads.flush() + leads.flush_recordset() with self.with_user('user_sales_manager'): with self.assertQueryCount(user_sales_manager=6487): @@ -184,7 +184,7 @@ class TestLeadAssignPerf(TestLeadAssignCommon): self.assertEqual(leads.user_id, sales_teams.member_ids) # salespersons assign - self.members.invalidate_cache(fnames=['lead_month_count']) + self.members.invalidate_model(['lead_month_count']) self.assertMemberAssign(self.sales_team_1_m1, 45) # 45 max on one month self.assertMemberAssign(self.sales_team_1_m2, 15) # 15 max on one month self.assertMemberAssign(self.sales_team_1_m3, 15) # 15 max on one month diff --git a/addons/crm_iap_enrich/tests/test_lead_enrich.py b/addons/crm_iap_enrich/tests/test_lead_enrich.py index 9b7efb0f895..dd18c3cce18 100644 --- a/addons/crm_iap_enrich/tests/test_lead_enrich.py +++ b/addons/crm_iap_enrich/tests/test_lead_enrich.py @@ -29,11 +29,11 @@ class TestLeadEnrich(TestCrmCommon, MockIAPEnrich): def test_enrich_internals(self): leads = self.env['crm.lead'].browse(self.leads.ids) leads[0].write({'partner_name': 'Already set', 'email_from': 'test@test1'}) - leads.flush() + leads.flush_recordset() with self.mockIAPEnrichGateway(email_data={'test1': {'country_code': 'AU', 'state_code': 'NSW'}}): leads.iap_enrich() - leads.flush() + leads.flush_recordset() self.assertEqual(leads[0].partner_name, 'Already set') self.assertEqual(leads[0].country_id, self.env.ref('base.au')) self.assertEqual(leads[0].state_id, self.env.ref('base.state_au_2')) diff --git a/addons/data_recycle/models/data_recycle_model.py b/addons/data_recycle/models/data_recycle_model.py index ffd870a3ca8..16c754ad3e9 100644 --- a/addons/data_recycle/models/data_recycle_model.py +++ b/addons/data_recycle/models/data_recycle_model.py @@ -105,7 +105,7 @@ class DataRecycleModel(models.Model): self.sudo()._notify_records_to_recycle() def _recycle_records(self, batch_commits=False): - self.flush() + self.env.flush_all() records_to_clean = [] is_test = bool(config['test_enable'] or config['test_file']) diff --git a/addons/delivery/models/delivery_carrier.py b/addons/delivery/models/delivery_carrier.py index 7f2c53f4c39..aa4f96244d8 100644 --- a/addons/delivery/models/delivery_carrier.py +++ b/addons/delivery/models/delivery_carrier.py @@ -226,7 +226,7 @@ class DeliveryCarrier(models.Model): self.ensure_one() if self.debug_logging: - self.flush() + self.env.flush_all() db_name = self._cr.dbname # Use a new cursor to avoid rollback that could be caused by an upper method @@ -384,8 +384,8 @@ class DeliveryCarrier(models.Model): def _neutralize(self): super()._neutralize() - self.flush() - self.invalidate_cache() + self.flush_model() + self.invalidate_model() self.env.cr.execute(""" UPDATE delivery_carrier SET prod_environment = false, active = false diff --git a/addons/delivery/tests/test_delivery_cost.py b/addons/delivery/tests/test_delivery_cost.py index 242c0df45ab..262edd2a70c 100644 --- a/addons/delivery/tests/test_delivery_cost.py +++ b/addons/delivery/tests/test_delivery_cost.py @@ -44,11 +44,11 @@ class TestDeliveryCost(common.TransactionCase): self.free_delivery = self.env.ref('delivery.free_delivery_carrier') # as the tests hereunder assume all the prices in USD, we must ensure # that the company actually uses USD - # We do an invalidate_cache so the cache is aware of it too. + # We do an invalidation so the cache is aware of it too. self.env.cr.execute( "UPDATE res_company SET currency_id = %s WHERE id = %s", [self.env.ref('base.USD').id, self.env.company.id]) - self.env.company.invalidate_cache() + self.env.company.invalidate_recordset() self.pricelist.currency_id = self.env.ref('base.USD').id def test_00_delivery_cost(self): diff --git a/addons/digest/models/digest.py b/addons/digest/models/digest.py index 4ef250018e8..b3a035c89a4 100644 --- a/addons/digest/models/digest.py +++ b/addons/digest/models/digest.py @@ -233,10 +233,10 @@ class Digest(models.Model): try: compute_value = digest[field_name + '_value'] # Context start and end date is different each time so invalidate to recompute. - digest.invalidate_cache([field_name + '_value']) + digest.invalidate_model([field_name + '_value']) previous_value = previous_digest[field_name + '_value'] # Context start and end date is different each time so invalidate to recompute. - previous_digest.invalidate_cache([field_name + '_value']) + previous_digest.invalidate_model([field_name + '_value']) except AccessError: # no access rights -> just skip that digest details from that user's digest email invalid_fields.append(field_name) continue diff --git a/addons/digest/tests/test_digest.py b/addons/digest/tests/test_digest.py index 2fbe72dec77..6b69f98bbc1 100644 --- a/addons/digest/tests/test_digest.py +++ b/addons/digest/tests/test_digest.py @@ -74,7 +74,7 @@ class TestDigest(mail_test.MailCommon): # range limit and dropping out of the digest's selection thing create_date=create_date, ) - messages.flush() + cls.env.flush_all() @users('admin') def test_digest_numbers(self): @@ -83,7 +83,7 @@ class TestDigest(mail_test.MailCommon): # digest creates its mails in auto_delete mode so we need to capture # the formatted body during the sending process - digest.flush() + digest.flush_recordset() with self.mock_mail_gateway(): digest.action_send() @@ -122,21 +122,21 @@ class TestDigest(mail_test.MailCommon): self.assertEqual(digest.periodicity, 'daily') # no logs for employee -> should tone down periodicity - digest.flush() + digest.flush_recordset() with self.mock_mail_gateway(): digest.action_send() self.assertEqual(digest.periodicity, 'weekly') # no logs for employee -> should tone down periodicity - digest.flush() + digest.flush_recordset() with self.mock_mail_gateway(): digest.action_send() self.assertEqual(digest.periodicity, 'monthly') # no logs for employee -> should tone down periodicity - digest.flush() + digest.flush_recordset() with self.mock_mail_gateway(): digest.action_send() @@ -181,7 +181,7 @@ class TestDigest(mail_test.MailCommon): # logs for employee -> should not tone down logs = self.env['res.users.log'].with_user(SUPERUSER_ID).create({'create_uid': self.user_employee.id}) - digest.flush() + digest.flush_recordset() with self.mock_mail_gateway(): digest.action_send() @@ -192,19 +192,19 @@ class TestDigest(mail_test.MailCommon): }) # logs for employee are more than 3 days old -> should tone down - digest.flush() + digest.flush_recordset() with self.mock_mail_gateway(): digest.action_send() self.assertEqual(digest.periodicity, 'weekly') # logs for employee are more than 2 weeks old -> should tone down - digest.flush() + digest.flush_recordset() with self.mock_mail_gateway(): digest.action_send() self.assertEqual(digest.periodicity, 'monthly') # logs for employee are less than 1 month old -> should not tone down - digest.flush() + digest.flush_recordset() with self.mock_mail_gateway(): digest.action_send() self.assertEqual(digest.periodicity, 'monthly') @@ -253,7 +253,7 @@ class TestUnsubscribe(HttpCaseWithUserDemo): self.authenticate(None, None) response = self._url_unsubscribe(token=self.user_demo_unsubscribe_token, user_id=self.user_demo.id) self.assertEqual(response.status_code, 200) - self.test_digest.invalidate_cache() + self.test_digest.invalidate_recordset() self.assertNotIn(self.user_demo, self.test_digest.user_ids) def test_unsubscribe_public(self): diff --git a/addons/event/models/event_event.py b/addons/event/models/event_event.py index c54371ae5dc..544ebf53aee 100644 --- a/addons/event/models/event_event.py +++ b/addons/event/models/event_event.py @@ -233,7 +233,7 @@ class EventEvent(models.Model): WHERE event_id IN %s AND state IN ('draft', 'open', 'done') AND active = true GROUP BY event_id, state """ - self.env['event.registration'].flush(['event_id', 'state', 'active']) + self.env['event.registration'].flush_model(['event_id', 'state', 'active']) self._cr.execute(query, (tuple(self.ids),)) res = self._cr.fetchall() for event_id, state, num in res: @@ -535,7 +535,7 @@ class EventEvent(models.Model): for res in events: if res.organizer_id: res.message_subscribe([res.organizer_id.id]) - events.flush() + self.env.flush_all() return events def write(self, vals): diff --git a/addons/event/models/event_mail.py b/addons/event/models/event_mail.py index 78e2c736942..9f404b970e0 100644 --- a/addons/event/models/event_mail.py +++ b/addons/event/models/event_mail.py @@ -239,7 +239,7 @@ You receive this email because you are: self.browse(scheduler.id).execute() except Exception as e: _logger.exception(e) - self.invalidate_cache() + self.env.invalidate_all() self._warn_template_error(scheduler, e) else: if autocommit and not getattr(threading.current_thread(), 'testing', False): diff --git a/addons/event/models/event_ticket.py b/addons/event/models/event_ticket.py index d5207f61f08..c1d8242e446 100644 --- a/addons/event/models/event_ticket.py +++ b/addons/event/models/event_ticket.py @@ -110,7 +110,7 @@ class EventTicket(models.Model): WHERE event_ticket_id IN %s AND state IN ('draft', 'open', 'done') AND active = true GROUP BY event_ticket_id, state """ - self.env['event.registration'].flush(['event_id', 'event_ticket_id', 'state', 'active']) + self.env['event.registration'].flush_model(['event_id', 'event_ticket_id', 'state', 'active']) self.env.cr.execute(query, (tuple(self.ids),)) for event_ticket_id, state, num in self.env.cr.fetchall(): results.setdefault(event_ticket_id, {})[state_field[state]] = num diff --git a/addons/event_crm/models/event_registration.py b/addons/event_crm/models/event_registration.py index 8eb360d8b49..621c35f9e12 100644 --- a/addons/event_crm/models/event_registration.py +++ b/addons/event_crm/models/event_registration.py @@ -64,7 +64,7 @@ class EventRegistration(models.Model): res = super(EventRegistration, self).write(vals) if not event_lead_rule_skip and to_update: - to_update.flush() # compute notably partner-based fields if necessary + self.env.flush_all() # compute notably partner-based fields if necessary to_update.sudo()._update_leads(vals, lead_tracked_vals) # handle triggers based on state diff --git a/addons/hr/tests/test_multi_company.py b/addons/hr/tests/test_multi_company.py index 4c01f6ecdc4..13e181aad72 100644 --- a/addons/hr/tests/test_multi_company.py +++ b/addons/hr/tests/test_multi_company.py @@ -24,8 +24,8 @@ class TestMultiCompany(TestHrCommon): cls.res_users_hr_officer.company_id = cls.company_1.id # flush and invalidate the cache, otherwise a full cache may prevent # access rights to be checked - cls.employees.flush() - cls.employees.invalidate_cache() + cls.env.flush_all() + cls.env.invalidate_all() def test_multi_company_report(self): content, content_type = self.env.ref('hr.hr_employee_print_badge').with_user(self.res_users_hr_officer).with_context( diff --git a/addons/hr_expense/tests/test_expenses_access_rights.py b/addons/hr_expense/tests/test_expenses_access_rights.py index 70b6f2de549..b9d9531f47e 100644 --- a/addons/hr_expense/tests/test_expenses_access_rights.py +++ b/addons/hr_expense/tests/test_expenses_access_rights.py @@ -47,7 +47,7 @@ class TestExpensesAccessRights(TestExpenseCommon): }), ], }) - expense_sheet.flush() + self.env.flush_all() self.assertRecordValues(expense_sheet, [{'state': 'draft'}]) diff --git a/addons/hr_holidays/models/hr_leave_allocation.py b/addons/hr_holidays/models/hr_leave_allocation.py index 43ff61b54be..9ddc7b258fa 100644 --- a/addons/hr_holidays/models/hr_leave_allocation.py +++ b/addons/hr_holidays/models/hr_leave_allocation.py @@ -492,7 +492,7 @@ class HolidaysAllocation(models.Model): [('allocation_type', '=', 'accrual'), ('state', '=', 'validate'), ('accrual_plan_id', '!=', False), ('employee_id', '!=', False), '|', ('date_to', '=', False), ('date_to', '>', fields.Datetime.now()), ('lastcall', '<', this_year_first_day)]) end_of_year_allocations._end_of_year_accrual() - end_of_year_allocations.flush() + end_of_year_allocations.flush_model() allocations = self.search( [('allocation_type', '=', 'accrual'), ('state', '=', 'validate'), ('accrual_plan_id', '!=', False), ('employee_id', '!=', False), '|', ('date_to', '=', False), ('date_to', '>', fields.Datetime.now()), diff --git a/addons/hr_holidays/models/res_users.py b/addons/hr_holidays/models/res_users.py index 0818a9e83ec..d70a57c8cc5 100644 --- a/addons/hr_holidays/models/res_users.py +++ b/addons/hr_holidays/models/res_users.py @@ -47,8 +47,8 @@ class User(models.Model): def _get_on_leave_ids(self, partner=False): now = fields.Datetime.now() field = 'partner_id' if partner else 'id' - self.env['res.users'].flush(fnames=['active']) - self.env['hr.leave'].flush(fnames=['user_id', 'state', 'date_from', 'date_to']) + self.flush_model(['active']) + self.env['hr.leave'].flush_model(['user_id', 'state', 'date_from', 'date_to']) self.env.cr.execute('''SELECT res_users.%s FROM res_users JOIN hr_leave ON hr_leave.user_id = res_users.id AND state in ('validate') diff --git a/addons/hr_holidays/tests/test_access_rights.py b/addons/hr_holidays/tests/test_access_rights.py index 8f36f6e7a98..873ad845a5e 100644 --- a/addons/hr_holidays/tests/test_access_rights.py +++ b/addons/hr_holidays/tests/test_access_rights.py @@ -499,7 +499,7 @@ class TestAccessRightsRead(TestHrHolidaysAccessRightsCommon): 'number_of_days': 1, }) with self.assertRaises(AccessError), self.cr.savepoint(): - other_leave.invalidate_cache(['name']) + other_leave.invalidate_model(['name']) name = other_leave.with_user(self.user_employee_id).name @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') @@ -794,7 +794,7 @@ class TestMultiCompany(TestHrHolidaysCommon): @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_access_other_company_user(self): employee_leave = self.employee_leave.with_user(self.user_employee) - employee_leave.invalidate_cache(['name']) + employee_leave.invalidate_model(['name']) with self.assertRaises(AccessError): employee_leave.name @@ -804,7 +804,7 @@ class TestMultiCompany(TestHrHolidaysCommon): @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_access_other_company_officer(self): employee_leave_hruser = self.employee_leave.with_user(self.user_hruser) - employee_leave_hruser.invalidate_cache(['name']) + employee_leave_hruser.invalidate_model(['name']) with self.assertRaises(AccessError): employee_leave_hruser.name @@ -814,7 +814,7 @@ class TestMultiCompany(TestHrHolidaysCommon): @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_access_other_company_manager(self): employee_leave_hrmanager = self.employee_leave.with_user(self.user_hrmanager) - employee_leave_hrmanager.invalidate_cache(['name']) + employee_leave_hrmanager.invalidate_model(['name']) with self.assertRaises(AccessError): employee_leave_hrmanager.name diff --git a/addons/hr_holidays/tests/test_holidays_flow.py b/addons/hr_holidays/tests/test_holidays_flow.py index f72e132b50b..8200c981fdf 100644 --- a/addons/hr_holidays/tests/test_holidays_flow.py +++ b/addons/hr_holidays/tests/test_holidays_flow.py @@ -165,7 +165,7 @@ class TestHolidaysFlow(TestHrHolidaysCommon): }) hol2_user_group = hol2.with_user(self.user_hruser_id) # Check left days: - 1 virtual remaining day - hol_status_2_employee_group.invalidate_cache() + hol_status_2_employee_group.invalidate_model() _check_holidays_status(hol_status_2_employee_group, 2.0, 0.0, 2.0, 1.0) # HrManager validates the second step @@ -181,7 +181,7 @@ class TestHolidaysFlow(TestHrHolidaysCommon): 'hr_holidays: refuse should lead to refuse state') # Check left days: 2 days left again - hol_status_2_employee_group.invalidate_cache(['max_leaves']) + hol_status_2_employee_group.invalidate_model(['max_leaves']) _check_holidays_status(hol_status_2_employee_group, 2.0, 0.0, 2.0, 2.0) self.assertEqual(hol2.state, 'refuse', diff --git a/addons/hr_holidays/tests/test_leave_requests.py b/addons/hr_holidays/tests/test_leave_requests.py index 0eba98bb75a..f8845f1cbde 100644 --- a/addons/hr_holidays/tests/test_leave_requests.py +++ b/addons/hr_holidays/tests/test_leave_requests.py @@ -131,12 +131,12 @@ class TestLeaveRequests(TestHrHolidaysCommon): 'number_of_days': 2, }) - holiday_status.invalidate_cache() + holiday_status.invalidate_model() self._check_holidays_status(holiday_status, 2.0, 0.0, 2.0, 0.0) hol.with_user(self.user_hrmanager_id).action_approve() - holiday_status.invalidate_cache(['max_leaves']) + holiday_status.invalidate_model(['max_leaves']) self._check_holidays_status(holiday_status, 2.0, 2.0, 0.0, 0.0) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') diff --git a/addons/hr_recruitment/models/hr_recruitment.py b/addons/hr_recruitment/models/hr_recruitment.py index d1c2f3a1b30..d7c8086a711 100644 --- a/addons/hr_recruitment/models/hr_recruitment.py +++ b/addons/hr_recruitment/models/hr_recruitment.py @@ -220,7 +220,7 @@ class Applicant(models.Model): @api.depends('email_from', 'partner_phone', 'partner_mobile') def _compute_application_count(self): - self.flush(fnames=['email_from']) + self.flush_model(['email_from']) applicants = self.env['hr.applicant'] for applicant in self: if applicant.email_from or applicant.partner_phone or applicant.partner_mobile: diff --git a/addons/hr_work_entry/models/hr_work_entry.py b/addons/hr_work_entry/models/hr_work_entry.py index 25c2f46c6f9..3417de0b459 100644 --- a/addons/hr_work_entry/models/hr_work_entry.py +++ b/addons/hr_work_entry/models/hr_work_entry.py @@ -142,7 +142,7 @@ class HrWorkEntry(models.Model): # use '()' to exlude the lower and upper bounds of the range. # Filter on date_start and date_stop (both indexed) in the EXISTS clause to # limit the resulting set size and fasten the query. - self.flush(['date_start', 'date_stop', 'employee_id', 'active']) + self.flush_model(['date_start', 'date_stop', 'employee_id', 'active']) query = """ SELECT b1.id, b2.id diff --git a/addons/hr_work_entry_holidays/models/hr_work_entry.py b/addons/hr_work_entry_holidays/models/hr_work_entry.py index 056eff67493..f28670f6897 100644 --- a/addons/hr_work_entry_holidays/models/hr_work_entry.py +++ b/addons/hr_work_entry_holidays/models/hr_work_entry.py @@ -32,8 +32,8 @@ class HrWorkEntry(models.Model): if not self: return False - self.flush(['date_start', 'date_stop', 'employee_id']) - self.env['hr.leave'].flush(['date_from', 'date_to', 'state', 'employee_id']) + self.flush_recordset(['date_start', 'date_stop', 'employee_id', 'active']) + self.env['hr.leave'].flush_model(['date_from', 'date_to', 'state', 'employee_id']) query = """ SELECT diff --git a/addons/iap/models/iap_account.py b/addons/iap/models/iap_account.py index 386ca3d42cc..aa920cb7933 100644 --- a/addons/iap/models/iap_account.py +++ b/addons/iap/models/iap_account.py @@ -38,7 +38,7 @@ class IapAccount(models.Model): # preventing the process to continue any further. # Flush the pending operations to avoid a deadlock. - self.flush() + self.env.flush_all() IapAccount = self.with_env(self.env(cr=cr)) account = IapAccount.search(domain, order='id desc', limit=1) if not account: @@ -121,8 +121,8 @@ class IapAccount(models.Model): def _neutralize(self): super()._neutralize() - self.flush() - self.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() self.env.cr.execute(""" INSERT INTO ir_config_parameter(key, value) diff --git a/addons/im_livechat/models/chatbot_script_step.py b/addons/im_livechat/models/chatbot_script_step.py index 1e267cd6183..fe1febfca9b 100644 --- a/addons/im_livechat/models/chatbot_script_step.py +++ b/addons/im_livechat/models/chatbot_script_step.py @@ -297,7 +297,7 @@ class ChatbotScriptStep(models.Model): if chatbot_message: chatbot_message.write({'user_raw_answer': message_body}) - chatbot_message.flush() + self.env.flush_all() return self._fetch_next_step(mail_channel.chatbot_message_ids.user_script_answer_id) diff --git a/addons/im_livechat/tests/test_chatbot_internals.py b/addons/im_livechat/tests/test_chatbot_internals.py index 3050f664730..54687e604ad 100644 --- a/addons/im_livechat/tests/test_chatbot_internals.py +++ b/addons/im_livechat/tests/test_chatbot_internals.py @@ -37,7 +37,7 @@ class ChatbotCase(chatbot_common.ChatbotCase): "should be flagged as forward operator child.") self.step_no_operator_dispatch.write({'triggering_answer_ids': [(6, 0, [self.step_dispatch_pricing.id])]}) - self.chatbot_script.script_step_ids.invalidate_cache(['is_forward_operator_child']) + self.chatbot_script.script_step_ids.invalidate_recordset(['is_forward_operator_child']) self.assertEqual([step.is_forward_operator_child for step in self.chatbot_script.script_step_ids], [False, False, False, False, False, False, False, True, False, False, False, False, False, False], diff --git a/addons/knowledge/models/knowledge_article.py b/addons/knowledge/models/knowledge_article.py index 17fec8879a6..67562207b69 100644 --- a/addons/knowledge/models/knowledge_article.py +++ b/addons/knowledge/models/knowledge_article.py @@ -1169,7 +1169,7 @@ class Article(models.Model): in the custom sql query. The query's output table and fields names does not match the model we are working on. """ - self.env['knowledge.article'].flush() + self.flush_model() args = [] base_where_domain = '' @@ -1212,7 +1212,8 @@ class Article(models.Model): The articles can be filtered using the article_ids param. The member model is fully flushed before running the request. """ - self.env['knowledge.article'].flush() + self.env['knowledge.article'].flush_model() + self.env['knowledge.article.member'].flush_model() args = [partner.id] base_where_domain = '' @@ -1273,7 +1274,9 @@ class Article(models.Model): Please note that these additional fields are not sanitized, the caller has the responsibility to check that user can access those fields and that no injection is possible. """ - self.env['knowledge.article'].flush() + self.env['res.partner'].flush_model() + self.env['knowledge.article'].flush_model() + self.env['knowledge.article.member'].flush_model() add_where_clause = '' args = [] diff --git a/addons/knowledge/tests/common.py b/addons/knowledge/tests/common.py index fdc7a2ccad5..750efccc00b 100644 --- a/addons/knowledge/tests/common.py +++ b/addons/knowledge/tests/common.py @@ -183,7 +183,7 @@ class KnowledgeCommonWData(KnowledgeCommon): 'parent_id': cls.article_private_manager.id, } ]) - cls.env['knowledge.article'].flush() + cls.env.flush_all() class KnowledgeArticlePermissionsCase(KnowledgeCommon): @@ -395,4 +395,4 @@ class KnowledgeArticlePermissionsCase(KnowledgeCommon): cls.article_write_contents + cls.article_write_contents_children + \ cls.article_read_contents + cls.article_read_contents_children + \ cls.article_write_desync + cls.article_read_desync - cls.env['knowledge.article'].flush() + cls.env.flush_all() diff --git a/addons/knowledge/tests/test_knowledge_article_business.py b/addons/knowledge/tests/test_knowledge_article_business.py index 4f537522dad..360b671395d 100644 --- a/addons/knowledge/tests/test_knowledge_article_business.py +++ b/addons/knowledge/tests/test_knowledge_article_business.py @@ -109,7 +109,7 @@ class TestKnowledgeArticleBusiness(KnowledgeCommonWData): # perform archive as user article_shared = self.article_shared.with_env(self.env) - article_shared.invalidate_cache(fnames=['child_ids']) # context dependent + article_shared.invalidate_model(['child_ids']) # context dependent shared_children = article_shared.child_ids writable_child, readonly_child = writable_child_su.with_env(self.env), readonly_child_su.with_env(self.env) self.assertEqual(len(shared_children), 2) @@ -410,7 +410,7 @@ class TestKnowledgeArticleBusiness(KnowledgeCommonWData): self.assertEqual(playground_articles.mapped('is_user_favorite'), [False, False, False]) playground_articles[0].action_toggle_favorite() - playground_articles.invalidate_cache(fnames=['is_user_favorite']) + playground_articles.invalidate_model(['is_user_favorite']) self.assertEqual(playground_articles.mapped('is_user_favorite'), [True, False, False]) # correct uid-based computation @@ -437,7 +437,7 @@ class TestKnowledgeArticleBusiness(KnowledgeCommonWData): # valid move: put second child of workspace under the first one workspace_children[1].move_to(parent_id=workspace_children[0].id) - workspace_children.flush() + workspace_children.flush_model() self.assertEqual(article_workspace.child_ids, workspace_children[0]) self.assertEqual(article_workspace._get_descendants(), workspace_children) self.assertEqual(workspace_children.root_article_id, article_workspace) @@ -450,7 +450,7 @@ class TestKnowledgeArticleBusiness(KnowledgeCommonWData): # other valid move: first child is moved to private section workspace_children[0].move_to(parent_id=False, is_private=True) - workspace_children.flush() + workspace_children.flush_model() self.assertMembers(workspace_children[0], 'none', {self.partner_employee: 'write'}) self.assertEqual(workspace_children[0].category, 'private') self.assertEqual(workspace_children[0].internal_permission, 'none') @@ -475,7 +475,7 @@ class TestKnowledgeArticleBusiness(KnowledgeCommonWData): 'name': 'Child3 without parent name in its name', 'parent_id': article_workspace.id, }) - (self.workspace_children + new_root_child).flush() + new_root_child.flush_model() # ensure initial values self.assertTrue(article_workspace.is_user_favorite) @@ -565,7 +565,9 @@ class TestKnowledgeArticleFields(KnowledgeCommonWData): article.with_user(self.user_employee2).write({ 'body': body_values[(index + 1) if index < (len(body_values)-1) else 0] }) - article.with_user(self.user_employee2).flush() + # the with_user() below is necessary for the test to succeed, + # and that's kind of a bad smell... + article.with_user(self.user_employee2).flush_model() self.assertEqual(article.last_edition_uid, self.user_employee2) self.assertEqual(article.last_edition_date, _reference_dt + timedelta(days=1)) diff --git a/addons/knowledge/tests/test_knowledge_article_permissions.py b/addons/knowledge/tests/test_knowledge_article_permissions.py index cedfec07a95..94a317f303d 100644 --- a/addons/knowledge/tests/test_knowledge_article_permissions.py +++ b/addons/knowledge/tests/test_knowledge_article_permissions.py @@ -199,7 +199,7 @@ class TestKnowledgeArticlePermissionsTools(KnowledgeArticlePermissionsCase): # downgrade write global perm to read writable_as1._set_internal_permission('none') - writable_as1.flush() # ACLs are done using SQL + writable_as1.flush_model() # ACLs are done using SQL self.assertMembers( writable_as1, 'none', {self.partner_portal: 'read', # untouched by downgrade @@ -222,7 +222,7 @@ class TestKnowledgeArticlePermissionsTools(KnowledgeArticlePermissionsCase): # downgrade write global perm to read writable_as1._set_internal_permission('read') - writable_as1.flush() # ACLs are done using SQL + writable_as1.flush_model() # ACLs are done using SQL self.assertMembers( writable_as1, 'read', {self.partner_portal: 'read', self.env.user.partner_id: 'write'}, diff --git a/addons/knowledge/tests/test_knowledge_article_sequence.py b/addons/knowledge/tests/test_knowledge_article_sequence.py index 053ff958755..4877e38144d 100644 --- a/addons/knowledge/tests/test_knowledge_article_sequence.py +++ b/addons/knowledge/tests/test_knowledge_article_sequence.py @@ -59,7 +59,7 @@ class TestKnowledgeArticleSequence(KnowledgeCommon): cls.article_private2 = cls._create_private_article(cls, 'Article2', target_user=cls.user_employee) # flush everything to ease resequencing and date-based computation - cls.env['knowledge.article'].flush() + cls.env.flush_all() @users('employee') def test_initial_tree(self): diff --git a/addons/knowledge/tests/test_knowledge_performance.py b/addons/knowledge/tests/test_knowledge_performance.py index a01fea0c72c..7c42379ecab 100644 --- a/addons/knowledge/tests/test_knowledge_performance.py +++ b/addons/knowledge/tests/test_knowledge_performance.py @@ -18,7 +18,7 @@ class KnowledgePerformanceCase(KnowledgeCommonWData): def _flush_tracking(self): """ Force the creation of tracking values notably, and ensure tests are reproducible. """ - self.env['base'].flush() + self.env.flush_all() self.cr.flush() @users('employee') diff --git a/addons/l10n_es_edi_sii/models/res_company.py b/addons/l10n_es_edi_sii/models/res_company.py index d3c09f5ddc8..193580c4bc7 100644 --- a/addons/l10n_es_edi_sii/models/res_company.py +++ b/addons/l10n_es_edi_sii/models/res_company.py @@ -46,6 +46,6 @@ class ResCompany(models.Model): def _neutralize(self): super()._neutralize() - self.flush() - self.invalidate_cache() + self.flush_model() + self.invalidate_model() self.env.cr.execute("UPDATE res_company SET l10n_es_edi_test_env = true") diff --git a/addons/l10n_in_edi/models/res_company.py b/addons/l10n_in_edi/models/res_company.py index ac7e2b2723b..4aad50bd07b 100644 --- a/addons/l10n_in_edi/models/res_company.py +++ b/addons/l10n_in_edi/models/res_company.py @@ -25,8 +25,8 @@ class ResCompany(models.Model): def _neutralize(self): super()._neutralize() - self.flush() - self.invalidate_cache() + self.flush_model() + self.invalidate_model() self.env.cr.execute("""UPDATE res_company SET l10n_in_edi_production_env = false, l10n_in_edi_username = Null, diff --git a/addons/l10n_it_stock_ddt/tests/test_ddt.py b/addons/l10n_it_stock_ddt/tests/test_ddt.py index fecea21bc16..a09fe8d0b35 100644 --- a/addons/l10n_it_stock_ddt/tests/test_ddt.py +++ b/addons/l10n_it_stock_ddt/tests/test_ddt.py @@ -92,11 +92,11 @@ class TestDDT(TestSaleCommon): self.inv2 = self.so._create_invoices() self.inv2.action_post() - self.inv2.flush() - self.inv2.invalidate_cache() + self.inv2.flush_model() + self.inv2.invalidate_model() self.assertIn(pickx1, self.inv2.l10n_it_ddt_ids) self.assertIn(pickx2, self.inv2.l10n_it_ddt_ids) # FIXME this check only worked because of a strange cache behavior # But is consistently broken after recent cleanings in sale - # with the flush & invalidate_cache, it always breaks, even without the cleanings + # with the flush & invalidate, it always breaks, even without the cleanings # self.assertEqual(self.inv2.l10n_it_ddt_ids.ids, (pickx1 | pickx2).ids, 'DDTs should be linked to the invoice') diff --git a/addons/lunch/models/lunch_order.py b/addons/lunch/models/lunch_order.py index 4098b7ce344..578832cb0e5 100644 --- a/addons/lunch/models/lunch_order.py +++ b/addons/lunch/models/lunch_order.py @@ -149,7 +149,7 @@ class LunchOrder(models.Model): # This also forces us to invalidate the cache for topping_ids_2 and topping_ids_3 that # could have changed through topping_ids_1 without the cache knowing about it toppings = self._extract_toppings(values) - self.invalidate_cache(['topping_ids_2', 'topping_ids_3']) + self.invalidate_model(['topping_ids_2', 'topping_ids_3']) values['topping_ids_1'] = [(6, 0, toppings)] matching_lines = self._find_matching_lines({ 'user_id': values.get('user_id', line.user_id.id), @@ -207,7 +207,7 @@ class LunchOrder(models.Model): return True def _check_wallet(self): - self.flush() + self.env.flush_all() for line in self: if self.env['lunch.cashmove'].get_wallet_balance(line.user_id) < 0: raise ValidationError(_('Your wallet does not contain enough money to order that. To add some money to your wallet, please contact your lunch manager.')) diff --git a/addons/lunch/tests/test_supplier.py b/addons/lunch/tests/test_supplier.py index fb1450ba962..a9c21ca4905 100644 --- a/addons/lunch/tests/test_supplier.py +++ b/addons/lunch/tests/test_supplier.py @@ -50,7 +50,7 @@ env['lunch.supplier'].browse([{self.supplier_kothai.id}])._send_auto_email()""") assert self.supplier_pizza_inn.available_today == result,\ 'supplier pizza inn should %s considered available on %s' % ('be' if result else 'not be', value) - self.env['lunch.supplier'].invalidate_cache(['available_today'], [self.supplier_pizza_inn.id]) + self.supplier_pizza_inn.invalidate_recordset(['available_today']) @common.users('cle-lunch-manager') def test_search_available_today(self): diff --git a/addons/mail/models/ir_model.py b/addons/mail/models/ir_model.py index a9c04476448..fcb5dae6a67 100644 --- a/addons/mail/models/ir_model.py +++ b/addons/mail/models/ir_model.py @@ -67,7 +67,7 @@ class IrModel(models.Model): if 'is_mail_blacklist' in vals and any(rec.is_mail_blacklist > vals['is_mail_blacklist'] for rec in self): raise UserError(_('Field "Mail Blacklist" cannot be changed to "False".')) res = super(IrModel, self).write(vals) - self.flush() + self.env.flush_all() # setup models; this reloads custom models in registry self.pool.setup_models(self._cr) # update database schema of models diff --git a/addons/mail/models/mail_activity.py b/addons/mail/models/mail_activity.py index a7a5acff8ef..79601fe3b19 100644 --- a/addons/mail/models/mail_activity.py +++ b/addons/mail/models/mail_activity.py @@ -359,7 +359,7 @@ class MailActivity(models.Model): # check read access rights before checking the actual rules on the given ids super(MailActivity, self.with_user(access_rights_uid or self._uid)).check_access_rights('read') - self.flush(['res_model', 'res_id']) + self.flush_model(['res_model', 'res_id']) activities_to_check = [] for sub_ids in self._cr.split_for_in_conditions(ids): self._cr.execute(""" diff --git a/addons/mail/models/mail_activity_mixin.py b/addons/mail/models/mail_activity_mixin.py index 11e7fa79a6b..9528886ace5 100644 --- a/addons/mail/models/mail_activity_mixin.py +++ b/addons/mail/models/mail_activity_mixin.py @@ -261,7 +261,9 @@ class MailActivityMixin(models.AbstractModel): # explicitly check access rights, since we bypass the ORM self.check_access_rights('read') self._flush_search(domain, fields=[group_by_fname], order='id') - self.env['mail.activity'].flush(['res_model', 'res_id', 'user_id', 'date_deadline']) + self.env['mail.activity'].flush_model(['res_model', 'res_id', 'user_id', 'date_deadline']) + self.env['res.users'].flush_model(['partner_id']) + self.env['res.partner'].flush_model(['tz']) query = self._where_calc(domain) self._apply_ir_rules(query, 'read') diff --git a/addons/mail/models/mail_channel.py b/addons/mail/models/mail_channel.py index ee213449d66..79b712ca7eb 100644 --- a/addons/mail/models/mail_channel.py +++ b/addons/mail/models/mail_channel.py @@ -562,8 +562,8 @@ class Channel(models.Model): recipients_data = [] if pids: - self.env['res.partner'].flush(fnames=['active', 'email', 'partner_share']) - self.env['res.users'].flush(fnames=['notification_type', 'partner_id']) + self.env['res.partner'].flush_model(['active', 'email', 'partner_share']) + self.env['res.users'].flush_model(['notification_type', 'partner_id']) sql_query = """ SELECT DISTINCT ON (partner.id) partner.id, partner.partner_share, @@ -899,7 +899,8 @@ class Channel(models.Model): if len(partners_to) > 2: raise UserError(_("A chat should not be created with more than 2 persons. Create a group instead.")) # determine type according to the number of partner in the channel - self.flush() + self.flush_model() + self.env['mail.channel.partner'].flush_model() self.env.cr.execute(""" SELECT P.channel_id FROM mail_channel C, mail_channel_partner P @@ -1188,7 +1189,7 @@ class Channel(models.Model): """ Return the last message of the given channels.""" if not self: return [] - self.flush() + self.env['mail.message'].flush_model() self.env.cr.execute(""" SELECT res_id AS id, MAX(id) AS message_id FROM mail_message diff --git a/addons/mail/models/mail_channel_partner.py b/addons/mail/models/mail_channel_partner.py index 382a64c4d8a..9a73e664c13 100644 --- a/addons/mail/models/mail_channel_partner.py +++ b/addons/mail/models/mail_channel_partner.py @@ -35,7 +35,8 @@ class ChannelPartner(models.Model): @api.depends('channel_id.message_ids', 'seen_message_id') def _compute_message_unread(self): - self.flush() + self.env['mail.message'].flush_model() + self.flush_recordset(['channel_id', 'seen_message_id']) self.env.cr.execute(""" SELECT count(mail_message.id) AS count, mail_channel_partner.id diff --git a/addons/mail/models/mail_followers.py b/addons/mail/models/mail_followers.py index 1f9f1473bea..65a17ee314a 100644 --- a/addons/mail/models/mail_followers.py +++ b/addons/mail/models/mail_followers.py @@ -108,11 +108,11 @@ class Followers(models.Model): 'type': summary of partner 'usage' (portal, customer, internal user); } """ - self.env['mail.followers'].flush(['partner_id', 'subtype_ids']) - self.env['mail.message.subtype'].flush(['internal']) - self.env['res.users'].flush(['notification_type', 'active', 'partner_id', 'groups_id']) - self.env['res.partner'].flush(['active', 'partner_share']) - self.env['res.groups'].flush(['users']) + self.env['mail.followers'].flush_model(['partner_id', 'subtype_ids']) + self.env['mail.message.subtype'].flush_model(['internal']) + self.env['res.users'].flush_model(['notification_type', 'active', 'partner_id', 'groups_id']) + self.env['res.partner'].flush_model(['active', 'partner_share']) + self.env['res.groups'].flush_model(['users']) # if we have records and a subtype: we have to fetch followers if records and subtype_id: query = """ diff --git a/addons/mail/models/mail_mail.py b/addons/mail/models/mail_mail.py index 9d01695ac35..347836c095f 100644 --- a/addons/mail/models/mail_mail.py +++ b/addons/mail/models/mail_mail.py @@ -427,7 +427,7 @@ class MailMail(models.Model): }) # `test_mail_bounce_during_send`, force immediate update to obtain the lock. # see rev. 56596e5240ef920df14d99087451ce6f06ac6d36 - notifs.flush(fnames=['notification_status', 'failure_type', 'failure_reason'], records=notifs) + notifs.flush_recordset(['notification_status', 'failure_type', 'failure_reason']) # build an RFC2822 email.message.Message object and send it without queuing res = None diff --git a/addons/mail/models/mail_message.py b/addons/mail/models/mail_message.py index 06622858f26..c7e9521a14a 100644 --- a/addons/mail/models/mail_message.py +++ b/addons/mail/models/mail_message.py @@ -290,8 +290,8 @@ class Message(models.Model): # check read access rights before checking the actual rules on the given ids super(Message, self.with_user(access_rights_uid or self._uid)).check_access_rights('read') - self.flush(['model', 'res_id', 'author_id', 'message_type', 'partner_ids']) - self.env['mail.notification'].flush(['mail_message_id', 'res_partner_id']) + self.flush_recordset(['model', 'res_id', 'author_id', 'message_type', 'partner_ids']) + self.env['mail.notification'].flush_model(['mail_message_id', 'res_partner_id']) for sub_ids in self._cr.split_for_in_conditions(ids): self._cr.execute(""" SELECT DISTINCT m.id, m.model, m.res_id, m.author_id, m.message_type, @@ -394,8 +394,8 @@ class Message(models.Model): # Read mail_message.ids to have their values message_values = dict((message_id, {}) for message_id in self.ids) - self.flush(['model', 'res_id', 'author_id', 'parent_id', 'message_type', 'partner_ids']) - self.env['mail.notification'].flush(['mail_message_id', 'res_partner_id']) + self.flush_recordset(['model', 'res_id', 'author_id', 'parent_id', 'message_type', 'partner_ids']) + self.env['mail.notification'].flush_model(['mail_message_id', 'res_partner_id']) if operation == 'read': self._cr.execute(""" @@ -1075,15 +1075,12 @@ class Message(models.Model): def _invalidate_documents(self, model=None, res_id=None): """ Invalidate the cache of the documents followed by ``self``. """ + fnames = ['message_ids', 'message_needaction', 'message_needaction_counter'] for record in self: model = model or record.model res_id = res_id or record.res_id if issubclass(self.pool[model], self.pool['mail.thread']): - self.env[model].invalidate_cache(fnames=[ - 'message_ids', - 'message_needaction', - 'message_needaction_counter', - ], ids=[res_id]) + self.env[model].browse(res_id).invalidate_recordset(fnames) def _get_search_domain_share(self): return ['&', '&', ('is_internal', '=', False), ('subtype_id', '!=', False), ('subtype_id.internal', '=', False)] diff --git a/addons/mail/models/mail_template.py b/addons/mail/models/mail_template.py index cca08844261..d3544717cf8 100644 --- a/addons/mail/models/mail_template.py +++ b/addons/mail/models/mail_template.py @@ -343,6 +343,6 @@ class MailTemplate(models.Model): def _neutralize(self): super()._neutralize() - self.flush() - self.invalidate_cache() + self.flush_model() + self.invalidate_model() self.env.cr.execute("UPDATE mail_template SET mail_server_id=NULL") diff --git a/addons/mail/models/mail_thread.py b/addons/mail/models/mail_thread.py index 0f7b87eb3af..69355b49598 100644 --- a/addons/mail/models/mail_thread.py +++ b/addons/mail/models/mail_thread.py @@ -153,7 +153,7 @@ class MailThread(models.AbstractModel): return [('id', 'not in', [res['res_id'] for res in followers.read(['res_id'])])] def _compute_has_message(self): - self.flush() + self.env['mail.message'].flush_model() self.env.cr.execute(""" SELECT distinct res_id FROM mail_message mm @@ -492,7 +492,7 @@ class MailThread(models.AbstractModel): record._message_track_post_template(changes) # this method is called after the main flush() and just before commit(); # we have to flush() again in case we triggered some recomputations - self.flush() + self.env.flush_all() def _track_set_log_message(self, message): """ Link tracking to a message logged as body, in addition to subtype diff --git a/addons/mail/models/mail_thread_blacklist.py b/addons/mail/models/mail_thread_blacklist.py index 05915b983f7..3a82173390c 100644 --- a/addons/mail/models/mail_thread_blacklist.py +++ b/addons/mail/models/mail_thread_blacklist.py @@ -52,8 +52,8 @@ class MailBlackListMixin(models.AbstractModel): @api.model def _search_is_blacklisted(self, operator, value): # Assumes operator is '=' or '!=' and value is True or False - self.flush(['email_normalized']) - self.env['mail.blacklist'].flush(['email', 'active']) + self.flush_model(['email_normalized']) + self.env['mail.blacklist'].flush_model(['email', 'active']) self._assert_primary_email() if operator != '=': if operator == '!=' and isinstance(value, bool): diff --git a/addons/mail/models/res_partner.py b/addons/mail/models/res_partner.py index 39ebe2f17bd..0f75b10b772 100644 --- a/addons/mail/models/res_partner.py +++ b/addons/mail/models/res_partner.py @@ -35,7 +35,7 @@ class Partner(models.Model): def _get_needaction_count(self): """ compute the number of needaction of the current partner """ self.ensure_one() - self.env['mail.notification'].flush(['is_read', 'res_partner_id']) + self.env['mail.notification'].flush_model(['is_read', 'res_partner_id']) self.env.cr.execute(""" SELECT count(*) as needaction_count FROM mail_notification R diff --git a/addons/mail/tests/common.py b/addons/mail/tests/common.py index b6acd739b87..8be978e4de6 100644 --- a/addons/mail/tests/common.py +++ b/addons/mail/tests/common.py @@ -558,7 +558,7 @@ class MailCase(MockEmail): def flush_tracking(self): """ Force the creation of tracking values. """ - self.env['base'].flush() + self.env.flush_all() self.cr.flush() # ------------------------------------------------------------ diff --git a/addons/mail/tests/test_mail_channel.py b/addons/mail/tests/test_mail_channel.py index d61d694b435..c5c404b1848 100644 --- a/addons/mail/tests/test_mail_channel.py +++ b/addons/mail/tests/test_mail_channel.py @@ -394,7 +394,7 @@ class TestChannelInternals(MailCommon): # Unsubscribe archived user from the private channels, but not from public channels and not from chat self.user_employee.active = False - (test_chat | self.test_channel).invalidate_cache(fnames=['channel_partner_ids']) + (test_chat | self.test_channel).invalidate_recordset(['channel_partner_ids']) self.assertEqual(test_channel_private.channel_partner_ids, test_partner) self.assertEqual(test_channel_group.channel_partner_ids, test_partner) self.assertEqual(self.test_channel.channel_partner_ids, self.user_employee.partner_id | test_partner) diff --git a/addons/mail/tests/test_rtc.py b/addons/mail/tests/test_rtc.py index 70a2ed7dc6d..0134766cc55 100644 --- a/addons/mail/tests/test_rtc.py +++ b/addons/mail/tests/test_rtc.py @@ -536,7 +536,7 @@ class TestChannelInternals(MailCommon): channel = self.env['mail.channel'].browse(self.env['mail.channel'].create_group(partners_to=self.user_employee.partner_id.ids)['id']) channel_partner = channel.sudo().channel_last_seen_partner_ids.filtered(lambda channel_partner: channel_partner.partner_id == self.user_employee.partner_id) channel_partner._rtc_join_call() - channel_partner.rtc_session_ids.flush() + channel_partner.rtc_session_ids.flush_model() channel_partner.rtc_session_ids._write({'write_date': fields.Datetime.now() - relativedelta(days=2)}) self.env['bus.bus'].sudo().search([]).unlink() with self.assertBus( @@ -606,7 +606,7 @@ class TestChannelInternals(MailCommon): 'channel_id': channel.id, }) test_session = self.env['mail.channel.rtc.session'].sudo().create({'channel_partner_id': test_channel_partner.id}) - test_session.flush() + test_session.flush_model() test_session._write({'write_date': fields.Datetime.now() - relativedelta(days=2)}) unused_ids = [9998, 9999] self.env['bus.bus'].sudo().search([]).unlink() diff --git a/addons/mail/wizard/mail_compose_message.py b/addons/mail/wizard/mail_compose_message.py index f264e170819..c15ad3eb36b 100644 --- a/addons/mail/wizard/mail_compose_message.py +++ b/addons/mail/wizard/mail_compose_message.py @@ -515,7 +515,7 @@ class MailComposer(models.TransientModel): def _get_blacklist_record_ids(self, mail_values_dict): blacklisted_rec_ids = set() if self.composition_mode == 'mass_mail' and issubclass(type(self.env[self.model]), self.pool['mail.thread.blacklist']): - self.env['mail.blacklist'].flush(['email']) + self.env['mail.blacklist'].flush_model(['email', 'active']) self._cr.execute("SELECT email FROM mail_blacklist WHERE active=true") blacklist = {x[0] for x in self._cr.fetchall()} if blacklist: diff --git a/addons/mail/wizard/mail_template_preview.py b/addons/mail/wizard/mail_template_preview.py index dbc407996e1..118fbf4fb93 100644 --- a/addons/mail/wizard/mail_template_preview.py +++ b/addons/mail/wizard/mail_template_preview.py @@ -75,7 +75,7 @@ class MailTemplatePreview(models.TransientModel): self._set_mail_attributes() self.error_msg = user_error.args[0] finally: - # Avoid to be change by a invalidate_cache call (in generate_mail), e.g. Quotation / Order report + # Avoid to be change by a cache invalidation (in generate_mail), e.g. Quotation / Order report for key, value in copy_depends_values.items(): self[key] = value diff --git a/addons/mail_group/tests/test_mail_group_message.py b/addons/mail_group/tests/test_mail_group_message.py index 69372b6f63f..bf3af153436 100644 --- a/addons/mail_group/tests/test_mail_group_message.py +++ b/addons/mail_group/tests/test_mail_group_message.py @@ -59,12 +59,12 @@ class TestMailGroupMessage(TestMailListCommon): with self.assertRaises(AccessError, msg='Non moderator should have access to only accepted message'): self.test_group_msg_1_pending.with_user(self.user_portal).check_access_rule('read') - self.test_group_msg_1_pending.invalidate_cache() + self.test_group_msg_1_pending.invalidate_recordset() self.assertEqual(self.test_group_msg_1_pending.with_user(self.user_employee).moderation_status, 'pending_moderation', msg='Moderators should have access to pending message') # Message accepted - self.test_group_msg_2_accepted.invalidate_cache() + self.test_group_msg_2_accepted.invalidate_recordset() self.assertEqual(self.test_group_msg_2_accepted.with_user(self.user_portal).moderation_status, 'accepted', msg='Portal should have access to accepted messages') @@ -83,7 +83,7 @@ class TestMailGroupMessage(TestMailListCommon): with self.assertRaises(AccessError, msg='Non moderator should have access to only accepted message'): self.test_group_msg_1_pending.with_user(self.user_employee_2).check_access_rule('read') - self.test_group_msg_1_pending.invalidate_cache() + self.test_group_msg_1_pending.invalidate_recordset() self.assertEqual(self.test_group_msg_1_pending.with_user(self.user_employee).moderation_status, 'pending_moderation', msg='Moderators should have access to pending message') @@ -95,7 +95,7 @@ class TestMailGroupMessage(TestMailListCommon): self.assertEqual(self.test_group_msg_2_accepted.with_user(self.user_portal).moderation_status, 'accepted', msg='Portal should have access to accepted messages') - self.test_group_msg_3_rejected.invalidate_cache() + self.test_group_msg_3_rejected.invalidate_recordset() self.assertEqual(self.test_group_msg_1_pending.with_user(self.user_admin).moderation_status, 'pending_moderation', msg='Mail Group Administrator should have access to all messages') diff --git a/addons/mail_group/tests/test_mail_group_moderation.py b/addons/mail_group/tests/test_mail_group_moderation.py index cdaddabf491..07a40f19936 100644 --- a/addons/mail_group/tests/test_mail_group_moderation.py +++ b/addons/mail_group/tests/test_mail_group_moderation.py @@ -35,7 +35,6 @@ class TestMailGroupModeration(TestMailListCommon): 'email': 'banned_member@test.com', 'status': 'ban', }) - moderation.flush() @mute_logger('odoo.models.unlink', 'odoo.addons.mail_group.models.mail_group_message') @users('employee') diff --git a/addons/mail_plugin/tests/test_controller.py b/addons/mail_plugin/tests/test_controller.py index fe5aea21a41..b4e5be44370 100644 --- a/addons/mail_plugin/tests/test_controller.py +++ b/addons/mail_plugin/tests/test_controller.py @@ -26,7 +26,7 @@ class TestMailPluginController(TestMailPluginControllerCommon): company_id = result["company"]["id"] company = self.env["res.partner"].browse(company_id) - partner.invalidate_cache() + partner.invalidate_recordset() self.assertEqual(partner.parent_id, company, "Should change the company of the partner") def test_get_partner_blacklisted_domain(self): diff --git a/addons/mail_plugin/tests/test_res_partner_iap.py b/addons/mail_plugin/tests/test_res_partner_iap.py index 047c7a7feda..0661d645262 100644 --- a/addons/mail_plugin/tests/test_res_partner_iap.py +++ b/addons/mail_plugin/tests/test_res_partner_iap.py @@ -25,7 +25,7 @@ class TestResPartnerIap(MailCommon): self.assertFalse(partner.iap_enrich_info) partner_iap = self.env["res.partner.iap"].create({"partner_id": partner.id, "iap_enrich_info": "test info"}) - partner.invalidate_cache() + partner.invalidate_recordset() self.assertEqual(partner.iap_enrich_info, "test info") partner_iap.unlink() @@ -36,7 +36,7 @@ class TestResPartnerIap(MailCommon): self.assertEqual(partner_iap.iap_enrich_info, "test info 2") partner.iap_enrich_info = "test info 3" - partner_iap.invalidate_cache() + partner_iap.invalidate_recordset() new_partner_iap = self.env["res.partner.iap"].search([("partner_id", "=", partner.id)]) self.assertEqual(new_partner_iap, partner_iap, "Should have write on the existing one") self.assertEqual(partner_iap.iap_enrich_info, "test info 3") @@ -48,7 +48,7 @@ class TestResPartnerIap(MailCommon): 'iap_search_domain': 'qsd@example.com', }) - partner.invalidate_cache() + partner.invalidate_recordset() self.assertEqual(partner.iap_enrich_info, 'enrichment information') self.assertEqual(partner.iap_search_domain, 'qsd@example.com') @@ -72,6 +72,6 @@ class TestResPartnerIap(MailCommon): self.assertEqual(partner_iap.iap_search_domain, 'xyz@example.com') partner.iap_search_domain = "only write on domain" - partner_iap.invalidate_cache() + partner_iap.invalidate_recordset() self.assertEqual(partner_iap.iap_enrich_info, 'second information') self.assertEqual(partner_iap.iap_search_domain, 'only write on domain') diff --git a/addons/mass_mailing/models/mailing.py b/addons/mass_mailing/models/mailing.py index 479fa46d47f..4f203d3578c 100644 --- a/addons/mass_mailing/models/mailing.py +++ b/addons/mass_mailing/models/mailing.py @@ -248,7 +248,8 @@ class MassMailing(models.Model): if not self.ids: return # ensure traces are sent to db - self.flush() + self.env['mailing.trace'].flush_model() + self.env['mailing.mailing'].flush_model() self.env.cr.execute(""" SELECT m.id as mailing_id, diff --git a/addons/mass_mailing/models/mailing_list.py b/addons/mass_mailing/models/mailing_list.py index 185969ef77a..2cfbb74bd38 100644 --- a/addons/mass_mailing/models/mailing_list.py +++ b/addons/mass_mailing/models/mailing_list.py @@ -218,8 +218,7 @@ class MassMailingList(models.Model): self.ensure_one() # Put destination is sources lists if not already the case src_lists |= self - self.env['mailing.contact'].flush(['email', 'email_normalized']) - self.env['mailing.contact.subscription'].flush(['contact_id', 'opt_out', 'list_id']) + self.env.flush_all() self.env.cr.execute(""" INSERT INTO mailing_contact_list_rel (contact_id, list_id) SELECT st.contact_id AS contact_id, %s AS list_id @@ -251,8 +250,7 @@ class MassMailingList(models.Model): ) ) st WHERE st.rn = 1;""", (self.id, tuple(src_lists.ids), self.id)) - self.flush() - self.invalidate_cache() + self.env.invalidate_all() if archive: (src_lists - self).action_archive() diff --git a/addons/mass_mailing/tests/test_mailing_ab_testing.py b/addons/mass_mailing/tests/test_mailing_ab_testing.py index 0c91113aaef..9d6a1a1d5db 100644 --- a/addons/mass_mailing/tests/test_mailing_ab_testing.py +++ b/addons/mass_mailing/tests/test_mailing_ab_testing.py @@ -26,7 +26,8 @@ class TestMailingABTesting(MassMailCommon): }) self.ab_testing_campaign = self.ab_testing_mailing_1.campaign_id self.ab_testing_mailing_ids = self.ab_testing_mailing_1 + self.ab_testing_mailing_2 - self.ab_testing_mailing_ids.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() @mute_logger('odoo.addons.mail.models.mail_mail') @users('user_marketing') @@ -46,14 +47,14 @@ class TestMailingABTesting(MassMailCommon): self.ab_testing_mailing_1.mailing_trace_ids[:10].set_opened() self.ab_testing_mailing_2.mailing_trace_ids[:15].set_opened() - self.ab_testing_mailing_ids.invalidate_cache() + self.ab_testing_mailing_ids.invalidate_recordset() self.assertEqual(self.ab_testing_mailing_1.opened_ratio, 66) self.assertEqual(self.ab_testing_mailing_2.opened_ratio, 50) with self.mock_mail_gateway(): self.ab_testing_mailing_2.action_send_winner_mailing() - self.ab_testing_mailing_ids.invalidate_cache() + self.ab_testing_mailing_ids.invalidate_recordset() winner_mailing = self.ab_testing_campaign.mailing_mail_ids.filtered(lambda mailing: mailing.ab_testing_pc == 100) self.assertEqual(winner_mailing.subject, 'A/B Testing V1') @@ -78,14 +79,14 @@ class TestMailingABTesting(MassMailCommon): self.ab_testing_mailing_1.mailing_trace_ids[:10].set_opened() self.ab_testing_mailing_2.mailing_trace_ids[:15].set_opened() - self.ab_testing_mailing_ids.invalidate_cache() + self.ab_testing_mailing_ids.invalidate_recordset() self.assertEqual(self.ab_testing_mailing_1.opened_ratio, 66) self.assertEqual(self.ab_testing_mailing_2.opened_ratio, 50) with self.mock_mail_gateway(): self.env.ref('mass_mailing.ir_cron_mass_mailing_ab_testing').sudo().method_direct_trigger() - self.ab_testing_mailing_ids.invalidate_cache() + self.ab_testing_mailing_ids.invalidate_recordset() winner_mailing = self.ab_testing_campaign.mailing_mail_ids.filtered(lambda mailing: mailing.ab_testing_pc == 100) self.assertEqual(winner_mailing.subject, 'A/B Testing V1') @@ -99,7 +100,7 @@ class TestMailingABTesting(MassMailCommon): 'ab_testing_winner_selection': 'manual', 'ab_testing_schedule_datetime': schedule_datetime, }) - ab_mailing.invalidate_cache() + ab_mailing.invalidate_recordset() # Check if the campaign is correclty created and the values set on the mailing are still the same self.assertTrue(ab_mailing.campaign_id, "A campaign id is present for the A/B test mailing") @@ -127,13 +128,13 @@ class TestMailingABTesting(MassMailCommon): self.ab_testing_mailing_1.mailing_trace_ids[:10].set_opened() self.ab_testing_mailing_2.mailing_trace_ids[:15].set_opened() - self.ab_testing_mailing_ids.invalidate_cache() + self.ab_testing_mailing_ids.invalidate_recordset() self.assertEqual(self.ab_testing_mailing_1.opened_ratio, 66) self.assertEqual(self.ab_testing_mailing_2.opened_ratio, 50) with self.mock_mail_gateway(): self.ab_testing_mailing_2.action_send_winner_mailing() - self.ab_testing_mailing_ids.invalidate_cache() + self.ab_testing_mailing_ids.invalidate_recordset() winner_mailing = self.ab_testing_campaign.mailing_mail_ids.filtered(lambda mailing: mailing.ab_testing_pc == 100) self.assertEqual(winner_mailing.subject, 'A/B Testing V2') diff --git a/addons/mass_mailing/tests/test_mailing_internals.py b/addons/mass_mailing/tests/test_mailing_internals.py index cb599aa6245..80b42b26596 100644 --- a/addons/mass_mailing/tests/test_mailing_internals.py +++ b/addons/mass_mailing/tests/test_mailing_internals.py @@ -221,13 +221,13 @@ class TestMassMailValues(MassMailCommon): }) with self.assertRaises(IntegrityError): activity.write({'model': False}) - activity.flush() + self.env.flush_all() with self.assertRaises(IntegrityError): activity.write({'res_id': False}) - activity.flush() + self.env.flush_all() with self.assertRaises(IntegrityError): activity.write({'res_id': 0}) - activity.flush() + self.env.flush_all() @freeze_time('2022-01-02') @patch.object(Cursor, 'now', lambda *args, **kwargs: datetime(2022, 1, 2)) diff --git a/addons/mrp/models/mrp_workorder.py b/addons/mrp/models/mrp_workorder.py index de7901aa2a8..02fbc6733b2 100644 --- a/addons/mrp/models/mrp_workorder.py +++ b/addons/mrp/models/mrp_workorder.py @@ -746,7 +746,7 @@ class MrpWorkorder(models.Model): :return: defaultdict with key as workorder id of self and value as related conflicted workorder """ - self.flush(['state', 'date_planned_start', 'date_planned_finished', 'workcenter_id']) + self.flush_model(['state', 'date_planned_start', 'date_planned_finished', 'workcenter_id']) sql = """ SELECT wo1.id, wo2.id FROM mrp_workorder wo1, mrp_workorder wo2 diff --git a/addons/mrp/tests/test_bom.py b/addons/mrp/tests/test_bom.py index be7a608557f..11968cf3c13 100644 --- a/addons/mrp/tests/test_bom.py +++ b/addons/mrp/tests/test_bom.py @@ -424,7 +424,7 @@ class TestBoM(TestMrpCommon): # Use the float_repr to remove extra small decimal (and represent the front-end behavior) self.assertEqual(float_repr(float_round(kit_product_qty, precision_digits=precision.digits), precision_digits=precision.digits), '-384.00000') - self.product_2.invalidate_cache(fnames=['qty_available'], ids=self.product_2.ids) + self.product_2.invalidate_recordset(['qty_available']) kit_product_qty, _ = (self.product_2 + self.product_3).mapped("qty_available") # With product_3 in the prefetch self.assertEqual(float_repr(float_round(kit_product_qty, precision_digits=precision.digits), precision_digits=precision.digits), '-384.00000') @@ -1044,7 +1044,7 @@ class TestBoM(TestMrpCommon): customer_picking.action_confirm() # We check the created orderpoint - self.env['report.stock.quantity'].flush() + self.env.flush_all() self.env['stock.warehouse.orderpoint']._get_orderpoint_action() orderpoint = self.env['stock.warehouse.orderpoint'].search([('product_id', '=', product_gram.id)]) manufacturing_route_id = self.ref('mrp.route_warehouse0_manufacture') diff --git a/addons/mrp/tests/test_order.py b/addons/mrp/tests/test_order.py index 9c633bbfb7a..d44ffaf38eb 100644 --- a/addons/mrp/tests/test_order.py +++ b/addons/mrp/tests/test_order.py @@ -1659,7 +1659,7 @@ class TestMrpOrder(TestMrpCommon): ) (move1 | move2 | move3)._action_confirm() - mo.invalidate_cache(['components_availability', 'components_availability_state'], mo.ids) + mo.invalidate_recordset(['components_availability', 'components_availability_state']) self.assertEqual(mo.components_availability, f'Exp {format_date(self.env, tommorrow)}') self.assertEqual(mo.components_availability_state, 'late') @@ -1671,7 +1671,7 @@ class TestMrpOrder(TestMrpCommon): (move1 | move2 | move3)._set_quantities_to_reservation() (move1 | move2 | move3)._action_done() - mo.invalidate_cache(['components_availability', 'components_availability_state'], mo.ids) + mo.invalidate_recordset(['components_availability', 'components_availability_state']) self.assertEqual(mo.components_availability, 'Available') self.assertEqual(mo.components_availability_state, 'available') diff --git a/addons/mrp/tests/test_warehouse_multistep_manufacturing.py b/addons/mrp/tests/test_warehouse_multistep_manufacturing.py index af1d644bcfb..9bce94adc2f 100644 --- a/addons/mrp/tests/test_warehouse_multistep_manufacturing.py +++ b/addons/mrp/tests/test_warehouse_multistep_manufacturing.py @@ -134,7 +134,7 @@ class TestMultistepManufacturingWarehouse(TestMrpCommon): with Form(self.warehouse) as warehouse: warehouse.manufacture_steps = 'pbm_sam' warehouse.delivery_steps = 'pick_pack_ship' - self.warehouse.flush() + self.warehouse.flush_model() self.env.ref('stock.route_warehouse0_mto').active = True self.env['stock.quant']._update_available_quantity(self.raw_product, self.warehouse.lot_stock_id, 4.0) picking_customer = self.env['stock.picking'].create({ @@ -215,7 +215,7 @@ class TestMultistepManufacturingWarehouse(TestMrpCommon): cancel depends on the default values on each rule of the chain. """ self.warehouse.manufacture_steps = 'pbm_sam' - self.warehouse.flush() + self.warehouse.flush_model() self.env['stock.quant']._update_available_quantity(self.raw_product, self.warehouse.lot_stock_id, 4.0) picking_customer = self.env['stock.picking'].create({ 'location_id': self.warehouse.lot_stock_id.id, diff --git a/addons/payment/models/account_journal.py b/addons/payment/models/account_journal.py index 284c75fd078..4dad7fb1702 100644 --- a/addons/payment/models/account_journal.py +++ b/addons/payment/models/account_journal.py @@ -16,9 +16,9 @@ class AccountJournal(models.Model): if not self.company_id: return - self.env['account.payment.method'].flush(['code', 'payment_type']) - self.env['account.payment.method.line'].flush(['payment_method_id']) - self.env['payment.acquirer'].flush(['provider', 'state']) + self.env['account.payment.method'].flush_model(['code', 'payment_type']) + self.env['account.payment.method.line'].flush_model(['payment_method_id']) + self.env['payment.acquirer'].flush_model(['provider', 'state']) self._cr.execute(''' SELECT acquirer.id diff --git a/addons/payment/models/payment_acquirer.py b/addons/payment/models/payment_acquirer.py index 4cf1fd8249f..b00ae9db7be 100644 --- a/addons/payment/models/payment_acquirer.py +++ b/addons/payment/models/payment_acquirer.py @@ -443,8 +443,8 @@ class PaymentAcquirer(models.Model): def _neutralize(self): super()._neutralize() - self.flush() - self.invalidate_cache() + self.flush_model() + self.invalidate_model() self.env.cr.execute(""" UPDATE payment_acquirer SET state = 'disabled' WHERE state NOT IN ('test', 'disabled') @@ -455,8 +455,8 @@ class PaymentAcquirer(models.Model): :param str provider: name of provider :param list fields: list of fields to nullify """ - self.flush() - self.invalidate_cache() + self.flush_model() + self.invalidate_model() query = sql.SQL(""" UPDATE payment_acquirer SET ({fields}) = ROW({vals}) diff --git a/addons/payment/models/payment_transaction.py b/addons/payment/models/payment_transaction.py index e7ce841cd6d..4e316829d6c 100644 --- a/addons/payment/models/payment_transaction.py +++ b/addons/payment/models/payment_transaction.py @@ -225,8 +225,8 @@ class PaymentTransaction(models.Model): # `amount` and `fees` fields for the created transactions. This forces the ORM to read the # values from the DB where there were stored using `float_repr`, which produces a result # consistent with the format expected by providers. - # E.g., tx.create(amount=1111.11) ; tx.invalidate_cache() -> tx.amount == 1111.11 - txs.invalidate_cache(['amount', 'fees']) + # E.g., tx.create(amount=1111.11) ; tx.invalidate_recordset() -> tx.amount == 1111.11 + txs.invalidate_recordset(['amount', 'fees']) return txs diff --git a/addons/payment/tests/test_flows.py b/addons/payment/tests/test_flows.py index 7479f2f7649..735daa98927 100644 --- a/addons/payment/tests/test_flows.py +++ b/addons/payment/tests/test_flows.py @@ -304,7 +304,7 @@ class TestFlows(PaymentCommon, PaymentHttpCommon): # Note: strangely, the check # self.assertEqual(tx_sudo.invoice_ids, invoice) # doesn't work, and cache invalidation doesn't work either. - self.invoice.invalidate_cache(['transaction_ids']) + self.invoice.invalidate_recordset(['transaction_ids']) self.assertEqual(self.invoice.transaction_ids, tx_sudo) def test_transaction_wrong_flow(self): diff --git a/addons/portal/tests/test_portal_wizard.py b/addons/portal/tests/test_portal_wizard.py index 3b5265b9a8c..6ba1ddbc502 100644 --- a/addons/portal/tests/test_portal_wizard.py +++ b/addons/portal/tests/test_portal_wizard.py @@ -45,13 +45,9 @@ class TestPortalWizard(MailCommon): with self.assertRaises(AccessError, msg='Standard users should not be able to open the portal wizard'): self.env['portal.wizard'].with_context(active_ids=[self.partner.id]).with_user(self.user_employee).create({}) - portal_wizard.invalidate_cache() - with self.assertRaises(AccessError, msg='Standard users should not be able to open the portal wizard'): portal_wizard.with_user(self.user_employee).welcome_message - portal_wizard.user_ids.invalidate_cache() - with self.assertRaises(AccessError, msg='Standard users should not be able to open the portal wizard'): portal_wizard.user_ids.with_user(self.user_employee).email diff --git a/addons/pos_sale/models/pos_order.py b/addons/pos_sale/models/pos_order.py index 7171de5e6a4..86a9cf1d8f5 100644 --- a/addons/pos_sale/models/pos_order.py +++ b/addons/pos_sale/models/pos_order.py @@ -63,7 +63,7 @@ class PosOrder(models.Model): # update the demand qty in the stock moves related to the sale order line # flush the qty_delivered to make sure the updated qty_delivered is used when # updating the demand value - so_lines.flush(['qty_delivered']) + so_lines.flush_recordset(['qty_delivered']) # track the waiting pickings waiting_picking_ids = set() for so_line in so_lines: diff --git a/addons/privacy_lookup/wizard/privacy_lookup_wizard.py b/addons/privacy_lookup/wizard/privacy_lookup_wizard.py index add23070aa8..c6aae3fa06b 100644 --- a/addons/privacy_lookup/wizard/privacy_lookup_wizard.py +++ b/addons/privacy_lookup/wizard/privacy_lookup_wizard.py @@ -168,7 +168,7 @@ class PrivacyLookupWizard(models.TransientModel): def action_lookup(self): self.ensure_one() query, values = self._get_query() - self.env['base'].flush() + self.env.flush_all() self.env.cr.execute(query, tuple(values)) results = self.env.cr.dictfetchall() self.line_ids = [(5, 0, 0)] + [(0, 0, reference) for reference in results] diff --git a/addons/product/models/product_attribute.py b/addons/product/models/product_attribute.py index a9fe26cf255..05351f596a5 100644 --- a/addons/product/models/product_attribute.py +++ b/addons/product/models/product_attribute.py @@ -66,13 +66,13 @@ class ProductAttribute(models.Model): _("You cannot change the Variants Creation Mode of the attribute %s because it is used on the following products:\n%s") % (pa.display_name, ", ".join(pa.product_tmpl_ids.mapped('display_name'))) ) - invalidate_cache = 'sequence' in vals and any(record.sequence != vals['sequence'] for record in self) + invalidate = 'sequence' in vals and any(record.sequence != vals['sequence'] for record in self) res = super(ProductAttribute, self).write(vals) - if invalidate_cache: + if invalidate: # prefetched o2m have to be resequenced # (eg. product.template: attribute_line_ids) - self.flush() - self.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() return res @api.ondelete(at_uninstall=False) @@ -151,13 +151,13 @@ class ProductAttributeValue(models.Model): (pav.display_name, ", ".join(pav.pav_attribute_line_ids.product_tmpl_id.mapped('display_name'))) ) - invalidate_cache = 'sequence' in values and any(record.sequence != values['sequence'] for record in self) + invalidate = 'sequence' in values and any(record.sequence != values['sequence'] for record in self) res = super(ProductAttributeValue, self).write(values) - if invalidate_cache: + if invalidate: # prefetched o2m have to be resequenced # (eg. product.template.attribute.line: value_ids) - self.flush() - self.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() return res @api.ondelete(at_uninstall=False) @@ -280,8 +280,8 @@ class ProductTemplateAttributeLine(models.Model): values['value_ids'] = [(5, 0, 0)] res = super(ProductTemplateAttributeLine, self).write(values) if 'active' in values: - self.flush() - self.env['product.template'].invalidate_cache(fnames=['attribute_line_ids']) + self.env.flush_all() + self.env['product.template'].invalidate_model(['attribute_line_ids']) # If coming from `create`, no need to update the values and the variants # before all lines are created. if self.env.context.get('update_product_template_attribute_values', True): diff --git a/addons/product/models/product_template.py b/addons/product/models/product_template.py index 9758e11012b..2213af9f4f2 100644 --- a/addons/product/models/product_template.py +++ b/addons/product/models/product_template.py @@ -443,7 +443,7 @@ class ProductTemplate(models.Model): if 'active' in vals and not vals.get('active'): self.with_context(active_test=False).mapped('product_variant_ids').write({'active': vals.get('active')}) if 'image_1920' in vals: - self.env['product.product'].invalidate_cache(fnames=[ + self.env['product.product'].invalidate_model([ 'image_1920', 'image_1024', 'image_512', @@ -583,7 +583,7 @@ class ProductTemplate(models.Model): if not self: return - self.flush() + self.env.flush_all() Product = self.env["product.product"] variants_to_create = [] @@ -670,10 +670,10 @@ class ProductTemplate(models.Model): # prefetched o2m have to be reloaded (because of active_test) # (eg. product.template: product_variant_ids) - # We can't rely on existing invalidate_cache because of the savepoint + # We can't rely on existing invalidate because of the savepoint # in _unlink_or_archive. - self.flush() - self.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() return True def _prepare_variant_values(self, combination): diff --git a/addons/product/tests/test_variants.py b/addons/product/tests/test_variants.py index 792b6a6054b..4176aea3487 100644 --- a/addons/product/tests/test_variants.py +++ b/addons/product/tests/test_variants.py @@ -272,7 +272,7 @@ class TestVariants(common.TestProductCommon): template.product_variant_ids.action_archive() self.assertFalse(template.active) - template.invalidate_cache(['barcode']) + template.invalidate_model(['barcode']) self.assertEqual(template.barcode, 'test') template.product_variant_ids.action_unarchive() template.action_unarchive() @@ -295,11 +295,11 @@ class TestVariants(common.TestProductCommon): variant_2.barcode = 'v2_barcode' variant_1.action_archive() - template.invalidate_cache(['barcode']) + template.invalidate_model(['barcode']) self.assertEqual(template.barcode, variant_2.barcode) # 1 active variant --> barcode on template variant_1.action_unarchive() - template.invalidate_cache(['barcode']) + template.invalidate_model(['barcode']) self.assertFalse(template.barcode) # 2 active variants --> no barcode on template def test_archive_all_variants(self): @@ -676,8 +676,8 @@ class TestVariantsImages(common.TestProductCommon): 'create_date': before, 'write_date': before, }) - self.template.invalidate_cache(['create_date', 'write_date'], self.template.ids) - self.variants.invalidate_cache(['create_date', 'write_date'], self.variants.ids) + self.template.invalidate_recordset(['create_date', 'write_date']) + self.variants.invalidate_recordset(['create_date', 'write_date']) f = io.BytesIO() Image.new('RGB', (800, 500), '#000000').save(f, 'PNG') diff --git a/addons/product_margin/models/product_product.py b/addons/product_margin/models/product_product.py index d5faed290b6..a381a4b1555 100644 --- a/addons/product_margin/models/product_product.py +++ b/addons/product_margin/models/product_product.py @@ -105,9 +105,9 @@ class ProductProduct(models.Model): company_id = self.env.context['force_company'] else: company_id = self.env.company.id - self.env['account.move.line'].flush(['price_unit', 'quantity', 'balance', 'product_id', 'display_type']) - self.env['account.move'].flush(['state', 'payment_state', 'move_type', 'invoice_date', 'company_id']) - self.env['product.template'].flush(['list_price']) + self.env['account.move.line'].flush_model(['price_unit', 'quantity', 'balance', 'product_id', 'display_type']) + self.env['account.move'].flush_model(['state', 'payment_state', 'move_type', 'invoice_date', 'company_id']) + self.env['product.template'].flush_model(['list_price']) sqlstr = """ WITH currency_rate AS ({}) SELECT diff --git a/addons/project/tests/test_access_rights.py b/addons/project/tests/test_access_rights.py index d32f3349043..8bab7f6f5bb 100644 --- a/addons/project/tests/test_access_rights.py +++ b/addons/project/tests/test_access_rights.py @@ -61,8 +61,8 @@ class TestCRUDVisibilityFollowers(TestAccessRights): @users('Internal user') def test_project_allowed_internal_read(self): self.project_pigs.message_subscribe(partner_ids=[self.env.user.partner_id.id]) - self.project_pigs.flush() - self.project_pigs.invalidate_cache() + self.project_pigs.flush_model() + self.project_pigs.invalidate_model() self.project_pigs.with_user(self.env.user).name @users('Internal user', 'Portal user') @@ -81,8 +81,8 @@ class TestCRUDVisibilityFollowers(TestAccessRights): @users('Internal user') def test_task_allowed_internal_read(self): self.project_pigs.message_subscribe(partner_ids=[self.env.user.partner_id.id]) - self.task.flush() - self.task.invalidate_cache() + self.task.flush_model() + self.task.invalidate_model() self.task.with_user(self.env.user).name @users('Internal user', 'Portal user') @@ -117,7 +117,7 @@ class TestCRUDVisibilityPortal(TestAccessRights): def setUp(self): super().setUp() self.project_pigs.privacy_visibility = 'portal' - self.env['base'].flush() + self.env.flush_all() @users('Portal user') def test_task_portal_no_read(self): @@ -127,14 +127,14 @@ class TestCRUDVisibilityPortal(TestAccessRights): @users('Portal user') def test_task_allowed_portal_read(self): self.project_pigs.message_subscribe(partner_ids=[self.env.user.partner_id.id]) - self.task.flush() - self.task.invalidate_cache() + self.task.flush_model() + self.task.invalidate_model() self.task.with_user(self.env.user).name @users('Internal user') def test_task_internal_read(self): - self.task.flush() - self.task.invalidate_cache() + self.task.flush_model() + self.task.invalidate_model() self.task.with_user(self.env.user).name class TestCRUDVisibilityEmployees(TestAccessRights): @@ -154,8 +154,8 @@ class TestCRUDVisibilityEmployees(TestAccessRights): @users('Internal user') def test_task_allowed_portal_read(self): - self.task.flush() - self.task.invalidate_cache() + self.task.flush_model() + self.task.invalidate_model() self.task.with_user(self.env.user).name class TestAllowedUsers(TestAccessRights): @@ -222,8 +222,8 @@ class TestAllowedUsers(TestAccessRights): self.user.groups_id |= self.env.ref('project.group_project_user') self.assertNotIn(self.user.partner_id, self.project_pigs.message_partner_ids) self.task.message_subscribe(partner_ids=[self.user.partner_id.id]) - self.project_pigs.invalidate_cache() - self.task.invalidate_cache() + self.project_pigs.invalidate_model() + self.task.invalidate_model() self.task.with_user(self.user).name = "I can edit a task!" def test_no_write_project(self): @@ -290,7 +290,6 @@ class TestPortalProject(TestProjectPortalCommon): def test_followers_project_access_rights(self): pigs = self.project_pigs pigs.write({'privacy_visibility': 'followers'}) - pigs.flush(['privacy_visibility']) # Do: Alfred reads project -> ko (employee ko followers) self.assertRaises(AccessError, pigs.with_user(self.user_projectuser).read, ['user_id']) # Test: no project task visible @@ -308,7 +307,7 @@ class TestPortalProject(TestProjectPortalCommon): # Do: Alfred reads project -> ok (follower ok followers) donkey = pigs.with_user(self.user_projectuser) - donkey.invalidate_cache() + donkey.invalidate_model() donkey.read(['user_id']) # Do: Donovan reads project -> ko (public ko follower even if follower) diff --git a/addons/project/tests/test_burndown_chart.py b/addons/project/tests/test_burndown_chart.py index 16399327139..f22b6ec1667 100644 --- a/addons/project/tests/test_burndown_chart.py +++ b/addons/project/tests/test_burndown_chart.py @@ -53,7 +53,7 @@ class TestBurndownChart(TransactionCase): 'type_ids': [Command.link(stage_id) for stage_id in stages.ids], }) self.set_create_date('project_project', project.id, create_date) - project.invalidate_cache() + project.invalidate_model() task_a = self.env['project.task'].create({ 'name': 'Task A', 'priority': 0, diff --git a/addons/project/tests/test_personal_stages.py b/addons/project/tests/test_personal_stages.py index 20dbaacd191..06cd7164a89 100644 --- a/addons/project/tests/test_personal_stages.py +++ b/addons/project/tests/test_personal_stages.py @@ -59,7 +59,7 @@ class TestPersonalStages(TestProjectCommon): self.task_1.user_ids += self.user_projectmanager self.task_1.with_user(self.user_projectmanager).personal_stage_type_id = self.manager_stages[1] #Makes sure the personal stage for project manager is saved in the database - self.env['project.task'].flush() + self.env.flush_all() read_group_user = self.env['project.task'].with_user(self.user_projectuser).read_group( [('user_ids', '=', self.user_projectuser.id)], fields=['sequence:avg'], groupby=['personal_stage_type_ids']) # Check that the result is at least a bit coherent diff --git a/addons/project/tests/test_project_flow.py b/addons/project/tests/test_project_flow.py index 81dea5c6d9b..ff0e87a58fb 100644 --- a/addons/project/tests/test_project_flow.py +++ b/addons/project/tests/test_project_flow.py @@ -241,7 +241,7 @@ class TestProjectFlow(TestProjectCommon, MailCommon): # We need to invalidate cache since it is not done automatically by the ORM # Our One2Many is linked to a res_id (int) for which the orm doesn't create an inverse - first_task.invalidate_cache() + self.env.invalidate_all() self.assertEqual(rating_good.rating_text, 'top') self.assertEqual(rating_bad.rating_text, 'ok') @@ -258,7 +258,7 @@ class TestProjectFlow(TestProjectCommon, MailCommon): # We need to invalidate cache since it is not done automatically by the ORM # Our One2Many is linked to a res_id (int) for which the orm doesn't create an inverse - first_task.invalidate_cache() + self.env.invalidate_all() rating_avg = (rating_good.rating + rating_bad.rating) / 2 self.assertEqual(first_task.rating_count, 2, "Task should have two ratings associated with it") @@ -274,7 +274,7 @@ class TestProjectFlow(TestProjectCommon, MailCommon): # We need to invalidate cache since it is not done automatically by the ORM # Our One2Many is linked to a res_id (int) for which the orm doesn't create an inverse - first_task.invalidate_cache() + self.env.invalidate_all() self.assertEqual(rating_good.parent_res_id, self.project_goats.id) self.assertEqual(self.project_goats.rating_percentage_satisfaction, 50) @@ -343,7 +343,7 @@ class TestProjectFlow(TestProjectCommon, MailCommon): with self.mock_mail_gateway(): tasks.with_user(self.user_projectmanager).write({'stage_id': won_stage.id}) - tasks.invalidate_cache(fnames=['rating_ids']) + tasks.invalidate_model(['rating_ids']) for task in tasks: self.assertEqual(len(task.rating_ids), 1, 'This task should have a generated rating when it arrives in the Won stage.') rating_request_message = task.message_ids[:1] diff --git a/addons/project/tests/test_project_recurrence.py b/addons/project/tests/test_project_recurrence.py index a03b43f9295..f68aa81a5c1 100644 --- a/addons/project/tests/test_project_recurrence.py +++ b/addons/project/tests/test_project_recurrence.py @@ -232,7 +232,7 @@ class TestProjectrecurrence(TransactionCase): self.set_task_create_date(task_a.id, datetime(2020, 1, 1)) self.set_task_create_date(task_b.id, datetime(2020, 1, 6)) self.set_task_create_date(task_c.id, datetime(2020, 1, 13)) - (task_a+task_b+task_c).invalidate_cache() + (task_a+task_b+task_c).invalidate_model() task_c.write({ 'name': 'my super updated task', diff --git a/addons/project/tests/test_task_dependencies.py b/addons/project/tests/test_task_dependencies.py index 34c43a693b9..853f6810221 100644 --- a/addons/project/tests/test_task_dependencies.py +++ b/addons/project/tests/test_task_dependencies.py @@ -27,7 +27,7 @@ class TestTaskDependencies(TestProjectCommon): def flush_tracking(self): """ Force the creation of tracking values. """ - self.env['base'].flush() + self.env.flush_all() self.cr.precommit.run() def test_task_dependencies(self): diff --git a/addons/project/tests/test_task_tracking.py b/addons/project/tests/test_task_tracking.py index 239d576c280..9c066de88e1 100644 --- a/addons/project/tests/test_task_tracking.py +++ b/addons/project/tests/test_task_tracking.py @@ -10,7 +10,7 @@ class TestTaskTracking(TestProjectCommon): def flush_tracking(self): """ Force the creation of tracking values. """ - self.env['base'].flush() + self.env.flush_all() self.cr.precommit.run() def test_many2many_tracking(self): diff --git a/addons/purchase/tests/test_access_rights.py b/addons/purchase/tests/test_access_rights.py index 724b8726682..230e8ae9e58 100644 --- a/addons/purchase/tests/test_access_rights.py +++ b/addons/purchase/tests/test_access_rights.py @@ -134,7 +134,7 @@ class TestPurchaseInvoice(AccountTestInvoicingCommon): # Check that calling 'action_view_invoice' return the same action despite the record rule action_user_1 = purchase_order_user2.with_user(self.purchase_user).action_view_invoice() - purchase_order_user2.invalidate_cache() + purchase_order_user2.invalidate_recordset() action_user_2 = purchase_order_user2.with_user(purchase_user_2).action_view_invoice() self.assertEqual(action_user_1, action_user_2) diff --git a/addons/purchase/tests/test_purchase_order_report.py b/addons/purchase/tests/test_purchase_order_report.py index 42e78b51873..0df4857a6c4 100644 --- a/addons/purchase/tests/test_purchase_order_report.py +++ b/addons/purchase/tests/test_purchase_order_report.py @@ -44,7 +44,7 @@ class TestPurchaseOrderReport(AccountTestInvoicingCommon): f.purchase_id = po invoice = f.save() invoice.action_post() - po.flush() + po.flush_model() res_product1 = self.env['purchase.report'].search([ ('order_id', '=', po.id), @@ -80,7 +80,7 @@ class TestPurchaseOrderReport(AccountTestInvoicingCommon): po.button_confirm() - po.flush() + po.flush_model() report = self.env['purchase.report'].read_group( [('order_id', '=', po.id)], ['order_id', 'delay', 'delay_pass'], diff --git a/addons/purchase_product_matrix/tests/test_purchase_matrix.py b/addons/purchase_product_matrix/tests/test_purchase_matrix.py index aafa4f53a17..85827110593 100644 --- a/addons/purchase_product_matrix/tests/test_purchase_matrix.py +++ b/addons/purchase_product_matrix/tests/test_purchase_matrix.py @@ -19,7 +19,7 @@ class TestPurchaseMatrixUi(TestMatrixCommon): self.assertEqual(len(self.matrix_template.attribute_line_ids.product_template_value_ids), 8) self.env['purchase.order.line'].search([('product_id', 'in', self.matrix_template.product_variant_ids.ids)]).order_id.button_confirm() - self.matrix_template.flush() + self.matrix_template.flush_recordset() self.assertEqual(round(self.matrix_template.purchased_product_qty, 2), 56.8) for variant in self.matrix_template.product_variant_ids: # 5 and 9.2 because of no variant attributes diff --git a/addons/purchase_stock/tests/test_purchase_order.py b/addons/purchase_stock/tests/test_purchase_order.py index 7c2314cbb15..cfa518d5d59 100644 --- a/addons/purchase_stock/tests/test_purchase_order.py +++ b/addons/purchase_stock/tests/test_purchase_order.py @@ -333,7 +333,7 @@ class TestPurchaseOrder(ValuationReconciliationTestCommon): # 1. Compute `res.partner.on_time_rate` regular non-stored comptued field partner_on_time_rate = po.partner_id.on_time_rate # 2. Invalidate the cache for that record and field, so it's not reused in the next step. - po.partner_id.invalidate_cache(fnames=["on_time_rate"], ids=po.partner_id.ids) + po.partner_id.invalidate_recordset(["on_time_rate"]) # 3. Compute the related field `purchase.order.on_time_rate` po_on_time_rate = po.on_time_rate # 4. Check both are equals. diff --git a/addons/purchase_stock/tests/test_reordering_rule.py b/addons/purchase_stock/tests/test_reordering_rule.py index 9b8eb9dbd13..323d59880f2 100644 --- a/addons/purchase_stock/tests/test_reordering_rule.py +++ b/addons/purchase_stock/tests/test_reordering_rule.py @@ -336,7 +336,7 @@ class TestReorderingRule(TransactionCase): customer_picking = picking_form.save() customer_picking.move_ids.filtered(lambda m: m.product_id == product_buy_mto).procure_method = 'make_to_order' customer_picking.action_confirm() - self.env['stock.warehouse.orderpoint'].flush() + self.env['stock.warehouse.orderpoint'].flush_model() self.env['stock.warehouse.orderpoint']._get_orderpoint_action() orderpoint_product = self.env['stock.warehouse.orderpoint'].search( @@ -411,7 +411,7 @@ class TestReorderingRule(TransactionCase): self.assertEqual(po_line_product_mto.product_uom_qty, 10.0) self.assertEqual(po_line_product.product_uom_qty, 20.0) - self.env['stock.warehouse.orderpoint'].flush() + self.env['stock.warehouse.orderpoint'].flush_model() self.env['stock.warehouse.orderpoint']._get_orderpoint_action() orderpoint_product = self.env['stock.warehouse.orderpoint'].search( [('product_id', '=', product.id)]) @@ -433,7 +433,7 @@ class TestReorderingRule(TransactionCase): customer_picking = picking_form.save() customer_picking.move_ids.filtered(lambda m: m.product_id == product_buy_mto).procure_method = 'make_to_order' customer_picking.action_confirm() - self.env['stock.warehouse.orderpoint'].flush() + self.env['stock.warehouse.orderpoint'].flush_model() self.env['stock.warehouse.orderpoint']._get_orderpoint_action() orderpoint_product = self.env['stock.warehouse.orderpoint'].search( diff --git a/addons/rating/models/rating_mixin.py b/addons/rating/models/rating_mixin.py index 72348232404..a73a48e91a4 100644 --- a/addons/rating/models/rating_mixin.py +++ b/addons/rating/models/rating_mixin.py @@ -28,7 +28,7 @@ class RatingMixin(models.AbstractModel): @api.depends('rating_ids.rating', 'rating_ids.consumed') def _compute_rating_last_value(self): # Pure SQL instead of calling read_group to allow ordering array_agg - self.flush(['rating_ids']) + self.flush_model(['rating_ids']) if not self.ids: self.rating_last_value = 0 return diff --git a/addons/sale/models/sale_order.py b/addons/sale/models/sale_order.py index 736acdb9464..6c4fe2e2f64 100644 --- a/addons/sale/models/sale_order.py +++ b/addons/sale/models/sale_order.py @@ -859,7 +859,7 @@ class SaleOrder(models.Model): def update_prices(self): self.ensure_one() lines_to_recompute = self.order_line.filtered(lambda line: not line.display_type) - lines_to_recompute.invalidate_cache(['pricelist_item_id']) + lines_to_recompute.invalidate_recordset(['pricelist_item_id']) lines_to_recompute._compute_price_unit() # Special case: we want to overwrite the existing discount on update_prices call # i.e. to make sure the discount is correctly reset diff --git a/addons/sale/models/sale_order_line.py b/addons/sale/models/sale_order_line.py index bead65ca926..e85a0ecbb5e 100644 --- a/addons/sale/models/sale_order_line.py +++ b/addons/sale/models/sale_order_line.py @@ -577,7 +577,7 @@ class SaleOrderLine(models.Model): 'price_total': amount_untaxed + amount_tax, }) if self.env.context.get('import_file', False) and not self.env.user.user_has_groups('account.group_account_manager'): - line.tax_id.invalidate_cache(['invoice_repartition_line_ids'], [line.tax_id.id]) + line.tax_id.invalidate_recordset(['invoice_repartition_line_ids']) @api.depends('price_subtotal', 'product_uom_qty') def _compute_price_reduce_taxexcl(self): diff --git a/addons/sale/models/utm_campaign.py b/addons/sale/models/utm_campaign.py index c5f222c7f69..da0857f7031 100644 --- a/addons/sale/models/utm_campaign.py +++ b/addons/sale/models/utm_campaign.py @@ -23,8 +23,8 @@ class UtmCampaign(models.Model): campaign.quotation_count = data_map.get(campaign.id, 0) def _compute_sale_invoiced_amount(self): - self.env['account.move.line'].flush(['balance', 'move_id', 'account_id', 'exclude_from_invoice_tab']) - self.env['account.move'].flush(['state', 'campaign_id', 'move_type']) + self.env['account.move.line'].flush_model(['balance', 'move_id', 'account_id', 'exclude_from_invoice_tab']) + self.env['account.move'].flush_model(['state', 'campaign_id', 'move_type']) query = """SELECT move.campaign_id, -SUM(line.balance) as price_subtotal FROM account_move_line line INNER JOIN account_move move ON line.move_id = move.id diff --git a/addons/sale/tests/test_reinvoice.py b/addons/sale/tests/test_reinvoice.py index c328070e520..1e7aa873d0a 100644 --- a/addons/sale/tests/test_reinvoice.py +++ b/addons/sale/tests/test_reinvoice.py @@ -139,7 +139,7 @@ class TestReInvoice(TestSaleCommon): .create({})\ ._create_payments() - invoices.flush() + invoices.flush_model() self.assertRecordValues(invoices.team_id, [{'invoiced': 500.0}]) def test_sales_price(self): diff --git a/addons/sale/tests/test_sale_order.py b/addons/sale/tests/test_sale_order.py index 8fc45637867..a1a0c6bde60 100644 --- a/addons/sale/tests/test_sale_order.py +++ b/addons/sale/tests/test_sale_order.py @@ -183,7 +183,7 @@ class TestSaleOrder(TestSaleCommon): # and the fact this method is called multiple times in the same transaction test case. # Here, we update `qty_delivered` on the origin record, but the `new` records which are in cache with this order line # as origin are not updated, nor the fields that depends on it. - self.sol_serv_order.flush() + self.env.flush_all() for field in self.env['sale.order.line']._fields.values(): for res_id in list(self.env.cache._data[field]): if not res_id: diff --git a/addons/sale/tests/test_sale_to_invoice.py b/addons/sale/tests/test_sale_to_invoice.py index b493e94cee4..bf2173769ff 100644 --- a/addons/sale/tests/test_sale_to_invoice.py +++ b/addons/sale/tests/test_sale_to_invoice.py @@ -365,7 +365,7 @@ class TestSaleToInvoice(TestSaleCommon): # Rounding to 0.1, should be rounded with UP (ceil) rounding_method # Not floor or half up rounding. sol_prod_deliver.product_uom.rounding *= 10 - sol_prod_deliver.product_uom.flush(['rounding']) + sol_prod_deliver.product_uom.flush_recordset(['rounding']) expected_qty = 5.2 qty_invoiced_field = sol_prod_deliver._fields.get('qty_invoiced') sol_prod_deliver.env.add_to_compute(qty_invoiced_field, sol_prod_deliver) diff --git a/addons/sale_loyalty/tests/test_program_numbers.py b/addons/sale_loyalty/tests/test_program_numbers.py index 67fccd3cf95..b710d089457 100644 --- a/addons/sale_loyalty/tests/test_program_numbers.py +++ b/addons/sale_loyalty/tests/test_program_numbers.py @@ -233,8 +233,8 @@ class TestSaleCouponProgramNumbers(TestSaleCouponCommon): self.assertEqual(len(order.order_line.ids), 1, "We should not get the reduction line since we dont have 320$ tax excluded (cabinet is 320$ tax included)") sol1.tax_id.price_include = False sol1._compute_tax_id() - self.env['account.tax'].flush() - self.env['account.tax'].invalidate_cache(fnames=['price_include']) + self.env.flush_all() + self.env['account.tax'].invalidate_model(['price_include']) self._auto_rewards(order, self.all_programs) self.assertEqual(len(order.order_line.ids), 2, "We should now get the reduction line since we have 320$ tax included (cabinet is 320$ tax included)") # Name | Qty | price_unit | Tax | HTVA | TVAC | TVA | diff --git a/addons/sale_margin/models/sale_order.py b/addons/sale_margin/models/sale_order.py index 226432e0bb0..047b8fb6fca 100644 --- a/addons/sale_margin/models/sale_order.py +++ b/addons/sale_margin/models/sale_order.py @@ -17,7 +17,6 @@ class SaleOrder(models.Model): order.margin = sum(order.order_line.mapped('margin')) order.margin_percent = order.amount_untaxed and order.margin/order.amount_untaxed else: - self.env["sale.order.line"].flush(['margin']) # On batch records recomputation (e.g. at install), compute the margins # with a single read_group query for better performance. # This isn't done in an onchange environment because (part of) the data diff --git a/addons/sale_mrp/tests/test_sale_mrp_flow.py b/addons/sale_mrp/tests/test_sale_mrp_flow.py index 6ae068d3dfe..4cd91beaacb 100644 --- a/addons/sale_mrp/tests/test_sale_mrp_flow.py +++ b/addons/sale_mrp/tests/test_sale_mrp_flow.py @@ -1063,7 +1063,7 @@ class TestSaleMrpFlow(ValuationReconciliationTestCommon): # Check that not enough enough quantities are available in the warehouse set in the SO # but there are enough quantities in Warehouse 1 for 1 kit_parent self.assertEqual(kit_parent_wh_order.virtual_available, 0) - kit_parent_wh_order.invalidate_cache() + self.env.invalidate_all() kit_parent_wh1 = self.kit_parent.with_context(warehouse=warehouse_1.id) self.assertEqual(kit_parent_wh1.virtual_available, 1) @@ -1086,7 +1086,7 @@ class TestSaleMrpFlow(ValuationReconciliationTestCommon): # But the quantity available in Warehouse 1 should stay 1 kit_parent_wh_order = self.kit_parent.with_context(warehouse=so.warehouse_id.id) self.assertEqual(kit_parent_wh_order.virtual_available, 3) - kit_parent_wh_order.invalidate_cache() + self.env.invalidate_all() kit_parent_wh1 = self.kit_parent.with_context(warehouse=warehouse_1.id) self.assertEqual(kit_parent_wh1.virtual_available, 1) diff --git a/addons/sale_purchase/tests/test_sale_purchase.py b/addons/sale_purchase/tests/test_sale_purchase.py index 307a3b02c2c..bf79a3859a5 100644 --- a/addons/sale_purchase/tests/test_sale_purchase.py +++ b/addons/sale_purchase/tests/test_sale_purchase.py @@ -199,7 +199,7 @@ class TestSalePurchase(TestCommonSalePurchaseNoChart): # decrease the ordered quantity on sale line self.sol1_service_purchase_1.write({'product_uom_qty': self.sol1_service_purchase_1.product_uom_qty - 5}) # product_uom_qty = 8 - purchase_order.invalidate_cache() # Note: creating a second activity will not refresh the cache + self.env.invalidate_all() # Note: creating a second activity will not refresh the cache self.assertEqual(purchase_line.product_qty, sale_line_old_quantity, "The quantity on the PO line should not have changed.") self.assertEqual(len(purchase_order.activity_ids), 2, "a second activity should have been created on the PO") diff --git a/addons/sale_stock/tests/test_create_perf.py b/addons/sale_stock/tests/test_create_perf.py index 109e7aa2440..971bc1c2529 100644 --- a/addons/sale_stock/tests/test_create_perf.py +++ b/addons/sale_stock/tests/test_create_perf.py @@ -33,7 +33,7 @@ class TestPERF(common.TransactionCase): cls.salesmans = cls.env.ref('base.user_admin') | cls.env.ref('base.user_demo') - cls.env['base'].flush() + cls.env.flush_all() @users('admin') @warmup diff --git a/addons/sale_stock/tests/test_sale_stock.py b/addons/sale_stock/tests/test_sale_stock.py index c30f4fc883a..896b996ed51 100644 --- a/addons/sale_stock/tests/test_sale_stock.py +++ b/addons/sale_stock/tests/test_sale_stock.py @@ -100,7 +100,7 @@ class TestSaleStock(TestSaleCommon, ValuationReconciliationTestCommon): # and the fact this method is called multiple times in the same transaction test case. # Here, we update `qty_delivered` on the origin record, but the `new` records which are in cache with this order line # as origin are not updated, nor the fields that depends on it. - self.so.flush() + self.env.flush_all() for field in self.env['sale.order.line']._fields.values(): for res_id in list(self.env.cache._data[field]): if not res_id: @@ -680,7 +680,7 @@ class TestSaleStock(TestSaleCommon, ValuationReconciliationTestCommon): so.warehouse_id = warehouse2 # invalidate product cache to ensure qty_available is recomputed # bc warehouse isn't in the depends_context of qty_available - line.product_id.invalidate_cache() + self.env.invalidate_all() self.assertEqual(line.virtual_available_at_date, 5) self.assertEqual(line.free_qty_today, 5) self.assertEqual(line.qty_available_today, 5) diff --git a/addons/sale_timesheet/tests/test_project.py b/addons/sale_timesheet/tests/test_project.py index c423a54dbeb..6819e85dd24 100644 --- a/addons/sale_timesheet/tests/test_project.py +++ b/addons/sale_timesheet/tests/test_project.py @@ -34,7 +34,7 @@ class TestProject(TestCommonSaleTimesheet): self.assertFalse(self.project_non_billable._get_sale_orders()) sale_item = self.so.order_line[0] - self.project_global.invalidate_cache() + self.env.invalidate_all() expected_task_sale_order_items = self.project_global.tasks.sale_line_id expected_sale_order_items = sale_item | expected_task_sale_order_items self.assertEqual(self.project_global._fetch_sale_order_items(), expected_sale_order_items) @@ -66,7 +66,7 @@ class TestProject(TestCommonSaleTimesheet): self.project_global.write({ 'sale_line_id': False, }) - self.project_global.invalidate_cache() + self.env.invalidate_all() expected_task_sale_order_items |= task.sale_line_id self.assertEqual(self.project_global._get_sale_order_items(), expected_task_sale_order_items | employee_mapping.sale_line_id) self.assertEqual(self.project_global._get_sale_orders(), self.so) @@ -85,7 +85,7 @@ class TestProject(TestCommonSaleTimesheet): task.write({ 'stage_id': done_stage.id, }) - self.env['project.task.type'].flush() + self.env.flush_all() self.assertEqual(self.project_global._fetch_sale_order_items({'project.task': [('stage_id.fold', '=', False)]}), employee_mapping.sale_line_id) self.assertEqual(self.project_global._fetch_sale_order_items({'project.task': [('stage_id.fold', '=', True)]}), task.sale_line_id | employee_mapping.sale_line_id) diff --git a/addons/sales_team/tests/test_sales_team.py b/addons/sales_team/tests/test_sales_team.py index 77b7c31b5d2..3556f5ade6c 100644 --- a/addons/sales_team/tests/test_sales_team.py +++ b/addons/sales_team/tests/test_sales_team.py @@ -49,7 +49,7 @@ class TestDefaultTeam(TestSalesCommon): def test_default_team_fallback(self): """ Test fallback: domain, order """ self.sales_team_1.member_ids = [(5,)] - self.sales_team_1.flush() + self.sales_team_1.flush_model() with self.with_user('user_sales_leads'): team = self.env['crm.team']._get_default_team_id() diff --git a/addons/sales_team/tests/test_sales_team_internals.py b/addons/sales_team/tests/test_sales_team_internals.py index 391fc42a9a9..31932ae2ba0 100644 --- a/addons/sales_team/tests/test_sales_team_internals.py +++ b/addons/sales_team/tests/test_sales_team_internals.py @@ -38,7 +38,7 @@ class TestCornerCases(TransactionCase): }) sales_team_1_m1.write({'active': False}) - sales_team_1_m1.flush() + sales_team_1_m1.flush_recordset() sales_team_1_m2 = self.env['crm.team.member'].create({ 'user_id': self.user_sales_leads.id, diff --git a/addons/sales_team/tests/test_sales_team_membership.py b/addons/sales_team/tests/test_sales_team_membership.py index 1d3923d3f38..9186c98e27e 100644 --- a/addons/sales_team/tests/test_sales_team_membership.py +++ b/addons/sales_team/tests/test_sales_team_membership.py @@ -62,7 +62,7 @@ class TestMembership(TestSalesCommon): self.assertEqual(new_team.member_ids, self.env.user | self.user_sales_leads | new_user) self.user_sales_manager.write({'groups_id': [(3, self.env.ref('base.group_system').id)]}) - new_team.flush() + self.env.flush_all() memberships = self.env['crm.team.member'].with_context(active_test=False).search([('user_id', '=', self.user_sales_leads.id)]) self.assertEqual(len(memberships), 3) # subscribed twice to new_team + subscribed to sales_team_1 self.assertEqual(memberships.crm_team_id, sales_team_1 | new_team) @@ -104,7 +104,7 @@ class TestMembership(TestSalesCommon): self.assertTrue(len(new_user)) self.assertEqual(new_team.member_ids, self.env.user | self.user_sales_leads | new_user) self.user_sales_manager.write({'groups_id': [(3, self.env.ref('base.group_system').id)]}) - new_team.flush() + self.env.flush_all() # still avoid duplicated team / user entries with self.assertRaises(exceptions.UserError): @@ -127,7 +127,7 @@ class TestMembership(TestSalesCommon): ]}) self.assertEqual(new_team.member_ids, self.env.user | self.user_sales_leads) self.assertEqual(sales_team_1.member_ids, self.user_admin) - new_team.flush() + self.env.flush_all() memberships = self.env['crm.team.member'].with_context(active_test=False).search([('user_id', '=', self.user_sales_leads.id)]) self.assertEqual(memberships.crm_team_id, sales_team_1 | new_team) @@ -182,7 +182,7 @@ class TestMembership(TestSalesCommon): ]}) self.assertEqual(new_team.member_ids, self.env.user | self.user_sales_leads) self.assertEqual(sales_team_1.member_ids, self.user_sales_leads | self.user_admin) - new_team.flush() + self.env.flush_all() memberships = self.env['crm.team.member'].with_context(active_test=False).search([('user_id', '=', self.user_sales_leads.id)]) self.assertEqual(memberships.crm_team_id, sales_team_1 | new_team) @@ -265,7 +265,7 @@ class TestMembership(TestSalesCommon): }) admin_original.write({'crm_team_id': new_team.id}) # send to db as errors may pop at that step (like trying to set NULL on a m2o inverse of o2m) - self.new_team.flush() + self.env.flush_all() self.assertTrue(self.user_admin in new_team.member_ids) self.assertTrue(admin_original.active) self.assertTrue(admin_archived.exists()) @@ -274,7 +274,6 @@ class TestMembership(TestSalesCommon): # change team of membership should raise unicity constraint with self.assertRaises(exceptions.UserError), mute_logger('odoo.sql_db'): added.write({'crm_team_id': sales_team_1.id}) - self.new_team.flush() def test_users_sale_team_id(self): self.assertTrue(self.sales_team_1.sequence < self.new_team.sequence) diff --git a/addons/stock/models/stock_location.py b/addons/stock/models/stock_location.py index 9ae9013d7cb..8a0257e4ffe 100644 --- a/addons/stock/models/stock_location.py +++ b/addons/stock/models/stock_location.py @@ -216,13 +216,13 @@ class Location(models.Model): }) res = super(Location, self).write(values) - self.invalidate_cache(['warehouse_id']) + self.invalidate_model(['warehouse_id']) return res @api.model_create_multi def create(self, vals_list): res = super().create(vals_list) - self.invalidate_cache(['warehouse_id']) + self.invalidate_model(['warehouse_id']) return res def _get_putaway_strategy(self, product, quantity=0, package=None, packaging=None, additional_qty=None): diff --git a/addons/stock/models/stock_quant.py b/addons/stock/models/stock_quant.py index 0714e54fada..f389f25ae75 100644 --- a/addons/stock/models/stock_quant.py +++ b/addons/stock/models/stock_quant.py @@ -832,7 +832,7 @@ class StockQuant(models.Model): try: with self.env.cr.savepoint(): self.env.cr.execute(query) - self.invalidate_cache() + self.env.invalidate_all() except Error as e: _logger.info('an error occurred while merging quants: %s', e.pgerror) diff --git a/addons/stock/tests/test_proc_rule.py b/addons/stock/tests/test_proc_rule.py index eacdf60465e..af09de49ed8 100644 --- a/addons/stock/tests/test_proc_rule.py +++ b/addons/stock/tests/test_proc_rule.py @@ -367,7 +367,7 @@ class TestProcRule(TransactionCase): }]) moves._action_confirm() # activate action of opening the replenishment view - self.env['report.stock.quantity'].flush() + self.env.flush_all() self.env['stock.warehouse.orderpoint'].action_open_orderpoints() replenishments = self.env['stock.warehouse.orderpoint'].search([ ('product_id', '=', product.id), diff --git a/addons/stock/tests/test_quant.py b/addons/stock/tests/test_quant.py index 36ff8126dde..d00b31ff01d 100644 --- a/addons/stock/tests/test_quant.py +++ b/addons/stock/tests/test_quant.py @@ -794,5 +794,5 @@ class StockQuant(TransactionCase): # The quants merging is processed thanks to a SQL query (see StockQuant._merge_quants). # At that point, the ORM is not aware of the new value. So we need to invalidate the # cache to ensure that the value will be the newest - quant.invalidate_cache(fnames=['quantity'], ids=quant.ids) + quant.invalidate_recordset(['quantity']) self.assertEqual(quant.quantity, 11) diff --git a/addons/stock/tests/test_report.py b/addons/stock/tests/test_report.py index 1ed7c451409..ad67df12749 100644 --- a/addons/stock/tests/test_report.py +++ b/addons/stock/tests/test_report.py @@ -79,7 +79,7 @@ class TestReports(TestReportsCommon): 'location_id': stock.id, 'inventory_quantity': 50 }).action_apply_inventory() - self.env['stock.move'].flush() + self.env.flush_all() report_records_today = self.env['report.stock.quantity'].read_group( [('product_id', '=', product.id), ('date', '=', date.today())], ['product_qty'], [], lazy=False) @@ -103,13 +103,13 @@ class TestReports(TestReportsCommon): 'product_uom': product.uom_id.id, 'product_uom_qty': 20.0, }) - self.env['stock.move'].flush() + self.env.flush_all() report_records_tomorrow = self.env['report.stock.quantity'].read_group( [('product_id', '=', product.id), ('date', '=', date.today() + timedelta(days=1))], ['product_qty'], []) self.assertEqual(sum([r['product_qty'] for r in report_records_tomorrow]), 50.0) move_out._action_confirm() - self.env['stock.move'].flush() + self.env.flush_all() report_records_tomorrow = self.env['report.stock.quantity'].read_group( [('product_id', '=', product.id), ('date', '=', date.today() + timedelta(days=1))], ['product_qty', 'state'], ['state'], lazy=False) @@ -131,7 +131,7 @@ class TestReports(TestReportsCommon): 'product_uom_qty': 10.0, }) move_in._action_confirm() - self.env['stock.move'].flush() + self.env.flush_all() report_records_tomorrow = self.env['report.stock.quantity'].read_group( [('product_id', '=', product.id), ('date', '=', date.today() + timedelta(days=1))], ['product_qty', 'state'], ['state'], lazy=False) @@ -154,7 +154,7 @@ class TestReports(TestReportsCommon): 'product_uom_qty': 30.0, }) move_out._action_confirm() - self.env['stock.move'].flush() + self.env.flush_all() report_records_today = self.env['report.stock.quantity'].read_group( [('product_id', '=', product.id), ('date', '=', date.today())], ['product_qty', 'state'], ['state'], lazy=False) @@ -215,7 +215,7 @@ class TestReports(TestReportsCommon): 'product_uom_qty': 10.0, }) move._action_confirm() - self.env['stock.move'].flush() + self.env.flush_all() report_records = self.env['report.stock.quantity'].read_group( [('product_id', '=', product.id), ('date', '=', date.today()), ('warehouse_id', '!=', False)], ['product_qty', 'state'], ['state'], lazy=False) @@ -233,7 +233,7 @@ class TestReports(TestReportsCommon): 'product_uom_qty': 10.0, }) move._action_confirm() - self.env['stock.move'].flush() + self.env.flush_all() report_records = self.env['report.stock.quantity'].read_group( [('product_id', '=', product.id), ('date', '=', date.today())], ['product_qty', 'state'], ['state'], lazy=False) @@ -257,7 +257,7 @@ class TestReports(TestReportsCommon): 'location_id': stock.id, }) - self.env['stock.move'].flush() + self.env.flush_all() report_records = self.env['report.stock.quantity'].read_group( [('product_id', '=', product.id), ('date', '=', date.today())], ['product_qty'], [], lazy=False) @@ -276,7 +276,7 @@ class TestReports(TestReportsCommon): move_in.move_line_ids.location_dest_id = stock_real_loc.id move_in.move_line_ids.qty_done = 20.0 move_in._action_done() - self.env['stock.move'].flush() + self.env.flush_all() report_records = self.env['report.stock.quantity'].read_group( [('product_id', '=', product.id), ('date', '=', date.today())], ['product_qty'], [], lazy=False) @@ -295,7 +295,7 @@ class TestReports(TestReportsCommon): move_out._action_assign() move_out.move_line_ids.qty_done = 10.0 move_out._action_done() - self.env['stock.move'].flush() + self.env.flush_all() report_records = self.env['report.stock.quantity'].read_group( [('product_id', '=', product.id), ('date', '=', date.today())], ['product_qty'], [], lazy=False) diff --git a/addons/stock/tests/test_report_stock_quantity.py b/addons/stock/tests/test_report_stock_quantity.py index d37b241487c..14881e4db69 100644 --- a/addons/stock/tests/test_report_stock_quantity.py +++ b/addons/stock/tests/test_report_stock_quantity.py @@ -95,7 +95,7 @@ class TestReportStockQuantity(tests.TransactionCase): 'date_deadline': fields.Datetime.now(), }) - self.env['base'].flush() + self.env.flush_all() report = self.env['report.stock.quantity'].read_group( [('date', '>=', fields.Date.today()), ('date', '<=', fields.Date.today()), ('product_id', '=', self.product1.id)], ['product_qty', 'date', 'product_id', 'state'], @@ -153,7 +153,7 @@ class TestReportStockQuantity(tests.TransactionCase): delivery_picking.action_confirm() # Trigger the manual orderpoint creation for missing product - self.env['stock.move'].flush() + self.env.flush_all() self.env['stock.warehouse.orderpoint'].action_open_orderpoints() orderpoint = self.env['stock.warehouse.orderpoint'].search([ @@ -223,7 +223,7 @@ class TestReportStockQuantity(tests.TransactionCase): move01.quantity_done = 1 move01._action_done() - self.env['stock.move'].flush() + self.env.flush_all() data = self.env['report.stock.quantity'].read_group( [('state', '=', 'forecast'), ('product_id', '=', product.id), ('date', '>=', two_days_ago), ('date', '<=', in_two_days)], diff --git a/addons/survey/models/survey_survey.py b/addons/survey/models/survey_survey.py index 2ff6778a74d..d8a71cc95d5 100644 --- a/addons/survey/models/survey_survey.py +++ b/addons/survey/models/survey_survey.py @@ -770,7 +770,7 @@ class Survey(models.Model): if self.env.user.has_group('survey.group_survey_user'): self.sudo().write({'session_state': 'in_progress'}) - self.sudo().flush(['session_state']) + self.sudo().flush_recordset(['session_state']) def _get_session_next_question(self, go_back): self.ensure_one() diff --git a/addons/survey/models/survey_user_input.py b/addons/survey/models/survey_user_input.py index f0d85ffba53..18761ae9977 100644 --- a/addons/survey/models/survey_user_input.py +++ b/addons/survey/models/survey_user_input.py @@ -129,7 +129,7 @@ class SurveyUserInput(models.Model): user_input.attempts_number = 1 if attempts_to_compute: - self.env['survey.user_input'].flush() + self.flush_model(['email', 'invite_token', 'partner_id', 'state', 'survey_id', 'test_entry']) self.env.cr.execute(""" SELECT user_input.id, diff --git a/addons/survey/tests/test_certification_badge.py b/addons/survey/tests/test_certification_badge.py index 762feba5d7c..f2103f04758 100644 --- a/addons/survey/tests/test_certification_badge.py +++ b/addons/survey/tests/test_certification_badge.py @@ -75,7 +75,6 @@ class TestCertificationBadge(common.TestSurveyCommon): 'certification_give_badge': True, 'certification_badge_id': self.certification_badge.id }) - self.certification_survey.flush() def test_badge_configuration(self): """ Test badge synchronization """ diff --git a/addons/survey/tests/test_certification_flow.py b/addons/survey/tests/test_certification_flow.py index 2a19cd81d5a..b3fddf2d1b2 100644 --- a/addons/survey/tests/test_certification_flow.py +++ b/addons/survey/tests/test_certification_flow.py @@ -110,7 +110,7 @@ class TestCertificationFlow(common.TestSurveyCommon, HttpCase): self._answer_question(q04, q04.suggested_answer_ids.ids[0], answer_token, csrf_token) self._answer_question(q05, [q05.suggested_answer_ids.ids[0], q05.suggested_answer_ids.ids[1], q05.suggested_answer_ids.ids[3]], answer_token, csrf_token) - user_inputs.invalidate_cache() + user_inputs.invalidate_recordset() # Check that certification is successfully passed self.assertEqual(user_inputs.scoring_percentage, 87.5) self.assertTrue(user_inputs.scoring_success) diff --git a/addons/survey/tests/test_survey_flow.py b/addons/survey/tests/test_survey_flow.py index 08a478fd37a..d09f0d74e15 100644 --- a/addons/survey/tests/test_survey_flow.py +++ b/addons/survey/tests/test_survey_flow.py @@ -95,7 +95,7 @@ class TestSurveyFlow(common.TestSurveyCommon, HttpCase): post_data = self._format_submission_data(page_0, answer_data, {'csrf_token': csrf_token, 'token': answer_token, 'button_submit': 'next'}) r = self._access_submit(survey, answer_token, post_data) self.assertResponse(r, 200) - answers.invalidate_cache() # TDE note: necessary as lots of sudo in controllers messing with cache + answers.invalidate_recordset() # TDE note: necessary as lots of sudo in controllers messing with cache # -> this should have generated answer lines self.assertAnswer(answers, 'in_progress', page_0) @@ -113,7 +113,7 @@ class TestSurveyFlow(common.TestSurveyCommon, HttpCase): post_data = self._format_submission_data(page_1, answer_data, {'csrf_token': csrf_token, 'token': answer_token, 'button_submit': 'next'}) r = self._access_submit(survey, answer_token, post_data) self.assertResponse(r, 200) - answers.invalidate_cache() # TDE note: necessary as lots of sudo in controllers messing with cache + answers.invalidate_recordset() # TDE note: necessary as lots of sudo in controllers messing with cache # -> this should have generated answer lines and closed the answer self.assertAnswer(answers, 'done', page_1) diff --git a/addons/survey/tests/test_survey_flow_with_conditions.py b/addons/survey/tests/test_survey_flow_with_conditions.py index feb64d6320c..494e064e84d 100644 --- a/addons/survey/tests/test_survey_flow_with_conditions.py +++ b/addons/survey/tests/test_survey_flow_with_conditions.py @@ -120,6 +120,6 @@ class TestSurveyFlowWithConditions(common.TestSurveyCommon, HttpCase): self._answer_page(page_0, answers, answer_token, csrf_token) - user_inputs.invalidate_cache() + user_inputs.invalidate_recordset() self.assertEqual(round(user_inputs.scoring_percentage), 60, "Three right answers out of five (the fourth one is still hidden)") self.assertFalse(user_inputs.scoring_success) diff --git a/addons/survey/tests/test_survey_invite.py b/addons/survey/tests/test_survey_invite.py index 14c58d13c17..0208a8a5b0b 100644 --- a/addons/survey/tests/test_survey_invite.py +++ b/addons/survey/tests/test_survey_invite.py @@ -102,7 +102,7 @@ class TestSurveyInvite(common.TestSurveyCommon): @users('survey_manager') def test_survey_invite_authentication_signup(self): self.env["ir.config_parameter"].sudo().set_param('auth_signup.invitation_scope', 'b2c') - self.survey.invalidate_cache() + self.env.invalidate_all() Answer = self.env['survey.user_input'] self.survey.write({'access_mode': 'public', 'users_login_required': True}) diff --git a/addons/test_base_automation/tests/test_flow.py b/addons/test_base_automation/tests/test_flow.py index 49ebbdd662a..7e765af754a 100644 --- a/addons/test_base_automation/tests/test_flow.py +++ b/addons/test_base_automation/tests/test_flow.py @@ -183,7 +183,7 @@ record['name'] = record.name + 'X'""", self.assertEqual(lead.user_id, self.user_root, "Responsible should not change on creation of Lead with state from 'draft' to 'open'.") # change partner, recompute on lead should trigger the rule partner.write({'employee': True}) - lead.flush() + self.env.flush_all() self.assertTrue(lead.employee, "Customer field should updated to True") self.assertEqual(lead.user_id, self.user_demo, "Responsible should be change on write of Lead when Customer becomes True.") @@ -423,7 +423,7 @@ class TestCompute(common.TransactionCase): # automatically assigned to project, too task = self.env['test_base_automation.task'].create({'project_id': project.id}) subtasks = task.create([{'parent_id': task.id} for _ in range(10)]) - subtasks.flush() + subtasks.flush_model() # This test checks what happens when a stored recursive computed field # is marked to compute on many records, and automated actions are diff --git a/addons/test_crm_full/tests/test_performance.py b/addons/test_crm_full/tests/test_performance.py index 85527cd8f6c..68494331a4e 100644 --- a/addons/test_crm_full/tests/test_performance.py +++ b/addons/test_crm_full/tests/test_performance.py @@ -27,7 +27,7 @@ class CrmPerformanceCase(TestCrmFullCommon): def _flush_tracking(self): """ Force the creation of tracking values notably, and ensure tests are reproducible. """ - self.env['base'].flush() + self.env.flush_all() self.cr.flush() diff --git a/addons/test_discuss_full/tests/test_performance.py b/addons/test_discuss_full/tests/test_performance.py index dd371a81aaa..f430c8e5892 100644 --- a/addons/test_discuss_full/tests/test_performance.py +++ b/addons/test_discuss_full/tests/test_performance.py @@ -99,8 +99,8 @@ class TestDiscussFullPerformance(TransactionCase): self.env.company.sudo().name = 'YourCompany' self.maxDiff = None - self.users[0].flush() - self.users[0].invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() with self.assertQueryCount(emp=83): init_messaging = self.users[0].with_user(self.users[0])._init_messaging() diff --git a/addons/test_event_full/tests/common.py b/addons/test_event_full/tests/common.py index d3c962cffc4..9107fb5aacc 100644 --- a/addons/test_event_full/tests/common.py +++ b/addons/test_event_full/tests/common.py @@ -459,4 +459,4 @@ class TestWEventCommon(HttpCaseWithUserDemo, HttpCaseWithUserPortal, MockVisitor 'room_participant_count': 9, }) - self.event.flush() + self.env.flush_all() diff --git a/addons/test_event_full/tests/test_event_event.py b/addons/test_event_full/tests/test_event_event.py index 7a96c7eee93..8bb0fdba6a7 100644 --- a/addons/test_event_full/tests/test_event_event.py +++ b/addons/test_event_full/tests/test_event_event.py @@ -63,14 +63,14 @@ class TestEventEvent(TestEventFullCommon): # check time dependent computation: registrations started with freeze_time(self.reference_now + timedelta(hours=1)): - event.invalidate_cache(fnames=['is_finished', 'is_ongoing', 'event_registrations_started']) + event.invalidate_model(['is_finished', 'is_ongoing', 'event_registrations_started']) self.assertFalse(event.is_finished) self.assertFalse(event.is_ongoing) self.assertTrue(event.event_registrations_started) # check time dependent computation: during event with freeze_time(self.reference_now + timedelta(days=1, hours=1)): - event.invalidate_cache(fnames=['is_finished', 'is_ongoing', 'event_registrations_started']) + event.invalidate_model(['is_finished', 'is_ongoing', 'event_registrations_started']) self.assertFalse(event.is_finished) self.assertTrue(event.is_ongoing) self.assertTrue(event.event_registrations_started) diff --git a/addons/test_event_full/tests/test_performance.py b/addons/test_event_full/tests/test_performance.py index 082e4b01fca..29bcf418fc0 100644 --- a/addons/test_event_full/tests/test_performance.py +++ b/addons/test_event_full/tests/test_performance.py @@ -22,7 +22,7 @@ class EventPerformanceCase(TestEventFullCommon): def _flush_tracking(self): """ Force the creation of tracking values notably, and ensure tests are reproducible. """ - self.env['base'].flush() + self.env.flush_all() self.cr.flush() diff --git a/addons/test_mail/tests/test_mail_activity.py b/addons/test_mail/tests/test_mail_activity.py index 83f5e9f96f7..f873c111492 100644 --- a/addons/test_mail/tests/test_mail_activity.py +++ b/addons/test_mail/tests/test_mail_activity.py @@ -159,11 +159,9 @@ class TestActivityFlow(TestActivityCommon): self.assertEqual(test_record.activity_state, 'planned') test_record.activity_ids.write({'date_deadline': date.today() - relativedelta(days=1)}) - test_record.invalidate_cache() # TDE note: should not have to do it I think self.assertEqual(test_record.activity_state, 'overdue') test_record.activity_ids.write({'date_deadline': date.today()}) - test_record.invalidate_cache() # TDE note: should not have to do it I think self.assertEqual(test_record.activity_state, 'today') # activity is done @@ -258,13 +256,13 @@ class TestActivityFlow(TestActivityCommon): }) with self.assertRaises(IntegrityError): activity.write({'res_model_id': False}) - activity.flush() + self.env.flush_all() with self.assertRaises(IntegrityError): activity.write({'res_id': False}) - activity.flush() + self.env.flush_all() with self.assertRaises(IntegrityError): activity.write({'res_id': 0}) - activity.flush() + self.env.flush_all() @tests.tagged('mail_activity') @@ -319,7 +317,7 @@ class TestActivityMixin(TestActivityCommon): # it therefore relies on the natural order of `activity_ids`, according to which activity comes first. # As we just created the activity, its not yet in the right order. # We force it by invalidating it so it gets fetched from database, in the right order. - self.test_record.invalidate_cache(['activity_ids']) + self.test_record.invalidate_recordset(['activity_ids']) self.assertEqual(self.test_record.activity_user_id, self.user_employee) act3 = self.test_record.activity_schedule( @@ -331,10 +329,10 @@ class TestActivityMixin(TestActivityCommon): # it therefore relies on the natural order of `activity_ids`, according to which activity comes first. # As we just created the activity, its not yet in the right order. # We force it by invalidating it so it gets fetched from database, in the right order. - self.test_record.invalidate_cache(['activity_ids']) + self.test_record.invalidate_recordset(['activity_ids']) self.assertEqual(self.test_record.activity_user_id, self.user_employee) - self.test_record.invalidate_cache(ids=self.test_record.ids) + self.test_record.invalidate_recordset() self.assertEqual(self.test_record.activity_ids, act1 | act2 | act3) # Perform todo activities for admin diff --git a/addons/test_mail/tests/test_mail_followers.py b/addons/test_mail/tests/test_mail_followers.py index 4a1e0d94258..6d746564a05 100644 --- a/addons/test_mail/tests/test_mail_followers.py +++ b/addons/test_mail/tests/test_mail_followers.py @@ -245,9 +245,9 @@ class AdvancedFollowersTest(TestMailCommon): """ Test inactive are not added as followers in automated subscription """ self.test_track.user_id = False self.user_admin.active = False - self.user_admin.flush() + self.user_admin.flush_recordset() self.partner_admin.active = False - self.partner_admin.flush() + self.partner_admin.flush_recordset() self.test_track.with_user(self.user_admin).message_post(body='Coucou hibou', message_type='comment') self.assertEqual(self.test_track.message_partner_ids, self.user_employee.partner_id) @@ -452,7 +452,7 @@ class RecipientsNotificationTest(TestMailCommon): 'partner_id': cls.common_partner.id, } ]) - (cls.user_1 + cls.user_2).flush() + cls.env.flush_all() def assertRecipientsData(self, recipients_data, records, partners, partner_to_users=None): """ Custom assert as recipients structure is custom and may change due @@ -570,7 +570,7 @@ class RecipientsNotificationTest(TestMailCommon): 'partner_id': shared_partner.id, } ]) - (user_2_1 + user_2_2 + user_2_3).flush() + (user_2_1 + user_2_2 + user_2_3).flush_recordset() # just ensure current share status self.assertFalse(shared_partner.partner_share) @@ -633,7 +633,7 @@ class RecipientsNotificationTest(TestMailCommon): # ensure filtering on internal: should exclude Portal even if misconfiguration follower_portal = test_records[0].message_follower_ids.filtered(lambda fol: fol.partner_id == self.partner_portal).sudo() follower_portal.write({'subtype_ids': [(4, self.env.ref('mail.mt_note').id)]}) - follower_portal.flush() + follower_portal.flush_recordset() recipients_data = self.env['mail.followers']._get_recipient_data( test_records[0], 'comment', self.env.ref('mail.mt_note').id, pids=(self.common_partner + self.partner_admin).ids diff --git a/addons/test_mail/tests/test_mail_gateway.py b/addons/test_mail/tests/test_mail_gateway.py index d416bb495d7..35fc2e74ed0 100644 --- a/addons/test_mail/tests/test_mail_gateway.py +++ b/addons/test_mail/tests/test_mail_gateway.py @@ -319,7 +319,7 @@ class TestMailgateway(TestMailCommon): # archived partner -> no follower self.partner_1.active = False - self.partner_1.flush() + self.partner_1.flush_recordset() with self.mock_mail_gateway(): record3 = self.format_and_process( MAIL_TEMPLATE, self.partner_1.email_formatted, 'groups@test.com', @@ -659,7 +659,7 @@ class TestMailgateway(TestMailCommon): # name order win self.test_record.message_unsubscribe(follower_user.partner_id.ids) - self.test_record.flush() + self.test_record.flush_recordset() record = self.format_and_process(MAIL_TEMPLATE, self.user_employee.email_formatted, 'groups@test.com', subject='FirstFoundWinner') self.assertEqual(record.create_uid, self.user_employee) self.assertEqual(record.message_ids[0].subject, 'FirstFoundWinner') diff --git a/addons/test_mail/tests/test_mail_mail.py b/addons/test_mail/tests/test_mail_mail.py index 94aeff5513a..347ea413a8a 100644 --- a/addons/test_mail/tests/test_mail_mail.py +++ b/addons/test_mail/tests/test_mail_mail.py @@ -81,7 +81,7 @@ class TestMailMail(TestMailCommon): if any(attachment.name in ('file 2', 'file 4') for attachment in self): raise AccessError('No access') - mail.invalidate_cache(ids=mail.ids) + mail.invalidate_recordset() new_attachment = self.env['ir.attachment'].create({ 'name': 'new file', @@ -113,13 +113,13 @@ class TestMailMail(TestMailCommon): self.assertEqual(len(mail.attachment_ids), 4) # Reset command - mail.invalidate_cache(ids=mail.ids) + mail.invalidate_recordset() mail.write({'unrestricted_attachment_ids': [Command.clear()]}) self.assertEqual(len(mail.unrestricted_attachment_ids), 0) self.assertEqual(len(mail.attachment_ids), 2) # Read in SUDO - mail.invalidate_cache(ids=mail.ids) + mail.invalidate_recordset() self.assertEqual(mail.sudo().restricted_attachment_count, 2) self.assertEqual(len(mail.sudo().unrestricted_attachment_ids), 0) diff --git a/addons/test_mail/tests/test_mail_message.py b/addons/test_mail/tests/test_mail_message.py index de217dae950..4aff8c5582a 100644 --- a/addons/test_mail/tests/test_mail_message.py +++ b/addons/test_mail/tests/test_mail_message.py @@ -55,8 +55,8 @@ class TestMessageValues(TestMailCommon): # We need to flush and invalidate the ORM cache since the record_name # is already cached from the creation. Otherwise it will leak inside # message_format. - message.flush() - message.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() res = message.with_user(self.user_employee).message_format() self.assertEqual(res[0].get('record_name'), 'Test1') diff --git a/addons/test_mail/tests/test_mail_template.py b/addons/test_mail/tests/test_mail_template.py index 5b5016ca39e..d9614c7b7f1 100644 --- a/addons/test_mail/tests/test_mail_template.py +++ b/addons/test_mail/tests/test_mail_template.py @@ -59,7 +59,7 @@ class TestMailTemplate(TestMailCommon, TestRecipients): # admin should receive emails cls.user_admin.write({'notification_type': 'email'}) # Force the attachments of the template to be in the natural order. - cls.test_template.invalidate_cache(['attachment_ids'], ids=cls.test_template.ids) + cls.test_template.invalidate_recordset(['attachment_ids']) @mute_logger('odoo.addons.mail.models.mail_mail') def test_template_send_email(self): diff --git a/addons/test_mail/tests/test_message_post.py b/addons/test_mail/tests/test_message_post.py index 53cc414e76b..24a543d1bb8 100644 --- a/addons/test_mail/tests/test_message_post.py +++ b/addons/test_mail/tests/test_message_post.py @@ -770,7 +770,7 @@ class TestMessagePostHelpers(TestMessagePostCommon): # admin should receive emails self.user_admin.write({'notification_type': 'email'}) # Force the attachments of the template to be in the natural order. - self.email_template.invalidate_cache(['attachment_ids'], ids=self.email_template.ids) + self.email_template.invalidate_recordset(['attachment_ids']) with self.mock_mail_gateway(): test_record.with_user(self.user_employee).message_post_with_template(self.email_template.id, composition_mode='comment') diff --git a/addons/test_mail/tests/test_message_track.py b/addons/test_mail/tests/test_message_track.py index 30f54dd4b7b..1388a7f3baa 100644 --- a/addons/test_mail/tests/test_message_track.py +++ b/addons/test_mail/tests/test_message_track.py @@ -370,7 +370,7 @@ class TestTrackingInternals(TestMailCommon): self.assertTrue(msg_sudo.get('tracking_values'), "should have protected tracking values") # test editing the record with user not in the group of the field - self.record.invalidate_cache() + self.env.invalidate_all() self.record.clear_caches() record_form = Form(self.record.with_user(self.user_employee)) record_form.name = 'TestDoNoCrash' diff --git a/addons/test_mail/tests/test_performance.py b/addons/test_mail/tests/test_performance.py index 9ee3f623395..7761dc7dc2b 100644 --- a/addons/test_mail/tests/test_performance.py +++ b/addons/test_mail/tests/test_performance.py @@ -626,17 +626,14 @@ class TestMailAPIPerformance(BaseMailPerformance): record = self.env['mail.performance.tracking'].create({'name': 'Zizizatestname'}) with self.assertQueryCount(__system__=3, employee=3): record.write({'name': 'Zizizanewtestname'}) - record.flush() with self.assertQueryCount(__system__=3, employee=3): record.write({'field_%s' % (i): 'Tracked Char Fields %s' % (i) for i in range(3)}) - record.flush() with self.assertQueryCount(__system__=4, employee=4): record.write({'field_%s' % (i): 'Field Without Cache %s' % (i) for i in range(3)}) - record.flush() + record.flush_recordset() record.write({'field_%s' % (i): 'Field With Cache %s' % (i) for i in range(3)}) - record.flush() @users('__system__', 'employee') @warmup @@ -694,7 +691,7 @@ class TestMailComplexPerformance(BaseMailPerformance): ]) # `test_complex_mail_mail_send` - self.container.flush() + self.env.flush_all() @mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink') @users('__system__', 'employee') @@ -1050,8 +1047,8 @@ class TestMailComplexPerformance(BaseMailPerformance): for message in res: self.assertEqual(len(message['attachment_ids']), 2) - messages.flush() - messages.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() with self.assertQueryCount(employee=17): res = messages.message_format() @@ -1078,8 +1075,8 @@ class TestMailComplexPerformance(BaseMailPerformance): res = messages.message_format() self.assertEqual(len(res), 6) - messages.flush() - messages.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() with self.assertQueryCount(employee=12): res = messages.message_format() diff --git a/addons/test_mail_full/tests/test_phone_blacklist.py b/addons/test_mail_full/tests/test_phone_blacklist.py index 799fecee797..0688a1f4bf6 100644 --- a/addons/test_mail_full/tests/test_phone_blacklist.py +++ b/addons/test_mail_full/tests/test_phone_blacklist.py @@ -27,17 +27,17 @@ class TestPhoneBlacklist(TestMailFullCommon, TestMailFullRecipients): self.assertFalse(test_record.phone_sanitized_blacklisted) bl_record = self.env['phone.blacklist'].sudo().create([{'number': self.test_numbers_san[1]}]) - test_record.invalidate_cache() + test_record.invalidate_recordset() self.assertTrue(test_record.phone_sanitized_blacklisted) self.env['phone.blacklist'].sudo().remove(self.test_numbers_san[1]) self.assertFalse(bl_record.active) - test_record.invalidate_cache() + test_record.invalidate_recordset() self.assertFalse(test_record.phone_sanitized_blacklisted) self.env['phone.blacklist'].sudo().add(self.test_numbers_san[1]) self.assertTrue(bl_record.active) - test_record.invalidate_cache() + test_record.invalidate_recordset() self.assertTrue(test_record.phone_sanitized_blacklisted) bl_record_2 = self.env['phone.blacklist'].sudo().create([{'number': self.test_numbers_san[1]}]) @@ -56,11 +56,11 @@ class TestPhoneBlacklist(TestMailFullCommon, TestMailFullRecipients): self.assertFalse(test_record.phone_sanitized_blacklisted) test_record._phone_set_blacklisted() - test_record.invalidate_cache() + test_record.invalidate_recordset() self.assertTrue(test_record.phone_sanitized_blacklisted) test_record._phone_reset_blacklisted() - test_record.invalidate_cache() + test_record.invalidate_recordset() self.assertFalse(test_record.phone_sanitized_blacklisted) def test_phone_sanitize_internals(self): diff --git a/addons/test_mail_full/tests/test_rating.py b/addons/test_mail_full/tests/test_rating.py index 203b02c25a8..065bc488075 100644 --- a/addons/test_mail_full/tests/test_rating.py +++ b/addons/test_mail_full/tests/test_rating.py @@ -114,7 +114,7 @@ class TestRatingFlow(TestMailFullCommon, TestMailFullRecipients): access_2 = record_rating._rating_get_access_token() last_rating = record_rating.rating_apply(5, token=access_2, feedback="This is the best record ever ! I wish I read the documentation before complaining !") last_rating.write_date = datetime(2022, 3, 1, 14, 00) - record_rating.rating_ids.flush(['write_date']) + record_rating.rating_ids.flush_model(['write_date']) self.assertEqual(record_rating.rating_last_value, 5, "The last rating is kept.") self.assertEqual(record_rating.rating_avg, 3, "The average should be equal to 3") @@ -143,7 +143,7 @@ class TestRatingFlow(TestMailFullCommon, TestMailFullRecipients): new_ratings = record_ratings.rating_ids.filtered(lambda r: r.rating == 1) new_ratings.write_date = datetime(2022, 2, 1, 14, 00) - new_ratings.flush(['write_date']) + new_ratings.flush_model(['write_date']) with self.assertQueryCount(__system__=2): record_ratings._compute_rating_last_value() vals = [val == 5 for val in record_ratings.mapped('rating_last_value')] diff --git a/addons/test_mail_full/tests/test_sms_composer.py b/addons/test_mail_full/tests/test_sms_composer.py index 938dec49548..6a46c7c59c9 100644 --- a/addons/test_mail_full/tests/test_sms_composer.py +++ b/addons/test_mail_full/tests/test_sms_composer.py @@ -154,7 +154,7 @@ class TestSMSComposerComment(TestMailFullCommon, TestMailFullRecipients): with self.mockSMSGateway(): composer.action_send_sms() - self.test_record.flush() + self.test_record.flush_recordset() self.assertEqual(self.test_record.phone_nbr, self.random_numbers[0]) def test_composer_comment_wo_partner_wo_value_update(self): diff --git a/addons/test_mass_mailing/tests/test_mailing.py b/addons/test_mass_mailing/tests/test_mailing.py index caada4b9fc5..5704ae907a3 100644 --- a/addons/test_mass_mailing/tests/test_mailing.py +++ b/addons/test_mass_mailing/tests/test_mailing.py @@ -53,7 +53,7 @@ class TestMassMailing(TestMassMailCommon): msg_id='<123456.%s.%d@test.example.com>' % (customers[2]._name, customers[2].id), target_model=customers[2]._name, target_field=customers[2]._rec_name, ) - mailing.flush() + mailing.flush_recordset() # check traces status traces = self.env['mailing.trace'].search([('model', '=', customers._name), ('res_id', 'in', customers.ids)]) @@ -108,13 +108,13 @@ class TestMassMailing(TestMassMailCommon): # simulate a click self.gateway_mail_click(mailing, recipients[0], 'https://www.odoo.be') - mailing.invalidate_cache() + mailing.invalidate_recordset() self.assertMailingStatistics(mailing, expected=5, delivered=5, sent=5, opened=1, clicked=1) # simulate a bounce self.assertEqual(recipients[1].message_bounce, 0) self.gateway_mail_bounce(mailing, recipients[1]) - mailing.invalidate_cache() + mailing.invalidate_recordset() self.assertMailingStatistics(mailing, expected=5, delivered=4, sent=5, opened=1, clicked=1, bounced=1) self.assertEqual(recipients[1].message_bounce, 1) @@ -232,7 +232,7 @@ class TestMassMailing(TestMassMailCommon): self.env['mail.blacklist'].action_remove_with_reason( recipients[2].email_normalized, "human error" ) - self.env['mail.blacklist'].flush(['active']) + self.env['mail.blacklist'].flush_model(['active']) mailing.write({'mailing_domain': [('id', 'in', recipients.ids)]}) with self.mock_mail_gateway(mail_unlink_sent=False): diff --git a/addons/test_mass_mailing/tests/test_performance.py b/addons/test_mass_mailing/tests/test_performance.py index 2a9509d2a86..3e7d6735307 100644 --- a/addons/test_mass_mailing/tests/test_performance.py +++ b/addons/test_mass_mailing/tests/test_performance.py @@ -71,7 +71,7 @@ class TestMassMailBlPerformance(TestMassMailPerformanceBase): self.env['mail.blacklist'].create({ 'email': 'rec.%s@example.com' % (x * 5) }) - self.env['mailing.performance.blacklist'].flush() + self.env.flush_all() @users('__system__', 'marketing') @warmup diff --git a/addons/test_sale_product_configurators/tests/test_sale_product_matrix.py b/addons/test_sale_product_configurators/tests/test_sale_product_matrix.py index cf12ad9a64e..4ef1815b3cf 100644 --- a/addons/test_sale_product_configurators/tests/test_sale_product_matrix.py +++ b/addons/test_sale_product_configurators/tests/test_sale_product_matrix.py @@ -44,7 +44,7 @@ class TestSaleMatrixUi(TestMatrixCommon): self.assertEqual(len(self.matrix_template.attribute_line_ids.product_template_value_ids), 8) self.env['sale.order.line'].search([('product_id', 'in', self.matrix_template.product_variant_ids.ids)]).order_id.action_confirm() - self.matrix_template.flush() + self.env.flush_all() self.assertEqual(round(self.matrix_template.sales_count, 2), 56.8) for variant in self.matrix_template.product_variant_ids: # 5 and 9.2 because of no variant attributes diff --git a/addons/test_website_slides_full/tests/test_ui_wslides.py b/addons/test_website_slides_full/tests/test_ui_wslides.py index 19bf16c4c04..bd8ba5e21aa 100644 --- a/addons/test_website_slides_full/tests/test_ui_wslides.py +++ b/addons/test_website_slides_full/tests/test_ui_wslides.py @@ -11,7 +11,6 @@ class TestUi(TestUICommon): def test_course_certification_employee(self): user_demo = self.user_demo - user_demo.flush() # Avoid Billing/Shipping address page user_demo.write({ 'groups_id': [(5, 0), (4, self.env.ref('base.group_user').id)], diff --git a/addons/website/models/ir_ui_view.py b/addons/website/models/ir_ui_view.py index 01aba7e14b9..1e9c6a911ce 100644 --- a/addons/website/models/ir_ui_view.py +++ b/addons/website/models/ir_ui_view.py @@ -124,8 +124,8 @@ class View(models.Model): # but in reality the values were only meant to go on the specific # page. Invalidate all fields and not only those in vals because # other fields could have been changed implicitly too. - pages.flush(records=pages) - pages.invalidate_cache(ids=pages.ids) + pages.flush_recordset() + pages.invalidate_recordset() # If already a specific view for this generic view, write on it website_specific_view = view.search([ diff --git a/addons/website/models/res_users.py b/addons/website/models/res_users.py index 1173757b10e..c03de1230e3 100644 --- a/addons/website/models/res_users.py +++ b/addons/website/models/res_users.py @@ -28,7 +28,7 @@ class ResUsers(models.Model): @api.constrains('login', 'website_id') def _check_login(self): """ Do not allow two users with the same login without website """ - self.flush(['login', 'website_id']) + self.flush_model(['login', 'website_id']) self.env.cr.execute( """SELECT login FROM res_users diff --git a/addons/website/models/website.py b/addons/website/models/website.py index 4ff7507e314..10a3ec6615d 100644 --- a/addons/website/models/website.py +++ b/addons/website/models/website.py @@ -1794,6 +1794,6 @@ class Website(models.Model): # ---------------------------------------------------------- def _neutralize(self): super()._neutralize() - self.flush() - self.invalidate_cache() + self.flush_model() + self.invalidate_model() self.env.cr.execute("UPDATE website SET domain=NULL") diff --git a/addons/website/tests/test_menu.py b/addons/website/tests/test_menu.py index 5a0fe9c4fc3..eb0e721292b 100644 --- a/addons/website/tests/test_menu.py +++ b/addons/website/tests/test_menu.py @@ -96,7 +96,7 @@ class TestMenu(common.TransactionCase): # loading translation add missing specific translation Translation._load_module_terms(['website'], ['fr_FR']) - Menu.invalidate_cache(['name']) + Menu.invalidate_model(['name']) self.assertEqual(specific1.name, 'Menu in french', 'Load translation without overwriting keep existing translation') self.assertEqual(specific2.name, 'Menu en français', @@ -104,7 +104,7 @@ class TestMenu(common.TransactionCase): # loading translation with overwrite sync all translations from menu template Translation._load_module_terms(['website'], ['fr_FR'], overwrite=True) - Menu.invalidate_cache(['name']) + Menu.invalidate_model(['name']) self.assertEqual(specific1.name, 'Menu en français', 'Load translation with overwriting update existing menu from template') diff --git a/addons/website/tests/test_views.py b/addons/website/tests/test_views.py index 728d62a82da..a332e99ae02 100644 --- a/addons/website/tests/test_views.py +++ b/addons/website/tests/test_views.py @@ -774,7 +774,7 @@ class TestCowViewSaving(TestViewSavingCommon): 'arch': '

COMPARE

', 'key': '_website_sale_comparison.product_add_to_compare', })]) - Website.with_context(load_all_views=True).viewref('_website_sale_comparison.product_add_to_compare').invalidate_cache() + Website.with_context(load_all_views=True).viewref('_website_sale_comparison.product_add_to_compare').invalidate_model() # Simulate end of installation/update View._create_all_specific_views(['_website_sale_comparison']) @@ -835,7 +835,7 @@ class TestCowViewSaving(TestViewSavingCommon): # Simulate website_sale update on top level view self._create_imd(self.base_view) - self.base_view.invalidate_cache() + self.base_view.invalidate_model() View._load_records([dict(xml_id='_website_sale.product', values={ 'website_meta_title': 'A bug got fixed by updating this field', })]) @@ -988,7 +988,7 @@ class TestCowViewSaving(TestViewSavingCommon): Translation._load_module_terms(['website'], ['en_US'], overwrite=True) - specific_view.invalidate_cache(['arch_db', 'arch']) + specific_view.invalidate_model(['arch_db', 'arch']) self.assertEqual(specific_view.with_context(lang='en_US').arch, '
hi
', "loading module translation copy translation from base to specific view") @@ -1059,7 +1059,7 @@ class TestCowViewSaving(TestViewSavingCommon): Website = self.env['website'] self._create_imd(self.inherit_view) # invalidate cache to recompute xml_id, or it will still be empty - self.inherit_view.invalidate_cache() + self.inherit_view.invalidate_model() base_view_2 = self.base_view.copy({'key': 'website.base_view2', 'arch': '
base2 content
'}) self.base_view.with_context(website_id=1).write({'arch': '
website 1 content
'}) specific_view = Website.with_context(load_all_views=True, website_id=1).viewref(self.base_view.key) @@ -1145,7 +1145,7 @@ class Crawler(HttpCase): event_child_view.copy({'name': 'Filter by Category', 'inherit_id': event_child_view.id, 'key': '_website_event.event_category'}) event_child_view.copy({'name': 'Filter by Country', 'inherit_id': event_child_view.id, 'key': '_website_event.event_location'}) - View.flush() + self.env.flush_all() # Customize # | Main Frontend Layout diff --git a/addons/website/tests/test_website_reset_password.py b/addons/website/tests/test_website_reset_password.py index 83e23a565cc..fc5c5b0e6aa 100644 --- a/addons/website/tests/test_website_reset_password.py +++ b/addons/website/tests/test_website_reset_password.py @@ -40,12 +40,12 @@ class TestWebsiteResetPassword(HttpCase): website_2.domain = "https://domain-not-used.fr" user.partner_id.website_id = 2 - user.invalidate_cache() # invalidate get_base_url + self.env.invalidate_all() # invalidate get_base_url user.action_reset_password() self.assertIn(website_2.domain, user.signup_url) - user.invalidate_cache() + self.env.invalidate_all() user.partner_id.website_id = 1 user.action_reset_password() @@ -54,7 +54,7 @@ class TestWebsiteResetPassword(HttpCase): (website_1 + website_2).domain = "" user.action_reset_password() - user.invalidate_cache() + self.env.invalidate_all() self.start_tour(user.signup_url, 'website_reset_password', login=None) diff --git a/addons/website/tests/test_website_visitor.py b/addons/website/tests/test_website_visitor.py index ad4727c1674..d164b66a43c 100644 --- a/addons/website/tests/test_website_visitor.py +++ b/addons/website/tests/test_website_visitor.py @@ -271,14 +271,14 @@ class WebsiteVisitorTests(MockVisitor, HttpCaseWithUserDemo): # visit a page self.url_open(self.tracked_page.url) - visitor_portal.invalidate_cache(fnames=['website_track_ids']) + visitor_portal.invalidate_model(['website_track_ids']) # tracks are created self.assertEqual(len(visitor_portal.website_track_ids), 5, "There should be 5 tracked page for the portal user") # simulate the portal user comes back 8hours later visitor_portal.write({'last_connection_datetime': visitor_portal.last_connection_datetime - timedelta(hours=8)}) self.url_open(self.tracked_page.url) - visitor_portal.invalidate_cache(fnames=['visit_count']) + visitor_portal.invalidate_model(['visit_count']) # check number of visits self.assertEqual(visitor_portal.visit_count, 2, "There should be 2 visits for the portal user") diff --git a/addons/website_crm/models/crm_lead.py b/addons/website_crm/models/crm_lead.py index dd9da4aa92e..164f78f7876 100644 --- a/addons/website_crm/models/crm_lead.py +++ b/addons/website_crm/models/crm_lead.py @@ -14,7 +14,8 @@ class Lead(models.Model): def _compute_visitor_page_count(self): mapped_data = {} if self.ids: - self.flush(['visitor_ids']) + self.flush_model(['visitor_ids']) + self.env['website.track'].flush_model(['visitor_id']) sql = """ SELECT l.id as lead_id, count(*) as page_view_count FROM crm_lead l JOIN crm_lead_website_visitor_rel lv ON l.id = lv.crm_lead_id diff --git a/addons/website_crm/models/website_visitor.py b/addons/website_crm/models/website_visitor.py index 33d6c29a2fb..717d5e0effd 100644 --- a/addons/website_crm/models/website_visitor.py +++ b/addons/website_crm/models/website_visitor.py @@ -19,7 +19,6 @@ class WebsiteVisitor(models.Model): @api.depends('partner_id.email_normalized', 'partner_id.mobile', 'lead_ids.email_normalized', 'lead_ids.mobile') def _compute_email_phone(self): super(WebsiteVisitor, self)._compute_email_phone() - self.flush() left_visitors = self.filtered(lambda visitor: not visitor.email or not visitor.mobile) leads = left_visitors.mapped('lead_ids').sorted('create_date', reverse=True) diff --git a/addons/website_crm_iap_reveal/models/crm_reveal_rule.py b/addons/website_crm_iap_reveal/models/crm_reveal_rule.py index 9d924c46ce4..b09a87831b8 100644 --- a/addons/website_crm_iap_reveal/models/crm_reveal_rule.py +++ b/addons/website_crm_iap_reveal/models/crm_reveal_rule.py @@ -344,7 +344,7 @@ class CRMRevealRule(models.Model): else: views = self.env['crm.reveal.view'].search([('reveal_ip', '=', res['ip'])]) views.write({'reveal_state': 'not_found'}) - views.flush() + views.flush_recordset() if result.get('credit_error'): self.env['crm.iap.lead.helpers'].notify_no_more_credit('reveal', self._name, 'reveal.already_notified') @@ -355,7 +355,7 @@ class CRMRevealRule(models.Model): ('reveal_ip', 'in', [ip for ip in all_ips if ip not in done_ips]) ]) views.write({'reveal_state': 'not_found'}) - views.flush() + views.flush_recordset() # reset notified parameter to re-send credit notice if appears again self.env['ir.config_parameter'].sudo().set_param('reveal.already_notified', False) return True diff --git a/addons/website_event/models/website_visitor.py b/addons/website_event/models/website_visitor.py index e64ea1c2b53..24a1b8f3a1a 100644 --- a/addons/website_event/models/website_visitor.py +++ b/addons/website_event/models/website_visitor.py @@ -38,7 +38,6 @@ class WebsiteVisitor(models.Model): @api.depends('event_registration_ids.email', 'event_registration_ids.mobile', 'event_registration_ids.phone') def _compute_email_phone(self): super(WebsiteVisitor, self)._compute_email_phone() - self.flush() for visitor in self.filtered(lambda visitor: not visitor.email or not visitor.mobile): linked_registrations = visitor.event_registration_ids.sorted(lambda reg: (reg.create_date, reg.id), reverse=False) diff --git a/addons/website_event_exhibitor/tests/test_sponsor_internals.py b/addons/website_event_exhibitor/tests/test_sponsor_internals.py index 64ac1595b58..8021c3c4e7c 100644 --- a/addons/website_event_exhibitor/tests/test_sponsor_internals.py +++ b/addons/website_event_exhibitor/tests/test_sponsor_internals.py @@ -17,48 +17,48 @@ class TestSponsorData(TestEventExhibitorCommon): with freeze_time(self.reference_now): event = self.env['event.event'].browse(self.event_0.id) sponsor = self.env['event.sponsor'].browse(self.sponsor_0.id) - event.invalidate_cache(fnames=['is_ongoing']) + event.invalidate_model(['is_ongoing']) self.assertTrue(sponsor.is_in_opening_hours) self.assertTrue(event.is_ongoing) # After hour_from (9 > 8) with freeze_time(datetime(2020, 7, 6, 7, 0, 0)): - event.invalidate_cache(fnames=['is_ongoing']) - sponsor.invalidate_cache(fnames=['is_in_opening_hours']) + event.invalidate_model(['is_ongoing']) + sponsor.invalidate_model(['is_in_opening_hours']) self.assertTrue(sponsor.is_in_opening_hours) self.assertTrue(event.is_ongoing) # At hour_from (8 = 8) with freeze_time(datetime(2020, 7, 6, 6, 0, 0)): - event.invalidate_cache(fnames=['is_ongoing']) - sponsor.invalidate_cache(fnames=['is_in_opening_hours']) + event.invalidate_model(['is_ongoing']) + sponsor.invalidate_model(['is_in_opening_hours']) self.assertTrue(sponsor.is_in_opening_hours) self.assertTrue(event.is_ongoing) # Started but not opened (7h59 < 8) with freeze_time(datetime(2020, 7, 6, 5, 59, 59)): - event.invalidate_cache(fnames=['is_ongoing']) - sponsor.invalidate_cache(fnames=['is_in_opening_hours']) + event.invalidate_model(['is_ongoing']) + sponsor.invalidate_model(['is_in_opening_hours']) self.assertFalse(sponsor.is_in_opening_hours) self.assertTrue(event.is_ongoing) # Evening event is not in opening hours (20 > 18) with freeze_time(datetime(2020, 7, 6, 18, 0, 0)): - event.invalidate_cache(fnames=['is_ongoing']) - sponsor.invalidate_cache(fnames=['is_in_opening_hours']) + event.invalidate_model(['is_ongoing']) + sponsor.invalidate_model(['is_in_opening_hours']) self.assertFalse(sponsor.is_in_opening_hours) self.assertTrue(event.is_ongoing) # First day begins later with freeze_time(datetime(2020, 7, 5, 6, 30, 0)): - event.invalidate_cache(fnames=['is_ongoing']) - sponsor.invalidate_cache(fnames=['is_in_opening_hours']) + event.invalidate_model(['is_ongoing']) + sponsor.invalidate_model(['is_in_opening_hours']) self.assertFalse(sponsor.is_in_opening_hours) self.assertFalse(event.is_ongoing) # End day finished sooner with freeze_time(datetime(2020, 7, 7, 13, 0, 1)): - event.invalidate_cache(fnames=['is_ongoing']) - sponsor.invalidate_cache(fnames=['is_in_opening_hours']) + event.invalidate_model(['is_ongoing']) + sponsor.invalidate_model(['is_in_opening_hours']) self.assertFalse(sponsor.is_in_opening_hours) self.assertFalse(event.is_ongoing) diff --git a/addons/website_event_sale/tests/test_frontend_buy_tickets.py b/addons/website_event_sale/tests/test_frontend_buy_tickets.py index 2ef773771e3..1be38006d59 100644 --- a/addons/website_event_sale/tests/test_frontend_buy_tickets.py +++ b/addons/website_event_sale/tests/test_frontend_buy_tickets.py @@ -56,8 +56,7 @@ class TestUi(HttpCaseWithUserDemo): # flush event to ensure having tickets available in the tests - self.event_2.flush() - self.event_3.flush() + self.env.flush_all() (self.env.ref('base.partner_admin') + self.partner_demo).write({ 'street': '215 Vine St', diff --git a/addons/website_event_track/tests/test_track_internals.py b/addons/website_event_track/tests/test_track_internals.py index f882100f525..e2af8a0af41 100644 --- a/addons/website_event_track/tests/test_track_internals.py +++ b/addons/website_event_track/tests/test_track_internals.py @@ -188,7 +188,7 @@ class TestTrackSuggestions(TestEventOnlineCommon): # remove keynote default, now based on tags track_5.write({'wishlisted_by_default': False}) - # all_suggestions.invalidate_cache(fnames=['is_reminder_on']) + # all_suggestions.invalidate_model(['is_reminder_on']) track_suggestion = current_track._get_track_suggestions(limit=1) self.assertEqual( track_suggestion, track_4, diff --git a/addons/website_knowledge/tests/test_knowledge_security.py b/addons/website_knowledge/tests/test_knowledge_security.py index f8daeec1671..9d2b3318788 100644 --- a/addons/website_knowledge/tests/test_knowledge_security.py +++ b/addons/website_knowledge/tests/test_knowledge_security.py @@ -41,7 +41,7 @@ class TestWKnowledgeSecurity(KnowledgeArticlePermissionsCase): # Read access gives access to favorite toggling article_shared.action_toggle_favorite() - article_shared.invalidate_cache(fnames=['is_user_favorite']) + article_shared.invalidate_model(['is_user_favorite']) self.assertTrue(article_shared.is_user_favorite) @mute_logger('odoo.addons.base.models.ir_model', 'odoo.addons.base.models.ir_rule') @@ -59,5 +59,5 @@ class TestWKnowledgeSecurity(KnowledgeArticlePermissionsCase): # Read access gives access to favorite toggling article_hidden.action_toggle_favorite() - article_hidden.invalidate_cache(fnames=['is_user_favorite']) + article_hidden.invalidate_model(['is_user_favorite']) self.assertTrue(article_hidden.is_user_favorite) diff --git a/addons/website_livechat/tests/test_livechat_request.py b/addons/website_livechat/tests/test_livechat_request.py index f50780da6a6..2a0f3a8f236 100644 --- a/addons/website_livechat/tests/test_livechat_request.py +++ b/addons/website_livechat/tests/test_livechat_request.py @@ -43,7 +43,7 @@ class TestLivechatRequestHttpCase(tests.HttpCase, TestLivechatCommon): ('livechat_active', '=', True)]) # Check that the chat request has been canceled. - chat_request.invalidate_cache() + chat_request.invalidate_recordset() self.assertEqual(chat_request.livechat_active, False, "The livechat request must be inactive as the visitor started himself a livechat session.") self.assertEqual(len(channel), 1) self.assertEqual(channel.livechat_operator_id, self.operator.partner_id, "Operator for active livechat session must be Michel Operator") diff --git a/addons/website_livechat/tests/test_ui.py b/addons/website_livechat/tests/test_ui.py index cf8336c1c4f..50c6b8f9c46 100644 --- a/addons/website_livechat/tests/test_ui.py +++ b/addons/website_livechat/tests/test_ui.py @@ -57,7 +57,7 @@ class TestLivechatUI(tests.HttpCase, TestLivechatCommon): self.assertEqual(channel.livechat_active, True, 'Livechat must be active while the chat window is not closed.') # Check that the chat request has been canceled. - chat_request.invalidate_cache() + chat_request.invalidate_recordset() self.assertEqual(chat_request.livechat_active, False, "The livechat request must be inactive as the visitor started himself a livechat session.") def test_chat_request_flow_with_rating_ui(self): diff --git a/addons/website_sale/tests/test_website_sale_pricelist.py b/addons/website_sale/tests/test_website_sale_pricelist.py index 61c08760568..1214f1907ff 100644 --- a/addons/website_sale/tests/test_website_sale_pricelist.py +++ b/addons/website_sale/tests/test_website_sale_pricelist.py @@ -111,7 +111,7 @@ class TestWebsitePriceList(TransactionCase): return self.get_pl(self.args.get('show'), self.args.get('current_pl'), self.args.get('country')) def get_pl(self, show_visible, current_pl_id, country_code): - self.website.invalidate_cache(['pricelist_ids'], [self.website.id]) + self.website.invalidate_recordset(['pricelist_ids']) pl_ids = self.website._get_pl_partner_order( country_code, show_visible, @@ -463,7 +463,7 @@ class TestWebsitePriceListHttp(HttpCaseWithUserPortal): reading that `property_product_pricelist`. ''' test_company = self.env['res.company'].create({'name': 'Test Company'}) - test_company.flush() + test_company.flush_recordset() self.env['product.pricelist'].create({ 'name': 'Backend Pricelist For "Test Company"', 'website_id': False, diff --git a/addons/website_sale_loyalty/tests/test_shop_sale_coupon.py b/addons/website_sale_loyalty/tests/test_shop_sale_coupon.py index 0bce403f3a7..50a2de6ccb0 100644 --- a/addons/website_sale_loyalty/tests/test_shop_sale_coupon.py +++ b/addons/website_sale_loyalty/tests/test_shop_sale_coupon.py @@ -18,8 +18,7 @@ class TestUi(TestSaleProductAttributeValueCommon, HttpCase): pricelist = cls.env.ref('product.list0') new_currency = cls._setup_currency(cls.currency_ratio) pricelist.currency_id = new_currency - pricelist.flush() - + cls.env.flush_all() def test_01_admin_shop_sale_loyalty_tour(self): # pre enable "Show # found" option to avoid race condition... @@ -247,7 +246,7 @@ class TestWebsiteSaleCoupon(TransactionCase): # 4. Test order not older than ICP validity -> Should not be removed ICP = self.env['ir.config_parameter'] icp_validity = ICP.create({'key': 'website_sale_coupon.abandonned_coupon_validity', 'value': 5}) - order.flush() + self.env.flush_all() query = """UPDATE %s SET write_date = %%s WHERE id = %%s""" % (order._table,) self.env.cr.execute(query, (fields.Datetime.to_string(fields.datetime.now() - timedelta(days=4, hours=2)), order.id)) order._gc_abandoned_coupons() diff --git a/addons/website_slides/models/slide_slide.py b/addons/website_slides/models/slide_slide.py index e000d0ec8db..f3a114d095b 100644 --- a/addons/website_slides/models/slide_slide.py +++ b/addons/website_slides/models/slide_slide.py @@ -880,7 +880,7 @@ class Slide(models.Model): ]) if quiz_attempts_inc and existing_sudo: sql.increment_field_skiplock(existing_sudo, 'quiz_attempts_count') - SlidePartnerSudo.invalidate_cache(fnames=['quiz_attempts_count'], ids=existing_sudo.ids) + existing_sudo.invalidate_recordset(['quiz_attempts_count']) new_slides = self_sudo - existing_sudo.mapped('slide_id') return SlidePartnerSudo.create([{ diff --git a/addons/website_slides/tests/test_security.py b/addons/website_slides/tests/test_security.py index 71aef50291f..6be198abfbf 100644 --- a/addons/website_slides/tests/test_security.py +++ b/addons/website_slides/tests/test_security.py @@ -72,36 +72,36 @@ class TestAccess(common.SlidesCase): def test_access_channel_publish(self): """ Unpublished channels and their content are visible only to eLearning people """ self.channel.write({'is_published': False, 'enroll': 'public'}) - self.channel.flush(['is_published', 'website_published', 'enroll']) + self.channel.flush_model() # channel available only to eLearning - self.channel.invalidate_cache(['name']) + self.channel.invalidate_model(['name']) self.channel.with_user(self.user_officer).read(['name']) - self.channel.invalidate_cache(['name']) + self.channel.invalidate_model(['name']) self.channel.with_user(self.user_manager).read(['name']) with self.assertRaises(AccessError): - self.channel.invalidate_cache(['name']) + self.channel.invalidate_model(['name']) self.channel.with_user(self.user_emp).read(['name']) with self.assertRaises(AccessError): - self.channel.invalidate_cache(['name']) + self.channel.invalidate_model(['name']) self.channel.with_user(self.user_portal).read(['name']) with self.assertRaises(AccessError): - self.channel.invalidate_cache(['name']) + self.channel.invalidate_model(['name']) self.channel.with_user(self.user_public).read(['name']) # slide available only to eLearning - self.channel.invalidate_cache(['name']) + self.channel.invalidate_model(['name']) self.slide.with_user(self.user_officer).read(['name']) - self.channel.invalidate_cache(['name']) + self.channel.invalidate_model(['name']) self.slide.with_user(self.user_manager).read(['name']) with self.assertRaises(AccessError): - self.slide.invalidate_cache(['name']) + self.slide.invalidate_model(['name']) self.slide.with_user(self.user_emp).read(['name']) with self.assertRaises(AccessError): - self.slide.invalidate_cache(['name']) + self.slide.invalidate_model(['name']) self.slide.with_user(self.user_portal).read(['name']) with self.assertRaises(AccessError): - self.slide.invalidate_cache(['name']) + self.slide.invalidate_model(['name']) self.slide.with_user(self.user_public).read(['name']) # even members cannot see unpublished content @@ -110,10 +110,10 @@ class TestAccess(common.SlidesCase): 'partner_id': self.user_emp.partner_id.id, }) with self.assertRaises(AccessError): - self.channel.invalidate_cache(['name']) + self.channel.invalidate_model(['name']) self.channel.with_user(self.user_emp).read(['name']) with self.assertRaises(AccessError): - self.slide.invalidate_cache(['name']) + self.slide.invalidate_model(['name']) self.slide.with_user(self.user_emp).read(['name']) # publish channel but content unpublished (even if can be previewed) still unavailable @@ -122,21 +122,21 @@ class TestAccess(common.SlidesCase): 'is_preview': True, 'is_published': False, }) - self.channel.flush(['website_published']) - self.slide.flush(['is_preview', 'website_published']) + self.channel.flush_model() + self.slide.flush_model() - self.slide.invalidate_cache(['name']) + self.slide.invalidate_model(['name']) self.slide.with_user(self.user_officer).read(['name']) - self.slide.invalidate_cache(['name']) + self.slide.invalidate_model(['name']) self.slide.with_user(self.user_manager).read(['name']) with self.assertRaises(AccessError): - self.slide.invalidate_cache(['name']) + self.slide.invalidate_model(['name']) self.slide.with_user(self.user_emp).read(['name']) with self.assertRaises(AccessError): - self.slide.invalidate_cache(['name']) + self.slide.invalidate_model(['name']) self.slide.with_user(self.user_portal).read(['name']) with self.assertRaises(AccessError): - self.slide.invalidate_cache(['name']) + self.slide.invalidate_model(['name']) self.slide.with_user(self.user_public).read(['name']) @mute_logger('odoo.models', 'odoo.addons.base.models.ir_rule') @@ -144,7 +144,7 @@ class TestAccess(common.SlidesCase): """ Slides with preview flag are always visible even to non members if published """ self.channel.write({'enroll': 'invite'}) self.slide.write({'is_preview': True}) - self.slide.flush(['is_preview']) + self.slide.flush_model() self.slide.with_user(self.user_officer).read(['name']) self.slide.with_user(self.user_manager).read(['name']) @@ -200,7 +200,7 @@ class TestAccessFeatures(common.SlidesCase): 'is_published': True, 'enroll_group_ids': [(4, self.ref('base.group_user'))] }) - channel.invalidate_cache(['partner_ids']) + channel.invalidate_model(['partner_ids']) self.assertEqual(channel.partner_ids, user_employees.mapped('partner_id')) new_user = self.env['res.users'].create({ @@ -208,7 +208,7 @@ class TestAccessFeatures(common.SlidesCase): 'login': 'NewUser', 'groups_id': [(6, 0, [self.ref('base.group_user')])] }) - channel.invalidate_cache() + channel.invalidate_model() self.assertEqual(channel.partner_ids, user_employees.mapped('partner_id') | new_user.partner_id) new_user_2 = self.env['res.users'].create({ @@ -216,10 +216,10 @@ class TestAccessFeatures(common.SlidesCase): 'login': 'NewUser2', 'groups_id': [(5, 0)] }) - channel.invalidate_cache() + channel.invalidate_model() self.assertEqual(channel.partner_ids, user_employees.mapped('partner_id') | new_user.partner_id) new_user_2.write({'groups_id': [(4, self.ref('base.group_user'))]}) - channel.invalidate_cache() + channel.invalidate_model() self.assertEqual(channel.partner_ids, user_employees.mapped('partner_id') | new_user.partner_id | new_user_2.partner_id) new_user_3 = self.env['res.users'].create({ @@ -227,10 +227,10 @@ class TestAccessFeatures(common.SlidesCase): 'login': 'NewUser3', 'groups_id': [(5, 0)] }) - channel.invalidate_cache() + channel.invalidate_model() self.assertEqual(channel.partner_ids, user_employees.mapped('partner_id') | new_user.partner_id | new_user_2.partner_id) self.env.ref('base.group_user').write({'users': [(4, new_user_3.id)]}) - channel.invalidate_cache() + channel.invalidate_model() self.assertEqual(channel.partner_ids, user_employees.mapped('partner_id') | new_user.partner_id | new_user_2.partner_id | new_user_3.partner_id) @mute_logger('odoo.models', 'odoo.addons.base.models.ir_rule') @@ -296,7 +296,7 @@ class TestAccessFeatures(common.SlidesCase): # superuser should always be able to publish even if they are not the responsible channel_superuser = self.channel.sudo() - channel_superuser.invalidate_cache(['can_upload', 'can_publish']) + channel_superuser.invalidate_recordset(['can_upload', 'can_publish']) self.assertTrue(channel_superuser.can_upload) self.assertTrue(channel_superuser.can_publish) diff --git a/addons/website_slides/tests/test_slide_channel.py b/addons/website_slides/tests/test_slide_channel.py index 6419575f178..a52ca46dad7 100644 --- a/addons/website_slides/tests/test_slide_channel.py +++ b/addons/website_slides/tests/test_slide_channel.py @@ -150,7 +150,7 @@ class TestSequencing(slides_common.SlidesCase): self.assertEqual([s.id for s in self.channel.slide_ids], [self.slide.id, self.category.id, self.slide_2.id, self.slide_3.id]) self.assertEqual(self.slide_2.category_id, self.category) self.slide_2.write({'sequence': 1}) - self.channel.invalidate_cache() + self.channel.invalidate_recordset() self.assertEqual([s.id for s in self.channel.slide_ids], [self.slide.id, self.slide_2.id, self.category.id, self.slide_3.id]) self.assertEqual(self.slide_2.category_id, self.env['slide.slide']) @@ -190,7 +190,7 @@ class TestSequencing(slides_common.SlidesCase): self.slide_2.write({'sequence': 8}) self.slide_3.write({'sequence': 3}) - self.channel.invalidate_cache() + self.channel.invalidate_recordset() self.assertEqual([s.id for s in self.channel.slide_ids], [self.slide.id, self.slide_3.id, self.category.id, self.slide_2.id]) self.assertEqual(self.slide.sequence, 1) @@ -202,8 +202,8 @@ class TestSequencing(slides_common.SlidesCase): 'is_published': True, 'sequence': 2, }) - new_category.flush() - self.channel.invalidate_cache() + self.env.flush_all() + self.channel.invalidate_recordset() self.channel._resequence_slides(self.slide_3, force_category=new_category) self.assertEqual(self.slide.sequence, 1) self.assertEqual(new_category.sequence, 2) diff --git a/addons/website_slides/tests/test_statistics.py b/addons/website_slides/tests/test_statistics.py index a55a667254d..c98f9366cf0 100644 --- a/addons/website_slides/tests/test_statistics.py +++ b/addons/website_slides/tests/test_statistics.py @@ -33,7 +33,7 @@ class TestChannelStatistics(common.SlidesCase): self.assertTrue(channel_asportal.partner_has_new_content) (self.slide | self.slide_2).write({'date_published': fields.Datetime.now() + relativedelta(days=-8)}) - channel_asportal.invalidate_cache(['partner_has_new_content']) + channel_asportal.invalidate_recordset(['partner_has_new_content']) self.assertFalse(channel_asportal.partner_has_new_content) @mute_logger('odoo.models') @@ -51,7 +51,7 @@ class TestChannelStatistics(common.SlidesCase): channel_publisher.action_add_member() self.assertEqual(channel_publisher.members_count, 1) channel_publisher._action_add_members(self.user_emp.partner_id) - channel_publisher.invalidate_cache(['partner_ids']) + channel_publisher.invalidate_recordset(['partner_ids']) self.assertEqual(channel_publisher.members_count, 2) self.assertEqual(channel_publisher.partner_ids, self.user_officer.partner_id | self.user_emp.partner_id) @@ -69,7 +69,7 @@ class TestChannelStatistics(common.SlidesCase): self.assertEqual(channel_emp.completion, 0) slides_emp.action_mark_completed() - channel_emp.invalidate_cache() + channel_emp.invalidate_recordset() self.assertEqual( channel_emp.completion, math.ceil(100.0 * len(slides_emp) / len(channel_publisher.slide_content_ids))) @@ -92,7 +92,7 @@ class TestChannelStatistics(common.SlidesCase): def test_channel_user_statistics_complete_check_member(self): slides = (self.slide | self.slide_2) slides.write({'is_preview': True}) - slides.flush(['is_preview']) + slides.flush_model() slides_emp = slides.with_user(self.user_emp) slides_emp.read(['name']) with self.assertRaises(UserError): @@ -102,7 +102,7 @@ class TestChannelStatistics(common.SlidesCase): def test_channel_user_statistics_view_check_member(self): slides = (self.slide | self.slide_2) slides.write({'is_preview': True}) - slides.flush(['is_preview']) + slides.flush_model() slides_emp = slides.with_user(self.user_emp) slides_emp.read(['name']) with self.assertRaises(UserError): @@ -115,7 +115,7 @@ class TestSlideStatistics(common.SlidesCase): def test_slide_user_statistics(self): channel_publisher = self.channel.with_user(self.user_officer) channel_publisher._action_add_members(self.user_emp.partner_id) - channel_publisher.invalidate_cache(['partner_ids']) + channel_publisher.invalidate_recordset(['partner_ids']) slide_emp = self.slide.with_user(self.user_emp) self.assertEqual(slide_emp.likes, 0) diff --git a/addons/website_slides/tests/test_ui_wslides.py b/addons/website_slides/tests/test_ui_wslides.py index 2062a788ac1..b392268c883 100644 --- a/addons/website_slides/tests/test_ui_wslides.py +++ b/addons/website_slides/tests/test_ui_wslides.py @@ -100,7 +100,6 @@ class TestUi(TestUICommon): def test_course_member_employee(self): user_demo = self.user_demo - user_demo.flush() user_demo.write({ 'karma': 1, 'groups_id': [(6, 0, self.env.ref('base.group_user').ids)] @@ -114,7 +113,6 @@ class TestUi(TestUICommon): def test_course_member_elearning_officer(self): user_demo = self.user_demo - user_demo.flush() user_demo.write({ 'karma': 1, 'groups_id': [(6, 0, (self.env.ref('base.group_user') | self.env.ref('website_slides.group_website_slides_officer')).ids)] @@ -128,7 +126,6 @@ class TestUi(TestUICommon): def test_course_member_portal(self): user_portal = self.user_portal - user_portal.flush() user_portal.karma = 1 self.browser_js( @@ -140,7 +137,6 @@ class TestUi(TestUICommon): def test_full_screen_edition_website_publisher(self): # group_website_designer user_demo = self.env.ref('base.user_demo') - user_demo.flush() user_demo.write({ 'groups_id': [(5, 0), (4, self.env.ref('base.group_user').id), (4, self.env.ref('website.group_website_publisher').id)] }) @@ -157,7 +153,6 @@ class TestUiPublisher(HttpCaseWithUserDemo): def test_course_publisher_elearning_manager(self): user_demo = self.user_demo - user_demo.flush() user_demo.write({ 'groups_id': [ (5, 0), @@ -179,7 +174,6 @@ class TestUiPublisherYoutube(HttpCaseWithUserDemo): def test_course_member_yt_employee(self): # remove membership because we need to be able to join the course during the tour user_demo = self.user_demo - user_demo.flush() user_demo.write({ 'groups_id': [(5, 0), (4, self.env.ref('base.group_user').id)] }) @@ -193,7 +187,6 @@ class TestUiPublisherYoutube(HttpCaseWithUserDemo): def test_course_publisher_elearning_manager(self): user_demo = self.user_demo - user_demo.flush() user_demo.write({ 'groups_id': [(5, 0), (4, self.env.ref('base.group_user').id), (4, self.env.ref('website_slides.group_website_slides_manager').id)] }) diff --git a/addons/website_slides_survey/tests/test_course_certification_failure.py b/addons/website_slides_survey/tests/test_course_certification_failure.py index 60f5eca9dc6..390553d7f38 100644 --- a/addons/website_slides_survey/tests/test_course_certification_failure.py +++ b/addons/website_slides_survey/tests/test_course_certification_failure.py @@ -58,7 +58,7 @@ class TestCourseCertificationFailureFlow(TestSurveyCommon): # Step 3: add public user as member of the channel self.channel._action_add_members(self.user_public.partner_id) # forces recompute of partner_ids as we create directly in relation - self.channel.invalidate_cache() + self.channel.invalidate_model() slide_partner = self.slide_certification._action_set_viewed(self.user_public.partner_id) self.slide_certification.with_user(self.user_public)._generate_certification_url() @@ -69,7 +69,7 @@ class TestCourseCertificationFailureFlow(TestSurveyCommon): self.assertFalse(slide_partner.survey_scoring_success, 'Quizz should not be marked as passed with wrong answers') # forces recompute of partner_ids as we delete directly in relation - self.channel.invalidate_cache() + self.channel.invalidate_model() self.assertIn(self.user_public.partner_id, self.channel.partner_ids, 'Public user should still be a member of the course because they still have attempts left') # Step 5: simulate a 'retry' @@ -84,13 +84,13 @@ class TestCourseCertificationFailureFlow(TestSurveyCommon): # Step 6: fill in the new user_input with wrong answers again self.fill_in_answer(retry_user_input, certification.question_ids) # forces recompute of partner_ids as we delete directly in relation - self.channel.invalidate_cache() + self.channel.invalidate_model() self.assertNotIn(self.user_public.partner_id, self.channel.partner_ids, 'Public user should have been kicked out of the course because they failed their last attempt') # Step 7: add public user as member of the channel once again self.channel._action_add_members(self.user_public.partner_id) # forces recompute of partner_ids as we create directly in relation - self.channel.invalidate_cache() + self.channel.invalidate_model() self.assertIn(self.user_public.partner_id, self.channel.partner_ids, 'Public user should be a member of the course once again') new_slide_partner = self.slide_certification._action_set_viewed(self.user_public.partner_id) @@ -101,7 +101,7 @@ class TestCourseCertificationFailureFlow(TestSurveyCommon): self.fill_in_answer(new_slide_partner.user_input_ids.filtered(lambda user_input: user_input.state != 'done')[0], certification.question_ids, good_answers=True) self.assertTrue(new_slide_partner.survey_scoring_success, 'Quizz should be marked as passed with correct answers') # forces recompute of partner_ids as we delete directly in relation - self.channel.invalidate_cache() + self.channel.invalidate_model() self.assertIn(self.user_public.partner_id, self.channel.partner_ids, 'Public user should still be a member of the course') def fill_in_answer(self, answer, questions, good_answers=False): diff --git a/odoo/addons/test_access_rights/tests/test_access_monetary_related.py b/odoo/addons/test_access_rights/tests/test_access_monetary_related.py index 3c9744f59a3..4e497b1db6e 100644 --- a/odoo/addons/test_access_rights/tests/test_access_monetary_related.py +++ b/odoo/addons/test_access_rights/tests/test_access_monetary_related.py @@ -30,7 +30,7 @@ class TestMonetaryAccess(TransactionCaseWithUserDemo): self.assertEqual(new_user.monetary, 1/3, "Because of previous point, no rounding was done.") - new_user.invalidate_cache() + self.env.invalidate_all() self.assertEqual(new_user.currency_id.rounding, 0.01, "We now get the correct currency.") diff --git a/odoo/addons/test_access_rights/tests/test_check_access.py b/odoo/addons/test_access_rights/tests/test_check_access.py index 0e85ea8e41f..7cf3d383e30 100644 --- a/odoo/addons/test_access_rights/tests/test_check_access.py +++ b/odoo/addons/test_access_rights/tests/test_check_access.py @@ -35,7 +35,7 @@ class TestAccess(odoo.tests.HttpCase): # at this point, some fields might already be loaded in cache. # if so, it means we would bypass the ACL when trying to read the field # while this is bad, this is not the object of this test - self.internal_user_partner.invalidate_cache(fnames=['active']) + self.internal_user_partner.invalidate_model(['active']) # from portal's _document_check_access: document.check_access_rights('read') document.check_access_rule('read') @@ -54,5 +54,5 @@ class TestAccess(odoo.tests.HttpCase): #Invalide cache in case the name is already there #and will not trigget check_access_rights when #the name_get will access the name - self.document.invalidate_cache(fnames=['name']) + self.document.invalidate_model(['name']) self.assertEqual(res[0][1], "Need help here") diff --git a/odoo/addons/test_access_rights/tests/test_feedback.py b/odoo/addons/test_access_rights/tests/test_feedback.py index 6ef9a35b509..e74e93066fd 100644 --- a/odoo/addons/test_access_rights/tests/test_feedback.py +++ b/odoo/addons/test_access_rights/tests/test_feedback.py @@ -107,8 +107,8 @@ class TestACLFeedback(Feedback): }) self.record = self.env['test_access_right.some_obj'].create({'val': 5}) # values are in cache, clear them up for the test - ACL.flush() - ACL.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() def test_no_groups(self): """ Operation is never allowed @@ -390,8 +390,8 @@ Note: this might be a multi-company issue. Contact your administrator to request access if necessary.""" % (self.record.display_name, self.record.id, self.record.sudo().company_id.display_name, self.user.name, self.user.id) ) p = self.env['test_access_right.parent'].create({'obj_id': self.record.id}) - p.flush() - p.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() with self.assertRaisesRegex( AccessError, r"Implicitly accessed through 'Object for testing related access rights' \(test_access_right.parent\)\.", diff --git a/odoo/addons/test_access_rights/tests/test_ir_rules.py b/odoo/addons/test_access_rights/tests/test_ir_rules.py index e19e1284015..dc2826123be 100644 --- a/odoo/addons/test_access_rights/tests/test_ir_rules.py +++ b/odoo/addons/test_access_rights/tests/test_ir_rules.py @@ -44,7 +44,7 @@ class TestRules(TransactionCase): self.assertEqual(browse1.val, 1) # but this should - browse1.invalidate_cache(['val']) + browse1.invalidate_model(['val']) with self.assertRaises(AccessError): self.assertEqual(browse2.val, -1) @@ -64,7 +64,7 @@ class TestRules(TransactionCase): browse1 = env['test_access_right.some_obj'].browse(self.id1) # everything should blow up - (browse1 + browse2).invalidate_cache(['val']) + (browse1 + browse2).invalidate_model(['val']) with self.assertRaises(AccessError): self.assertEqual(browse2.val, -1) with self.assertRaises(AccessError): @@ -80,21 +80,21 @@ class TestRules(TransactionCase): # check the container as the public user container_user = container_admin.with_user(self.browse_ref('base.public_user')) - container_user.invalidate_cache(['some_ids']) + container_user.invalidate_model(['some_ids']) self.assertItemsEqual(container_user.some_ids.ids, [self.id1]) # this should not fail container_user.write({'some_ids': [Command.set(ids)]}) - container_user.invalidate_cache(['some_ids']) + container_user.invalidate_model(['some_ids']) self.assertItemsEqual(container_user.some_ids.ids, [self.id1]) - container_admin.invalidate_cache(['some_ids']) + container_admin.invalidate_model(['some_ids']) self.assertItemsEqual(container_admin.some_ids.ids, ids) # this removes all records container_user.write({'some_ids': [Command.clear()]}) - container_user.invalidate_cache(['some_ids']) + container_user.invalidate_model(['some_ids']) self.assertItemsEqual(container_user.some_ids.ids, []) - container_admin.invalidate_cache(['some_ids']) + container_admin.invalidate_model(['some_ids']) self.assertItemsEqual(container_admin.some_ids.ids, []) def test_access_rule_performance(self): diff --git a/odoo/addons/test_assetsbundle/tests/test_assetsbundle.py b/odoo/addons/test_assetsbundle/tests/test_assetsbundle.py index d00fd2528df..e1d50d0f9c4 100644 --- a/odoo/addons/test_assetsbundle/tests/test_assetsbundle.py +++ b/odoo/addons/test_assetsbundle/tests/test_assetsbundle.py @@ -692,7 +692,7 @@ class TestAssetsBundleInBrowser(HttpCase): 'arch': view_arch, 'inherit_id': self.browse_ref('test_assetsbundle.bundle1').id, }) - self.env.user.flush() + self.env.flush_all() self.browser_js( "/test_assetsbundle/js", @@ -782,9 +782,9 @@ class TestAssetsBundleWithIRAMock(FileTouchable): # has really been modified. If we do not update the write_date to a posterior date, we are # not able to reproduce the case where we compile this bundle again without changing # anything. - self.env['ir.attachment'].flush(['checksum', 'write_date']) + self.env['ir.attachment'].flush_model(['checksum', 'write_date']) self.cr.execute("update ir_attachment set write_date=clock_timestamp() + interval '10 seconds' where id = (select max(id) from ir_attachment)") - self.env['ir.attachment'].invalidate_cache(['write_date']) + self.env['ir.attachment'].invalidate_model(['write_date']) # Compile a fourth time, without changes self._bundle(self._get_asset(), False, False) diff --git a/odoo/addons/test_auth_custom/tests/test_endpoints.py b/odoo/addons/test_auth_custom/tests/test_endpoints.py index 8a7b51ca3c9..4a688f0edbd 100644 --- a/odoo/addons/test_auth_custom/tests/test_endpoints.py +++ b/odoo/addons/test_auth_custom/tests/test_endpoints.py @@ -14,7 +14,7 @@ class TestCustomAuth(HttpCase): self.assertEqual(e['data']['name'], 'odoo.exceptions.AccessDenied') # but preflight should work - self.env['base'].flush() + self.env.flush_all() url = f"{self.base_url()}/test_auth_custom/json" r = self.opener.options(url, headers={ 'Origin': 'localhost', @@ -33,7 +33,7 @@ class TestCustomAuth(HttpCase): self.assertEqual(r.status_code, HTTPStatus.FORBIDDEN) # but preflight should work - self.env['base'].flush() + self.env.flush_all() url = f"{self.base_url()}/test_auth_custom/http" r = self.opener.options(url, headers={ 'Origin': 'localhost', diff --git a/odoo/addons/test_impex/tests/test_export.py b/odoo/addons/test_impex/tests/test_export.py index 2b97a281bfb..cf10c68acca 100644 --- a/odoo/addons/test_impex/tests/test_export.py +++ b/odoo/addons/test_impex/tests/test_export.py @@ -25,7 +25,7 @@ class CreatorCase(common.TransactionCase): def export(self, value, fields=('value',), context=None): record = self.make(value, context=context) - record.invalidate_cache() + self.env.invalidate_all() return record._export_rows([f.split('/') for f in fields]) class test_xids(CreatorCase): @@ -40,7 +40,7 @@ class test_xids(CreatorCase): 'model': self.model_name, 'res_id': record.id, }) - record.invalidate_cache() + self.env.invalidate_all() self.assertEqual( record._export_rows([['id'], ['value']]), [[u'x', True]] @@ -358,7 +358,7 @@ class test_m2o(CreatorCase): | self.make(m2o) | self.make(m2o) ) - records.invalidate_cache() + self.env.invalidate_all() xp = [r[0] for r in records._export_rows([['value', 'id']])] self.assertEqual(len(xp), 4) self.assertRegex( @@ -662,7 +662,7 @@ class test_m2m(CreatorCase): }).complete_name for sub in r.value ] - r.invalidate_cache() + self.env.invalidate_all() self.assertEqual( r._export_rows([['value', 'id']]), @@ -728,7 +728,7 @@ class test_xid_perfs(common.TransactionCase): Model = self.env['export.integer'] for i in range(10000): Model.create({'value': i}) - Model.invalidate_cache() + self.env.invalidate_all() records = Model.search([]) self.profile.runcall(records._export_rows, [['id'], ['value']]) @@ -738,7 +738,7 @@ class test_xid_perfs(common.TransactionCase): Model = self.env['export.many2one'] for _ in range(10000): Model.create({'value': rid}) - Model.invalidate_cache() + self.env.invalidate_all() records = Model.search([]) self.profile.runcall(records._export_rows, [['id'], ['value','id']]) @@ -750,7 +750,7 @@ class test_xid_perfs(common.TransactionCase): Model.create({ 'value': Integer.create({'value': i}).id }) - Model.invalidate_cache() + self.env.invalidate_all() records = Model.search([]) self.profile.runcall(records._export_rows, [['id'], ['value', 'id']]) diff --git a/odoo/addons/test_inherits/tests/test_inherits.py b/odoo/addons/test_inherits/tests/test_inherits.py index b3591928b2d..1b5829ade75 100644 --- a/odoo/addons/test_inherits/tests/test_inherits.py +++ b/odoo/addons/test_inherits/tests/test_inherits.py @@ -54,14 +54,14 @@ class test_inherits(common.TransactionCase): self.assertTrue(all(box.line_ids._ids)) self.assertEqual(box.line_ids.mapped('name'), ['Line 1']) self.assertEqual(box.line_ids, box.unit_id.line_ids) - box.flush() - box.invalidate_cache(['line_ids']) + self.env.flush_all() + box.invalidate_model(['line_ids']) box.write({'line_ids': [Command.create({'name': 'Line 2'})]}) self.assertTrue(all(box.line_ids._ids)) self.assertEqual(box.line_ids.mapped('name'), ['Line 1', 'Line 2']) self.assertEqual(box.line_ids, box.unit_id.line_ids) - box.flush() - box.invalidate_cache(['line_ids']) + self.env.flush_all() + box.invalidate_model(['line_ids']) box.write({'line_ids': [Command.update(box.line_ids[0].id, {'name': 'First line'})]}) self.assertTrue(all(box.line_ids._ids)) self.assertEqual(box.line_ids.mapped('name'), ['First line', 'Line 2']) diff --git a/odoo/addons/test_new_api/models/test_new_api.py b/odoo/addons/test_new_api/models/test_new_api.py index 320b81a4836..713301dd37d 100644 --- a/odoo/addons/test_new_api/models/test_new_api.py +++ b/odoo/addons/test_new_api/models/test_new_api.py @@ -177,7 +177,7 @@ class Message(models.Model): if operator not in ('=', '!=', '<', '<=', '>', '>=', 'in', 'not in'): return [] # retrieve all the messages that match with a specific SQL query - self.flush(['body']) + self.flush_model(['body']) query = """SELECT id FROM "%s" WHERE char_length("body") %s %%s""" % \ (self._table, operator) self.env.cr.execute(query, (value,)) diff --git a/odoo/addons/test_new_api/tests/test_new_fields.py b/odoo/addons/test_new_api/tests/test_new_fields.py index 05e2ade2b32..a8c28253f4c 100644 --- a/odoo/addons/test_new_api/tests/test_new_fields.py +++ b/odoo/addons/test_new_api/tests/test_new_fields.py @@ -30,7 +30,7 @@ class TestFields(TransactionCaseWithUserDemo): self.env.ref('test_new_api.discussion_0').write({'participants': [Command.link(self.user_demo.id)]}) # YTI FIX ME: The cache shouldn't be inconsistent (rco is gonna fix it) # self.env.ref('test_new_api.discussion_0').participants -> 1 user - # self.env.ref('test_new_api.discussion_0').invalidate_cache() + # self.env.ref('test_new_api.discussion_0').invalidate() # self.env.ref('test_new_api.discussion_0').with_context(active_test=False).participants -> 2 users self.env.ref('test_new_api.message_0_1').write({'author': self.user_demo.id}) @@ -149,7 +149,7 @@ class TestFields(TransactionCaseWithUserDemo): """ check definition of custom computed fields """ # Flush demo user before creating a new ir.model.fields to avoid # a deadlock - self.user_demo.flush() + self.env.flush_all() self.env['ir.model.fields'].create({ 'name': 'x_bool_false_computed', 'model_id': self.env.ref('test_new_api.model_test_new_api_message').id, @@ -317,7 +317,7 @@ class TestFields(TransactionCaseWithUserDemo): # switch message from discussion, and check again # See YTI FIXME - discussion1.invalidate_cache() + self.env.invalidate_all() discussion2 = discussion1.copy({'name': 'Another discussion'}) message2 = discussion1.messages[0] @@ -405,7 +405,7 @@ class TestFields(TransactionCaseWithUserDemo): # to test the below access error. Otherwise the above create calls set in the cache the information needed # to compute `company_type` ('is_company'), and doesn't need to trigger a read. # We need to force the read in order to test the security access - User.invalidate_cache() + self.env.invalidate_all() # group users as a recordset, and read them as user demo users = (user1 + user2 + user3).with_user(self.user_demo) user1, user2, user3 = users @@ -506,7 +506,7 @@ class TestFields(TransactionCaseWithUserDemo): def test_12_cascade(self): """ test computed field depending on computed field """ message = self.env.ref('test_new_api.message_0_0') - message.invalidate_cache() + self.env.invalidate_all() double_size = message.double_size self.assertEqual(double_size, message.size) @@ -523,7 +523,7 @@ class TestFields(TransactionCaseWithUserDemo): self.env['ir.config_parameter'].set_param('test_new_api.full_name', 'name1,name2') # this must re-evaluate the field's dependencies - self.env['base'].flush() + self.env.flush_all() self.registry.setup_models(self.cr) self.assertEqual(self.registry.field_depends[Model.full_name], ('name1', 'name2')) @@ -707,7 +707,7 @@ class TestFields(TransactionCaseWithUserDemo): def test_15_constraint(self): """ test new-style Python constraints """ discussion = self.env.ref('test_new_api.discussion_0') - discussion.flush() + self.env.flush_all() # remove oneself from discussion participants: we can no longer create # messages in discussion @@ -727,7 +727,6 @@ class TestFields(TransactionCaseWithUserDemo): self.assertTrue(discussion.messages) with self.assertRaises(ValidationError): discussion.name = "X" - discussion.flush() def test_15_constraint_inverse(self): """ test constraint method on normal field and field with inverse """ @@ -783,12 +782,12 @@ class TestFields(TransactionCaseWithUserDemo): def test_16_compute_unassigned_access_error(self): # create two records records = self.env['test_new_api.compute.unassigned'].create([{}, {}]) - records.flush() + self.env.flush_all() # alter access rights: regular users cannot read 'records' access = self.env.ref('test_new_api.access_test_new_api_compute_unassigned') access.perm_read = False - access.flush() + self.env.flush_all() # switch to environment with user demo records = records.with_user(self.user_demo) @@ -813,13 +812,13 @@ class TestFields(TransactionCaseWithUserDemo): # - fetch records[1].bars -> access error records[0].foo = "assign" records[1].foo = "x" - records.flush() + self.env.flush_all() # try the other way around, too - records.env.cache.invalidate() + self.env.invalidate_all() records[0].foo = "x" records[1].foo = "assign" - records.flush() + self.env.flush_all() def test_20_float(self): """ test rounding of float fields """ @@ -828,14 +827,14 @@ class TestFields(TransactionCaseWithUserDemo): # 2.49609375 (exact float) must be rounded to 2.5 record.write({'number': 2.49609375}) - record.flush() + self.env.flush_all() self.cr.execute(query, [record.id, '2.5']) self.assertTrue(self.cr.rowcount) self.assertEqual(record.number, 2.5) # 1.1 (1.1000000000000000888178420 in float) must be 1.1 in database record.write({'number': 1.1}) - record.flush() + self.env.flush_all() self.cr.execute(query, [record.id, '1.1']) self.assertTrue(self.cr.rowcount) self.assertEqual(record.number, 1.1) @@ -861,7 +860,7 @@ class TestFields(TransactionCaseWithUserDemo): self.assertIn(record.amount, [ramount, samount], msg) # check the value in the database - record.flush() + self.env.flush_all() self.cr.execute('SELECT amount FROM test_new_api_mixed WHERE id=%s', [record.id]) value = self.cr.fetchone()[0] self.assertEqual(value, samount, msg) @@ -914,7 +913,7 @@ class TestFields(TransactionCaseWithUserDemo): def check(value): self.assertEqual(record.total, value) - record.flush() + self.env.flush_all() self.cr.execute('SELECT total FROM test_new_api_monetary_order WHERE id=%s', [record.id]) [total] = self.cr.fetchone() self.assertEqual(total, value) @@ -1154,7 +1153,7 @@ class TestFields(TransactionCaseWithUserDemo): self.assertEqual(demo_message.discussion.env, demo_env) # See YTI FIXME - message.discussion.invalidate_cache() + self.env.invalidate_all() # assign record's parent to a record in demo_env message.discussion = message.discussion.copy({'name': 'Copy'}) @@ -1271,7 +1270,7 @@ class TestFields(TransactionCaseWithUserDemo): self.assertEqual(bar.value1, 1) self.assertEqual(bar.value2, 2) - foo.invalidate_cache() + self.env.invalidate_all() bar.write({'value1': 3, 'value2': 4}) self.assertEqual(foo.value1, 3) self.assertEqual(foo.value2, 4) @@ -1389,7 +1388,7 @@ class TestFields(TransactionCaseWithUserDemo): # regression: duplicated records caused values to be browse(browse(id)) recs = record.create({}) + record + record - recs.invalidate_cache() + self.env.invalidate_all() for rec in recs.with_user(user0): self.assertIsInstance(rec.tag_id.id, int) @@ -1405,7 +1404,7 @@ class TestFields(TransactionCaseWithUserDemo): self.assertEqual(record.with_user(user2).foo, 'default') record.with_user(user0).with_company(company1).foo = 'beta' - record.invalidate_cache() + self.env.invalidate_all() self.assertEqual(record.with_user(user0).foo, 'main') self.assertEqual(record.with_user(user1).foo, 'beta') self.assertEqual(record.with_user(user2).foo, 'default') @@ -1415,7 +1414,6 @@ class TestFields(TransactionCaseWithUserDemo): self.patch(type(record).foo, 'groups', 'base.group_system') with self.assertRaises(AccessError): record.with_user(user0).foo = 'forbidden' - record.flush() user0.write({'groups_id': [Command.link(self.env.ref('base.group_system').id)]}) record.with_user(user0).foo = 'yes we can' @@ -1429,7 +1427,6 @@ class TestFields(TransactionCaseWithUserDemo): }) with self.assertRaises(AccessError): record.with_user(user0).foo = 'forbidden' - record.flush() # create company record and attribute company_record = self.env['test_new_api.company'].create({'foo': 'ABC'}) @@ -1489,14 +1486,14 @@ class TestFields(TransactionCaseWithUserDemo): # set default value to False Property._set_default(field_name, Model._name, False) - Property.flush() - Property.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() test_cases(field_name, operations, False) # set default value to truthy_values[0] Property._set_default(field_name, Model._name, truthy_values[0]) - Property.flush() - Property.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() test_cases(field_name, operations, truthy_values[0]) def test_cases(field_name, operations, default=None): @@ -1901,7 +1898,7 @@ class TestFields(TransactionCaseWithUserDemo): move = self.env['test_new_api.move'].create({ 'line_ids': [Command.create({'quantity': 1}), Command.create({'quantity': 1})], }) - move.flush() + self.env.flush_all() line = move.line_ids[0] new_move = move.new(origin=move) @@ -1923,7 +1920,7 @@ class TestFields(TransactionCaseWithUserDemo): """ Check command on one2many field on new record. """ move = self.env['test_new_api.move'].create({}) line = self.env['test_new_api.move_line'].create({'move_id': move.id, 'quantity': 1}) - move.flush() + self.env.flush_all() new_move = move.new(origin=move) new_line = line.new(origin=line) @@ -2031,8 +2028,8 @@ class TestFields(TransactionCaseWithUserDemo): """ test the cache consistency of a many2many field with a domain """ tag = self.env['test_new_api.multi.tag'].create({'name': 'bar'}) record = self.env['test_new_api.multi'].create({'tags': tag.ids}) - record.flush() - record.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() self.assertEqual(type(record).tags.domain, [('name', 'ilike', 'a')]) @@ -2050,7 +2047,7 @@ class TestFields(TransactionCaseWithUserDemo): def test_70_x2many_write(self): discussion = self.env.ref('test_new_api.discussion_0') # See YTI FIXME - discussion.invalidate_cache() + self.env.invalidate_all() Message = self.env['test_new_api.message'] # There must be 3 messages, 0 important @@ -2083,8 +2080,7 @@ class TestFields(TransactionCaseWithUserDemo): self.assertEqual(demo_discussion.messages, discussion.messages) # See YTI FIXME - discussion.invalidate_cache() - demo_discussion.invalidate_cache() + self.env.invalidate_all() # add a message as user demo messages = demo_discussion.messages @@ -2103,9 +2099,9 @@ class TestFields(TransactionCaseWithUserDemo): move1 = self.env['test_new_api.move'].create({}) move2 = self.env['test_new_api.move'].create({}) line = self.env['test_new_api.move_line'].create({'move_id': move1.id}) - line.flush() + self.env.flush_all() + self.env.invalidate_all() - self.env.cache.invalidate() line.with_context(prefetch_fields=False).move_id # Setting 'move_id' updates the one2many field that is based on it, @@ -2337,7 +2333,7 @@ class TestFields(TransactionCaseWithUserDemo): 'name': 'image', 'image_512': image_w, }) - record.invalidate_cache(fnames=['image_512'], ids=record.ids) + record.invalidate_recordset(['image_512']) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_512))).size, (512, 256)) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image))).size, (4000, 2000)) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_256))).size, (256, 128)) @@ -2345,7 +2341,7 @@ class TestFields(TransactionCaseWithUserDemo): record.write({ 'image_512': image_h, }) - record.invalidate_cache(fnames=['image_512'], ids=record.ids) + record.invalidate_recordset(['image_512']) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_512))).size, (256, 512)) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image))).size, (2000, 4000)) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_256))).size, (128, 256)) @@ -2355,7 +2351,7 @@ class TestFields(TransactionCaseWithUserDemo): 'name': 'image', 'image_256': image_w, }) - record.invalidate_cache(fnames=['image_256'], ids=record.ids) + record.invalidate_recordset(['image_256']) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_512))).size, (512, 256)) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image))).size, (4000, 2000)) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_256))).size, (256, 128)) @@ -2363,7 +2359,7 @@ class TestFields(TransactionCaseWithUserDemo): record.write({ 'image_256': image_h, }) - record.invalidate_cache(fnames=['image_256'], ids=record.ids) + record.invalidate_recordset(['image_256']) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_512))).size, (256, 512)) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image))).size, (2000, 4000)) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_256))).size, (128, 256)) @@ -2405,8 +2401,8 @@ class TestFields(TransactionCaseWithUserDemo): # created, flushed, and first read without context record = self.env['test_new_api.model_binary'].create({'binary': binary_value}) - record.flush() - record.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() record_no_bin_size = record.with_context(bin_size=False) record_bin_size = record.with_context(bin_size=True) @@ -2416,8 +2412,8 @@ class TestFields(TransactionCaseWithUserDemo): # created, flushed, and first read with bin_size=False record_no_bin_size = self.env['test_new_api.model_binary'].with_context(bin_size=False).create({'binary': binary_value}) - record_no_bin_size.flush() - record_no_bin_size.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() record = self.env['test_new_api.model_binary'].browse(record.id) record_bin_size = record.with_context(bin_size=True) @@ -2427,8 +2423,8 @@ class TestFields(TransactionCaseWithUserDemo): # created, flushed, and first read with bin_size=True record_bin_size = self.env['test_new_api.model_binary'].with_context(bin_size=True).create({'binary': binary_value}) - record_bin_size.flush() - record_bin_size.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() record = self.env['test_new_api.model_binary'].browse(record.id) record_no_bin_size = record.with_context(bin_size=False) @@ -2440,8 +2436,8 @@ class TestFields(TransactionCaseWithUserDemo): record = self.env['test_new_api.model_binary'].create({'binary': binary_value}) record_no_bin_size = record.with_context(bin_size=False) record_bin_size = record.with_context(bin_size=True) - record_bin_size.flush() - record_bin_size.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() assertBinaryValue(record, binary_value) assertBinaryValue(record_no_bin_size, binary_value) @@ -2449,8 +2445,8 @@ class TestFields(TransactionCaseWithUserDemo): # check computed binary field with arbitrary Python value record = self.env['test_new_api.model_binary'].create({}) - record.flush() - record.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() record_no_bin_size = record.with_context(bin_size=False) record_bin_size = record.with_context(bin_size=True) @@ -2556,8 +2552,8 @@ class TestFields(TransactionCaseWithUserDemo): def test_99_prefetch_group(self): records = self.env['test_new_api.prefetch'].create([{} for _ in range(10)]) - records.flush() - records.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() with self.assertQueries([""" SELECT @@ -2598,7 +2594,7 @@ class TestFields(TransactionCaseWithUserDemo): records.mapped('hansel') # fetch all fields with prefetch='Hansel and Gretel' records.mapped('gretel') # fetched already - records.invalidate_cache() + self.env.invalidate_all() with self.assertQueryCount(4): records.mapped('name') # fetch all fields with prefetch=True @@ -3689,8 +3685,8 @@ class test_shared_cache(TransactionCaseWithUserDemo): }) self.assertEqual(task.total_amount, 1) - self.env['base'].flush() - task.invalidate_cache() # Start fresh, as it would be the case on 2 different sessions. + self.env.flush_all() + self.env.invalidate_all() # Start fresh, as it would be the case on 2 different sessions. task = task.with_user(self.user_demo) with common.Form(task) as task_form: @@ -3932,8 +3928,8 @@ class TestPrecompute(common.TransactionCase): # warmup model.create({'partner_id': partners[0].id}) - model.flush() - model.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() # check the number of queries: 1 SELECT + 1 INSERT with self.assertQueryCount(2): @@ -3946,8 +3942,8 @@ class TestPrecompute(common.TransactionCase): # warmup model.create({}) - model.flush() - model.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() fnames = [fname for fname, field in currency._fields.items() if field.prefetch] QUERIES = [ diff --git a/odoo/addons/test_new_api/tests/test_onchange.py b/odoo/addons/test_new_api/tests/test_onchange.py index 51939ddb15e..0cd2d9282ac 100644 --- a/odoo/addons/test_new_api/tests/test_onchange.py +++ b/odoo/addons/test_new_api/tests/test_onchange.py @@ -838,7 +838,7 @@ class TestComputeOnchange(common.TransactionCase): Command.create({'name': 'Z'}), ], }) - record.flush() + self.env.flush_all() self.assertEqual(record.child_ids.mapped('name'), list('WXYZ')) self.assertEqual(record.cost, 22) @@ -859,7 +859,7 @@ class TestComputeOnchange(common.TransactionCase): def test_onchange_editable_compute_one2many(self): # create a record with a computed editable field ('edit') on lines record = self.env['test_new_api.compute_editable'].create({'line_ids': [(0, 0, {'value': 7})]}) - record.flush() + self.env.flush_all() line = record.line_ids self.assertRecordValues(line, [{'value': 7, 'edit': 7, 'count': 0}]) @@ -929,8 +929,8 @@ class TestComputeOnchange(common.TransactionCase): {'name': 'bar', 'count': 1}, {'name': 'baz', 'count': 0}, ]) - record.flush() - record.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() self.assertRecordValues(record.line_ids, [ {'name': 'foo', 'count': 1}, {'name': 'bar', 'count': 1}, diff --git a/odoo/addons/test_new_api/tests/test_one2many.py b/odoo/addons/test_new_api/tests/test_one2many.py index 4d323e16f9d..21e25bd7e79 100644 --- a/odoo/addons/test_new_api/tests/test_one2many.py +++ b/odoo/addons/test_new_api/tests/test_one2many.py @@ -57,7 +57,7 @@ class One2manyCase(TransactionCase): return # Invalidate the cache and check again; this crashes if the value # of self.multi.lines in cache contains new records - self.multi.invalidate_cache() + self.env.invalidate_all() self.assertEqual(len(self.multi.lines), 9) self.assertIn("hello", self.multi.lines.mapped('name')) @@ -180,7 +180,7 @@ class One2manyCase(TransactionCase): 'res_model': record0._name, 'res_id': record0.id, }) - attachment.flush() + self.env.flush_all() with self.assertQueryCount(0): self.assertEqual(attachment.name, record0.display_name, "field should be computed") @@ -198,7 +198,7 @@ class One2manyCase(TransactionCase): # writing on res_id must recompute name and invalidate attachment_ids attachment.res_id = record1.id - attachment.flush() + self.env.flush_all() with self.assertQueryCount(0): self.assertEqual(attachment.name, record1.display_name, "field should be recomputed") @@ -247,7 +247,7 @@ class One2manyCase(TransactionCase): # delete parent, and check that recomputation ends parent.unlink() - parent.flush() + self.env.flush_all() def test_compute_stored_many2one_one2many(self): container = self.env['test_new_api.compute.container'].create({'name': 'Foo'}) diff --git a/odoo/addons/test_performance/tests/test_performance.py b/odoo/addons/test_performance/tests/test_performance.py index 8d3d213b815..0032736a73e 100644 --- a/odoo/addons/test_performance/tests/test_performance.py +++ b/odoo/addons/test_performance/tests/test_performance.py @@ -128,12 +128,12 @@ class TestPerformance(SavepointCaseWithUserDemo): # create N lines on rec1: O(N) queries with self.assertQueryCount(3): - rec1.invalidate_cache() + self.env.invalidate_all() rec1.write({'line_ids': [Command.create({'value': 0})]}) self.assertEqual(len(rec1.line_ids), 1) with self.assertQueryCount(5): - rec1.invalidate_cache() + self.env.invalidate_all() rec1.write({'line_ids': [Command.create({'value': val}) for val in range(1, 12)]}) self.assertEqual(len(rec1.line_ids), 12) @@ -141,23 +141,23 @@ class TestPerformance(SavepointCaseWithUserDemo): # update N lines: O(N) queries with self.assertQueryCount(6): - rec1.invalidate_cache() + self.env.invalidate_all() rec1.write({'line_ids': [Command.update(line.id, {'value': 42}) for line in lines[0]]}) self.assertEqual(rec1.line_ids, lines) with self.assertQueryCount(26): - rec1.invalidate_cache() + self.env.invalidate_all() rec1.write({'line_ids': [Command.update(line.id, {'value': 42 + line.id}) for line in lines[1:]]}) self.assertEqual(rec1.line_ids, lines) # delete N lines: O(1) queries with self.assertQueryCount(14): - rec1.invalidate_cache() + self.env.invalidate_all() rec1.write({'line_ids': [Command.delete(line.id) for line in lines[0]]}) self.assertEqual(rec1.line_ids, lines[1:]) with self.assertQueryCount(12): - rec1.invalidate_cache() + self.env.invalidate_all() rec1.write({'line_ids': [Command.delete(line.id) for line in lines[1:]]}) self.assertFalse(rec1.line_ids) self.assertFalse(lines.exists()) @@ -167,12 +167,12 @@ class TestPerformance(SavepointCaseWithUserDemo): # unlink N lines: O(1) queries with self.assertQueryCount(14): - rec1.invalidate_cache() + self.env.invalidate_all() rec1.write({'line_ids': [Command.unlink(line.id) for line in lines[0]]}) self.assertEqual(rec1.line_ids, lines[1:]) with self.assertQueryCount(12): - rec1.invalidate_cache() + self.env.invalidate_all() rec1.write({'line_ids': [Command.unlink(line.id) for line in lines[1:]]}) self.assertFalse(rec1.line_ids) self.assertFalse(lines.exists()) @@ -183,35 +183,35 @@ class TestPerformance(SavepointCaseWithUserDemo): # link N lines from rec1 to rec2: O(1) queries with self.assertQueryCount(8): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'line_ids': [Command.link(line.id) for line in lines[0]]}) self.assertEqual(rec1.line_ids, lines[1:]) self.assertEqual(rec2.line_ids, lines[0]) with self.assertQueryCount(8): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'line_ids': [Command.link(line.id) for line in lines[1:]]}) self.assertFalse(rec1.line_ids) self.assertEqual(rec2.line_ids, lines) with self.assertQueryCount(4): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'line_ids': [Command.link(line.id) for line in lines[0]]}) self.assertEqual(rec2.line_ids, lines) with self.assertQueryCount(4): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'line_ids': [Command.link(line.id) for line in lines[1:]]}) self.assertEqual(rec2.line_ids, lines) # empty N lines in rec2: O(1) queries with self.assertQueryCount(13): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'line_ids': [Command.clear()]}) self.assertFalse(rec2.line_ids) with self.assertQueryCount(3): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'line_ids': [Command.clear()]}) self.assertFalse(rec2.line_ids) @@ -220,19 +220,19 @@ class TestPerformance(SavepointCaseWithUserDemo): # set N lines in rec2: O(1) queries with self.assertQueryCount(8): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'line_ids': [Command.set(lines[0].ids)]}) self.assertEqual(rec1.line_ids, lines[1:]) self.assertEqual(rec2.line_ids, lines[0]) with self.assertQueryCount(6): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'line_ids': [Command.set(lines.ids)]}) self.assertFalse(rec1.line_ids) self.assertEqual(rec2.line_ids, lines) with self.assertQueryCount(4): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'line_ids': [Command.set(lines.ids)]}) self.assertEqual(rec2.line_ids, lines) @@ -256,12 +256,12 @@ class TestPerformance(SavepointCaseWithUserDemo): # create N tags on rec1: O(N) queries with self.assertQueryCount(4): - rec1.invalidate_cache() + self.env.invalidate_all() rec1.write({'tag_ids': [Command.create({'name': 0})]}) self.assertEqual(len(rec1.tag_ids), 1) with self.assertQueryCount(4): - rec1.invalidate_cache() + self.env.invalidate_all() rec1.write({'tag_ids': [Command.create({'name': val}) for val in range(1, 12)]}) self.assertEqual(len(rec1.tag_ids), 12) @@ -269,23 +269,23 @@ class TestPerformance(SavepointCaseWithUserDemo): # update N tags: O(N) queries with self.assertQueryCount(3): - rec1.invalidate_cache() + self.env.invalidate_all() rec1.write({'tag_ids': [Command.update(tag.id, {'name': 'X'}) for tag in tags[0]]}) self.assertEqual(rec1.tag_ids, tags) with self.assertQueryCount(3): - rec1.invalidate_cache() + self.env.invalidate_all() rec1.write({'tag_ids': [Command.update(tag.id, {'name': 'X'}) for tag in tags[1:]]}) self.assertEqual(rec1.tag_ids, tags) # delete N tags: O(1) queries with self.assertQueryCount(__system__=8, demo=8): - rec1.invalidate_cache() + self.env.invalidate_all() rec1.write({'tag_ids': [Command.delete(tag.id) for tag in tags[0]]}) self.assertEqual(rec1.tag_ids, tags[1:]) with self.assertQueryCount(__system__=8, demo=8): - rec1.invalidate_cache() + self.env.invalidate_all() rec1.write({'tag_ids': [Command.delete(tag.id) for tag in tags[1:]]}) self.assertFalse(rec1.tag_ids) self.assertFalse(tags.exists()) @@ -295,12 +295,12 @@ class TestPerformance(SavepointCaseWithUserDemo): # unlink N tags: O(1) queries with self.assertQueryCount(3): - rec1.invalidate_cache() + self.env.invalidate_all() rec1.write({'tag_ids': [Command.unlink(tag.id) for tag in tags[0]]}) self.assertEqual(rec1.tag_ids, tags[1:]) with self.assertQueryCount(3): - rec1.invalidate_cache() + self.env.invalidate_all() rec1.write({'tag_ids': [Command.unlink(tag.id) for tag in tags[1:]]}) self.assertFalse(rec1.tag_ids) self.assertTrue(tags.exists()) @@ -309,55 +309,55 @@ class TestPerformance(SavepointCaseWithUserDemo): # link N tags from rec1 to rec2: O(1) queries with self.assertQueryCount(3): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'tag_ids': [Command.link(tag.id) for tag in tags[0]]}) self.assertEqual(rec2.tag_ids, tags[0]) with self.assertQueryCount(3): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'tag_ids': [Command.link(tag.id) for tag in tags[1:]]}) self.assertEqual(rec2.tag_ids, tags) with self.assertQueryCount(2): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'tag_ids': [Command.link(tag.id) for tag in tags[1:]]}) self.assertEqual(rec2.tag_ids, tags) # empty N tags in rec2: O(1) queries with self.assertQueryCount(3): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'tag_ids': [Command.clear()]}) self.assertFalse(rec2.tag_ids) self.assertTrue(tags.exists()) with self.assertQueryCount(2): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'tag_ids': [Command.clear()]}) self.assertFalse(rec2.tag_ids) # set N tags in rec2: O(1) queries with self.assertQueryCount(3): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'tag_ids': [Command.set(tags.ids)]}) self.assertEqual(rec2.tag_ids, tags) with self.assertQueryCount(3): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'tag_ids': [Command.set(tags[:8].ids)]}) self.assertEqual(rec2.tag_ids, tags[:8]) with self.assertQueryCount(4): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'tag_ids': [Command.set(tags[4:].ids)]}) self.assertEqual(rec2.tag_ids, tags[4:]) with self.assertQueryCount(3): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'tag_ids': [Command.set(tags.ids)]}) self.assertEqual(rec2.tag_ids, tags) with self.assertQueryCount(2): - rec1.invalidate_cache() + self.env.invalidate_all() rec2.write({'tag_ids': [Command.set(tags.ids)]}) self.assertEqual(rec2.tag_ids, tags) @@ -430,11 +430,11 @@ class TestPerformance(SavepointCaseWithUserDemo): records.mapped('value') with self.assertQueryCount(__system__=2, demo=2): - records.invalidate_cache(['value']) + records.invalidate_model(['value']) records.mapped('value') with self.assertQueryCount(__system__=2, demo=2): - records.invalidate_cache(['value']) + records.invalidate_model(['value']) new_recs = records.browse(records.new(origin=record).id for record in records) new_recs.mapped('value') @@ -463,7 +463,7 @@ class TestPerformance(SavepointCaseWithUserDemo): expected = self.expected_read_group() # use read_group and check the expected result with self.assertQueryCount(__system__=2, demo=2): - model.invalidate_cache() + self.env.invalidate_all() result = model.read_group([], ['partner_id', 'value'], ['partner_id']) self.assertEqual(result, expected) @@ -473,7 +473,7 @@ class TestPerformance(SavepointCaseWithUserDemo): expected = self.expected_read_group() # use read_group and check the expected result with self.assertQueryCount(__system__=1, demo=1): - model.invalidate_cache() + self.env.invalidate_all() result = model.read_group([], ['partner_id', 'value'], ['partner_id']) self.assertEqual(len(result), len(expected)) for res, exp in zip(result, expected): @@ -564,8 +564,8 @@ class TestMapped(TransactionCase): {'name': 'foo%d' % index, 'line_ids': [Command.create({'value': index})]} for index in range(1000) ]) - recs.flush() - recs.invalidate_cache() + self.env.flush_all() + self.env.invalidate_all() # expected same performance as recs.line_ids.mapped('value') with self.assertQueryCount(3):