- Do not copy the contextual action nor the submitter role with a template: a copy sharing the action would rewrite or delete the original's. - Make the template ID read-only once fetched from Docuseal: another Docuseal template needs a new entry. - Report an invalid API URL or token, an unexpected (non-JSON) response and a connection dropped mid-response as a readable UserError. - Refuse to email a signature request to contacts without a valid email address (email_normalize), before any call to Docuseal. - Stop logging the field values and the Docuseal response, which hold personal data and the signing links. - Prevent adding mapping lines by hand: they come from Docuseal only. Assisted-By: Claude Opus 5.5 <noreply@anthropic.com>
251 lines
9.9 KiB
Python
251 lines
9.9 KiB
Python
import http.client
|
|
import io
|
|
import json
|
|
import urllib.error
|
|
from unittest import mock
|
|
|
|
from odoo.exceptions import UserError
|
|
from odoo.tests import TransactionCase
|
|
|
|
from odoo.addons.docuseal_signing.models import (
|
|
docuseal_template as docuseal_template_module,
|
|
)
|
|
|
|
from .common import DocusealApiMockMixin
|
|
|
|
|
|
class TestCreateSubmissions(DocusealApiMockMixin, TransactionCase):
|
|
"""Payload sent to the Docuseal API by _create_submissions."""
|
|
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
super().setUpClass()
|
|
|
|
def partner_field(fname):
|
|
return cls.env["ir.model.fields"].search([
|
|
("model", "=", "res.partner"), ("name", "=", fname),
|
|
], limit=1)
|
|
|
|
cls.template = cls.env["docuseal.template"].create({
|
|
"name": "Onboarding",
|
|
"template_id": 777,
|
|
})
|
|
cls.template.submitter_role_id = cls.env["docuseal.template.role"].create({
|
|
"template_id": cls.template.id,
|
|
"name": "Signer",
|
|
})
|
|
for docuseal_name, fname in [
|
|
("full_name", "name"),
|
|
("email", "email"),
|
|
("company_type", "company_type"),
|
|
("birth_date", "create_date"),
|
|
("country", "country_id"),
|
|
("categories", "category_id"),
|
|
("phone", "phone"),
|
|
]:
|
|
cls.env["docuseal.template.field"].create({
|
|
"template_id": cls.template.id,
|
|
"docuseal_field_name": docuseal_name,
|
|
"partner_field_id": partner_field(fname).id,
|
|
})
|
|
|
|
cls.country = cls.env["res.country"].search([], limit=1)
|
|
cls.categories = cls.env["res.partner.category"].create([
|
|
{"name": "Gold"}, {"name": "Silver"},
|
|
])
|
|
cls.partner = cls.env["res.partner"].create({
|
|
"name": "Camille Dupont",
|
|
"email": "camille@example.com",
|
|
"phone": False,
|
|
"country_id": cls.country.id,
|
|
"category_id": cls.categories.ids,
|
|
})
|
|
|
|
def test_submission_payload_conversion(self):
|
|
"""Field values are converted per type and locked when set."""
|
|
self._set_api_config()
|
|
with self._mock_api({"id": 55}):
|
|
results = self.template._create_submissions(self.partner)
|
|
|
|
self.assertEqual(results, [{"id": 55}])
|
|
request = self.requests[0]
|
|
self.assertEqual(
|
|
request["url"], "https://sign.example.com/api/submissions"
|
|
)
|
|
self.assertIn("test-token", request["headers"].values())
|
|
|
|
payload = request["payload"]
|
|
self.assertEqual(payload["template_id"], 777)
|
|
self.assertTrue(payload["send_email"])
|
|
self.assertEqual(len(payload["submitters"]), 1)
|
|
|
|
submitter = payload["submitters"][0]
|
|
self.assertEqual(submitter["name"], "Camille Dupont")
|
|
self.assertEqual(submitter["email"], "camille@example.com")
|
|
self.assertEqual(submitter["role"], "Signer")
|
|
|
|
fields = {field["name"]: field for field in submitter["fields"]}
|
|
self.assertEqual(
|
|
fields["full_name"]["default_value"], "Camille Dupont"
|
|
)
|
|
self.assertTrue(fields["full_name"]["readonly"])
|
|
# selection: human-readable label, not the raw key
|
|
self.assertEqual(fields["company_type"]["default_value"], "Individual")
|
|
self.assertTrue(fields["company_type"]["readonly"])
|
|
# many2one / many2many: display names joined with ", "
|
|
self.assertEqual(
|
|
fields["country"]["default_value"], self.country.display_name
|
|
)
|
|
self.assertEqual(
|
|
fields["categories"]["default_value"],
|
|
", ".join(self.categories.mapped("display_name")),
|
|
)
|
|
# datetime: dd/mm/yyyy
|
|
self.assertEqual(
|
|
fields["birth_date"]["default_value"],
|
|
self.partner.create_date.strftime("%d/%m/%Y"),
|
|
)
|
|
# empty value: sent as "" and left editable for the signer
|
|
self.assertEqual(fields["phone"]["default_value"], "")
|
|
self.assertFalse(fields["phone"]["readonly"])
|
|
|
|
def test_draft_submissions_do_not_send_email(self):
|
|
"""_create_draft_submissions creates pre-filled submissions
|
|
without asking Docuseal to email the signers."""
|
|
self._set_api_config()
|
|
with self._mock_api({"id": 56}):
|
|
self.template._create_draft_submissions(self.partner)
|
|
self.assertFalse(self.requests[0]["payload"]["send_email"])
|
|
|
|
def test_one_submission_per_partner(self):
|
|
"""Each partner gets its own submission with a single submitter."""
|
|
self._set_api_config()
|
|
partner2 = self.env["res.partner"].create({
|
|
"name": "Alex Martin",
|
|
"email": "alex@example.com",
|
|
})
|
|
with self._mock_api({"id": 57}):
|
|
self.template._create_submissions(self.partner | partner2)
|
|
|
|
self.assertEqual(len(self.requests), 2)
|
|
for request in self.requests:
|
|
self.assertEqual(len(request["payload"]["submitters"]), 1)
|
|
self.assertEqual(
|
|
self.requests[1]["payload"]["submitters"][0]["name"],
|
|
"Alex Martin",
|
|
)
|
|
|
|
def test_api_url_trailing_slash(self):
|
|
"""A configured API URL with a trailing slash does not produce
|
|
a double slash in the request URL."""
|
|
self._set_api_config(api_url="https://sign.example.com/")
|
|
with self._mock_api({"id": 58}):
|
|
self.template._create_submissions(self.partner)
|
|
self.assertEqual(
|
|
self.requests[0]["url"],
|
|
"https://sign.example.com/api/submissions",
|
|
)
|
|
|
|
def test_missing_token_raises_user_error(self):
|
|
"""Without API token, the user is told to configure it instead of
|
|
getting a technical error."""
|
|
self._set_api_config()
|
|
self.env["ir.config_parameter"].sudo().set_param("docuseal.api_token", "")
|
|
with self._mock_api({"id": 59}), self.assertRaisesRegex(
|
|
UserError, "API token"
|
|
):
|
|
self.template._create_submissions(self.partner)
|
|
self.assertFalse(self.requests)
|
|
|
|
def test_docuseal_error_raises_user_error_with_detail(self):
|
|
"""A Docuseal rejection is reported with the explanation it sent."""
|
|
self._set_api_config()
|
|
error = urllib.error.HTTPError(
|
|
"https://sign.example.com/api/submissions",
|
|
422,
|
|
"Unprocessable Entity",
|
|
{},
|
|
io.BytesIO(json.dumps({"error": "Role not found"}).encode()),
|
|
)
|
|
with mock.patch.object(
|
|
docuseal_template_module.urllib.request,
|
|
"urlopen",
|
|
side_effect=error,
|
|
), self.assertRaisesRegex(UserError, "422: Role not found"):
|
|
self.template._create_submissions(self.partner)
|
|
|
|
def test_partner_without_email_is_refused(self):
|
|
"""No request is sent when a contact cannot receive the email,
|
|
even if the other contacts can."""
|
|
self._set_api_config()
|
|
no_email = self.env["res.partner"].create({"name": "Sam Leroy"})
|
|
with self._mock_api({"id": 62}), self.assertRaisesRegex(
|
|
UserError, "Sam Leroy"
|
|
):
|
|
self.template._create_submissions(self.partner | no_email)
|
|
self.assertFalse(self.requests)
|
|
|
|
# A draft is not emailed: no email address is required.
|
|
with self._mock_api({"id": 63}):
|
|
self.template._create_draft_submissions(no_email)
|
|
self.assertEqual(len(self.requests), 1)
|
|
|
|
def _assert_user_error(self, regex, **urlopen_patch):
|
|
with mock.patch.object(
|
|
docuseal_template_module.urllib.request, "urlopen", **urlopen_patch
|
|
), self.assertRaisesRegex(UserError, regex):
|
|
self.template._create_submissions(self.partner)
|
|
|
|
def test_invalid_api_url_raises_user_error(self):
|
|
"""An API URL without scheme is reported, not a traceback."""
|
|
self._set_api_config(api_url="sign.example.com")
|
|
with self.assertRaisesRegex(UserError, "is invalid"):
|
|
self.template._create_submissions(self.partner)
|
|
|
|
def test_unexpected_response_raises_user_error(self):
|
|
"""A non-JSON response (proxy, login page) is reported."""
|
|
self._set_api_config()
|
|
resp = mock.MagicMock()
|
|
resp.read.return_value = b"<html>Login</html>"
|
|
context = mock.MagicMock()
|
|
context.__enter__.return_value = resp
|
|
self._assert_user_error("unexpected response", return_value=context)
|
|
|
|
def test_dropped_connection_raises_user_error(self):
|
|
"""A connection dropped mid-response is reported."""
|
|
self._set_api_config()
|
|
self._assert_user_error(
|
|
"could not be reached",
|
|
side_effect=http.client.RemoteDisconnected("closed"),
|
|
)
|
|
self._assert_user_error(
|
|
"could not be reached",
|
|
side_effect=http.client.IncompleteRead(b""),
|
|
)
|
|
|
|
def test_malformed_email_is_refused(self):
|
|
"""Malformed and multiple email addresses are refused too."""
|
|
self._set_api_config()
|
|
for email in (" ", "not-an-email", "a@example.com; b@example.com"):
|
|
self.partner.email = email
|
|
with self._mock_api({"id": 64}), self.assertRaisesRegex(
|
|
UserError, "valid email"
|
|
):
|
|
self.template._create_submissions(self.partner)
|
|
self.assertFalse(self.requests)
|
|
|
|
def test_invalid_token_raises_user_error(self):
|
|
"""A token pasted with a line break is reported as a token problem,
|
|
not as an invalid URL."""
|
|
self._set_api_config()
|
|
self.env["ir.config_parameter"].sudo().set_param(
|
|
"docuseal.api_token", "abc\ndef"
|
|
)
|
|
with self.assertRaisesRegex(UserError, "API token"):
|
|
self.template._create_submissions(self.partner)
|
|
|
|
def test_error_without_message_names_the_exception(self):
|
|
"""An exception without message still explains what happened."""
|
|
self._set_api_config()
|
|
self._assert_user_error("TimeoutError", side_effect=TimeoutError())
|