Skip to content

Commit 3db0cd9

Browse files
committed
TST: Use capture_stdout in testing
1 parent 88f5851 commit 3db0cd9

File tree

6 files changed

+65
-81
lines changed

6 files changed

+65
-81
lines changed

pandas/tests/frame/test_repr_info.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -191,18 +191,16 @@ def test_latex_repr(self):
191191
# GH 12182
192192
self.assertIsNone(df._repr_latex_())
193193

194+
@tm.capture_stdout
194195
def test_info(self):
195196
io = StringIO()
196197
self.frame.info(buf=io)
197198
self.tsframe.info(buf=io)
198199

199200
frame = DataFrame(np.random.randn(5, 3))
200201

201-
import sys
202-
sys.stdout = StringIO()
203202
frame.info()
204203
frame.info(verbose=False)
205-
sys.stdout = sys.__stdout__
206204

207205
def test_info_wide(self):
208206
from pandas import set_option, reset_option

pandas/tests/io/parser/common.py

Lines changed: 23 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1254,6 +1254,7 @@ def test_regex_separator(self):
12541254
columns=['a', 'b', 'c'])
12551255
tm.assert_frame_equal(result, expected)
12561256

1257+
@tm.capture_stdout
12571258
def test_verbose_import(self):
12581259
text = """a,b,c,d
12591260
one,1,2,3
@@ -1265,22 +1266,19 @@ def test_verbose_import(self):
12651266
one,1,2,3
12661267
two,1,2,3"""
12671268

1268-
buf = StringIO()
1269-
sys.stdout = buf
1270-
1271-
try: # engines are verbose in different ways
1272-
self.read_csv(StringIO(text), verbose=True)
1273-
if self.engine == 'c':
1274-
self.assertIn('Tokenization took:', buf.getvalue())
1275-
self.assertIn('Parser memory cleanup took:', buf.getvalue())
1276-
else: # Python engine
1277-
self.assertEqual(buf.getvalue(),
1278-
'Filled 3 NA values in column a\n')
1279-
finally:
1280-
sys.stdout = sys.__stdout__
1269+
# Engines are verbose in different ways.
1270+
self.read_csv(StringIO(text), verbose=True)
1271+
output = sys.stdout.getvalue()
1272+
1273+
if self.engine == 'c':
1274+
self.assertIn('Tokenization took:', output)
1275+
self.assertIn('Parser memory cleanup took:', output)
1276+
else: # Python engine
1277+
exp = 'Filled 3 NA values in column a\n'
1278+
self.assertEqual(output, exp)
12811279

1282-
buf = StringIO()
1283-
sys.stdout = buf
1280+
# Reset the stdout buffer.
1281+
sys.stdout = StringIO()
12841282

12851283
text = """a,b,c,d
12861284
one,1,2,3
@@ -1292,16 +1290,16 @@ def test_verbose_import(self):
12921290
seven,1,2,3
12931291
eight,1,2,3"""
12941292

1295-
try: # engines are verbose in different ways
1296-
self.read_csv(StringIO(text), verbose=True, index_col=0)
1297-
if self.engine == 'c':
1298-
self.assertIn('Tokenization took:', buf.getvalue())
1299-
self.assertIn('Parser memory cleanup took:', buf.getvalue())
1300-
else: # Python engine
1301-
self.assertEqual(buf.getvalue(),
1302-
'Filled 1 NA values in column a\n')
1303-
finally:
1304-
sys.stdout = sys.__stdout__
1293+
self.read_csv(StringIO(text), verbose=True, index_col=0)
1294+
output = sys.stdout.getvalue()
1295+
1296+
# Engines are verbose in different ways.
1297+
if self.engine == 'c':
1298+
self.assertIn('Tokenization took:', output)
1299+
self.assertIn('Parser memory cleanup took:', output)
1300+
else: # Python engine
1301+
exp = 'Filled 1 NA values in column a\n'
1302+
self.assertEqual(output, exp)
13051303

13061304
def test_iteration_open_handle(self):
13071305
if PY3:

pandas/tests/io/parser/python_parser_only.py

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
"""
99

1010
import csv
11-
import sys
1211
import pytest
1312

1413
import pandas.util.testing as tm
@@ -92,16 +91,9 @@ def test_BytesIO_input(self):
9291

9392
def test_single_line(self):
9493
# see gh-6607: sniff separator
95-
96-
buf = StringIO()
97-
sys.stdout = buf
98-
99-
try:
100-
df = self.read_csv(StringIO('1,2'), names=['a', 'b'],
101-
header=None, sep=None)
102-
tm.assert_frame_equal(DataFrame({'a': [1], 'b': [2]}), df)
103-
finally:
104-
sys.stdout = sys.__stdout__
94+
df = self.read_csv(StringIO('1,2'), names=['a', 'b'],
95+
header=None, sep=None)
96+
tm.assert_frame_equal(DataFrame({'a': [1], 'b': [2]}), df)
10597

10698
def test_skipfooter(self):
10799
# see gh-6607

pandas/tests/io/test_sql.py

Lines changed: 19 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
import sqlite3
2424
import csv
2525
import os
26-
import sys
2726

2827
import warnings
2928
import numpy as np
@@ -36,7 +35,7 @@
3635
from pandas import DataFrame, Series, Index, MultiIndex, isnull, concat
3736
from pandas import date_range, to_datetime, to_timedelta, Timestamp
3837
import pandas.compat as compat
39-
from pandas.compat import StringIO, range, lrange, string_types, PY36
38+
from pandas.compat import range, lrange, string_types, PY36
4039
from pandas.tseries.tools import format as date_format
4140

4241
import pandas.io.sql as sql
@@ -2220,6 +2219,7 @@ def test_schema(self):
22202219
cur = self.conn.cursor()
22212220
cur.execute(create_sql)
22222221

2222+
@tm.capture_stdout
22232223
def test_execute_fail(self):
22242224
create_sql = """
22252225
CREATE TABLE test
@@ -2236,14 +2236,11 @@ def test_execute_fail(self):
22362236
sql.execute('INSERT INTO test VALUES("foo", "bar", 1.234)', self.conn)
22372237
sql.execute('INSERT INTO test VALUES("foo", "baz", 2.567)', self.conn)
22382238

