Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `get_file` and the other result-file downloads without `stream=True` delete the file at `download_path` when writing it fails (for example on a full disk) before raising. Up to 3.0.1 the error was raised but the truncated file stayed behind, where it could be read as the result.
- `ZeroBounceWarmup.download_seeds` and `download_statistics` with a `download_path` delete that file when writing it fails (for example on a full disk) before raising. Up to 3.0.1 the truncated CSV stayed behind.
- `delete_inbox_placement_test` returns `None` when the API answers with an empty 2xx (204 No Content), as the Go SDK does. Up to 3.0.1 it raised `ZBApiException` ("Empty response"). A JSON answer is returned as before; the other Inbox Placement calls still treat an empty body as an error.
- `ZeroBounceWarmup` errors reported on a 200 carry `status_code` 200: an HTML page (such as a proxy's "Access denied" page), a body that is not valid JSON, and a JSON body or empty body from `download_seeds` or `download_statistics`. Up to 3.0.1 their `status_code` was `None`.
- `ZeroBounceWarmup.add_sending_account` parses `ignore_conflict` strictly, as `ZeroBounce` parses its boolean options: `True`/`False`, `"true"`/`"false"` (any case) and `1`/`0` are accepted, and anything else raises `ZBClientException("Invalid parameter: ignore_conflict must be true or false")` before a request is sent. Up to 3.0.1 the value went through `bool()`, so `ignore_conflict="false"` sent `true`.

## [3.0.1] - 2026-11-11

Expand Down
23 changes: 18 additions & 5 deletions src/zerobouncesdk/zb_warmup.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,14 @@
from requests.exceptions import RequestException

from .zb_exceptions import ZBApiException, ZBClientException
from .zerobouncesdk import _check_api_key, _looks_like_html, _message_from_body, _path_segment, _response_text
from .zerobouncesdk import (
_check_api_key,
_looks_like_html,
_message_from_body,
_path_segment,
_response_text,
_strict_bool,
)

DateLike = Union[date, str]

Expand Down Expand Up @@ -106,18 +113,24 @@ def _json(self, method: str, path: str, *, params=None, json=None, secrets=()):
return None
content_type = response.headers.get("Content-Type", "")
if _looks_like_html(body, content_type):
raise ZBApiException(self._redact(_message_from_body(body, response.status_code), secrets))
raise ZBApiException(
self._redact(_message_from_body(body, response.status_code), secrets), status_code=response.status_code
)
try:
return response.json()
except ValueError:
raise ZBApiException(self._redact(_message_from_body(body, response.status_code), secrets)) from None
raise ZBApiException(
self._redact(_message_from_body(body, response.status_code), secrets), status_code=response.status_code
) from None

def _csv(self, path: str, params=None, download_path: Optional[str] = None) -> str:
response = self._send("GET", path, params=params)
body = _response_text(response)
content_type = response.headers.get("Content-Type", "")
if not body.strip() or _looks_like_html(body, content_type) or "application/json" in content_type.lower():
raise ZBApiException(self._redact(_message_from_body(body, response.status_code)))
raise ZBApiException(
self._redact(_message_from_body(body, response.status_code)), status_code=response.status_code
)
if download_path:
directory = os.path.dirname(download_path)
if directory:
Expand Down Expand Up @@ -218,7 +231,7 @@ def add_sending_account(
if email_content is not None or managed_sending is not None:
raise ZBClientException("Invalid parameter: email_content and managed_sending are for zb_managed")
if ignore_conflict is not None:
body["ignore_conflict"] = bool(ignore_conflict)
body["ignore_conflict"] = _strict_bool(ignore_conflict, "ignore_conflict")
if email_content is not None:
content = dict(email_content)
types = content.get("types_of_emails")
Expand Down
135 changes: 135 additions & 0 deletions tests/test_transport_guards_offline.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
``ZeroBounceWarmup`` (the list below), each with a guard that fails when a method is missing from it.
"""

import contextlib
import errno
import io
import socket
import tempfile
import threading
import warnings
Expand All @@ -16,6 +18,7 @@
from unittest.mock import patch

from requests import Response
from requests.exceptions import RequestException

from tests import test_standard_parity_offline as parity
from zerobouncesdk import ZBApiException, ZeroBounce, ZeroBounceWarmup
Expand Down Expand Up @@ -172,6 +175,138 @@ def test_no_warmup_request_follows_a_redirect(self):
self._refused(name, lambda c=call: c(warmup))



class RawSocketServer:
"""A loopback HTTP server on a raw socket: reads each whole request, writes ``answer(request_line)`` and
closes the connection, so a response can promise more bytes than it sends."""

def __init__(self, answer):
self.hits = []
self._sock = socket.socket()
self._sock.bind(("127.0.0.1", 0))
self._sock.listen(16)
self.url = f"http://127.0.0.1:{self._sock.getsockname()[1]}"
self._answer = answer
threading.Thread(target=self._serve, daemon=True).start()

def close(self):
self._sock.close()

def _serve(self):
while True:
try:
conn, _ = self._sock.accept()
except OSError:
return
threading.Thread(target=self._reply, args=(conn,), daemon=True).start()

def _reply(self, conn):
with conn:
conn.settimeout(5)
line = self._read_request(conn)
self.hits.append(line)
conn.sendall(self._answer(line))
# Read until the client hangs up, so closing never resets a connection it is still reading.
with contextlib.suppress(OSError):
conn.shutdown(socket.SHUT_WR)
while conn.recv(65536):
pass

@staticmethod
def _read_request(conn):
"""The request line, after the headers and the whole body (Content-Length or chunked) are read."""
data = b""
while b"\r\n\r\n" not in data:
chunk = conn.recv(65536)
if not chunk:
break
data += chunk
head, _, body = data.partition(b"\r\n\r\n")
headers = head.decode("latin-1").lower()
length = 0
for header in headers.split("\r\n")[1:]:
name, _, value = header.partition(":")
if name.strip() == "content-length":
length = int(value)
if "transfer-encoding: chunked" in headers:
while not body.endswith(b"0\r\n\r\n"):
body += conn.recv(65536)
while len(body) < length:
chunk = conn.recv(65536)
if not chunk:
break
body += chunk
return head.split(b"\r\n", 1)[0].decode("latin-1")


class CutShortBodySweepTest(TestCase):
"""A 200 whose body is cut short is an error on every request path, including downloads (streamed or not)
and Warmup, and leaves no file behind. The fake sends a valid 25-byte JSON or CSV body that would read as a
complete result, then closes the connection: only the length check (``Content-Length``, or a chunked body
missing its last chunk) tells the transfer was broken."""

CSV = b"email,status\na@b.c,valid\n" # 25 bytes
JSON = b'{"Credits":"5","a":"bbb"}' # 25 bytes, valid JSON on its own

def setUp(self):
self.mode = "length"
self.server = RawSocketServer(self._answer)
self.addCleanup(self.server.close)
# Plain http to the loopback server; https is enforced by its own sweep.
patcher = patch("zerobouncesdk.zerobouncesdk._https_url", lambda url: url)
patcher.start()
self.addCleanup(patcher.stop)
self.folder = Path(tempfile.mkdtemp())
self.out = str(self.folder / "out.csv")

def _answer(self, request_line):
download = "getfile" in request_line or "/download" in request_line
content_type, body = ("text/csv", self.CSV) if download else ("application/json", self.JSON)
if self.mode == "length":
head = f"Content-Length: {len(body) + 975}"
else: # chunked: one complete chunk, then the connection closes without the last (empty) chunk
head = "Transfer-Encoding: chunked"
body = b"%x\r\n%s\r\n" % (len(body), body)
return f"HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\n{head}\r\nConnection: close\r\n\r\n".encode() + body

def _client_calls(self):
client = ZeroBounce(KEY, timeout=timedelta(seconds=5))
client._base_url = self.server.url + "/v2"
for attribute, path in _BASE_URL_ATTRIBUTES.items():
setattr(client, attribute, self.server.url + path)
calls = client_calls(client, self.out)
self.assertEqual(_public(ZeroBounce, parity.HttpsSweepTest.NOT_REQUESTS) - set(calls), set())
# Every download, streamed too.
for name in [name for name in calls if name.endswith("get_file")]:
calls[name] = [
lambda m=getattr(client, name): m("f1", self.out),
lambda m=getattr(client, name): m("f1", self.out, stream=True),
]
return calls

def _warmup_calls(self):
warmup = ZeroBounceWarmup(KEY, timeout=timedelta(seconds=5))
warmup._root = self.server.url + ZeroBounceWarmup.BASE_PATH
return {name: [lambda c=call: c(warmup)] for name, call in warmup_calls(self.out).items()}

def _sweep(self, calls):
for mode in ("length", "chunked"):
self.mode = mode
for name, variants in calls.items():
for call in variants:
before = len(self.server.hits)
with self.assertRaises(RequestException, msg=f"{name} ({mode})") as caught:
_quiet(call)
self.assertGreater(len(self.server.hits), before, f"{name} sent nothing")
self.assertNotIn(KEY, str(caught.exception), name)
self.assertEqual(list(self.folder.iterdir()), [], f"{name} ({mode}) left a file behind")

def test_every_client_request(self):
self._sweep(self._client_calls())

def test_every_warmup_request(self):
self._sweep(self._warmup_calls())

class TimeoutSweepTest(TestCase):
"""Every request goes out with the client's timeout (requests has none by default)."""

Expand Down
38 changes: 34 additions & 4 deletions tests/test_warmup_offline.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,22 @@ def test_request_bodies_and_queries(self):
self.client.create_custom_engagement("sender@example.com", 20, 25, 25)
self.assertEqual(self._only().json, {"c_from": "sender@example.com", "reply_pct": 20, "important_pct": 25, "click_pct": 25})

def test_ignore_conflict_is_parsed_strictly(self):
# Parsed as the validation client parses its boolean options: "false" is false, junk raises.
for value, sent in ((False, False), ("false", False), ("FALSE", False), (0, False), ("0", False),
(True, True), ("true", True), (1, True), ("1", True)):
self.requests.clear()
self.client.add_sending_account("s@example.com", "self_managed", engagement_rule_id=0, ignore_conflict=value)
self.assertIs(self._only().json["ignore_conflict"], sent, repr(value))
self.requests.clear()
for value in ("junk", "yes", "", 2, [], object()):
with self.assertRaises(ZBClientException, msg=repr(value)) as caught:
self.client.add_sending_account("s@example.com", "self_managed", engagement_rule_id=0, ignore_conflict=value)
self.assertIn("ignore_conflict", str(caught.exception))
self.assertEqual(self.requests, [])
self.client.add_sending_account("s@example.com", "self_managed", engagement_rule_id=0, ignore_conflict=None)
self.assertNotIn("ignore_conflict", self._only().json)

def test_invalid_arguments_send_nothing(self):
attempts = [
lambda: ZeroBounceWarmup(" "),
Expand Down Expand Up @@ -262,15 +278,29 @@ def test_redirects_html_and_csv_errors(self):
self.assertEqual(caught.exception.status_code, 302)
self.assertEqual(len(self.requests), 1) # not followed

# Errors on a 200 carry that status, as every other error the API reports does.
self.replies["*"] = _response(200, b"<html><title>Access denied</title></html>", "text/html")
with self.assertRaises(ZBApiException):
for call in (self.client.get_seeds, self.client.download_seeds):
with self.assertRaises(ZBApiException) as caught:
call()
self.assertEqual(caught.exception.status_code, 200)
self.assertIn("Access denied", str(caught.exception))

self.replies["*"] = _response(200, b'{"seeds": [', "application/json")
with self.assertRaises(ZBApiException) as caught:
self.client.get_seeds()
with self.assertRaises(ZBApiException):
self.client.download_seeds()
self.assertEqual(caught.exception.status_code, 200)

self.replies["*"] = _response(200, {"error": "c_from not found"})
with self.assertRaises(ZBApiException):
with self.assertRaises(ZBApiException) as caught:
self.client.download_statistics("s@example.com")
self.assertEqual(caught.exception.status_code, 200)
self.assertIn("c_from not found", str(caught.exception))

self.replies["*"] = _response(200, b"", "text/csv")
with self.assertRaises(ZBApiException) as caught:
self.client.download_seeds()
self.assertEqual(caught.exception.status_code, 200)

def test_secrets_never_reach_error_messages(self):
self.replies["*"] = lambda r: _response(400, {"error": f"bad login for password {r.json['password']} key {KEY}"})
Expand Down
Loading