Debian Codegraph @

tests/mysqldb_test.py

raw
1 import os
2 import time
3 import traceback
4
5 import eventlet
6 from eventlet import event
7 try:
8 from eventlet.green import MySQLdb
9 except ImportError:
10 MySQLdb = False
11 import tests
12
13
14 def mysql_requirement(_f):
15 """We want to skip tests if MySQLdb is not installed, or if
16 there is no database running on the localhost that the auth file grants
17 us access to.
18
19 This errs on the side of skipping tests if everything is not right, but
20 it's better than a million tests failing when you don't care about mysql
21 support."""
22 if MySQLdb is False:
23 print("Skipping mysql tests, MySQLdb not importable")
24 return False
25 try:
26 auth = tests.get_database_auth()['MySQLdb'].copy()
27 MySQLdb.connect(**auth)
28 return True
29 except MySQLdb.OperationalError:
30 print("Skipping mysql tests, error when connecting:")
31 traceback.print_exc()
32 return False
33
34
35 class TestMySQLdb(tests.LimitedTestCase):
36 TEST_TIMEOUT = 50
37
38 def setUp(self):
39 self._auth = tests.get_database_auth()['MySQLdb']
40 self.create_db()
41 self.connection = None
42 self.connection = MySQLdb.connect(**self._auth)
43 cursor = self.connection.cursor()
44 cursor.execute("""CREATE TABLE gargleblatz
45 (
46 a INTEGER
47 );""")
48 self.connection.commit()
49 cursor.close()
50
51 super().setUp()
52
53 def tearDown(self):
54 if self.connection:
55 self.connection.close()
56 self.drop_db()
57
58 super().tearDown()
59
60 @tests.skip_unless(mysql_requirement)
61 def create_db(self):
62 auth = self._auth.copy()
63 try:
64 self.drop_db()
65 except Exception:
66 pass
67 dbname = 'test_%d_%d' % (os.getpid(), int(time.time() * 1000))
68 db = MySQLdb.connect(**auth).cursor()
69 db.execute("create database " + dbname)
70 db.close()
71 self._auth['db'] = dbname
72 del db
73
74 def drop_db(self):
75 db = MySQLdb.connect(**self._auth).cursor()
76 db.execute("drop database IF EXISTS " + self._auth['db'])
77 db.close()
78 del db
79
80 def set_up_dummy_table(self, connection=None):
81 close_connection = False
82 if connection is None:
83 close_connection = True
84 if self.connection is None:
85 connection = MySQLdb.connect(**self._auth)
86 else:
87 connection = self.connection
88
89 cursor = connection.cursor()
90 cursor.execute(self.dummy_table_sql)
91 connection.commit()
92 cursor.close()
93 if close_connection:
94 connection.close()
95
96 dummy_table_sql = """CREATE TEMPORARY TABLE test_table
97 (
98 row_id INTEGER PRIMARY KEY AUTO_INCREMENT,
99 value_int INTEGER,
100 value_float FLOAT,
101 value_string VARCHAR(200),
102 value_uuid CHAR(36),
103 value_binary BLOB,
104 value_binary_string VARCHAR(200) BINARY,
105 value_enum ENUM('Y','N'),
106 created TIMESTAMP
107 ) ENGINE=InnoDB;"""
108
109 def assert_cursor_yields(self, curs):
110 counter = [0]
111
112 def tick():
113 while True:
114 counter[0] += 1
115 eventlet.sleep()
116 gt = eventlet.spawn(tick)
117 curs.execute("select 1")
118 rows = curs.fetchall()
119 self.assertEqual(len(rows), 1)
120 self.assertEqual(len(rows[0]), 1)
121 self.assertEqual(rows[0][0], 1)
122 assert counter[0] > 0, counter[0]
123 gt.kill()
124
125 def assert_cursor_works(self, cursor):
126 cursor.execute("select 1")
127 rows = cursor.fetchall()
128 self.assertEqual(len(rows), 1)
129 self.assertEqual(len(rows[0]), 1)
130 self.assertEqual(rows[0][0], 1)
131 self.assert_cursor_yields(cursor)
132
133 def assert_connection_works(self, conn):
134 curs = conn.cursor()
135 self.assert_cursor_works(curs)
136
137 def test_module_attributes(self):
138 import MySQLdb as orig
139 for key in dir(orig):
140 if key not in ('__author__', '__path__', '__revision__',
141 '__version__', '__loader__'):
142 assert hasattr(MySQLdb, key), "%s %s" % (key, getattr(orig, key))
143
144 def test_connecting(self):
145 assert self.connection is not None
146
147 def test_connecting_annoyingly(self):
148 self.assert_connection_works(MySQLdb.Connect(**self._auth))
149 self.assert_connection_works(MySQLdb.Connection(**self._auth))
150 self.assert_connection_works(MySQLdb.connections.Connection(**self._auth))
151
152 def test_create_cursor(self):
153 cursor = self.connection.cursor()
154 cursor.close()
155
156 def test_run_query(self):
157 cursor = self.connection.cursor()
158 self.assert_cursor_works(cursor)
159 cursor.close()
160
161 def test_run_bad_query(self):
162 cursor = self.connection.cursor()
163 try:
164 cursor.execute("garbage blah blah")
165 assert False
166 except AssertionError:
167 raise
168 except Exception:
169 pass
170 cursor.close()
171
172 def fill_up_table(self, conn):
173 curs = conn.cursor()
174 for i in range(1000):
175 curs.execute('insert into test_table (value_int) values (%s)' % i)
176 conn.commit()
177
178 def test_yields(self):
179 conn = self.connection
180 self.set_up_dummy_table(conn)
181 self.fill_up_table(conn)
182 curs = conn.cursor()
183 results = []
184 SHORT_QUERY = "select * from test_table"
185 evt = event.Event()
186
187 def a_query():
188 self.assert_cursor_works(curs)
189 curs.execute(SHORT_QUERY)
190 results.append(2)
191 evt.send()
192 eventlet.spawn(a_query)
193 results.append(1)
194 self.assertEqual([1], results)
195 evt.wait()
196 self.assertEqual([1, 2], results)
197
198 def test_visibility_from_other_connections(self):
199 conn = MySQLdb.connect(**self._auth)
200 conn2 = MySQLdb.connect(**self._auth)
201 curs = conn.cursor()
202 try:
203 curs2 = conn2.cursor()
204 curs2.execute("insert into gargleblatz (a) values (%s)" % (314159))
205 self.assertEqual(curs2.rowcount, 1)
206 conn2.commit()
207 selection_query = "select * from gargleblatz"
208 curs2.execute(selection_query)
209 self.assertEqual(curs2.rowcount, 1)
210 del curs2, conn2
211 # create a new connection, it should see the addition
212 conn3 = MySQLdb.connect(**self._auth)
213 curs3 = conn3.cursor()
214 curs3.execute(selection_query)
215 self.assertEqual(curs3.rowcount, 1)
216 # now, does the already-open connection see it?
217 curs.execute(selection_query)
218 self.assertEqual(curs.rowcount, 1)
219 del curs3, conn3
220 finally:
221 # clean up my litter
222 curs.execute("delete from gargleblatz where a=314159")
223 conn.commit()
224
225
226 class TestMonkeyPatch(tests.LimitedTestCase):
227 @tests.skip_unless(mysql_requirement)
228 def test_monkey_patching(self):
229 tests.run_isolated('mysqldb_monkey_patch.py')