diff options
author | zsquareplusc <cliechti@gmx.net> | 2017-07-01 23:26:06 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-07-01 23:26:06 +0200 |
commit | bcbfcddd4e70ba2ada267c49574f1902f4c1c3e8 (patch) | |
tree | 440e9e4100fa93e1056897df8f8166d76eb64fe2 | |
parent | 13c8f6da4539b7c4ca8372fe614560cfe0e4eddd (diff) | |
parent | 48a5ce1b914f3a56c77b599316a1c50f675b3212 (diff) | |
download | pyserial-git-bcbfcddd4e70ba2ada267c49574f1902f4c1c3e8.tar.gz |
Merge pull request #240 from AmberAussie/master
serial: SerialBase with is idempotent
-rw-r--r-- | serial/serialutil.py | 2 | ||||
-rwxr-xr-x | test/test_context.py | 49 |
2 files changed, 51 insertions, 0 deletions
diff --git a/serial/serialutil.py b/serial/serialutil.py index e4df90f..7d51752 100644 --- a/serial/serialutil.py +++ b/serial/serialutil.py @@ -557,6 +557,8 @@ class SerialBase(io.RawIOBase): # context manager def __enter__(self): + if not self.is_open: + self.open() return self def __exit__(self, *args, **kwargs): diff --git a/test/test_context.py b/test/test_context.py new file mode 100755 index 0000000..456c85a --- /dev/null +++ b/test/test_context.py @@ -0,0 +1,49 @@ +#! /usr/bin/env python
+#
+# This file is part of pySerial - Cross platform serial port support for Python
+# (C) 2017 Guillaume Galeazzi <guillaume.g@leazzi.ch>
+#
+# SPDX-License-Identifier: BSD-3-Clause
+"""\
+Some tests for the serial module.
+Part of pySerial (http://pyserial.sf.net) (C)2001-2011 cliechti@gmx.net
+
+Intended to be run on different platforms, to ensure portability of
+the code.
+
+Cover some of the aspects of context managment
+"""
+
+import unittest
+import serial
+
+# on which port should the tests be performed:
+PORT = 'loop://'
+
+
+class Test_Context(unittest.TestCase):
+ """Test context"""
+
+ def setUp(self):
+ # create a closed serial port
+ self.s = serial.serial_for_url(PORT)
+
+ def tearDown(self):
+ self.s.close()
+
+ def test_with_idempotent(self):
+ with self.s as stream:
+ stream.write(b'1234')
+
+ # do other stuff like calling an exe which use COM4
+
+ with self.s as stream:
+ stream.write(b'5678')
+
+
+if __name__ == '__main__':
+ import sys
+ sys.stdout.write(__doc__)
+ sys.argv[1:] = ['-v']
+ # When this module is executed from the command-line, it runs all its tests
+ unittest.main()
|