Mock pdm build and publish in Python

Simulate pdm build and publish commands with unittest.mock to test packaging workflows without triggering real builds or uploads.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 12 views 0 copies

Requires third-party packages — install first
pip install pdm

Python code

25 lines
Python 3.9+
from unittest.mock import Mock, patch

import pdm


def build_package() -> str:
    """Simulate building a package with pdm."""
    build_mock = Mock(return_value="dist/mypackage-0.1.0-py3-none-any.whl")
    with patch.object(pdm, "build", build_mock):
        result = pdm.build()
    return result


def publish_package(dist_path: str) -> str:
    """Simulate publishing a built package."""
    publish_mock = Mock(return_value=f"Published to PyPI: {dist_path}")
    with patch.object(pdm, "publish", publish_mock):
        result = pdm.publish(dist_path)
    return result


if __name__ == "__main__":
    dist = build_package()
    output = publish_package(dist)
    print(output)

Output

stdout
Published to PyPI: dist/mypackage-0.1.0-py3-none-any.whl

How it works

Mock(return_value=...) creates a callable that always returns the given value, allowing you to replace pdm.build and pdm.publish with controlled stand-ins. patch.object temporarily swaps the real function for the mock for the duration of the with block, then restores it automatically. This isolates the code under test from external side effects (disk writes, network calls) and makes the behavior deterministic. The __name__ == "__main__" guard runs the simulation when the script is executed directly, printing the final publish message. This pattern is standard for unit testing CLI wrappers and build tooling.

Common mistakes

  • Forgetting to import Mock before using it, causing a NameError.
  • Using `patch` instead of `patch.object`—the latter is needed when targeting a method on a module.
  • Not asserting that the mock was called with the expected arguments, missing verification.

Variations

  1. Use `unittest.mock.patch('pdm.build')` directly if you import pdm functions individually.
  2. Apply `patch` as a decorator for cleaner test methods: `@patch('pdm.publish')`.

Real-world use cases

  • Testing CI/CD scripts that invoke pdm build before publishing artifacts without actually creating wheels.
  • Writing unit tests for release automation components that call publish commands, avoiding accidental PyPI uploads.
  • Simulating packaging steps in development environments to validate end-to-end flow logic.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Modern tooling

Related tutorials and quizzes for this topic.