diff options
| author | Eugene Triguba <eugenetriguba@gmail.com> | 2021-11-28 17:58:09 -0600 |
|---|---|---|
| committer | Eugene Triguba <eugenetriguba@gmail.com> | 2021-11-28 17:58:09 -0600 |
| commit | c1eaaca5a370b384b8b6fea4b385bbe676021bdc (patch) | |
| tree | 2f9ce3a67fe3f12fb0112286eda7e623e509dcec | |
| parent | Move maintenance section (diff) | |
| download | lirc-c1eaaca5a370b384b8b6fea4b385bbe676021bdc.zip | |
Use single underscore internal attribute prefixes
| -rw-r--r-- | CHANGELOG.rst | 6 | ||||
| -rw-r--r-- | lirc/client.py | 50 | ||||
| -rw-r--r-- | lirc/connection/default_connection.py | 12 | ||||
| -rw-r--r-- | lirc/connection/lircd_connection.py | 36 | ||||
| -rw-r--r-- | lirc/reply_packet_parser.py | 78 | ||||
| -rw-r--r-- | tests/test_client.py | 22 | ||||
| -rw-r--r-- | tests/test_lircd_connection.py | 14 | ||||
| -rw-r--r-- | tests/test_reply_packet_parser.py | 2 |
8 files changed, 108 insertions, 112 deletions
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 96fdd08..f5240d0 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -10,6 +10,12 @@ adheres to `Semantic Versioning <https://semver.org/spec/v2.0.0.html>`_. Unreleased ------------------ +**Changed** + +- All double underscore (`__`) internal attributes have been changed to instead + be prefixed by a single underscore (`_`). This removes the name mangling that Python + does on those attributes. + **Fixed** - `lirc.Client` will throw a `TypeError` only if the passed `connection` diff --git a/lirc/client.py b/lirc/client.py index b659c00..7b65457 100644 --- a/lirc/client.py +++ b/lirc/client.py @@ -29,13 +29,13 @@ class Client: raise TypeError("`connection` must be an instance of `AbstractConnection`") # Used for start_repeat and stop_repeat - self.__last_send_start_remote = None - self.__last_send_start_key = None + self._last_send_start_remote = None + self._last_send_start_key = None - self.__connection = connection - self.__connection.connect() + self._connection = connection + self._connection.connect() - def __send_command(self, command: str) -> Union[str, List[str]]: + def _send_command(self, command: str) -> Union[str, List[str]]: """ Send a command to lircd. @@ -45,11 +45,11 @@ class Client: Returns: The data from the lirc response packet. """ - self.__connection.send(command) + self._connection.send(command) parser = ReplyPacketParser() while not parser.is_finished: - line = self.__connection.readline() + line = self._connection.readline() parser.feed(line) parser_data = parser.data[0] if len(parser.data) == 1 else parser.data @@ -63,7 +63,7 @@ class Client: def close(self) -> None: """Close the connection to the socket.""" - self.__connection.close() + self._connection.close() def send_once(self, remote: str, key: str, repeat_count: int = 0) -> None: """ @@ -85,7 +85,7 @@ class Client: Raises: LircdCommandFailure: If the command fails. """ - self.__send_command(f"SEND_ONCE {remote} {key} {repeat_count}") + self._send_command(f"SEND_ONCE {remote} {key} {repeat_count}") def send_start(self, remote: str, key: str) -> None: """ @@ -101,9 +101,9 @@ class Client: Raises: LircdCommandFailure: If the command fails. """ - self.__last_send_start_remote = remote - self.__last_send_start_key = key - self.__send_command(f"SEND_START {remote} {key}") + self._last_send_start_remote = remote + self._last_send_start_key = key + self._send_command(f"SEND_START {remote} {key}") def send_stop(self, remote: str = "", key: str = "") -> None: """ @@ -121,13 +121,13 @@ class Client: Raises: LircdCommandFailure: If the command fails. """ - if not remote and self.__last_send_start_remote: - remote = self.__last_send_start_remote + if not remote and self._last_send_start_remote: + remote = self._last_send_start_remote - if not key and self.__last_send_start_key: - key = self.__last_send_start_key + if not key and self._last_send_start_key: + key = self._last_send_start_key - self.__send_command(f"SEND_STOP {remote} {key}") + self._send_command(f"SEND_STOP {remote} {key}") def list_remotes(self) -> List[str]: """ @@ -140,7 +140,7 @@ class Client: Returns: The list of all remotes. """ - return self.__send_command("LIST") + return self._send_command("LIST") def list_remote_keys(self, remote: str) -> List[str]: """ @@ -155,7 +155,7 @@ class Client: Returns: The list of keys from the remote. """ - return self.__send_command(f"LIST {remote}") + return self._send_command(f"LIST {remote}") def start_logging(self, path: Union[str, Path]) -> None: """ @@ -168,7 +168,7 @@ class Client: Raises: LircdCommandFailure: If the command fails. """ - self.__send_command(f"SET_INPUTLOG {path}") + self._send_command(f"SET_INPUTLOG {path}") def stop_logging(self) -> None: """ @@ -179,7 +179,7 @@ class Client: """ # When calling SET_INPUTLOG without the path argument, # it will stop logging and close the logfile. - self.__send_command("SET_INPUTLOG") + self._send_command("SET_INPUTLOG") def version(self) -> str: """ @@ -191,7 +191,7 @@ class Client: Returns: The version of LIRC being used. """ - return self.__send_command("VERSION") + return self._send_command("VERSION") def driver_option(self, key: str, value: str) -> None: """ @@ -204,7 +204,7 @@ class Client: Raises: LircdCommandFailure: If the command fails. """ - self.__send_command(f"DRV_OPTION {key} {value}") + self._send_command(f"DRV_OPTION {key} {value}") def simulate( self, remote: str, key: str, repeat_count: int = 1, keycode: int = 0 @@ -232,7 +232,7 @@ class Client: Raises: LircdCommandFailure: If the command fails. """ - self.__send_command( + self._send_command( "SIMULATE %016d %02d %s %s\n" % (keycode, repeat_count, key, remote) ) @@ -262,4 +262,4 @@ class Client: for transmitter in transmitters: mask |= 1 << (int(transmitter) - 1) - self.__send_command(f"SET_TRANSMITTERS {mask}") + self._send_command(f"SET_TRANSMITTERS {mask}") diff --git a/lirc/connection/default_connection.py b/lirc/connection/default_connection.py index e9c7272..5d3c3b1 100644 --- a/lirc/connection/default_connection.py +++ b/lirc/connection/default_connection.py @@ -11,7 +11,7 @@ class DefaultConnection: This class provides our operating specific default connection parameters. """ - self.__operating_system = platform.system() + self._operating_system = platform.system() @property def socket(self) -> socket.socket: @@ -26,14 +26,14 @@ class DefaultConnection: UnsupportedOperatingSystemError: If the OS is not Linux, Windows, or Darwin. """ - if self.__operating_system == "Linux" or self.__operating_system == "Darwin": + if self._operating_system == "Linux" or self._operating_system == "Darwin": return socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - if self.__operating_system == "Windows": + if self._operating_system == "Windows": return socket.socket(socket.AF_INET, socket.SOCK_STREAM) raise UnsupportedOperatingSystemError( - f"{self.__operating_system} is not supported for a default OS " + f"{self._operating_system} is not supported for a default OS " "socket to lircd." ) @@ -57,9 +57,9 @@ class DefaultConnection: "Linux": "/var/run/lirc/lircd", "Windows": ("localhost", 8765), "Darwin": "/opt/local/var/run/lirc/lircd", - }[self.__operating_system] + }[self._operating_system] except KeyError: raise UnsupportedOperatingSystemError( - f"{self.__operating_system} is not supported for a default OS " + f"{self._operating_system} is not supported for a default OS " "address to lircd." ) diff --git a/lirc/connection/lircd_connection.py b/lirc/connection/lircd_connection.py index 30be4b8..3b2c6aa 100644 --- a/lirc/connection/lircd_connection.py +++ b/lirc/connection/lircd_connection.py @@ -44,11 +44,11 @@ class LircdConnection(AbstractConnection): if socket is None: socket = default.socket - self.__buffer = deque() - self.__buffer_size = 4096 - self.__address = address - self.__socket = socket - self.__socket.settimeout(timeout) + self._buffer = deque() + self._buffer_size = 4096 + self._address = address + self._socket = socket + self._socket.settimeout(timeout) def connect(self): """ @@ -59,11 +59,11 @@ class LircdConnection(AbstractConnection): is not running. """ try: - self.__socket.connect(self.__address) + self._socket.connect(self._address) except FileNotFoundError: raise LircdConnectionError( - f"Could not connect to lircd at {self.__address} with socket " - f"{self.__socket}. Did you start the `lircd` daemon?" + f"Could not connect to lircd at {self._address} with socket " + f"{self._socket}. Did you start the `lircd` daemon?" ) except Exception as error: raise LircdConnectionError(error) @@ -77,13 +77,13 @@ class LircdConnection(AbstractConnection): Returns: The current address being used. """ - return self.__address + return self._address def close(self): """ Closes the socket connection. """ - self.__socket.close() + self._socket.close() def send(self, data: str): """ @@ -101,7 +101,7 @@ class LircdConnection(AbstractConnection): if not data.endswith("\n"): data += "\n" - self.__socket.sendall(data.encode("utf-8")) + self._socket.sendall(data.encode("utf-8")) def readline(self) -> str: """ @@ -125,27 +125,27 @@ class LircdConnection(AbstractConnection): Returns: A line from the lircd socket. """ - if len(self.__buffer) >= 1: - return self.__buffer.popleft() + if len(self._buffer) >= 1: + return self._buffer.popleft() try: - packet = self.__socket.recv(self.__buffer_size) + packet = self._socket.recv(self._buffer_size) if packet.endswith(b"\n"): packet = packet.strip() if b"\n" in packet: - self.__buffer.extend( + self._buffer.extend( line.decode("utf-8") for line in packet.split(b"\n") ) else: - self.__buffer.append(packet.decode("utf-8")) + self._buffer.append(packet.decode("utf-8")) - return self.__buffer.popleft() + return self._buffer.popleft() except socket.timeout: raise TimeoutError( "could not find any data on the socket after " - f"{self.__socket.gettimeout()} seconds, socket timed out." + f"{self._socket.gettimeout()} seconds, socket timed out." ) except socket.error as error: raise LircdSocketError( diff --git a/lirc/reply_packet_parser.py b/lirc/reply_packet_parser.py index 08be1e0..bbcd00d 100644 --- a/lirc/reply_packet_parser.py +++ b/lirc/reply_packet_parser.py @@ -72,20 +72,20 @@ class ReplyPacketParser: # the given line to the function at our current state. # That function is then responsible for handling any errors # and advancing the state forward. - self.__fsm = { - self.State.BEGIN: self.__begin, - self.State.COMMAND: self.__command, - self.State.RESULT: self.__result, - self.State.DATA: self.__data, - self.State.LINE_COUNT_LEFT: self.__line_count_left, - self.State.DATA_BODY: self.__data_body, - self.State.SIGHUP_END: self.__sighup_end, - self.State.END: self.__end, + self._fsm = { + self.State.BEGIN: self._begin, + self.State.COMMAND: self._command, + self.State.RESULT: self._result, + self.State.DATA: self._data, + self.State.LINE_COUNT_LEFT: self._line_count_left, + self.State.DATA_BODY: self._data_body, + self.State.SIGHUP_END: self._sighup_end, + self.State.END: self._end, } - self.__state = self.State.BEGIN - self.__command_result = self.Result.UNDETERMINED - self.__data_response = [] - self.__lines_left = None + self._state = self.State.BEGIN + self._command_result = self.Result.UNDETERMINED + self._data_response = [] + self._lines_left = None @property def data(self) -> list: @@ -95,7 +95,7 @@ class ReplyPacketParser: Returns: The data response. """ - return self.__data_response + return self._data_response @property def is_finished(self) -> bool: @@ -105,7 +105,7 @@ class ReplyPacketParser: Returns: True if we are in the finished state; False otherwise. """ - return self.__state == self.State.FINISHED + return self._state == self.State.FINISHED @property def success(self) -> bool: @@ -115,9 +115,9 @@ class ReplyPacketParser: Returns: True if the command result is success; False otherwise. """ - return self.__command_result == self.Result.SUCCESS + return self._command_result == self.Result.SUCCESS - def __begin(self, line: str) -> None: + def _begin(self, line: str) -> None: """ Handles the BEGIN state. This should be the state we start in and transition to reading in @@ -130,13 +130,13 @@ class ReplyPacketParser: LircdInvalidReplyPacketError: If line is not BEGIN. """ if line == "BEGIN": - self.__state = self.State.COMMAND + self._state = self.State.COMMAND else: raise LircdInvalidReplyPacketError( f"Expected a BEGIN line from lircd, got `{line}`." ) - def __command(self, line: str) -> None: + def _command(self, line: str) -> None: """ Handles the COMMAND state. For parsing the reply packet, we don't care too much about this state. As long as we got @@ -153,15 +153,15 @@ class ReplyPacketParser: if the line is empty, feed() simply returns. """ if line == "SIGHUP": - self.__state = self.State.SIGHUP_END + self._state = self.State.SIGHUP_END elif line: - self.__state = self.State.RESULT + self._state = self.State.RESULT else: raise LircdInvalidReplyPacketError( f"Expected a command line from lircd, got `{line}`." ) - def __result(self, line: str) -> None: + def _result(self, line: str) -> None: """ Handles the RESULT state. An lircd result is either SUCCESS or ERROR, followed by data. @@ -173,8 +173,8 @@ class ReplyPacketParser: LircdInvalidReplyPacketError: If the line is not SUCCESS or ERROR. """ if line in ["SUCCESS", "ERROR"]: - self.__state = self.State.DATA - self.__command_result = ( + self._state = self.State.DATA + self._command_result = ( self.Result.SUCCESS if line == "SUCCESS" else self.Result.FAIL ) else: @@ -182,7 +182,7 @@ class ReplyPacketParser: f"Expected a result line from lircd, got `{line}`." ) - def __data(self, line: str) -> None: + def _data(self, line: str) -> None: """ Handles the DATA state. In this state, we could either be finished now if there is @@ -196,15 +196,15 @@ class ReplyPacketParser: LircdInvalidReplyPacketError: If line is not END or DATA. """ if line == "END": - self.__state = self.State.FINISHED + self._state = self.State.FINISHED elif line == "DATA": - self.__state = self.State.LINE_COUNT_LEFT + self._state = self.State.LINE_COUNT_LEFT else: raise LircdInvalidReplyPacketError( f"Expected an END or DATA line from lircd, got `{line}`." ) - def __line_count_left(self, line: str) -> None: + def _line_count_left(self, line: str) -> None: """ Handles the LINE COUNT LEFT state. This corresponds to the `n` line in the packet format, since it tells @@ -219,17 +219,15 @@ class ReplyPacketParser: lines left at this state. """ try: - self.__lines_left = int(line) + self._lines_left = int(line) except ValueError: raise LircdInvalidReplyPacketError( f"Expected a remaining line count line from lircd, got `{line}`." ) - self.__state = ( - self.State.END if self.__lines_left == 0 else self.State.DATA_BODY - ) + self._state = self.State.END if self._lines_left == 0 else self.State.DATA_BODY - def __data_body(self, line: str) -> None: + def _data_body(self, line: str) -> None: """ Handles the DATA BODY state by appending every line we recieve to the data response. @@ -242,11 +240,11 @@ class ReplyPacketParser: Args: line: A line read in from an lircd connection. """ - self.__data_response.append(line) - if len(self.__data_response) >= self.__lines_left: - self.__state = self.State.END + self._data_response.append(line) + if len(self._data_response) >= self._lines_left: + self._state = self.State.END - def __sighup_end(self, line: str) -> None: + def _sighup_end(self, line: str) -> None: """ Handle a SIGHUP END line by resetting the parser. @@ -268,7 +266,7 @@ class ReplyPacketParser: f"lircd, got `{line}` instead." ) - def __end(self, line: str) -> None: + def _end(self, line: str) -> None: """ Handle a END line by transitioning the parser's state to finished. This means we have finished reading in the @@ -281,7 +279,7 @@ class ReplyPacketParser: LircdInvalidReplyPacketError: If the line does not contain END. """ if line == "END": - self.__state = self.State.FINISHED + self._state = self.State.FINISHED else: raise LircdInvalidReplyPacketError( "Expected an END line from lircd's reply packet, " @@ -300,4 +298,4 @@ class ReplyPacketParser: if not line: return - self.__fsm[self.__state](line) + self._fsm[self._state](line) diff --git a/tests/test_client.py b/tests/test_client.py index e7b80d5..b930f5d 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -17,7 +17,7 @@ def test_that_custom_connections_can_be_used(mock_socket): client = Client(connection=connection) # SUT - assert client._Client__connection == connection + assert client._connection == connection def test_that_custom_connection_that_is_not_an_abstract_connection_raises_error( @@ -50,7 +50,7 @@ def test_that_no_connection_passed_in_creates_default_one(): with mock.patch("lirc.client.LircdConnection", MockedLircdConnection): c = Client() - assert isinstance(c._Client__connection, MockedLircdConnection) + assert isinstance(c._connection, MockedLircdConnection) def test_that_close_closes_the_socket(mock_client_and_connection): @@ -63,7 +63,7 @@ def test_that_close_closes_the_socket(mock_client_and_connection): client.close() # SUT - connection._LircdConnection__socket.close.assert_called() + connection._socket.close.assert_called() @pytest.mark.parametrize( @@ -124,13 +124,11 @@ def test_that_client_commands_send_the_correct_command( lircd_command: The expected corresponding command sent to lircd. """ client, connection = mock_client_and_connection - connection._LircdConnection__socket.recv.return_value = ( - b"BEGIN\nCOMMAND\nSUCCESS\nEND\n" - ) + connection._socket.recv.return_value = b"BEGIN\nCOMMAND\nSUCCESS\nEND\n" getattr(client, client_command)(**args) # SUT - connection._LircdConnection__socket.sendall.assert_called_with( + connection._socket.sendall.assert_called_with( (lircd_command + "\n").encode("utf-8") ) @@ -143,9 +141,7 @@ def test_unsuccessful_command_raises_custom_exception(mock_client_and_connection LircdCommandFailureError. """ client, connection = mock_client_and_connection - connection._LircdConnection__socket.recv.return_value = ( - b"BEGIN\nCOMMAND\nERROR\nEND\n" - ) + connection._socket.recv.return_value = b"BEGIN\nCOMMAND\nERROR\nEND\n" with pytest.raises(LircdCommandFailureError) as error: client.send_once("remote", "key") @@ -163,13 +159,11 @@ def test_last_send_start_remote_and_key_is_used(mock_client_and_connection): had passed in as args if no args are provided to send_stop. """ client, connection = mock_client_and_connection - connection._LircdConnection__socket.recv.return_value = ( - b"BEGIN\nCOMMAND\nSUCCESS\nEND\n" - ) + connection._socket.recv.return_value = b"BEGIN\nCOMMAND\nSUCCESS\nEND\n" client.send_start("remote", "key") client.send_stop() # SUT - connection._LircdConnection__socket.sendall.assert_called_with( + connection._socket.sendall.assert_called_with( "SEND_STOP remote key\n".encode("utf-8") ) diff --git a/tests/test_lircd_connection.py b/tests/test_lircd_connection.py index 7221215..f8693b4 100644 --- a/tests/test_lircd_connection.py +++ b/tests/test_lircd_connection.py @@ -16,7 +16,7 @@ def test_close_closes_the_socket_connection(mock_connection): """ mock_connection.close() # SUT - mock_connection._LircdConnection__socket.close.assert_called() + mock_connection._socket.close.assert_called() def test_that_retrieving_the_address_property_retrieves_the_address(mock_socket): @@ -97,7 +97,7 @@ def test_that_send_adds_a_newline_to_the_end(mock_connection, test_command): """ mock_connection.send(test_command) # SUT - mock_connection._LircdConnection__socket.sendall.assert_called_with( + mock_connection._socket.sendall.assert_called_with( f"{test_command}\n".encode("utf-8") ) @@ -113,9 +113,7 @@ def test_that_send_does_not_add_too_many_newlines(mock_connection): mock_connection.send(command) # SUT - mock_connection._LircdConnection__socket.sendall.assert_called_with( - f"{command}".encode("utf-8") - ) + mock_connection._socket.sendall.assert_called_with(f"{command}".encode("utf-8")) @pytest.mark.parametrize("test_command", [5, False, 0.1, b"hello"]) @@ -147,7 +145,7 @@ def test_that_readline_uses_buffer_if_items_are_present_in_it( Ensure that readline uses the buffer if there are items in it. """ - mock_connection._LircdConnection__buffer.extend(buffer_payload) + mock_connection._buffer.extend(buffer_payload) line = mock_connection.readline() # SUT @@ -171,12 +169,12 @@ def test_that_readline_retrieves_data_from_socket_and_adds_to_buffer( Ensure that when we call readline(), it adds to the buffer if we retrieved more than a single line. """ - mock_connection._LircdConnection__socket.recv.return_value = socket_payload + mock_connection._socket.recv.return_value = socket_payload line = mock_connection.readline() # SUT assert line == expected_return - assert mock_connection._LircdConnection__buffer == expected_buffer + assert mock_connection._buffer == expected_buffer @patch("socket.socket.recv") diff --git a/tests/test_reply_packet_parser.py b/tests/test_reply_packet_parser.py index 304bb74..82af1a5 100644 --- a/tests/test_reply_packet_parser.py +++ b/tests/test_reply_packet_parser.py @@ -203,4 +203,4 @@ def test_command_state_raises_exception_on_empty_line(line): parser = ReplyPacketParser() with pytest.raises(LircdInvalidReplyPacketError): - parser._ReplyPacketParser__command(line) + parser._command(line) |