From 0758a79e64e377329810ec15f4ecd4413e935b2f Mon Sep 17 00:00:00 2001 From: Patrick Kanzler Date: Sun, 8 Nov 2020 22:33:51 +0100 Subject: [PATCH 1/2] test for graceful closing of socket --- test/test_printer_network.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 test/test_printer_network.py diff --git a/test/test_printer_network.py b/test/test_printer_network.py new file mode 100644 index 0000000..0669653 --- /dev/null +++ b/test/test_printer_network.py @@ -0,0 +1,23 @@ +#!/usr/bin/python + +import escpos.printer as printer +import pytest +import mock +import socket + + +@pytest.fixture +def instance(): + socket.socket.connect = mock.Mock() + return printer.Network("localhost") + +def test_close_without_open(instance): + """try to close without opening (should fail gracefully) + + Currently we never open from our fixture, so calling close once + should be enough. In the future this might not be enough, + therefore we have to close twice in order to provoke an error + (if possible, this should not raise) + """ + instance.close() + instance.close() \ No newline at end of file From 36bbb6690f6a5327c537f12d7ec4bb74b682d4fe Mon Sep 17 00:00:00 2001 From: Patrick Kanzler Date: Sun, 8 Nov 2020 22:34:57 +0100 Subject: [PATCH 2/2] handle socket error when closing --- src/escpos/printer.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/escpos/printer.py b/src/escpos/printer.py index 59bacad..47834f6 100644 --- a/src/escpos/printer.py +++ b/src/escpos/printer.py @@ -242,7 +242,10 @@ class Network(Escpos): def close(self): """ Close TCP connection """ if self.device is not None: - self.device.shutdown(socket.SHUT_RDWR) + try: + self.device.shutdown(socket.SHUT_RDWR) + except socket.error: + pass self.device.close()