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.
pip install pdm
Python code
25 linesfrom 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
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
- Use `unittest.mock.patch('pdm.build')` directly if you import pdm functions individually.
- 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
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.