Mock Certbot Renewal in Python for Testing

Simulates a Let's Encrypt certificate renewal by writing a mock certificate file and printing realistic certbot CLI output, without calling the actual certbot.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 16 views 0 copies

Python code

39 lines
Python 3.9+
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path


def renew_cert(domain: str, output_dir: str = "certs") -> str:
    """Simulate a Let's Encrypt renewal with mock certbot output."""
    out = Path(output_dir)
    out.mkdir(parents=True, exist_ok=True)

    cert_path = out / f"{domain}.pem"
    expiry = datetime.now() + timedelta(days=90)

    # Simulated certificate content
    cert_content = (
        f"-----BEGIN CERTIFICATE-----\n"
        f"MOCK-CERT-FOR-{domain}\n"
        f"EXPIRES:{expiry.isoformat()}\n"
        f"-----END CERTIFICATE-----\n"
    )

    # Write mock certificate (would be real cert from certbot)
    cert_path.write_text(cert_content)

    # Simulate certbot CLI output
    return (
        f"Saving debug log to /var/log/letsencrypt/letsencrypt.log\n"
        f"Renewing an existing certificate for {domain}\n"
        f"Successfully received certificate.\n"
        f"Certificate is saved at: {cert_path}\n"
        f"Certificate will expire on: {expiry.date()}\n"
        f"Renewal simulation complete."
    )


if __name__ == "__main__":
    # Prevent actual certbot call — use a fake domain for the mock
    print(renew_cert("example.com"))

Output

stdout
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Renewing an existing certificate for example.com
Successfully received certificate.
Certificate is saved at: certs/example.com.pem
Certificate will expire on: 2026-04-12
Renewal simulation complete.

How it works

The function creates a directory if it doesn't exist, writes a fake PEM file with a future expiry date, and returns simulated certbot output. This lets you test automation that triggers or handles certificate renewals without actually invoking certbot or needing a valid domain. The output mimics the real tool's messages so downstream logic can parse or assert on them reliably.

Common mistakes

  • Hardcoding the expiry date instead of computing it relative to now, causing tests to fail later.
  • Forgetting to create the output directory before writing the file, leading to FileNotFoundError.
  • Using actual certbot subprocess calls in unit tests, which are slow and environment-dependent.

Variations

  1. Use tempfile.TemporaryDirectory to keep test artifacts isolated.
  2. Capture the output with subprocess.run in a wrapper to simulate an exit code.

Real-world use cases

  • Writing integration tests for a script that provisions TLS certificates in a staging environment.
  • Validating log parsers that watch certbot output to detect successful renewals or failures.
  • Developing a cron job that triggers renewals and needs deterministic test data without hitting Let's Encrypt rate limits.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.