OCA reporting engine fork for dev and update.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

194 lines
8.0 KiB

  1. # Copyright 2016 ACSONE SA/NV
  2. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).).
  3. import base64
  4. from base64 import b64decode
  5. import mock
  6. import os
  7. import pkg_resources
  8. import shutil
  9. import tempfile
  10. from contextlib import contextmanager
  11. from odoo import tools
  12. from odoo.tests.common import TransactionCase
  13. from odoo.exceptions import ValidationError
  14. from odoo.addons.base.tests.test_mimetypes import PNG
  15. from ..models.py3o_report import TemplateNotFound
  16. from ..models._py3o_parser_context import format_multiline_value
  17. from base64 import b64encode
  18. import logging
  19. logger = logging.getLogger(__name__)
  20. try:
  21. from genshi.core import Markup
  22. except ImportError:
  23. logger.debug('Cannot import genshi.core')
  24. @contextmanager
  25. def temporary_copy(path):
  26. filname, ext = os.path.splitext(path)
  27. tmp_filename = tempfile.mktemp(suffix='.' + ext)
  28. try:
  29. shutil.copy2(path, tmp_filename)
  30. yield tmp_filename
  31. finally:
  32. os.unlink(tmp_filename)
  33. class TestReportPy3o(TransactionCase):
  34. def setUp(self):
  35. super(TestReportPy3o, self).setUp()
  36. self.env.user.image = PNG
  37. self.report = self.env.ref("report_py3o.res_users_report_py3o")
  38. self.py3o_report = self.env['py3o.report'].create({
  39. 'ir_actions_report_id': self.report.id})
  40. def test_required_py3_filetype(self):
  41. self.assertEqual(self.report.report_type, "py3o")
  42. with self.assertRaises(ValidationError) as e:
  43. self.report.py3o_filetype = False
  44. self.assertEqual(
  45. e.exception.name,
  46. "Field 'Output Format' is required for Py3O report")
  47. def _render_patched(self, result_text='test result', call_count=1):
  48. py3o_report = self.env['py3o.report']
  49. py3o_report_obj = py3o_report.create({
  50. "ir_actions_report_id": self.report.id
  51. })
  52. with mock.patch.object(
  53. py3o_report.__class__, '_create_single_report') as patched_pdf:
  54. result = tempfile.mktemp('.txt')
  55. with open(result, 'w') as fp:
  56. fp.write(result_text)
  57. patched_pdf.side_effect = lambda record, data:\
  58. py3o_report_obj._postprocess_report(
  59. record, result
  60. ) or result
  61. # test the call the the create method inside our custom parser
  62. self.report.render(self.env.user.ids)
  63. self.assertEqual(call_count, patched_pdf.call_count)
  64. # generated files no more exists
  65. self.assertFalse(os.path.exists(result))
  66. def test_reports(self):
  67. res = self.report.render(self.env.user.ids)
  68. self.assertTrue(res)
  69. self.report.py3o_filetype = 'pdf'
  70. def test_report_load_from_attachment(self):
  71. self.report.write({"attachment_use": True,
  72. "attachment": "'my_saved_report'"})
  73. attachments = self.env['ir.attachment'].search([])
  74. self._render_patched()
  75. new_attachments = self.env['ir.attachment'].search([])
  76. created_attachement = new_attachments - attachments
  77. self.assertEqual(1, len(created_attachement))
  78. content = b64decode(created_attachement.datas)
  79. self.assertEqual(b"test result", content)
  80. # put a new content into tha attachement and check that the next
  81. # time we ask the report we received the saved attachment not a newly
  82. # generated document
  83. created_attachement.datas = base64.encodestring(b"new content")
  84. res = self.report.render(self.env.user.ids)
  85. self.assertEqual((b'new content', self.report.py3o_filetype), res)
  86. def test_report_post_process(self):
  87. """
  88. By default the post_process method is in charge to save the
  89. generated report into an ir.attachment if requested.
  90. """
  91. self.report.attachment = "object.name + '.txt'"
  92. ir_attachment = self.env['ir.attachment']
  93. attachements = ir_attachment.search([(1, '=', 1)])
  94. self._render_patched()
  95. attachements = ir_attachment.search([(1, '=', 1)]) - attachements
  96. self.assertEqual(1, len(attachements.ids))
  97. self.assertEqual(self.env.user.name + '.txt', attachements.name)
  98. self.assertEqual(self.env.user._name, attachements.res_model)
  99. self.assertEqual(self.env.user.id, attachements.res_id)
  100. self.assertEqual(b'test result', b64decode(attachements.datas))
  101. @tools.misc.mute_logger('odoo.addons.report_py3o.models.py3o_report')
  102. def test_report_template_configs(self):
  103. # the demo template is specified with a relative path in in the module
  104. # path
  105. tmpl_name = self.report.py3o_template_fallback
  106. flbk_filename = pkg_resources.resource_filename(
  107. "odoo.addons.%s" % self.report.module,
  108. tmpl_name)
  109. self.assertTrue(os.path.exists(flbk_filename))
  110. res = self.report.render(self.env.user.ids)
  111. self.assertTrue(res)
  112. # The generation fails if the template is not found
  113. self.report.module = False
  114. with self.assertRaises(TemplateNotFound), self.env.cr.savepoint():
  115. self.report.render(self.env.user.ids)
  116. # the template can also be provided as an abspath if it's root path
  117. # is trusted
  118. self.report.py3o_template_fallback = flbk_filename
  119. with self.assertRaises(TemplateNotFound):
  120. self.report.render(self.env.user.ids)
  121. with temporary_copy(flbk_filename) as tmp_filename:
  122. self.report.py3o_template_fallback = tmp_filename
  123. tools.config.misc['report_py3o'] = {
  124. 'root_tmpl_path': os.path.dirname(tmp_filename)}
  125. res = self.report.render(self.env.user.ids)
  126. self.assertTrue(res)
  127. # the tempalte can also be provided as a binary field
  128. self.report.py3o_template_fallback = False
  129. with open(flbk_filename, 'rb') as tmpl_file:
  130. tmpl_data = b64encode(tmpl_file.read())
  131. py3o_template = self.env['py3o.template'].create({
  132. 'name': 'test_template',
  133. 'py3o_template_data': tmpl_data,
  134. 'filetype': 'odt'})
  135. self.report.py3o_template_id = py3o_template
  136. self.report.py3o_template_fallback = flbk_filename
  137. res = self.report.render(self.env.user.ids)
  138. self.assertTrue(res)
  139. @tools.misc.mute_logger('odoo.addons.report_py3o.models.py3o_report')
  140. def test_report_template_fallback_validity(self):
  141. tmpl_name = self.report.py3o_template_fallback
  142. flbk_filename = pkg_resources.resource_filename(
  143. "odoo.addons.%s" % self.report.module,
  144. tmpl_name)
  145. # an exising file in a native format is a valid template if it's
  146. self.assertTrue(self.py3o_report._get_template_from_path(
  147. tmpl_name))
  148. self.report.module = None
  149. # a directory is not a valid template..
  150. self.assertFalse(self.py3o_report._get_template_from_path('/etc/'))
  151. self.assertFalse(self.py3o_report._get_template_from_path('.'))
  152. # an vaild template outside the root_tmpl_path is not a valid template
  153. # path
  154. # located in trusted directory
  155. self.report.py3o_template_fallback = flbk_filename
  156. self.assertFalse(self.py3o_report._get_template_from_path(
  157. flbk_filename))
  158. with temporary_copy(flbk_filename) as tmp_filename:
  159. self.assertTrue(self.py3o_report._get_template_from_path(
  160. tmp_filename))
  161. # check security
  162. self.assertFalse(self.py3o_report._get_template_from_path(
  163. 'rm -rf . & %s' % flbk_filename))
  164. # a file in a non native LibreOffice format is not a valid template
  165. with tempfile.NamedTemporaryFile(suffix='.toto')as f:
  166. self.assertFalse(self.py3o_report._get_template_from_path(
  167. f.name))
  168. # non exising files are not valid template
  169. self.assertFalse(self.py3o_report._get_template_from_path(
  170. '/etc/test.odt'))
  171. def test_escape_html_characters_format_multiline_value(self):
  172. self.assertEqual(Markup('&lt;&gt;<text:line-break/>&amp;test;'),
  173. format_multiline_value('<>\n&test;'))