Skip to content

Commit bcbfcdd

Browse files
authored
Merge pull request pyserial#240 from AmberAussie/master
serial: SerialBase with is idempotent
2 parents 13c8f6d + 48a5ce1 commit bcbfcdd

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

serial/serialutil.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -557,6 +557,8 @@ def readinto(self, b):
557557
# context manager
558558

559559
def __enter__(self):
560+
if not self.is_open:
561+
self.open()
560562
return self
561563

562564
def __exit__(self, *args, **kwargs):

test/test_context.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#! /usr/bin/env python
2+
#
3+
# This file is part of pySerial - Cross platform serial port support for Python
4+
# (C) 2017 Guillaume Galeazzi <[email protected]>
5+
#
6+
# SPDX-License-Identifier: BSD-3-Clause
7+
"""\
8+
Some tests for the serial module.
9+
Part of pySerial (http://pyserial.sf.net) (C)2001-2011 [email protected]
10+
11+
Intended to be run on different platforms, to ensure portability of
12+
the code.
13+
14+
Cover some of the aspects of context managment
15+
"""
16+
17+
import unittest
18+
import serial
19+
20+
# on which port should the tests be performed:
21+
PORT = 'loop://'
22+
23+
24+
class Test_Context(unittest.TestCase):
25+
"""Test context"""
26+
27+
def setUp(self):
28+
# create a closed serial port
29+
self.s = serial.serial_for_url(PORT)
30+
31+
def tearDown(self):
32+
self.s.close()
33+
34+
def test_with_idempotent(self):
35+
with self.s as stream:
36+
stream.write(b'1234')
37+
38+
# do other stuff like calling an exe which use COM4
39+
40+
with self.s as stream:
41+
stream.write(b'5678')
42+
43+
44+
if __name__ == '__main__':
45+
import sys
46+
sys.stdout.write(__doc__)
47+
sys.argv[1:] = ['-v']
48+
# When this module is executed from the command-line, it runs all its tests
49+
unittest.main()

0 commit comments

Comments
 (0)