Files
docuseal-tools/docuseal_signing/tests/test_submissions.py
Quentin Mondot 87653552b1
Some checks failed
pre-commit / pre-commit (pull_request) Failing after 1m31s
tests / test (pull_request) Successful in 50s
[FIX] docuseal_signing: restrict signature requests and report API errors
- Reserve the generated "Request signature" action to administrators
  (base.group_system), who are the only ones able to read the Docuseal
  templates, instead of letting other users hit an AccessError.
- Request the signature of a single contact from the contextual action
  (_action_request_signature): with several contacts, a failure could
  leave some of them already emailed while the action reports an error.
  A notification confirms the request.
- Share the Docuseal API call in _docuseal_request: a missing token or a
  Docuseal error (with the explanation it sends) now raises a readable
  UserError when sending submissions too, not only when fetching.

Assisted-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 17:04:23 +01:00

172 lines
6.6 KiB
Python

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"})
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)