From a74f9ce5e0659ca8bacdc8887a00009ac6ce39e5 Mon Sep 17 00:00:00 2001 From: Tomas Date: Wed, 4 Nov 2026 22:22:41 -0600 Subject: [PATCH 1/2] Add Python 2.1 API coverage and fix request handling --- .github/workflows/test.yml | 5 +- CHANGELOG.md | 29 +++++ README.md | 5 +- examples/usage.md | 118 +++++++++++++++++++ mifiel/__init__.py | 2 + mifiel/base.py | 49 +++++--- mifiel/document.py | 76 ++++++++---- mifiel/query.py | 17 +++ mifiel/version.py | 2 +- pyproject.toml | 2 +- test/mifiellib/test_document_operations.py | 128 +++++++++++++++++++++ test/mifiellib/test_query.py | 41 +++++++ test/mifiellib/test_transport.py | 110 ++++++++++++++++++ test/mifiellib/test_webhook.py | 54 +++++++++ 14 files changed, 595 insertions(+), 43 deletions(-) create mode 100644 examples/usage.md create mode 100644 mifiel/query.py create mode 100644 test/mifiellib/test_document_operations.py create mode 100644 test/mifiellib/test_query.py create mode 100644 test/mifiellib/test_transport.py create mode 100644 test/mifiellib/test_webhook.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 8f4853f..43bb5a5 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -11,7 +11,7 @@ jobs: strategy: fail-fast: false matrix: - python-version: ["3.10", "3.11", "3.12"] + python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"] steps: - uses: actions/checkout@v5 @@ -29,5 +29,8 @@ jobs: - name: Install dependencies run: poetry install --no-interaction --no-ansi + - name: Check package metadata + run: poetry check --lock + - name: Run tests run: poetry run pytest diff --git a/CHANGELOG.md b/CHANGELOG.md index a95b682..eabb2e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,34 @@ # Changelog # +## v2.1.0 - Unreleased + +### Features + +- Add `Document.get_state()`, `add_stakeholder()`, `update_stakeholder()` and + `delete_stakeholder()` for document state and signer/reviewer management. +- Add `Document.save_zip()` for signed PDF/XML archives. +- Export `Query.execute(client, params)` for advanced queries at `/api/query`, + preserving the entire response and pagination metadata. +- Add Python examples, webhook coverage and CI coverage through Python 3.14. + +### Bug fixes + +- Send form data on PUT requests so document and template updates persist changes. +- Encode form booleans as lowercase `true`/`false`; retain zero and empty values. +- Support GET query parameters through `params`. +- Raise `requests.HTTPError` for failed API requests, including lists, deletes and + webhook operations that previously returned error payloads as successful results. +- Close uploads on request failure and omit the local file path from upload form data. +- Save XML as original response bytes and check document IDs before downloads. + +### Compatibility + +- Python >=3.10 and Requests 2.x requirements are unchanged. +- `delete_stakeholder()` returns the HTTP response so callers can inspect empty + 204 responses (documented) or 205 responses (observed in sandbox). +- Existing successful return values remain unchanged; callers should handle + `requests.HTTPError` for unsuccessful HTTP responses. + ## v2.0.0 - 21.Aug.2026 ### Breaking changes diff --git a/README.md b/README.md index a64ee60..33f023e 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,8 @@ API reference, guides, and examples: - English: https://docs.mifiel.com/en/ - Español: https://docs.mifiel.com/es/ -This README covers installation and client setup only. +This README covers installation and client setup. See [Python examples](examples/usage.md) +for document state, stakeholders, signed downloads, advanced queries and webhooks. ## Installation @@ -39,6 +40,8 @@ client.use_sandbox() ## Development +Python 3.10 or later is required. CI tests Python 3.10–3.14. + This project uses [Poetry](https://python-poetry.org/docs/#installation): ```bash diff --git a/examples/usage.md b/examples/usage.md new file mode 100644 index 0000000..315551d --- /dev/null +++ b/examples/usage.md @@ -0,0 +1,118 @@ +# Python API examples + +These examples target the unreleased 2.1.0 SDK. The API contract is documented at +[docs.mifiel.com](https://docs.mifiel.com/en/). + +## Configure a sandbox client + +```python +import os + +from mifiel import Client, Document, Query, Webhook + +client = Client(os.environ['MIFIEL_APP_ID'], os.environ['MIFIEL_APP_SECRET']) +client.use_sandbox() +client.set_timeout(30) +``` + +## Create a document and read its state + +```python +document = Document.create( + client, + [{'email': 'signer@example.com', 'allowed_signature_methods': ['FEA']}], + file='contract.pdf', + send_invites=False, + remind_every=0, +) +state = document.get_state() +print(state['state'], state['signing_groups']) + +# Work with an existing document without first fetching its legacy representation: +document = Document(client) +document.id = 'DOCUMENT_ID' +state = document.get_state() +``` + +## Manage document stakeholders + +```python +reviewer = document.add_stakeholder({ + 'email': 'reviewer@example.com', + 'name': 'Contract reviewer', + 'type': 'reviewer', + 'send_invite': False, +}) +updated = document.update_stakeholder(reviewer['id'], { + 'email': reviewer['email'], + 'name': 'Updated reviewer', + 'type': 'reviewer', + 'send_invite': False, +}) +response = document.delete_stakeholder(reviewer['id']) +print(response.status_code) # 204 in the reference; 205 observed in sandbox. +``` + +State and stakeholder helpers return decoded dictionaries without replacing the +document's local attributes. Stakeholder deletion returns `requests.Response`, +including its status and any body. A deleted stakeholder may remain in document +state with `state: deleted`. Participation and document completion restrict edits. + +## Download completed documents + +```python +document.save_file_signed('downloads/signed.pdf') +document.save_xml('downloads/signature.xml') +document.save_zip('downloads/signed.zip') +``` + +These methods create parent directories and write original response bytes. They +use the client's timeout or a 30-second download timeout. Failed HTTP responses +raise before opening the destination file. + +## Query records with pagination + +```python +result = Query.execute(client, { + 'resource': 'document', + 'fields': 'id,file_name,created_at', + 'page': 1, + 'per_page': 25, + 'sort': 'created_at-desc', + 'version': '1.0.0', +}) +records = result['records'] +metadata = result.get('___metadata', {}) +``` + +Queries use `/api/query` on the configured server. Other resource methods use +`/api/v1/`. All query response fields, including pagination metadata, pass through. + +## Webhook subscriptions + +```python +subscriptions = Webhook.all(client) +subscription = Webhook.create(client, 'https://example.com/callback', 'document_signed') + +# This sends a real callback; invoke it only when the receiver is ready. +delivery = subscription.trigger(document.id, instant=False) +Webhook.delete(client, subscription.id) +``` + +Webhook support already exists in 2.0.0; 2.1.0 adds tests and consistent HTTP error +handling. Empty successful webhook deletions return `None`. + +## Handle API errors + +```python +import requests + +try: + state = document.get_state() +except requests.HTTPError as error: + print('API request failed:', error.response.status_code) +``` + +All SDK HTTP methods now raise `requests.HTTPError` for unsuccessful HTTP responses. +Existing successful return values, including document/template objects and delete +results, are retained. diff --git a/mifiel/__init__.py b/mifiel/__init__.py index a37c86f..14cc209 100644 --- a/mifiel/__init__.py +++ b/mifiel/__init__.py @@ -6,6 +6,7 @@ from .document import Document from .template import Template from .webhook import Webhook +from .query import Query __all__ = [ '__version__', @@ -15,4 +16,5 @@ 'Document', 'Template', 'Webhook', + 'Query', ] diff --git a/mifiel/base.py b/mifiel/base.py index add9736..ac598dd 100644 --- a/mifiel/base.py +++ b/mifiel/base.py @@ -22,7 +22,9 @@ def url(self, path=None): return self.client.url().format(path=p) - def execute_request(self, method, url=None, data=None, json=None, files=None): + def execute_request(self, method, url=None, data=None, json=None, files=None, params=None): + if method not in ('post', 'put', 'get', 'delete'): + raise ValueError(f'Unsupported HTTP method: {method}') if not url: url = self.url() @@ -31,32 +33,45 @@ def execute_request(self, method, url=None, data=None, json=None, files=None): auth=self.client.auth, json=json, ) + if params is not None: + kwargs['params'] = params if self.client.timeout: kwargs.update({ 'timeout': self.client.timeout }) - if method == 'post': + if method in ('post', 'put'): kwargs.update({ - 'data': data, + 'data': self._form_data(data), 'files': files }) - response = requests.post(**kwargs) - if files: - for file_name in files: - file = files[file_name] - if file: file[1].close() - elif method == 'put': - response = requests.put(**kwargs) - elif method == 'get': - response = requests.get(**kwargs) - elif method == 'delete': - response = requests.delete(**kwargs) - return response + try: + response = getattr(requests, method)(**kwargs) + response.raise_for_status() + return response + finally: + # Close uploads even when the request or HTTP status validation fails. + if files and method in ('post', 'put'): + parts = files.values() if isinstance(files, dict) else (part for _, part in files) + for part in parts: + stream = part[1] if isinstance(part, (tuple, list)) else part + if hasattr(stream, 'close'): + stream.close() - def process_request(self, method, url=None, data=None, json=None, files=None): - response = self.execute_request(method, url, data, json, files) + @staticmethod + def _form_data(data): + # Requests otherwise serializes booleans as "False"/"True", which are not + # canonical boolean values for the API's form parameters. + if isinstance(data, dict): + data = data.items() + elif not isinstance(data, (list, tuple)): + return data + return [(key, str(value).lower() if isinstance(value, bool) else value) + for key, value in data] + + def process_request(self, method, url=None, data=None, json=None, files=None, params=None): + response = self.execute_request(method, url, data, json, files, params) self.set_data(response) def set_data(self, response): diff --git a/mifiel/document.py b/mifiel/document.py index 35f7366..823cd50 100644 --- a/mifiel/document.py +++ b/mifiel/document.py @@ -1,4 +1,4 @@ -from mifiel import Base, Response +from mifiel import Base import mimetypes import os from os.path import basename @@ -42,6 +42,7 @@ def create(client, signatories, **kwargs): raise ValueError('A name is required when using hash') data = kwargs.copy() + data.pop('file', None) signatory_array_fields = [] for index, item in enumerate(signatories): for key, val in item.items(): @@ -69,15 +70,49 @@ def create(client, signatories, **kwargs): if signatory_array_fields: data = list(data.items()) + signatory_array_fields - if file: - mimetype = mimetypes.guess_type(file)[0] - _file = open(file, 'rb') - file = {'file': (basename(_file.name), _file, mimetype)} - doc = Document(client) - doc.process_request('post', data=data, files=file) + if file: + mimetype = mimetypes.guess_type(str(file))[0] + with open(file, 'rb') as upload: + files = {'file': (basename(upload.name), upload, mimetype)} + doc.process_request('post', data=data, files=files) + else: + doc.process_request('post', data=data) return doc + def get_state(self): + """Return document state, signing groups and stakeholders as a dictionary.""" + response = self.execute_request('get', url=self.url(self._document_path('state'))) + return response.json() + + def add_stakeholder(self, params): + """Add a signer or reviewer and return the decoded API response.""" + response = self.execute_request( + 'post', url=self.url(self._document_path('stakeholders')), json=params, + ) + return response.json() + + def update_stakeholder(self, stakeholder_id, params): + """Update a stakeholder without replacing this document's attributes.""" + response = self.execute_request( + 'put', url=self.url(self._stakeholder_path(stakeholder_id)), json=params, + ) + return response.json() + + def delete_stakeholder(self, stakeholder_id): + """Return the HTTP response, including empty 204 or 205 responses.""" + return self.execute_request('delete', url=self.url(self._stakeholder_path(stakeholder_id))) + + def _document_path(self, operation): + if not self.id: + raise ValueError('Document id is required') + return f'{self.id}/{operation}' + + def _stakeholder_path(self, stakeholder_id): + if not stakeholder_id: + raise ValueError('Stakeholder id is required') + return self._document_path(f'stakeholders/{stakeholder_id}') + def request_signature(self, signer, cc=None): path = '{}/{}'.format(self.id, 'request_signature') data = { @@ -117,28 +152,25 @@ def create_many_from_template(client, args={}): return response.json() def save_file(self, path): - url_ = self.url('{}/file').format(self.id) - response = requests.get(url_, auth=self.client.auth, timeout=self._request_timeout()) - response.raise_for_status() - self._ensure_parent_dir(path) - with open(path, 'wb') as file_: - file_.write(response.content) + self._save_download(path, 'file') def save_file_signed(self, path): - url_ = self.url('{}/file_signed').format(self.id) - response = requests.get(url_, auth=self.client.auth, timeout=self._request_timeout()) - response.raise_for_status() - self._ensure_parent_dir(path) - with open(path, 'wb') as file_: - file_.write(response.content) + self._save_download(path, 'file_signed') + + def save_zip(self, path): + """Download the signed PDF/XML archive to a local file.""" + self._save_download(path, 'zip') def save_xml(self, path): - url_ = self.url('{}/xml').format(self.id) + self._save_download(path, 'xml') + + def _save_download(self, path, operation): + url_ = self.url(self._document_path(operation)) response = requests.get(url_, auth=self.client.auth, timeout=self._request_timeout()) response.raise_for_status() self._ensure_parent_dir(path) - with open(path, 'w') as file_: - file_.write(response.text) + with open(path, 'wb') as file_: + file_.write(response.content) def _request_timeout(self): return self.client.timeout if self.client.timeout else 30 diff --git a/mifiel/query.py b/mifiel/query.py new file mode 100644 index 0000000..e3b5153 --- /dev/null +++ b/mifiel/query.py @@ -0,0 +1,17 @@ +from urllib.parse import urljoin + +from .base import Base + + +class Query: + """Advanced queries at /api/query, outside the versioned resource routes.""" + + @staticmethod + def execute(client, params): + """Return the full decoded response, preserving records and pagination metadata.""" + if not params.get('resource') or not params.get('fields'): + raise ValueError('Query resource and fields are required') + response = Base(client, 'query').execute_request( + 'post', url=urljoin(client.url(), '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/api/query'), json=params, + ) + return response.json() diff --git a/mifiel/version.py b/mifiel/version.py index afced14..a33997d 100644 --- a/mifiel/version.py +++ b/mifiel/version.py @@ -1 +1 @@ -__version__ = '2.0.0' +__version__ = '2.1.0' diff --git a/pyproject.toml b/pyproject.toml index 5d57147..59b87ba 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "mifiel" -version = "2.0.0" +version = "2.1.0" description = "Python API Client library for mifiel.com" authors = ["Genaro Madrid "] readme = "README.md" diff --git a/test/mifiellib/test_document_operations.py b/test/mifiellib/test_document_operations.py new file mode 100644 index 0000000..113f86a --- /dev/null +++ b/test/mifiellib/test_document_operations.py @@ -0,0 +1,128 @@ +import io +import json +import zipfile +from unittest.mock import patch + +import pytest +import requests +import responses + +from mifiel import Client, Document + + +@pytest.fixture +def document(): + client = Client('test-app-id', 'test-secret') + client.set_base_url('http://localhost:3000') + document = Document(client) + document.id = 'document-id' + return document + + +@responses.activate +def test_state_preserves_document_attributes(document): + state = {'id': document.id, 'state': 'pending', 'signing_groups': [{'stakeholders': []}]} + responses.get(document.url('document-id/state'), json=state) + assert document.get_state() == state + assert document.get_data() == {'id': 'document-id'} + + +@responses.activate +@pytest.mark.parametrize('operation,method,status', [ + ('add_stakeholder', 'POST', 201), ('update_stakeholder', 'PUT', 200), +]) +def test_stakeholder_payloads_and_results(document, operation, method, status): + payload = { + 'email': 'reviewer@example.com', 'type': 'reviewer', 'name': 'José', + 'send_invite': False, 'allowed_signature_methods': ['FEA', 'FESCV'], + } + path = 'document-id/stakeholders' + args = [payload] + if operation == 'update_stakeholder': + path += '/stakeholder-id' + args.insert(0, 'stakeholder-id') + result = {'id': 'stakeholder-id', **payload} + responses.add(method, document.url(path), json=result, status=status) + assert getattr(document, operation)(*args) == result + request = responses.calls[0].request + assert json.loads(request.body) == payload + assert request.headers['Content-Type'] == 'application/json' + assert document.id == 'document-id' + + +@responses.activate +@pytest.mark.parametrize('status', [204, 205]) +def test_delete_stakeholder_preserves_empty_response_and_status(document, status): + responses.delete(document.url('document-id/stakeholders/stakeholder-id'), status=status) + response = document.delete_stakeholder('stakeholder-id') + assert isinstance(response, requests.Response) + assert response.status_code == status + assert response.content == b'' + + +@responses.activate +def test_zip_is_written_without_binary_changes(document, tmp_path): + archive = io.BytesIO() + with zipfile.ZipFile(archive, 'w') as zip_file: + zip_file.writestr('signed.pdf', b'%PDF-1.4\n\x00\xff') + zip_file.writestr('signature.xml', b'') + payload = archive.getvalue() + responses.get(document.url('document-id/zip'), body=payload, + content_type='application/zip') + path = tmp_path / 'nested' / 'signed.zip' + document.save_zip(path) + assert path.read_bytes() == payload + with zipfile.ZipFile(path) as zip_file: + assert zip_file.testzip() is None + + +@responses.activate +@pytest.mark.parametrize('method,endpoint', [ + ('save_zip', 'zip'), ('save_file_signed', 'file_signed'), ('save_xml', 'xml'), +]) +def test_failed_download_does_not_overwrite_existing_file(document, tmp_path, method, endpoint): + path = tmp_path / 'existing' + path.write_bytes(b'keep existing contents') + responses.get(document.url(f'document-id/{endpoint}'), status=423) + with pytest.raises(requests.HTTPError): + getattr(document, method)(path) + assert path.read_bytes() == b'keep existing contents' + + +@responses.activate +def test_xml_is_written_as_original_bytes(document, tmp_path): + payload = 'José'.encode() + responses.get(document.url('document-id/xml'), body=payload, + content_type='application/xml') + path = tmp_path / 'signature.xml' + document.save_xml(path) + assert path.read_bytes() == payload + + +@pytest.mark.parametrize('timeout', [None, 7]) +def test_zip_uses_download_timeout(document, tmp_path, timeout): + if timeout: + document.client.set_timeout(timeout) + with patch('mifiel.document.requests.get') as get: + get.return_value.content = b'zip' + document.save_zip(tmp_path / 'file.zip') + assert get.call_args.kwargs['timeout'] == (timeout or 30) + + +@pytest.mark.parametrize('operation,args', [ + ('get_state', []), ('add_stakeholder', [{}]), + ('update_stakeholder', ['stakeholder-id', {}]), + ('delete_stakeholder', ['stakeholder-id']), ('save_zip', ['unused.zip']), +]) +def test_document_id_required_before_network(document, operation, args): + document.id = None + with pytest.raises(ValueError, match='Document id'): + getattr(document, operation)(*args) + + +@pytest.mark.parametrize('operation,args', [ + ('update_stakeholder', ['', {}]), ('delete_stakeholder', ['']), +]) +def test_stakeholder_id_required_before_network(document, operation, args): + with pytest.raises(ValueError, match='Stakeholder id'): + getattr(document, operation)(*args) diff --git a/test/mifiellib/test_query.py b/test/mifiellib/test_query.py new file mode 100644 index 0000000..1862eab --- /dev/null +++ b/test/mifiellib/test_query.py @@ -0,0 +1,41 @@ +import json + +import pytest +import requests +import responses + +import mifiel + + +@responses.activate +@pytest.mark.parametrize('server', [ + 'https://app.mifiel.com', 'https://app-sandbox.mifiel.com', 'http://localhost:3000', +]) +def test_query_uses_unversioned_route_and_preserves_metadata(server): + client = mifiel.Client('test-app-id', 'test-secret') + client.set_base_url(server) + params = {'resource': 'document', 'fields': 'id,file_name', 'page': 2, 'per_page': 1, + 'q': {'file_name': {'eq': 'Contrato.pdf'}}, 'version': '1.0.0'} + result = {'records': [{'id': 'document-id'}], + '___metadata': {'page': 2, 'total_count': 3, 'page_count': 3}} + responses.post(server + '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/api/query', json=result) + assert mifiel.Query.execute(client, params) == result + request = responses.calls[0].request + assert json.loads(request.body) == params + assert request.headers['Authorization'].startswith('APIAuth test-app-id:') + + +@pytest.mark.parametrize('params', [{}, {'resource': 'document'}, {'fields': 'id'}, + {'resource': '', 'fields': 'id'}]) +def test_query_requires_resource_and_fields(params): + with pytest.raises(ValueError, match='resource and fields'): + mifiel.Query.execute(mifiel.Client('test-app-id', 'test-secret'), params) + + +@responses.activate +def test_query_raises_http_errors(): + client = mifiel.Client('test-app-id', 'test-secret') + client.use_sandbox() + responses.post('https://app-sandbox.mifiel.com/api/query', status=400) + with pytest.raises(requests.HTTPError): + mifiel.Query.execute(client, {'resource': 'document', 'fields': 'id'}) diff --git a/test/mifiellib/test_transport.py b/test/mifiellib/test_transport.py new file mode 100644 index 0000000..0e8b9f3 --- /dev/null +++ b/test/mifiellib/test_transport.py @@ -0,0 +1,110 @@ +import io +from unittest.mock import patch +from urllib.parse import parse_qs, urlparse + +import pytest +import requests +import responses + +from mifiel import Base, Client, Document, Template, Webhook + + +@pytest.fixture +def client(): + client = Client('test-app-id', 'test-secret') + client.set_base_url('http://localhost:3000') + return client + + +@responses.activate +@pytest.mark.parametrize('resource', [Document, Template]) +def test_save_sends_changed_attributes(client, resource): + obj = resource(client) + obj.id = 'resource-id' + obj.callback_url = 'https://example.com/callback' + responses.put(obj.url(obj.id), json={'id': obj.id}) + + obj.save() + + assert parse_qs(responses.calls[0].request.body)['callback_url'] == [ + 'https://example.com/callback', + ] + + +@responses.activate +@pytest.mark.parametrize('method', ['post', 'put']) +@pytest.mark.parametrize('as_pairs', [False, True]) +def test_form_values_preserve_false_zero_and_empty_strings(client, method, as_pairs): + base = Base(client, 'documents') + responses.add(method.upper(), base.url(), json={}) + data = {'send_invites': False, 'remind_every': 0, 'name': '', 'active': True} + if as_pairs: + data = list(data.items()) + + base.execute_request(method, data=data) + + assert parse_qs(responses.calls[0].request.body, keep_blank_values=True) == { + 'send_invites': ['false'], 'remind_every': ['0'], 'name': [''], 'active': ['true'], + } + + +@responses.activate +def test_get_parameters_are_signed_in_url(client): + base = Base(client, 'documents') + responses.get(base.url(), json=[]) + base.execute_request('get', params={'page': 2, 'name': 'a b'}) + request = responses.calls[0].request + assert parse_qs(urlparse(request.url).query) == {'page': ['2'], 'name': ['a b']} + assert request.body is None + assert request.headers['Authorization'].startswith('APIAuth test-app-id:') + + +@responses.activate +@pytest.mark.parametrize('method', ['get', 'post', 'put', 'delete']) +def test_http_errors_raise_before_returning_json(client, method): + base = Base(client, 'documents') + responses.add(method.upper(), base.url(), json={'error': 'denied'}, status=403) + with pytest.raises(requests.HTTPError) as error: + base.execute_request(method) + assert error.value.response.status_code == 403 + + +@responses.activate +@pytest.mark.parametrize('resource', [Document, Template, Webhook]) +def test_collection_errors_do_not_become_resource_lists(client, resource): + responses.get(resource(client).url(), json={'error': 'unauthorized'}, status=401) + with pytest.raises(requests.HTTPError): + resource.all(client) + + +def test_upload_is_closed_when_connection_fails(client): + upload = io.BytesIO(b'pdf data') + with (patch('mifiel.base.requests.post', side_effect=requests.ConnectionError), + pytest.raises(requests.ConnectionError)): + Base(client, 'documents').execute_request('post', files={'file': ('file.pdf', upload)}) + assert upload.closed + + +@responses.activate +def test_create_upload_does_not_send_local_path_as_a_form_field(client, tmp_path): + path = tmp_path / 'local-private-name.pdf' + path.write_bytes(b'%PDF-1.4\n') + responses.post(Document(client).url(), json={'id': 'document-id'}) + Document.create(client, [{'email': 'signer@example.com'}], file=path, send_invites=False) + body = responses.calls[0].request.body + assert body.count(b'name="file"') == 1 + assert str(path).encode() not in body + assert b'\r\nfalse\r\n' in body + + +def test_explicit_timeout_reaches_every_request_method(client): + client.set_timeout(12) + for method in ['get', 'post', 'put', 'delete']: + with patch('mifiel.base.requests.' + method) as send: + Base(client, 'documents').execute_request(method) + assert send.call_args.kwargs['timeout'] == 12 + + +def test_unknown_method_fails_before_network(client): + with pytest.raises(ValueError, match='Unsupported'): + Base(client, 'documents').execute_request('invalid') diff --git a/test/mifiellib/test_webhook.py b/test/mifiellib/test_webhook.py new file mode 100644 index 0000000..a1008c8 --- /dev/null +++ b/test/mifiellib/test_webhook.py @@ -0,0 +1,54 @@ +import json + +import pytest +import requests +import responses + +from mifiel import Client, Webhook + + +@pytest.fixture +def client(): + client = Client('test-app-id', 'test-secret') + client.set_base_url('http://localhost:3000') + return client + + +@responses.activate +def test_create_and_list_webhooks(client): + payload = {'url': 'https://example.com/callback', 'callback_type': 'document_signed'} + result = {'id': 'webhook-id', **payload} + responses.post(Webhook(client).url(), json=result, status=201) + responses.get(Webhook(client).url(), json=[result]) + webhook = Webhook.create(client, **payload) + assert webhook.id == 'webhook-id' + assert json.loads(responses.calls[0].request.body) == payload + assert [hook.id for hook in Webhook.all(client)] == ['webhook-id'] + + +@responses.activate +@pytest.mark.parametrize('instant,status,result', [ + (False, 202, {'status': 'queued'}), (True, 200, {'status': 'sent'}), +]) +def test_trigger_preserves_instant_flag(client, instant, status, result): + webhook = Webhook(client) + webhook.id = 'webhook-id' + responses.post(webhook.url('webhook-id/trigger'), json=result, status=status) + assert webhook.trigger('document-id', instant=instant) == result + assert json.loads(responses.calls[0].request.body) == { + 'resource': 'document-id', 'instant': instant, + } + + +@responses.activate +@pytest.mark.parametrize('status', [204, 205]) +def test_delete_empty_response(client, status): + responses.delete(Webhook(client).url('webhook-id'), status=status) + assert Webhook.delete(client, 'webhook-id') is None + + +@responses.activate +def test_delete_error_raises(client): + responses.delete(Webhook(client).url('webhook-id'), json={'error': 'denied'}, status=403) + with pytest.raises(requests.HTTPError): + Webhook.delete(client, 'webhook-id') From 1f1186a8db2b093b13c6a6ab8e1aa72a292d5e70 Mon Sep 17 00:00:00 2001 From: Tomas Date: Wed, 4 Nov 2026 22:27:42 -0600 Subject: [PATCH 2/2] Keep API usage examples in central documentation --- CHANGELOG.md | 2 +- README.md | 3 +- examples/usage.md | 118 ---------------------------------------------- 3 files changed, 2 insertions(+), 121 deletions(-) delete mode 100644 examples/usage.md diff --git a/CHANGELOG.md b/CHANGELOG.md index eabb2e7..bbdaca2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ - Add `Document.save_zip()` for signed PDF/XML archives. - Export `Query.execute(client, params)` for advanced queries at `/api/query`, preserving the entire response and pagination metadata. -- Add Python examples, webhook coverage and CI coverage through Python 3.14. +- Add webhook coverage and CI coverage through Python 3.14. ### Bug fixes diff --git a/README.md b/README.md index 33f023e..0c8fa3d 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,7 @@ API reference, guides, and examples: - English: https://docs.mifiel.com/en/ - Español: https://docs.mifiel.com/es/ -This README covers installation and client setup. See [Python examples](examples/usage.md) -for document state, stakeholders, signed downloads, advanced queries and webhooks. +This README covers installation and client setup only. ## Installation diff --git a/examples/usage.md b/examples/usage.md deleted file mode 100644 index 315551d..0000000 --- a/examples/usage.md +++ /dev/null @@ -1,118 +0,0 @@ -# Python API examples - -These examples target the unreleased 2.1.0 SDK. The API contract is documented at -[docs.mifiel.com](https://docs.mifiel.com/en/). - -## Configure a sandbox client - -```python -import os - -from mifiel import Client, Document, Query, Webhook - -client = Client(os.environ['MIFIEL_APP_ID'], os.environ['MIFIEL_APP_SECRET']) -client.use_sandbox() -client.set_timeout(30) -``` - -## Create a document and read its state - -```python -document = Document.create( - client, - [{'email': 'signer@example.com', 'allowed_signature_methods': ['FEA']}], - file='contract.pdf', - send_invites=False, - remind_every=0, -) -state = document.get_state() -print(state['state'], state['signing_groups']) - -# Work with an existing document without first fetching its legacy representation: -document = Document(client) -document.id = 'DOCUMENT_ID' -state = document.get_state() -``` - -## Manage document stakeholders - -```python -reviewer = document.add_stakeholder({ - 'email': 'reviewer@example.com', - 'name': 'Contract reviewer', - 'type': 'reviewer', - 'send_invite': False, -}) -updated = document.update_stakeholder(reviewer['id'], { - 'email': reviewer['email'], - 'name': 'Updated reviewer', - 'type': 'reviewer', - 'send_invite': False, -}) -response = document.delete_stakeholder(reviewer['id']) -print(response.status_code) # 204 in the reference; 205 observed in sandbox. -``` - -State and stakeholder helpers return decoded dictionaries without replacing the -document's local attributes. Stakeholder deletion returns `requests.Response`, -including its status and any body. A deleted stakeholder may remain in document -state with `state: deleted`. Participation and document completion restrict edits. - -## Download completed documents - -```python -document.save_file_signed('downloads/signed.pdf') -document.save_xml('downloads/signature.xml') -document.save_zip('downloads/signed.zip') -``` - -These methods create parent directories and write original response bytes. They -use the client's timeout or a 30-second download timeout. Failed HTTP responses -raise before opening the destination file. - -## Query records with pagination - -```python -result = Query.execute(client, { - 'resource': 'document', - 'fields': 'id,file_name,created_at', - 'page': 1, - 'per_page': 25, - 'sort': 'created_at-desc', - 'version': '1.0.0', -}) -records = result['records'] -metadata = result.get('___metadata', {}) -``` - -Queries use `/api/query` on the configured server. Other resource methods use -`/api/v1/`. All query response fields, including pagination metadata, pass through. - -## Webhook subscriptions - -```python -subscriptions = Webhook.all(client) -subscription = Webhook.create(client, 'https://example.com/callback', 'document_signed') - -# This sends a real callback; invoke it only when the receiver is ready. -delivery = subscription.trigger(document.id, instant=False) -Webhook.delete(client, subscription.id) -``` - -Webhook support already exists in 2.0.0; 2.1.0 adds tests and consistent HTTP error -handling. Empty successful webhook deletions return `None`. - -## Handle API errors - -```python -import requests - -try: - state = document.get_state() -except requests.HTTPError as error: - print('API request failed:', error.response.status_code) -``` - -All SDK HTTP methods now raise `requests.HTTPError` for unsuccessful HTTP responses. -Existing successful return values, including document/template objects and delete -results, are retained.