46 lines
1.6 KiB
Python
46 lines
1.6 KiB
Python
import pytest
|
|
from unittest.mock import patch, MagicMock
|
|
import serial
|
|
from m2m.serial.serial_port import SerialPort
|
|
from m2m.exceptions import SerialError
|
|
|
|
def test_serial_port_standard():
|
|
with patch('serial.serial_for_url') as mock_for_url:
|
|
mock_serial = MagicMock()
|
|
mock_for_url.return_value = mock_serial
|
|
|
|
with SerialPort(port='/dev/ttyUSB0', baudrate=115200) as sp:
|
|
mock_for_url.assert_called_once_with(
|
|
url='/dev/ttyUSB0',
|
|
baudrate=115200,
|
|
timeout=1.0
|
|
)
|
|
|
|
def test_serial_port_tcp_url():
|
|
with patch('serial.serial_for_url') as mock_for_url:
|
|
mock_serial = MagicMock()
|
|
mock_for_url.return_value = mock_serial
|
|
|
|
url = 'socket://1.2.3.4:5678'
|
|
with SerialPort(port=url, baudrate=9600) as sp:
|
|
mock_for_url.assert_called_once_with(
|
|
url=url,
|
|
baudrate=9600,
|
|
timeout=1.0
|
|
)
|
|
|
|
def test_serial_port_invalid_url():
|
|
with patch('serial.serial_for_url') as mock_for_url:
|
|
mock_for_url.side_effect = ValueError("invalid URL")
|
|
|
|
with pytest.raises(SerialError) as excinfo:
|
|
SerialPort(port='invalid://port')
|
|
assert "Could not open invalid://port" in str(excinfo.value)
|
|
|
|
def test_serial_port_mock():
|
|
# Verify 'MOCK' still uses MockSerial and NOT serial_for_url
|
|
with patch('m2m.serial.serial_port.MockSerial') as mock_mock:
|
|
with patch('serial.serial_for_url') as mock_for_url:
|
|
sp = SerialPort(port='MOCK')
|
|
mock_mock.assert_called_once()
|
|
mock_for_url.assert_not_called()
|