2239-
try:
2240-
sys.stdout = StringIO()
2241-
self.assertRaises(Exception, sql.execute,
2242-
'INSERT INTO test VALUES("foo", "bar", 7)',
2243-
self.conn)
2244-
finally:
2245-
sys.stdout = sys.__stdout__
2239+
self.assertRaises(Exception, sql.execute,
2240+
'INSERT INTO test VALUES("foo", "bar", 7)',
2241+
self.conn)
22462242

2243+
@tm.capture_stdout
22472244
def test_execute_closed_connection(self):
22482245
create_sql = """
22492246
CREATE TABLE test
@@ -2259,12 +2256,10 @@ def test_execute_closed_connection(self):
22592256

22602257
sql.execute('INSERT INTO test VALUES("foo", "bar", 1.234)', self.conn)
22612258
self.conn.close()
2262-
try:
2263-
sys.stdout = StringIO()
2264-
self.assertRaises(Exception, tquery, "select * from test",
2265-
con=self.conn)
2266-
finally:
2267-
sys.stdout = sys.__stdout__
2259+
2260+
self.assertRaises(Exception, tquery,
2261+
"select * from test",
2262+
con=self.conn)
22682263

22692264
# Initialize connection again (needed for tearDown)
22702265
self.setUp()
@@ -2534,6 +2529,7 @@ def test_schema(self):
25342529
cur.execute(drop_sql)
25352530
cur.execute(create_sql)
25362531

2532+
@tm.capture_stdout
25372533
def test_execute_fail(self):
25382534
_skip_if_no_pymysql()
25392535
drop_sql = "DROP TABLE IF EXISTS test"
@@ -2553,14 +2549,11 @@ def test_execute_fail(self):
25532549
sql.execute('INSERT INTO test VALUES("foo", "bar", 1.234)', self.conn)
25542550
sql.execute('INSERT INTO test VALUES("foo", "baz", 2.567)', self.conn)
25552551

2556-
try:
2557-
sys.stdout = StringIO()
2558-
self.assertRaises(Exception, sql.execute,
2559-
'INSERT INTO test VALUES("foo", "bar", 7)',
2560-
self.conn)
2561-
finally:
2562-
sys.stdout = sys.__stdout__
2552+
self.assertRaises(Exception, sql.execute,
2553+
'INSERT INTO test VALUES("foo", "bar", 7)',
2554+
self.conn)
25632555

2556+
@tm.capture_stdout
25642557
def test_execute_closed_connection(self):
25652558
_skip_if_no_pymysql()
25662559
drop_sql = "DROP TABLE IF EXISTS test"
@@ -2579,12 +2572,10 @@ def test_execute_closed_connection(self):
25792572

25802573
sql.execute('INSERT INTO test VALUES("foo", "bar", 1.234)', self.conn)
25812574
self.conn.close()
2582-
try:
2583-
sys.stdout = StringIO()
2584-
self.assertRaises(Exception, tquery, "select * from test",
2585-
con=self.conn)
2586-
finally:
2587-
sys.stdout = sys.__stdout__
2575+
2576+
self.assertRaises(Exception, tquery,
2577+
"select * from test",
2578+
con=self.conn)
25882579

25892580
# Initialize connection again (needed for tearDown)
25902581
self.setUp()

pandas/util/decorators.py

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1-
from pandas.compat import StringIO, callable, signature
1+
from pandas.compat import callable, signature
22
from pandas._libs.lib import cache_readonly # noqa
33
import types
4-
import sys
54
import warnings
65
from textwrap import dedent
76
from functools import wraps, update_wrapper
@@ -196,17 +195,6 @@ def indent(text, indents=1):
196195
return jointext.join(text.split('\n'))
197196

198197

199-
def suppress_stdout(f):
200-
def wrapped(*args, **kwargs):
201-
try:
202-
sys.stdout = StringIO()
203-
f(*args, **kwargs)
204-
finally:
205-
sys.stdout = sys.__stdout__
206-
207-
return wrapped
208-
209-
210198
def make_signature(func):
211199
"""
212200
Returns a string repr of the arg list of a func call, with any defaults

pandas/util/testing.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
from pandas.compat import (
3939
filter, map, zip, range, unichr, lrange, lmap, lzip, u, callable, Counter,
4040
raise_with_traceback, httplib, is_platform_windows, is_platform_32bit,
41-
PY3
41+
StringIO, PY3
4242
)
4343

4444
from pandas.computation import expressions as expr
@@ -2790,3 +2790,20 @@ def setTZ(tz):
27902790
yield
27912791
finally:
27922792
setTZ(orig_tz)
2793+
2794+
2795+
def capture_stdout(f):
2796+
"""
2797+
Capture stdout in a buffer so that it can be checked
2798+
(or suppressed) during testing.
2799+
"""
2800+
2801+
@wraps(f)
2802+
def wrapped(*args, **kwargs):
2803+
try:
2804+
sys.stdout = StringIO()
2805+
f(*args, **kwargs)
2806+
finally:
2807+
sys.stdout = sys.__stdout__
2808+
2809+
return wrapped

0 commit comments

Comments
 (0)