Skip to content

Commit 976a2db

Browse files
simonjayhawkinsjreback
authored andcommitted
STY: use pytest.raises context manager (io.sql) (#25597)
1 parent 9352e69 commit 976a2db

File tree

1 file changed

+60
-60
lines changed

1 file changed

+60
-60
lines changed

pandas/tests/io/test_sql.py

+60-60
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
import pytest
2929

3030
import pandas.compat as compat
31-
from pandas.compat import PY36, lrange, range, string_types
31+
from pandas.compat import PY2, PY36, lrange, range, string_types
3232

3333
from pandas.core.dtypes.common import (
3434
is_datetime64_dtype, is_datetime64tz_dtype)
@@ -400,8 +400,10 @@ def _to_sql_fail(self):
400400
self.test_frame1, 'test_frame1', if_exists='fail')
401401
assert self.pandasSQL.has_table('test_frame1')
402402

403-
pytest.raises(ValueError, self.pandasSQL.to_sql,
404-
self.test_frame1, 'test_frame1', if_exists='fail')
403+
msg = "Table 'test_frame1' already exists"
404+
with pytest.raises(ValueError, match=msg):
405+
self.pandasSQL.to_sql(
406+
self.test_frame1, 'test_frame1', if_exists='fail')
405407

406408
self.drop_table('test_frame1')
407409

@@ -563,8 +565,10 @@ def test_to_sql_fail(self):
563565
self.conn, if_exists='fail')
564566
assert sql.has_table('test_frame2', self.conn)
565567

566-
pytest.raises(ValueError, sql.to_sql, self.test_frame1,
567-
'test_frame2', self.conn, if_exists='fail')
568+
msg = "Table 'test_frame2' already exists"
569+
with pytest.raises(ValueError, match=msg):
570+
sql.to_sql(self.test_frame1, 'test_frame2',
571+
self.conn, if_exists='fail')
568572

