Michael WS Michael WS - 1 year ago 131
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download