def _get_mocked_request(self, httprequest=None, extra_headers=None): mocked_request = MockRequest(self.env) # Make sure headers are there, no header in default mocked request :( headers = {"Cookie": "IaMaCookie!", "Api-Key": "I_MUST_STAY_SECRET"} headers.update(extra_headers or {}) httprequest = httprequest or {} httprequest["headers"] = headers mocked_request.request["httprequest"] = httprequest return mocked_request
def test_create_visitor_on_tracked_product(self): self.WebsiteSaleController = WebsiteSale() Visitor = self.env['website.visitor'] Track = self.env['website.track'] self.assertEqual(len(Visitor.search([])), 0, "No visitor at the moment") self.assertEqual(len(Track.search([])), 0, "No track at the moment") product = self.env['product.product'].create({ 'name': 'Storage Box', 'website_published': True, }) with MockRequest(self.env, website=self.website): self.cookies = self.WebsiteSaleController.products_recently_viewed_update( product.id) self.assertEqual( len(Visitor.search([])), 1, "A visitor should be created after visiting a tracked product") self.assertEqual( len(Track.search([])), 1, "A track should be created after visiting a tracked product") with MockRequest(self.env, website=self.website, cookies=self.cookies): self.WebsiteSaleController.products_recently_viewed_update( product.id) self.assertEqual( len(Visitor.search([])), 1, "No visitor should be created after visiting another tracked product" ) self.assertEqual( len(Track.search([])), 1, "No track should be created after visiting the same tracked product before 30 min" ) product = self.env['product.product'].create({ 'name': 'Large Cabinet', 'website_published': True, 'list_price': 320.0, }) with MockRequest(self.env, website=self.website, cookies=self.cookies): self.WebsiteSaleController.products_recently_viewed_update( product.id) self.assertEqual( len(Visitor.search([])), 1, "No visitor should be created after visiting another tracked product" ) self.assertEqual( len(Track.search([])), 2, "A track should be created after visiting another tracked product")
def test_blog_comment(self): """Test comment on blog post with attachment.""" attachment = self.env['ir.attachment'].sudo().create({ 'name': 'some_attachment.pdf', 'res_model': 'mail.compose.message', 'datas': 'test', 'type': 'binary', 'access_token': 'azerty', }) with MockRequest(self.env): PortalChatter().portal_chatter_post( 'blog.post', self.test_blog_post.id, 'Test message blog post', attachment_ids=[attachment.id], attachment_tokens=[attachment.access_token]) self.assertTrue(self.env['mail.message'].sudo().search([ ('model', '=', 'blog.post'), ('attachment_ids', 'in', attachment.ids) ])) second_attachment = self.env['ir.attachment'].sudo().create({ 'name': 'some_attachment.pdf', 'res_model': 'mail.compose.message', 'datas': 'test', 'type': 'binary', 'access_token': 'azerty', }) with self.assertRaises(UserError), MockRequest(self.env): PortalChatter().portal_chatter_post( 'blog.post', self.test_blog_post.id, 'Test message blog post', attachment_ids=[second_attachment.id], attachment_tokens=['wrong_token']) self.assertFalse(self.env['mail.message'].sudo().search([ ('model', '=', 'blog.post'), ('attachment_ids', 'in', second_attachment.ids) ]))
def test_03_public_user_address_and_company(self): ''' Same as test_02 but with public user ''' self._setUp_multicompany_env() so = self._create_so(self.website.user_id.partner_id.id) env = api.Environment(self.env.cr, self.website.user_id.id, {}) # change also website env for `sale_get_order` to not change order partner_id with MockRequest(env, website=self.website.with_env(env), sale_order_id=so.id): # 1. Public user, new billing self.default_address_values['partner_id'] = -1 self.WebsiteSaleController.address(**self.default_address_values) new_partner = so.partner_id self.assertNotEqual( new_partner, self.website.user_id.partner_id, "New billing should have created a new partner and assign it on the SO" ) self.assertEqual( new_partner.company_id, self.website.company_id, "The new partner should get the company of the website") # 2. Public user, edit billing self.default_address_values['partner_id'] = new_partner.id self.WebsiteSaleController.address(**self.default_address_values) self.assertEqual( new_partner.company_id, self.website.company_id, "Public user edited billing (the partner itself) should not get its company modified." )
def test_02_demo_address_and_company(self): ''' This test ensure that the company_id of the address (partner) is correctly set and also, is not wrongly changed. eg: new shipping should use the company of the website and not the one from the admin, and editing a billing should not change its company. ''' self._setUp_multicompany_env() so = self._create_so(self.demo_partner.id) env = api.Environment(self.env.cr, self.demo_user.id, {}) # change also website env for `sale_get_order` to not change order partner_id with MockRequest(env, website=self.website.with_env(env), sale_order_id=so.id): # 1. Logged in user, new shipping self.WebsiteSaleController.address(**self.default_address_values) new_shipping = self._get_last_address(self.demo_partner) self.assertTrue( new_shipping.company_id != self.env.user.company_id, "Logged in user new shipping should not get the company of the sudo() neither the one from it's partner.." ) self.assertEqual(new_shipping.company_id, self.website.company_id, ".. but the one from the website.") # 2. Logged in user, edit billing self.default_address_values['partner_id'] = self.demo_partner.id self.WebsiteSaleController.address(**self.default_address_values) self.assertEqual( self.demo_partner.company_id, self.company_c, "Logged in user edited billing (the partner itself) should not get its company modified." )
def test_03_error_page_debug(self): with MockRequest(self.env, website=self.env['website'].browse(1)): self.base_view.arch = self.base_view.arch.replace( 'I am a generic page', '<t t-esc="15/0"/>') # first call, no debug, traceback should not be visible r = self.url_open(self.page.url) self.assertEqual(r.status_code, 500, "15/0 raise a 500 error page") self.assertNotIn('ZeroDivisionError: division by zero', r.text, "Error should not be shown when not in debug.") # second call, enable debug, traceback should be visible r = self.url_open(self.page.url + '?debug=1') self.assertEqual(r.status_code, 500, "15/0 raise a 500 error page (2)") self.assertIn('ZeroDivisionError: division by zero', r.text, "Error should be shown in debug.") # third call, no explicit debug but it should be enabled by # the session, traceback should be visible r = self.url_open(self.page.url) self.assertEqual(r.status_code, 500, "15/0 raise a 500 error page (2)") self.assertIn('ZeroDivisionError: division by zero', r.text, "Error should be shown in debug.")
def test_01_activate_coupon_with_existing_program(self): order = self.empty_order with MockRequest(self.env, website=self.website, sale_order_id=order.id, website_sale_current_pl=1) as request: self.WebsiteSaleController.cart_update_json(self.largeCabinet.id, set_qty=2) self.WebsiteSaleController.pricelist( self.global_program.rule_ids.code) self.assertEqual( order.amount_total, 576, "The order total should equal 576: 2*320 - 10% discount ") self.assertEqual( len(order.order_line), 2, "There should be 2 lines 1 for the product and 1 for the discount" ) self.WebsiteSaleController.activate_coupon(self.coupon.code) promo_code = request.session.get('pending_coupon_code') self.assertFalse( promo_code, "The promo code should be removed from the pending coupon dict" ) self.assertEqual( order.amount_total, 576, "The order total should equal 576: 2*320 - 0 (free product) - 10%" ) self.assertEqual( len(order.order_line), 3, "There should be 3 lines 1 for the product, 1 for the free product and 1 for the discount" )
def test_process_att_with_request_lang(self): with MockRequest(self.env, website=self.website, context={'lang': 'fr_FR'}): self._test_att('/', {'href': '/fr/'}) self._test_att('/en/', {'href': '/'}) self._test_att('/fr/', {'href': '/fr/'})
def test_01(self): """Test authenticated_partner_id In this case we check that the default service context provider provides no authenticated_partner_id """ # pylint: disable=R7980 class TestServiceNewApi(Component): _inherit = "base.rest.service" _name = "test.partner.service" _usage = "partner" _collection = self._collection_name _description = "test" @restapi.method( [(["/<int:id>/get", "/<int:id>"], "GET")], output_param=restapi.CerberusValidator("_get_partner_schema"), auth="public", ) def get(self, _id): return {"name": self.env["res.partner"].browse(_id).name} self._build_services(self, TestServiceNewApi) controller = self._get_controller_for(TestServiceNewApi) with MockRequest(self.env), controller().service_component( "partner") as service: self.assertFalse(service.work.authenticated_partner_id)
def test_02_update_cart_with_multi_warehouses(self): """ When the user updates his cart and increases a product quantity, if this quantity is not available in the SO's warehouse, a warning should be returned and the quantity updated to its maximum. """ so = self.env['sale.order'].create({ 'partner_id': self.env.user.partner_id.id, 'order_line': [(0, 0, { 'name': self.product_A.name, 'product_id': self.product_A.id, 'product_uom_qty': 5, 'product_uom': self.product_A.uom_id.id, 'price_unit': self.product_A.list_price, })] }) with MockRequest(self.env, website=self.website, sale_order_id=so.id): website_so = self.website.sale_get_order() self.assertEqual( website_so.order_line.product_id.virtual_available, 10, "This quantity should be based on SO's warehouse") values = so._cart_update(product_id=self.product_A.id, line_id=so.order_line.id, set_qty=20) self.assertTrue(values.get('warning', False)) self.assertEqual(values.get('quantity'), 10)
def test_process_att_monolang_route(self): with MockRequest(self.env, website=self.website, multilang=False): # lang not changed in URL but CDN enabled self._test_att('/a', {'href': 'http://test.cdn/a'}) self._test_att('/en/a', {'href': 'http://test.cdn/en/a'}) self._test_att('/b', {'href': 'http://test.cdn/b'}) self._test_att('/en/b', {'href': '/en/b'})
def _get_mocked_request(self, httprequest=None, extra_headers=None): with MockRequest(self.env) as mocked_request: mocked_request.httprequest = httprequest or mocked_request.httprequest headers = {"Cookie": "IaMaCookie!", "Api-Key": "I_MUST_STAY_SECRET"} headers.update(extra_headers or {}) mocked_request.httprequest.headers = headers yield mocked_request
def test_process_attendees_form(self): event = self.env['event.event'].create({ 'name': 'Event Update Type', 'event_type_id': self.event_type_complex.with_user(self.env.user).id, 'date_begin': FieldsDatetime.to_string(datetime.today() + timedelta(days=1)), 'date_end': FieldsDatetime.to_string(datetime.today() + timedelta(days=15)), }) form_details = { '1-name': 'Pixis', '1-email': '*****@*****.**', '1-phone': '+32444444444', '1-event_ticket_id': '2', '1-answer_ids-8': '5', '2-name': 'Geluchat', '2-email': '*****@*****.**', '2-phone': '+32777777777', '2-event_ticket_id': '3', '2-answer_ids-8': '9', '0-answer_ids-3': '7', '0-answer_ids-4': '1', } with MockRequest(self.env): registrations = WebsiteEvent()._process_attendees_form(event, form_details) self.assertEqual(registrations, [ {'name': 'Pixis', 'email': '*****@*****.**', 'phone': '+32444444444', 'event_ticket_id': 2, 'answer_ids': [[4, 5], [4, 7], [4, 1]]}, {'name': 'Geluchat', 'email': '*****@*****.**', 'phone': '+32777777777', 'event_ticket_id': 3, 'answer_ids': [[4, 9], [4, 7], [4, 1]]} ])
def test_create_visitor_on_tracked_product(self): self.WebsiteSaleController = WebsiteSale() Visitor = self.env['website.visitor'] Track = self.env['website.track'] self.assertEqual(len(Visitor.search([])), 0, "No visitor at the moment") self.assertEqual(len(Track.search([])), 0, "No track at the moment") product = self.env.ref('product.product_product_7') with MockRequest(self.env, website=self.website): self.cookies = self.WebsiteSaleController.products_recently_viewed_update( product.id) self.assertEqual( len(Visitor.search([])), 1, "A visitor should be created after visiting a tracked product") self.assertEqual( len(Track.search([])), 1, "A track should be created after visiting a tracked product") with MockRequest(self.env, website=self.website, cookies=self.cookies): self.WebsiteSaleController.products_recently_viewed_update( product.id) self.assertEqual( len(Visitor.search([])), 1, "No visitor should be created after visiting another tracked product" ) self.assertEqual( len(Track.search([])), 1, "No track should be created after visiting the same tracked product before 30 min" ) product = self.env.ref('product.product_product_6') with MockRequest(self.env, website=self.website, cookies=self.cookies): self.WebsiteSaleController.products_recently_viewed_update( product.id) self.assertEqual( len(Visitor.search([])), 1, "No visitor should be created after visiting another tracked product" ) self.assertEqual( len(Track.search([])), 2, "A track should be created after visiting another tracked product")
def test_case_1_app_controller(self): self.core_app_controller = app_main.OpenEduCatAppController() with MockRequest(self.env): self.core_app = self.core_app_controller.compute_app_dashboard_data( ) self.core_app = self.core_app_controller.compute_faculty_dashboard_data( )
def test_process_att_no_route(self): with MockRequest(self.env, website=self.website, context={'lang': 'fr_FR'}, routing=False): # default on multilang=True if route is not /{module}/static/ self._test_att('/web/static/hi', {'href': '/web/static/hi'}) self._test_att('/my-page', {'href': '/fr/my-page'})
def test_process_att_no_website(self): with MockRequest(self.env): # no website so URL rewriting self._test_att('/', {'href': '/'}) self._test_att('/en/', {'href': '/en/'}) self._test_att('/fr/', {'href': '/fr/'}) # no URL rewritting for CDN self._test_att('/a', {'href': '/a'})
def test_pricelist_combination(self): product = self.env['product.product'].create({ 'name': 'Super Product', 'list_price': 100, 'taxes_id': False, }) current_website = self.env['website'].get_current_website() website_pricelist = current_website.get_current_pricelist() website_pricelist.write({ 'discount_policy': 'with_discount', 'item_ids': [(5, 0, 0), (0, 0, { 'applied_on': '1_product', 'product_tmpl_id': product.product_tmpl_id.id, 'min_quantity': 500, 'compute_price': 'percentage', 'percent_price': 63, })] }) promo_pricelist = self.env['product.pricelist'].create({ 'name': 'Super Pricelist', 'discount_policy': 'without_discount', 'item_ids': [(0, 0, { 'applied_on': '1_product', 'product_tmpl_id': product.product_tmpl_id.id, 'base': 'pricelist', 'base_pricelist_id': website_pricelist.id, 'compute_price': 'formula', 'price_discount': 25 })] }) so = self.env['sale.order'].create({ 'partner_id': self.env.user.partner_id.id, 'order_line': [(0, 0, { 'name': product.name, 'product_id': product.id, 'product_uom_qty': 1, 'product_uom': product.uom_id.id, 'price_unit': product.list_price, 'tax_id': False, })] }) sol = so.order_line self.assertEqual(sol.price_total, 100.0) so.pricelist_id = promo_pricelist with MockRequest(self.env, website=current_website, sale_order_id=so.id): so._cart_update(product_id=product.id, line_id=sol.id, set_qty=500) self.assertEqual(sol.price_unit, 37.0, 'Both reductions should be applied') self.assertEqual(sol.price_reduce, 27.75, 'Both reductions should be applied') self.assertEqual(sol.price_total, 13875)
def _get_mocked_request(self, httprequest=None, extra_headers=None): with MockRequest(self.env) as mocked_request: mocked_request.httprequest = httprequest or mocked_request.httprequest headers = {} headers.update(extra_headers or {}) mocked_request.httprequest.headers = headers mocked_request.auth_api_key_id = self.api_key.id mocked_request.make_response = lambda data, **kw: data yield mocked_request
def test_process_att_matching_cdn_and_lang(self): with MockRequest(self.env, website=self.website): # lang prefix is added before CDN self._test_att('/a', {'href': 'http://test.cdn/a'}) self._test_att('/en/a', {'href': 'http://test.cdn/a'}) self._test_att('/fr/a', {'href': 'http://test.cdn/fr/a'}) self._test_att('/b', {'href': 'http://test.cdn/b'}) self._test_att('/en/b', {'href': 'http://test.cdn/b'}) self._test_att('/fr/b', {'href': '/fr/b'})
def _get_mocked_request(self, partner): with MockRequest(self.env) as mocked_request: mocked_request.httprequest.environ.update({ "HTTP_PARTNER_EMAIL": partner.email, "HTTP_WEBSITE_UNIQUE_KEY": self.backend.website_unique_key, }) yield mocked_request
def test_process_att_url_crap(self): with MockRequest(self.env, website=self.website): match = http.root.get_db_router.return_value.bind.return_value.match # #{fragment} is stripped from URL when testing route self._test_att('/x#y?z', {'href': '/x#y?z'}) match.assert_called_with('/x', method='POST', query_args=None) match.reset_calls() self._test_att('/x?y#z', {'href': '/x?y#z'}) match.assert_called_with('/x', method='POST', query_args='y')
def test_cart_update_with_fpos(self): # We will test that the mapping of an 10% included tax by a 0% by a fiscal position is taken into account when updating the cart self.env.user.partner_id.country_id = False current_website = self.env['website'].get_current_website() pricelist = current_website.get_current_pricelist() (self.env['product.pricelist'].search([]) - pricelist).write({'active': False}) # Add 10% tax on product tax10 = self.env['account.tax'].create({'name': "Test tax 10", 'amount': 10, 'price_include': True, 'amount_type': 'percent'}) tax0 = self.env['account.tax'].create({'name': "Test tax 0", 'amount': 0, 'price_include': True, 'amount_type': 'percent'}) test_product = self.env['product.template'].create({ 'name': 'Test Product', 'price': 110, 'taxes_id': [(6, 0, [tax10.id])], }).with_context(website_id=current_website.id) # Add discout of 50% for pricelist pricelist.item_ids = self.env['product.pricelist.item'].create({ 'applied_on': "1_product", 'base': "list_price", 'compute_price': "percentage", 'percent_price': 50, 'product_tmpl_id': test_product.id, }) pricelist.discount_policy = 'without_discount' # Create fiscal position mapping taxes 10% -> 0% fpos = self.env['account.fiscal.position'].create({ 'name': 'test', }) self.env['account.fiscal.position.tax'].create({ 'position_id': fpos.id, 'tax_src_id': tax10.id, 'tax_dest_id': tax0.id, }) so = self.env['sale.order'].create({ 'partner_id': self.env.user.partner_id.id, }) sol = self.env['sale.order.line'].create({ 'name': test_product.name, 'product_id': test_product.product_variant_id.id, 'product_uom_qty': 1, 'product_uom': test_product.uom_id.id, 'price_unit': test_product.list_price, 'order_id': so.id, 'tax_id': [(6, 0, [tax10.id])], }) self.assertEqual(round(sol.price_total), 110.0, "110$ with 10% included tax") so.pricelist_id = pricelist so.fiscal_position_id = fpos sol.product_id_change() with MockRequest(self.env, website=current_website, sale_order_id=so.id): so._cart_update(product_id=test_product.product_variant_id.id, line_id=sol.id, set_qty=1) self.assertEqual(round(sol.price_total), 50, "100$ with 50% discount + 0% tax (mapped from fp 10% -> 0%)")
def test_03_snippets_all_drag_and_drop(self): with MockRequest(self.env, website=self.env['website'].browse(1)): snippets_template = self.env['ir.ui.view'].render_public_asset('website.snippets') html_template = html.fromstring(snippets_template) data_snippet_els = html_template.xpath("//*[@class='o_panel' and not(contains(@class, 'd-none'))]//*[@data-snippet]") blacklist = [ 's_facebook_page', # avoid call to external services (facebook.com) 's_map', # avoid call to maps.google.com ] snippets_names = ','.join(set(el.attrib['data-snippet'] for el in data_snippet_els if el.attrib['data-snippet'] not in blacklist)) self.start_tour("/?enable_editor=1&snippets_names=%s" % snippets_names, "snippets_all_drag_and_drop", login='******', timeout=300)
def test_add_cart_unpublished_product(self): # Try to add an unpublished product product = self.env['product.product'].create({ 'name': 'Test Product', 'sale_ok': True, }) with self.assertRaises(UserError): with MockRequest(product.with_user(self.public_user).env, website=self.website.with_user(self.public_user)): self.WebsiteSaleController.cart_update_json( product_id=product.id, add_qty=1) # public but remove sale_ok product.sale_ok = False product.website_published = True with self.assertRaises(UserError): with MockRequest(product.with_user(self.public_user).env, website=self.website.with_user(self.public_user)): self.WebsiteSaleController.cart_update_json( product_id=product.id, add_qty=1)
def test_03_error_page_debug(self): with MockRequest(self.env, website=self.env['website'].browse(1)): self.base_view.arch = self.base_view.arch.replace( 'I am a generic page', '<t t-esc="15/0"/>') r = self.url_open(self.page.url) self.assertEqual(r.status_code, 500, "15/0 raise a 500 error page") self.assertNotIn('ZeroDivisionError: division by zero', r.text, "Error should not be shown when not in debug.") r = self.url_open(self.page.url + '?debug=1') self.assertEqual(r.status_code, 500, "15/0 raise a 500 error page (2)") self.assertIn('ZeroDivisionError: division by zero', r.text, "Error should be shown in debug.")
def test_01_create_shipping_address_specific_user_account(self): ''' Ensure `website_id` is correctly set (specific_user_account) ''' p = self.env.user.partner_id so = self._create_so(p.id) with MockRequest(self.env, website=self.website, sale_order_id=so.id): self.WebsiteSaleController.address(**self.default_address_values) self.assertFalse(self._get_last_address(p).website_id, "New shipping address should not have a website set on it (no specific_user_account).") self.website.specific_user_account = True self.WebsiteSaleController.address(**self.default_address_values) self.assertEqual(self._get_last_address(p).website_id, self.website, "New shipping address should have a website set on it (specific_user_account).")
def test_recently_viewed_company_changed(self): # Test that, by changing the company of a tracked product, the recently viewed product do not crash new_company = self.env['res.company'].create({ 'name': 'Test Company', }) public_user = self.env.ref('base.public_user') product = self.env['product.product'].create({ 'name': 'Test Product', 'website_published': True, 'sale_ok': True, }) self.website = self.website.with_user(public_user).with_context(website_id=self.website.id) with MockRequest(self.website.env, website=self.website): self.cookies = self.WebsiteSaleController.products_recently_viewed_update(product.id) product.product_tmpl_id.company_id = new_company product.product_tmpl_id.flush_recordset(['company_id']) with MockRequest(self.website.env, website=self.website, cookies=self.cookies): # Should not raise an error res = self.website.env['website.snippet.filter']._get_products_latest_viewed(self.website, 16, [], {}) self.assertFalse(res)
def test_process_att_url_crap(self): with MockRequest(self.env, website=self.website) as request: # #{fragment} is stripped from URL when testing route self._test_att('/x#y?z', {'href': '/x#y?z'}) self.assertEqual( request.httprequest.app._log_call[-1], (('/x',), {'method': 'POST', 'query_args': None}) ) self._test_att('/x?y#z', {'href': '/x?y#z'}) self.assertEqual( request.httprequest.app._log_call[-1], (('/x',), {'method': 'POST', 'query_args': 'y'}) )
def test_04_apply_empty_pl(self): ''' Ensure empty pl code reset the applied pl ''' so = self._create_so(self.env.user.partner_id.id) eur_pl = self.env['product.pricelist'].create({ 'name': 'EUR_test', 'website_id': self.website.id, 'code': 'EUR_test', }) with MockRequest(self.env, website=self.website, sale_order_id=so.id): self.WebsiteSaleController.pricelist('EUR_test') self.assertEqual(so.pricelist_id, eur_pl, "Ensure EUR_test is applied") self.WebsiteSaleController.pricelist('') self.assertNotEqual(so.pricelist_id, eur_pl, "Pricelist should be removed when sending an empty pl code")