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.

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