Debian Codegraph @

addons/l10n_es_edi_verifactu/tests/common.py

raw symbols SCIP
1 import base64
2 import json
3 import requests
4
5 from unittest import mock
6
7 from odoo import _, release, Command
8 from odoo.tools import file_open, html_sanitize, misc, zeep
9 from odoo.addons.account.tests.common import AccountTestInvoicingCommon
10
11
12 class TestL10nEsEdiVerifactuCommon(AccountTestInvoicingCommon):
13
14 @classmethod
15 @AccountTestInvoicingCommon.setup_country('es')
16 def setUpClass(cls):
17 super().setUpClass()
18
19 fake_db_identifier = '7244834601315494189'
20 db_identifier_function = 'odoo.addons.l10n_es_edi_verifactu.models.verifactu_document.L10nEsEdiVerifactuDocument._get_db_identifier'
21 patch_db_identifier = mock.patch(db_identifier_function, lambda _self: fake_db_identifier)
22 cls.startClassPatcher(patch_db_identifier)
23
24 # Allow to see the full result of AssertionError.
25 cls.maxDiff = None
26
27 cls.other_currency = cls.setup_other_currency('USD')
28
29 certificate_path = 'l10n_es_edi_verifactu/demo/certificates/Certificado_RPJ_A39200019_CERTIFICADO_ENTIDAD_PRUEBAS_5_Pre.p12'
30 cls.certificate = cls.env['certificate.certificate'].create({
31 'content': base64.encodebytes(misc.file_open(certificate_path, 'rb').read()),
32 'pkcs12_password': '1234',
33 'scope': 'verifactu',
34 })
35
36 cls.company = cls.company_data['company']
37 cls.company.write({
38 'country_id': cls.env.ref('base.es').id,
39 'state_id': cls.env.ref('base.state_es_z').id,
40 # Use the VAT / NIF that was used to generate the responses
41 # This is needed to have the correct record identifiers on the invoices
42 'vat': 'ESA39200019',
43 'l10n_es_edi_verifactu_required': True,
44 'l10n_es_edi_verifactu_certificate_ids': [Command.set(cls.certificate.ids)],
45 'l10n_es_edi_verifactu_test_environment': True,
46 })
47 # Create a second Spanish Company. To ensure we set `IndicadorMultiplesOT` correctly
48 cls.company_data_2 = cls.setup_other_company(country_id=cls.env.ref('base.es').id)
49
50 cls.partner_a.write({
51 'vat': 'BE0477472701',
52 'country_id': cls.env.ref('base.be').id,
53 })
54
55 cls.partner_b.write({
56 'vat': 'ESF35999705',
57 })
58
59 cls.product_1 = cls.env['product.product'].create({
60 'name': "Product 1",
61 })
62
63 ChartTemplate = cls.env['account.chart.template'].with_company(cls.company)
64 cls.tax21_goods = ChartTemplate.ref('account_tax_template_s_iva21b')
65 cls.tax21_services = ChartTemplate.ref('account_tax_template_s_iva21s')
66 cls.tax10_goods = ChartTemplate.ref('account_tax_template_s_iva10b')
67 cls.tax10_services = ChartTemplate.ref('account_tax_template_s_iva10s')
68 cls.tax1p4_services_recargo = ChartTemplate.ref('account_tax_template_s_req014')
69 cls.tax5p2_services_recargo = ChartTemplate.ref('account_tax_template_s_req52')
70 cls.tax1_withholding = ChartTemplate.ref('account_tax_template_s_irpf1')
71 cls.tax0_no_sujeto_loc = ChartTemplate.ref('account_tax_template_s_iva_ns')
72 cls.tax0_isp = ChartTemplate.ref('account_tax_template_s_iva0_isp')
73 cls.tax0_exento = ChartTemplate.ref('account_tax_template_s_iva0')
74 cls.tax0_exento_export = ChartTemplate.ref('account_tax_template_s_iva0_g_e')
75 # We create a 'no_sujeto' tax since there is currently no such tax in the standard chart
76 cls.tax0_no_sujeto = cls.tax0_no_sujeto_loc.copy()
77 cls.tax0_no_sujeto.l10n_es_type = 'no_sujeto'
78
79 # Everything in the tests should be possible without being administrator.
80 # We do not want to hide access errors the user may have in production (i.e. with access to the certificates)
81 cls.user.group_ids = [Command.unlink(cls.env.ref('base.group_system').id)]
82
83 # Do not do any zeep operations by default.
84 # I.e. do not do xml / xsd validation during tests (needs network connection to create the client).
85 cls.startClassPatcher(cls._mock_get_zeep_operation(None, None, None))
86
87 # Do avoid updating the test files for every version we just assume that we are in 17.0
88 cls.startClassPatcher(mock.patch.object(release, 'version', '17.0+e'))
89
90 @classmethod
91 def _read_file(cls, path, *args):
92 with file_open(path, *args) as f:
93 content = f.read()
94 return content
95
96 def _json_file_to_dict(self, json_file):
97 json_string = self._read_file(json_file, 'rb')
98 res = json.loads(json_string)
99 return self.replace_ignore(res)
100
101 def _mock_response(self, status_code, response_file, content_type='text/xml;charset=UTF-8'):
102 response = mock.Mock(spec=requests.Response)
103 response.status_code = status_code
104 response.text = self._read_file(response_file)
105 response.content = response.text.encode()
106 response.headers = {
107 'content-type': content_type,
108 }
109 return response
110
111 def _mock_request(self, mock_response):
112 request_function_path = 'odoo.addons.l10n_es_edi_verifactu.models.verifactu_document.L10nEsEdiVerifactuDocument._soap_request'
113 return mock.patch(request_function_path, return_value=mock_response)
114
115 def _mock_get_zeep_operation(self, registration_return_value=None, registration_xml_return_value=None):
116 request_function_path = 'odoo.addons.l10n_es_edi_verifactu.models.verifactu_document._get_zeep_operation'
117
118 def mocked_get_zeep_operation(company, operation):
119 if operation not in ('registration', 'registration_xml'):
120 raise NotImplementedError()
121 function = registration_return_value if operation == 'registration' else registration_xml_return_value
122 return (function, {})
123
124 return mock.patch(request_function_path, mocked_get_zeep_operation)
125
126 def _mock_zeep_registration_operation(self, response_file_json, name=""):
127 # Note: The real result is of type 'odoo.tools.zeep.client.SerialProxy'; here it is a dict
128 zeep_response_dict = json.loads(self._read_file(response_file_json))
129 if name:
130 zeep_response_dict['RespuestaLinea'][0]['IDFactura']['NumSerieFactura'] = name
131 return self._mock_get_zeep_operation(registration_return_value=lambda *args, **kwargs: zeep_response_dict)
132
133 def _mock_zeep_registration_operation_certificate_issue(self):
134 def _raise_certificate_error(*args, **kwargs):
135 certificate_error = "No autorizado. Se ha producido un error al verificar el certificado presentado"
136 raise zeep.exceptions.TransportError(certificate_error)
137
138 return self._mock_get_zeep_operation(registration_return_value=_raise_certificate_error)
139
140 def _mock_cron_trigger(self, cron_trigger_result_dict):
141 trigger_function_path = 'odoo.addons.base.models.ir_cron.IrCron._trigger'
142
143 def _put_at_in_dict(self, at=None):
144 cron_trigger_result_dict['at'] = at
145
146 return mock.patch(trigger_function_path, _put_at_in_dict)
147
148 def _mock_format_document_errors(self, errors, title):
149 """Mock the computation of field `errors` of model 'l10n_es_edi_verifactu.document' from a list of translated errors."""
150 error = {
151 'error_title': title,
152 'errors': errors,
153 }
154 return html_sanitize(self.env['account.move.send']._format_error_html(error))
155
156 def _mock_format_document_generic_errors(self, errors):
157 title = _("Error")
158 return self._mock_format_document_errors(errors, title)
159
160 def _mock_format_document_aeat_errors(self, errors):
161 title = _("The Veri*Factu document contains the following errors according to the AEAT")
162 return self._mock_format_document_errors(errors, title)
163
164 def _mock_format_document_generation_errors(self, errors):
165 title = _("The Veri*Factu document could not be created")
166 return self._mock_format_document_errors(errors, title)
167
168 def _mock_last_document(self, document):
169 # Note: returns the same document for all companies
170 function_path = 'odoo.addons.l10n_es_edi_verifactu.models.res_company.ResCompany._l10n_es_edi_verifactu_get_last_document'
171 return mock.patch(function_path, return_value=(document or self.env['l10n_es_edi_verifactu.document']))
172
173 def _mock_create_date(self, date):
174 return mock.patch.object(self.env.cr, 'now', lambda: date)
175
176 def _create_dummy_invoice(self, name=None, invoice_date=None):
177 # The only values we care about are the ones relevant for the record identifier.
178 invoice_vals = {
179 'move_type': 'out_invoice',
180 'invoice_date': '2019-01-30',
181 'date': '2019-01-30',
182 'partner_id': self.partner_b.id, # Spanish customer
183 'invoice_line_ids': [
184 Command.create({'product_id': self.product_1.id, 'price_unit': 100.0, 'tax_ids': [Command.set(self.tax21_goods.ids)]}),
185 ],
186 }
187
188 # Adjust some values to give the record the needed record identifier
189 if invoice_date is not None:
190 invoice_vals['invoice_date'] = invoice_date
191 if name is not None:
192 invoice_vals['name'] = name
193
194 invoice = self.env['account.move'].create(invoice_vals)
195 invoice.action_post()
196
197 return invoice
198
199 def _mock_zeep_registration_operation_single_accept_no_wait(self):
200 # Note: The real result is of type 'odoo.tools.zeep.client.SerialProxy'; here it is a dict
201 zeep_response_dict = json.loads(self._read_file('l10n_es_edi_verifactu/tests/responses/batch_single_accepted_registration.json'))
202 self.env.company.sudo().l10n_es_edi_verifactu_next_batch_time = False # to not get blocked by the wait time
203
204 def _mock_register_accept(*args, **kwargs):
205 document_id_factura = args[1][0]['RegistroAlta']['IDFactura']
206 response_id_factura = zeep_response_dict['RespuestaLinea'][0]['IDFactura']
207 response_id_factura.update(document_id_factura)
208 return zeep_response_dict
209
210 return self._mock_get_zeep_operation(registration_return_value=_mock_register_accept)