How to Check an External Gateway vs Use an Internal Mock in Python
This code checks whether an external network gateway is reachable using ping, then falls back to a deterministic internal mock for testing environments.
Python code
34 linesimport subprocess
import sys
def check_external_gateway():
"""True if we can reach an external network target."""
try:
subprocess.run(
["ping", "-c", "1", "-W", "2", "8.8.8.8"],
capture_output=True,
timeout=3,
check=True,
)
return True
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError):
return False
class MockGateway:
"""Deterministic stand-in for external network access during tests."""
def __init__(self, success=True):
self.success = success
def reachable(self):
return self.success
def main():
external_available = check_external_gateway()
mock = MockGateway(success=True)
print(f"External gateway reachable: {external_available}")
print(f"Internal mock reachable: {mock.reachable()}")
print(f"Using {'EXTERNAL' if external_available else 'MOCK'} gateway")
if __name__ == "__main__":
main()
Output
External gateway reachable: True
Internal mock reachable: True
Using EXTERNAL gateway
How it works
The check_external_gateway function runs the system ping command via subprocess.run with a 2-second timeout per host. It captures output and suppresses errors so the function returns a clean boolean. The MockGateway class provides a simple, deterministic stand-in with a reachable() method that returns a preset value. The script prints the status of both gateways and selects which one to use — a common pattern in service discovery or feature-flag logic. This approach keeps tests reliable and offline-capable while production code retains real connectivity checks.
Common mistakes
- Hardcoding ping options that don't work on Windows (e.g. missing -W flag)
- Forgetting to catch FileNotFoundError when ping isn't installed
- Not using capture_output=True, causing noisy subprocess output
Variations
- Use socket.create_connection to an IP/port instead of ping for TCP-based checks
- Read reachability from an environment variable or config to skip the check entirely
Real-world use cases
- Service health checks that decide whether to call a live payment API or a sandbox mock in CI.
- Feature-flag systems that route traffic to external providers only when network is verified up.
- Local development containers that deterministically simulate cloud dependencies for offline testing.
Sponsored
More from Microservices patterns
- BFF aggregation pattern: combine multiple service responses in Python easy
- Backward Compatible Schema Evolution in Python medium
- Bulkhead Thread Pool per Service Mock in Python medium
- CQRS with Separate Read and Write Repositories in Python medium
- Cache-Aside Pattern in Python: Per-Service Mock easy
- Consumer Driven Contract Pact Mock in Python medium
Keep learning
Related tutorials and quizzes for this topic.