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.

202 lines
8.5 KiB

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