569573
def test_to_sql_replace(self):
570574
sql.to_sql(self.test_frame1, 'test_frame3',
@@ -699,10 +703,11 @@ def test_timedelta(self):
699703
result = sql.read_sql_query('SELECT * FROM test_timedelta', self.conn)
700704
tm.assert_series_equal(result['foo'], df['foo'].astype('int64'))
701705

702-
def test_complex(self):
706+
def test_complex_raises(self):
703707
df = DataFrame({'a': [1 + 1j, 2j]})
704-
# Complex data type should raise error
705-
pytest.raises(ValueError, df.to_sql, 'test_complex', self.conn)
708+
msg = "Complex datatypes not supported"
709+
with pytest.raises(ValueError, match=msg):
710+
df.to_sql('test_complex', self.conn)
706711

707712
@pytest.mark.parametrize("index_name,index_label,expected", [
708713
# no index name, defaults to 'index'
@@ -758,10 +763,11 @@ def test_to_sql_index_label_multiindex(self):
758763
frame = sql.read_sql_query('SELECT * FROM test_index_label', self.conn)
759764
assert frame.columns[:2].tolist() == ['C', 'D']
760765

761-
# wrong length of index_label
762-
pytest.raises(ValueError, sql.to_sql, temp_frame,
763-
'test_index_label', self.conn, if_exists='replace',
764-
index_label='C')
766+
msg = ("Length of 'index_label' should match number of levels, which"
767+
" is 2")
768+
with pytest.raises(ValueError, match=msg):
769+
sql.to_sql(temp_frame, 'test_index_label', self.conn,
770+
if_exists='replace', index_label='C')
765771

766772
def test_multiindex_roundtrip(self):
767773
df = DataFrame.from_records([(1, 2.1, 'line1'), (2, 1.5, 'line2')],
@@ -866,6 +872,8 @@ def test_escaped_table_name(self):
866872

867873

868874
@pytest.mark.single
875+
@pytest.mark.skipif(
876+
not SQLALCHEMY_INSTALLED, reason='SQLAlchemy not installed')
869877
class TestSQLApi(SQLAlchemyMixIn, _TestSQLApi):
870878
"""
871879
Test the public API as it would be used directly
@@ -878,10 +886,7 @@ class TestSQLApi(SQLAlchemyMixIn, _TestSQLApi):
878886
mode = 'sqlalchemy'
879887

880888
def connect(self):
881-
if SQLALCHEMY_INSTALLED:
882-
return sqlalchemy.create_engine('sqlite:///:memory:')
883-
else:
884-
pytest.skip('SQLAlchemy not installed')
889+
return sqlalchemy.create_engine('sqlite:///:memory:')
885890

886891
def test_read_table_columns(self):
887892
# test columns argument in read_table
@@ -1091,20 +1096,21 @@ def test_sql_open_close(self):
10911096

10921097
tm.assert_frame_equal(self.test_frame3, result)
10931098

1099+
@pytest.mark.skipif(SQLALCHEMY_INSTALLED, reason='SQLAlchemy is installed')
10941100
def test_con_string_import_error(self):
1095-
if not SQLALCHEMY_INSTALLED:
1096-
conn = 'mysql://root@localhost/pandas_nosetest'
1097-
pytest.raises(ImportError, sql.read_sql, "SELECT * FROM iris",
1098-
conn)
1099-
else:
1100-
pytest.skip('SQLAlchemy is installed')
1101+
conn = 'mysql://root@localhost/pandas_nosetest'
1102+
msg = "Using URI string without sqlalchemy installed"
1103+
with pytest.raises(ImportError, match=msg):
1104+
sql.read_sql("SELECT * FROM iris", conn)
11011105

11021106
def test_read_sql_delegate(self):
11031107
iris_frame1 = sql.read_sql_query("SELECT * FROM iris", self.conn)
11041108
iris_frame2 = sql.read_sql("SELECT * FROM iris", self.conn)
11051109
tm.assert_frame_equal(iris_frame1, iris_frame2)
11061110

1107-
pytest.raises(sql.DatabaseError, sql.read_sql, 'iris', self.conn)
1111+
msg = "Execution failed on sql 'iris': near \"iris\": syntax error"
1112+
with pytest.raises(sql.DatabaseError, match=msg):
1113+
sql.read_sql('iris', self.conn)
11081114

11091115
def test_safe_names_warning(self):
11101116
# GH 6798
@@ -1260,9 +1266,10 @@ def test_read_table_columns(self):
12601266
tm.equalContents(
12611267
iris_frame.columns.values, ['SepalLength', 'SepalLength'])
12621268

1263-
def test_read_table_absent(self):
1264-
pytest.raises(
1265-
ValueError, sql.read_sql_table, "this_doesnt_exist", con=self.conn)
1269+
def test_read_table_absent_raises(self):
1270+
msg = "Table this_doesnt_exist not found"
1271+
with pytest.raises(ValueError, match=msg):
1272+
sql.read_sql_table("this_doesnt_exist", con=self.conn)
12661273

12671274
def test_default_type_conversion(self):
12681275
df = sql.read_sql_table("types_test_data", self.conn)
@@ -1601,8 +1608,9 @@ def test_dtype(self):
16011608
meta.reflect()
16021609
sqltype = meta.tables['dtype_test2'].columns['B'].type
16031610
assert isinstance(sqltype, sqlalchemy.TEXT)
1604-
pytest.raises(ValueError, df.to_sql,
1605-
'error', self.conn, dtype={'B': str})
1611+
msg = "The type of B is not a SQLAlchemy type"
1612+
with pytest.raises(ValueError, match=msg):
1613+
df.to_sql('error', self.conn, dtype={'B': str})
16061614

16071615
# GH9083
16081616
df.to_sql('dtype_test3', self.conn, dtype={'B': sqlalchemy.String(10)})
@@ -1887,8 +1895,9 @@ def test_schema_support(self):
18871895
res4 = sql.read_sql_table('test_schema_other', self.conn,
18881896
schema='other')
18891897
tm.assert_frame_equal(df, res4)
1890-
pytest.raises(ValueError, sql.read_sql_table, 'test_schema_other',
1891-
self.conn, schema='public')
1898+
msg = "Table test_schema_other not found"
1899+
with pytest.raises(ValueError, match=msg):
1900+
sql.read_sql_table('test_schema_other', self.conn, schema='public')
18921901

18931902
# different if_exists options
18941903

@@ -2104,6 +2113,7 @@ def _get_sqlite_column_type(self, table, column):
21042113
return ctype
21052114
raise ValueError('Table %s, column %s not found' % (table, column))
21062115

2116+
@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
21072117
def test_dtype(self):
21082118
if self.flavor == 'mysql':
21092119
pytest.skip('Not applicable to MySQL legacy')
@@ -2120,8 +2130,9 @@ def test_dtype(self):
21202130

21212131
assert self._get_sqlite_column_type(
21222132
'dtype_test2', 'B') == 'STRING'
2123-
pytest.raises(ValueError, df.to_sql,
2124-
'error', self.conn, dtype={'B': bool})
2133+
msg = r"B \(<class 'bool'>\) not a string"
2134+
with pytest.raises(ValueError, match=msg):
2135+
df.to_sql('error', self.conn, dtype={'B': bool})
21252136

21262137
# single dtype
21272138
df.to_sql('single_dtype_test', self.conn, dtype='STRING')
@@ -2153,8 +2164,9 @@ def test_illegal_names(self):
21532164
# For sqlite, these should work fine
21542165
df = DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
21552166

2156-
# Raise error on blank
2157-
pytest.raises(ValueError, df.to_sql, "", self.conn)
2167+
msg = "Empty table or column name specified"
2168+
with pytest.raises(ValueError, match=msg):
2169+
df.to_sql("", self.conn)
21582170

21592171
for ndx, weird_name in enumerate(
21602172
['test_weird_name]', 'test_weird_name[',
@@ -2383,25 +2395,19 @@ def clean_up(test_table_to_drop):
23832395
"""
23842396
self.drop_table(test_table_to_drop)
23852397

2386-
# test if invalid value for if_exists raises appropriate error
2387-
pytest.raises(ValueError,
2388-
sql.to_sql,
2389-
frame=df_if_exists_1,
2390-
con=self.conn,
2391-
name=table_name,
2392-
if_exists='notvalidvalue')
2398+
msg = "'notvalidvalue' is not valid for if_exists"
2399+
with pytest.raises(ValueError, match=msg):
2400+
sql.to_sql(frame=df_if_exists_1, con=self.conn, name=table_name,
2401+
if_exists='notvalidvalue')
23932402
clean_up(table_name)
23942403

23952404
# test if_exists='fail'
23962405
sql.to_sql(frame=df_if_exists_1, con=self.conn,
23972406
name=table_name, if_exists='fail')
2398-
pytest.raises(ValueError,
2399-
sql.to_sql,
2400-
frame=df_if_exists_1,
2401-
con=self.conn,
2402-
name=table_name,
2403-
if_exists='fail')
2404-
2407+
msg = "Table 'table_if_exists' already exists"
2408+
with pytest.raises(ValueError, match=msg):
2409+
sql.to_sql(frame=df_if_exists_1, con=self.conn, name=table_name,
2410+
if_exists='fail')
24052411
# test if_exists='replace'
24062412
sql.to_sql(frame=df_if_exists_1, con=self.conn, name=table_name,
24072413
if_exists='replace', index=False)
@@ -2647,23 +2653,17 @@ def clean_up(test_table_to_drop):
26472653
self.drop_table(test_table_to_drop)
26482654

26492655
# test if invalid value for if_exists raises appropriate error
2650-
pytest.raises(ValueError,
2651-
sql.to_sql,
2652-
frame=df_if_exists_1,
2653-
con=self.conn,
2654-
name=table_name,
2655-
if_exists='notvalidvalue')
2656+
with pytest.raises(ValueError, match="<insert message here>"):
2657+
sql.to_sql(frame=df_if_exists_1, con=self.conn, name=table_name,
2658+
if_exists='notvalidvalue')
26562659
clean_up(table_name)
26572660

26582661
# test if_exists='fail'
26592662
sql.to_sql(frame=df_if_exists_1, con=self.conn, name=table_name,
26602663
if_exists='fail', index=False)
2661-
pytest.raises(ValueError,
2662-
sql.to_sql,
2663-
frame=df_if_exists_1,
2664-
con=self.conn,
2665-
name=table_name,
2666-
if_exists='fail')
2664+
with pytest.raises(ValueError, match="<insert message here>"):
2665+
sql.to_sql(frame=df_if_exists_1, con=self.conn, name=table_name,
2666+
if_exists='fail')
26672667

26682668
# test if_exists='replace'
26692669
sql.to_sql(frame=df_if_exists_1, con=self.conn, name=table_name,

0 commit comments

Comments
 (0)