How to make tests for scripts that access a serial port
<p>I am developing a package that connects to an external device to ask to do some functions. For instance, a sample script of the package could be the following:</p>

<pre><code>from serial import Serial
import glob

class SerialComm():
    def __init__(self)
        # Do some stuff
        # ...
        self.port = glob.glob('/dev/ttyUSB*')[0]
        self.serial = Serial(port=self.port)

    def ask_if_ready(port, baudrate):
        """Send an acknowledge request through serial port."""
        message = SerialComm.build_message(function='ready')
        my_serial = Serial(port=port, baudrate=baudrate)
        my_serial.write(message) 
        return my_serial.read()

    def build_message(function):
        """Makes a message based on a protocol"""
        #Do stuff
        return message
</code></pre>

<p>I would like to write some tests to assess the code, and I would like this test to be autonomous and do not depend on whether there is a device connected to the PC or not. However, if there is not any device connected, the previous code will crash before any assertion could be made (glob.glob() function and serial functions require some device connected).</p>

<p>I can not figure out how to trick the code in order to simulate the behaviour of a device connected to a serial port and test the different methods of my class.</p>