Debian Codegraph @

petl/test/io/test_db_server.py

raw
1 # -*- coding: utf-8 -*-
2 from __future__ import absolute_import, print_function, division
3 import logging
4 import os
5 import warnings
6
7 import pytest
8
9 import petl as etl
10 from petl.test.helpers import ieq
11
12
13 logger = logging.getLogger(__name__)
14 debug = logger.debug
15
16
17 def get_from_env(prefix, name, current, default):
18 if current != default:
19 return current
20 varname = "{}_{}".format(prefix.upper(), name.upper())
21 return os.getenv(varname, default)
22
23
24 def get_db_args(*prefixes):
25 host = '127.0.0.1'
26 user = 'petl'
27 pwrd = 'test'
28 base = 'petl'
29 for prefix in prefixes:
30 host = get_from_env(prefix, 'HOST', host, '127.0.0.1')
31 user = get_from_env(prefix, 'USER', user, 'petl')
32 pwrd = get_from_env(prefix, 'PASSWORD', pwrd, 'test')
33 base = get_from_env(prefix, 'DATABASE', base, 'petl')
34 return host, user, pwrd, base
35
36
37 def get_mysql_args(*prefixes):
38 prefixes += ('PYMYSQL', 'MYSQL',)
39 return get_db_args(*prefixes)
40
41
42 def get_pg_args(*prefixes):
43 prefixes += ('PSYCOPG2', 'POSTGRESQL', 'POSTGRES', 'PG',)
44 return get_db_args(*prefixes)
45
46
47 def _test_dbo(write_dbo, read_dbo=None):
48 if read_dbo is None:
49 read_dbo = write_dbo
50
51 expect_empty = (('foo', 'bar'),)
52 expect = (('foo', 'bar'),
53 ('a', 1),
54 ('b', 2))
55 expect_appended = (('foo', 'bar'),
56 ('a', 1),
57 ('b', 2),
58 ('a', 1),
59 ('b', 2))
60 actual = etl.fromdb(read_dbo, 'SELECT * FROM test')
61
62 debug('verify empty to start with...')
63 debug(etl.look(actual))
64 ieq(expect_empty, actual)
65
66 debug('write some data and verify...')
67 etl.todb(expect, write_dbo, 'test')
68 debug(etl.look(actual))
69 ieq(expect, actual)
70
71 debug('append some data and verify...')
72 etl.appenddb(expect, write_dbo, 'test')
73 debug(etl.look(actual))
74 ieq(expect_appended, actual)
75
76 debug('overwrite and verify...')
77 etl.todb(expect, write_dbo, 'test')
78 debug(etl.look(actual))
79 ieq(expect, actual)
80
81 debug('cut, overwrite and verify')
82 etl.todb(etl.cut(expect, 'bar', 'foo'), write_dbo, 'test')
83 debug(etl.look(actual))
84 ieq(expect, actual)
85
86 debug('cut, append and verify')
87 etl.appenddb(etl.cut(expect, 'bar', 'foo'), write_dbo, 'test')
88 debug(etl.look(actual))
89 ieq(expect_appended, actual)
90
91 debug('try a single row')
92 etl.todb(etl.head(expect, 1), write_dbo, 'test')
93 debug(etl.look(actual))
94 ieq(etl.head(expect, 1), actual)
95
96
97 def _test_with_schema(dbo, schema):
98
99 expect = (('foo', 'bar'),
100 ('a', 1),
101 ('b', 2))
102 expect_appended = (('foo', 'bar'),
103 ('a', 1),
104 ('b', 2),
105 ('a', 1),
106 ('b', 2))
107 actual = etl.fromdb(dbo, 'SELECT * FROM test')
108
109 print('write some data and verify...')
110 etl.todb(expect, dbo, 'test', schema=schema)
111 ieq(expect, actual)
112 print(etl.look(actual))
113
114 print('append some data and verify...')
115 etl.appenddb(expect, dbo, 'test', schema=schema)
116 ieq(expect_appended, actual)
117 print(etl.look(actual))
118
119
120 def _test_unicode(dbo):
121 expect = ((u'name', u'id'),
122 (u'Արամ Խաչատրյան', 1),
123 (u'Johann Strauß', 2),
124 (u'Вагиф Сәмәдоғлу', 3),
125 (u'章子怡', 4),
126 )
127 actual = etl.fromdb(dbo, 'SELECT * FROM test_unicode')
128
129 print('write some data and verify...')
130 etl.todb(expect, dbo, 'test_unicode')
131 ieq(expect, actual)
132 print(etl.look(actual))
133
134
135 def _setup_mysql(dbapi_connection):
136 # setup table
137 cursor = dbapi_connection.cursor()
138 # deal with quote compatibility
139 cursor.execute('SET SQL_MODE=ANSI_QUOTES')
140 cursor.execute('DROP TABLE IF EXISTS test')
141 cursor.execute('CREATE TABLE test (foo TEXT, bar INT)')
142 cursor.execute('DROP TABLE IF EXISTS test_unicode')
143 cursor.execute('CREATE TABLE test_unicode (name TEXT, id INT) '
144 'CHARACTER SET utf8')
145 cursor.close()
146 dbapi_connection.commit()
147
148
149 def _setup_postgresql(dbapi_connection):
150 # setup table
151 cursor = dbapi_connection.cursor()
152 cursor.execute('DROP TABLE IF EXISTS test')
153 cursor.execute('CREATE TABLE test (foo TEXT, bar INT)')
154 cursor.execute('DROP TABLE IF EXISTS test_unicode')
155 # assume character encoding UTF-8 already set at database level
156 cursor.execute('CREATE TABLE test_unicode (name TEXT, id INT)')
157 cursor.close()
158 dbapi_connection.commit()
159
160
161 def _setup_sqlalchemy_quotes(dbapi_connection, connection_record):
162 cursor = dbapi_connection.cursor()
163 cursor.execute("SET sql_mode = 'ANSI_QUOTES'")
164
165
166 SKIP_PYMYSQL = False
167 try:
168 import pymysql
169 import sqlalchemy
170 myhost, myuser, mypassword, mydatabase = get_mysql_args()
171 pymysql.connect(host=myhost,
172 user=myuser,
173 password=mypassword,
174 database=mydatabase)
175 except Exception as e:
176 SKIP_PYMYSQL = 'SKIP pymysql tests: %s' % e
177 warnings.warn(SKIP_PYMYSQL, UserWarning)
178 finally:
179 @pytest.mark.skipif(bool(SKIP_PYMYSQL), reason=str(SKIP_PYMYSQL))
180 def test_pymysql():
181
182 import pymysql
183
184 # assume database already created
185 dbapi_connection = pymysql.connect(host=myhost,
186 user=myuser,
187 password=mypassword,
188 database=mydatabase)
189
190 # exercise using a dbapi_connection
191 _setup_mysql(dbapi_connection)
192 _test_dbo(dbapi_connection)
193
194 # exercise using a dbapi_cursor
195 _setup_mysql(dbapi_connection)
196 dbapi_cursor = dbapi_connection.cursor()
197 _test_dbo(dbapi_cursor)
198 dbapi_cursor.close()
199
200 # exercise sqlalchemy dbapi_connection
201 _setup_mysql(dbapi_connection)
202 from sqlalchemy import create_engine
203 sqlalchemy_engine = create_engine('mysql+pymysql://%s:%s@%s/%s' %
204 (myuser, mypassword, myhost, mydatabase))
205 from sqlalchemy.event import listen
206 listen(sqlalchemy_engine, "connect", _setup_sqlalchemy_quotes)
207 sqlalchemy_connection = sqlalchemy_engine.connect()
208 _test_dbo(sqlalchemy_connection)
209 sqlalchemy_connection.close()
210
211 # exercise sqlalchemy session
212 _setup_mysql(dbapi_connection)
213 from sqlalchemy.orm import sessionmaker
214 Session = sessionmaker(bind=sqlalchemy_engine)
215 sqlalchemy_session = Session()
216 _test_dbo(sqlalchemy_session)
217 sqlalchemy_session.close()
218
219 # exercise sqlalchemy engine
220 _setup_mysql(dbapi_connection)
221 sqlalchemy_engine2 = create_engine('mysql+pymysql://%s:%s@%s/%s' %
222 (myuser, mypassword, myhost, mydatabase), echo_pool='debug')
223 listen(sqlalchemy_engine2, "connect", _setup_sqlalchemy_quotes)
224 _test_dbo(sqlalchemy_engine2)
225 sqlalchemy_engine2.dispose()
226
227 # other exercises
228 _test_with_schema(dbapi_connection, mydatabase)
229 utf8_connection = pymysql.connect(host=myhost,
230 user=myuser,
231 password=mypassword,
232 database=mydatabase,
233 charset='utf8')
234 utf8_connection.cursor().execute('SET SQL_MODE=ANSI_QUOTES')
235 _test_unicode(utf8_connection)
236 utf8_connection.close()
237
238
239 SKIP_MYSQLDB = False
240 try:
241 import MySQLdb
242 import sqlalchemy
243 myhost, myuser, mypassword, mydatabase = get_db_args('MYSQLDB', 'MYSQL')
244 MySQLdb.connect(host=myhost,
245 user=myuser,
246 passwd=mypassword,
247 db=mydatabase)
248 except Exception as e:
249 SKIP_MYSQLDB = 'SKIP MySQLdb tests: %s' % e
250 warnings.warn(SKIP_MYSQLDB, UserWarning)
251 finally:
252 @pytest.mark.skipif(bool(SKIP_MYSQLDB), reason=str(SKIP_MYSQLDB))
253 def test_mysqldb():
254
255 import MySQLdb
256
257 # assume database already created
258 dbapi_connection = MySQLdb.connect(host=myhost,
259 user=myuser,
260 passwd=mypassword,
261 db=mydatabase)
262
263 # exercise using a dbapi_connection
264 _setup_mysql(dbapi_connection)
265 _test_dbo(dbapi_connection)
266
267 # exercise using a dbapi_cursor
268 _setup_mysql(dbapi_connection)
269 dbapi_cursor = dbapi_connection.cursor()
270 _test_dbo(dbapi_cursor)
271 dbapi_cursor.close()
272
273 # exercise sqlalchemy dbapi_connection
274 _setup_mysql(dbapi_connection)
275 from sqlalchemy import create_engine
276 sqlalchemy_engine = create_engine('mysql+mysqldb://%s:%s@%s/%s' %
277 (myuser, mypassword, myhost, mydatabase))
278 from sqlalchemy.event import listen
279 listen(sqlalchemy_engine, "connect", _setup_sqlalchemy_quotes)
280 sqlalchemy_connection = sqlalchemy_engine.connect()
281 sqlalchemy_connection.execute('SET SQL_MODE=ANSI_QUOTES')
282 _test_dbo(sqlalchemy_connection)
283 sqlalchemy_connection.close()
284
285 # exercise sqlalchemy session
286 _setup_mysql(dbapi_connection)
287 from sqlalchemy.orm import sessionmaker
288 Session = sessionmaker(bind=sqlalchemy_engine)
289 sqlalchemy_session = Session()
290 _test_dbo(sqlalchemy_session)
291 sqlalchemy_session.close()
292
293 # other exercises
294 _test_with_schema(dbapi_connection, mydatabase)
295 utf8_connection = MySQLdb.connect(host=myhost,
296 user=myuser,
297 passwd=mypassword,
298 db=mydatabase,
299 charset='utf8')
300 utf8_connection.cursor().execute('SET SQL_MODE=ANSI_QUOTES')
301 _test_unicode(utf8_connection)
302
303 SKIP_TEST_POSTGRES = False
304 try:
305 import psycopg2
306 import sqlalchemy
307 pghost, pguser, pgpassword, pgdatabase = get_pg_args()
308 psycopg2.connect(
309 'host=%s dbname=%s user=%s password=%s'
310 % (pghost, pgdatabase, pguser, pgpassword)
311 )
312 except Exception as e:
313 SKIP_TEST_POSTGRES = 'SKIP psycopg2 tests: %s' % e
314 warnings.warn(SKIP_TEST_POSTGRES, UserWarning)
315 finally:
316 @pytest.mark.skipif(bool(SKIP_TEST_POSTGRES), reason=str(SKIP_TEST_POSTGRES))
317 def test_postgresql():
318
319 import psycopg2
320 import psycopg2.extensions
321 psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
322 psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
323
324 # assume database already created
325 dbapi_connection = psycopg2.connect(
326 'host=%s dbname=%s user=%s password=%s'
327 % (pghost, pgdatabase, pguser, pgpassword)
328 )
329
330 # exercise using a dbapi_connection
331 _setup_postgresql(dbapi_connection)
332 _test_dbo(dbapi_connection)
333
334 # exercise using a dbapi_cursor
335 _setup_postgresql(dbapi_connection)
336 dbapi_cursor = dbapi_connection.cursor()
337 _test_dbo(dbapi_cursor)
338 dbapi_cursor.close()
339
340 # exercise sqlalchemy dbapi_connection
341 _setup_postgresql(dbapi_connection)
342 from sqlalchemy import create_engine
343 sqlalchemy_engine = create_engine('postgresql+psycopg2://%s:%s@%s/%s' %
344 (pguser, pgpassword, pghost, pgdatabase))
345 sqlalchemy_connection = sqlalchemy_engine.connect()
346 _test_dbo(sqlalchemy_connection)
347 sqlalchemy_connection.close()
348
349 # exercise sqlalchemy session
350 _setup_postgresql(dbapi_connection)
351 from sqlalchemy.orm import sessionmaker
352 Session = sessionmaker(bind=sqlalchemy_engine)
353 sqlalchemy_session = Session()
354 _test_dbo(sqlalchemy_session)
355 sqlalchemy_session.close()
356
357 # other exercises
358 _test_dbo(dbapi_connection,
359 lambda: dbapi_connection.cursor(name='arbitrary'))
360 _test_with_schema(dbapi_connection, 'public')
361 _test_unicode(dbapi_connection)