Michael WS Michael WS - 5 months ago 24
Python Question

change hostname for continuous integration testing

I have some functionality that only runs in specific physical locations and it is known by the hostname. This is produced in a cython module that calls socket.gethostname().

Is there anyway to make a test using socket.gethostname() have different data from the host the test is running on?


You could use the mock module:

import mock
import socket

with mock.patch("socket.gethostname", return_value="completely fake"):
    print socket.gethostname()

Thsi prints completely fake on stdout.

mock is bundled with Python 3.3 and over (as unittest.mock) and is available as a backport for Python 2.6.x and up. The above code runs as-is with Python 2.7.x.