~james-w/ubuntu/lucid/psycopg2/precise-backport

« back to all changes in this revision

Viewing changes to tests/test_cursor.py

  • Committer: Bazaar Package Importer
  • Author(s): Fabio Tranchitella, Jakub Wilk, Fabio Tranchitella
  • Date: 2011-06-19 18:25:53 UTC
  • mfrom: (5.1.10 sid)
  • Revision ID: james.westby@ubuntu.com-20110619182553-uye7z0g5ewab98px
Tags: 2.4.2-1
[ Jakub Wilk ]
* Add Debian Python Modules Team to Uploaders.

[ Fabio Tranchitella ]
* New upstream release.
* debian/watch: updated, use pypi.
* debian/control, debian/rules: switched to dh_python2.
* debian/control: bumped Standard-Version to 3.9.2, no changes required.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
 
 
3
# test_cursor.py - unit test for cursor attributes
 
4
#
 
5
# Copyright (C) 2010-2011 Daniele Varrazzo  <daniele.varrazzo@gmail.com>
 
6
#
 
7
# psycopg2 is free software: you can redistribute it and/or modify it
 
8
# under the terms of the GNU Lesser General Public License as published
 
9
# by the Free Software Foundation, either version 3 of the License, or
 
10
# (at your option) any later version.
 
11
#
 
12
# In addition, as a special exception, the copyright holders give
 
13
# permission to link this program with the OpenSSL library (or with
 
14
# modified versions of OpenSSL that use the same license as OpenSSL),
 
15
# and distribute linked combinations including the two.
 
16
#
 
17
# You must obey the GNU Lesser General Public License in all respects for
 
18
# all of the code used other than OpenSSL.
 
19
#
 
20
# psycopg2 is distributed in the hope that it will be useful, but WITHOUT
 
21
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 
22
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 
23
# License for more details.
 
24
 
 
25
import time
 
26
import psycopg2
 
27
import psycopg2.extensions
 
28
from psycopg2.extensions import b
 
29
from testconfig import dsn
 
30
from testutils import unittest, skip_before_postgres, skip_if_no_namedtuple
 
31
 
 
32
class CursorTests(unittest.TestCase):
 
33
 
 
34
    def setUp(self):
 
35
        self.conn = psycopg2.connect(dsn)
 
36
 
 
37
    def tearDown(self):
 
38
        self.conn.close()
 
39
 
 
40
    def test_empty_query(self):
 
41
        cur = self.conn.cursor()
 
42
        self.assertRaises(psycopg2.ProgrammingError, cur.execute, "")
 
43
        self.assertRaises(psycopg2.ProgrammingError, cur.execute, " ")
 
44
        self.assertRaises(psycopg2.ProgrammingError, cur.execute, ";")
 
45
 
 
46
    def test_executemany_propagate_exceptions(self):
 
47
        conn = self.conn
 
48
        cur = conn.cursor()
 
49
        cur.execute("create temp table test_exc (data int);")
 
50
        def buggygen():
 
51
            yield 1//0
 
52
        self.assertRaises(ZeroDivisionError,
 
53
            cur.executemany, "insert into test_exc values (%s)", buggygen())
 
54
        cur.close()
 
55
 
 
56
    def test_mogrify_unicode(self):
 
57
        conn = self.conn
 
58
        cur = conn.cursor()
 
59
 
 
60
        # test consistency between execute and mogrify.
 
61
 
 
62
        # unicode query containing only ascii data
 
63
        cur.execute(u"SELECT 'foo';")
 
64
        self.assertEqual('foo', cur.fetchone()[0])
 
65
        self.assertEqual(b("SELECT 'foo';"), cur.mogrify(u"SELECT 'foo';"))
 
66
 
 
67
        conn.set_client_encoding('UTF8')
 
68
        snowman = u"\u2603"
 
69
 
 
70
        # unicode query with non-ascii data
 
71
        cur.execute(u"SELECT '%s';" % snowman)
 
72
        self.assertEqual(snowman.encode('utf8'), b(cur.fetchone()[0]))
 
73
        self.assertEqual(("SELECT '%s';" % snowman).encode('utf8'),
 
74
            cur.mogrify(u"SELECT '%s';" % snowman).replace(b("E'"), b("'")))
 
75
 
 
76
        # unicode args
 
77
        cur.execute("SELECT %s;", (snowman,))
 
78
        self.assertEqual(snowman.encode("utf-8"), b(cur.fetchone()[0]))
 
79
        self.assertEqual(("SELECT '%s';" % snowman).encode('utf8'),
 
80
            cur.mogrify("SELECT %s;", (snowman,)).replace(b("E'"), b("'")))
 
81
 
 
82
        # unicode query and args
 
83
        cur.execute(u"SELECT %s;", (snowman,))
 
84
        self.assertEqual(snowman.encode("utf-8"), b(cur.fetchone()[0]))
 
85
        self.assertEqual(("SELECT '%s';" % snowman).encode('utf8'),
 
86
            cur.mogrify(u"SELECT %s;", (snowman,)).replace(b("E'"), b("'")))
 
87
 
 
88
    def test_mogrify_decimal_explodes(self):
 
89
        # issue #7: explodes on windows with python 2.5 and psycopg 2.2.2
 
90
        try:
 
91
            from decimal import Decimal
 
92
        except:
 
93
            return
 
94
 
 
95
        conn = self.conn
 
96
        cur = conn.cursor()
 
97
        self.assertEqual(b('SELECT 10.3;'),
 
98
            cur.mogrify("SELECT %s;", (Decimal("10.3"),)))
 
99
 
 
100
    def test_bad_placeholder(self):
 
101
        cur = self.conn.cursor()
 
102
        self.assertRaises(psycopg2.ProgrammingError,
 
103
            cur.mogrify, "select %(foo", {})
 
104
        self.assertRaises(psycopg2.ProgrammingError,
 
105
            cur.mogrify, "select %(foo", {'foo': 1})
 
106
        self.assertRaises(psycopg2.ProgrammingError,
 
107
            cur.mogrify, "select %(foo, %(bar)", {'foo': 1})
 
108
        self.assertRaises(psycopg2.ProgrammingError,
 
109
            cur.mogrify, "select %(foo, %(bar)", {'foo': 1, 'bar': 2})
 
110
 
 
111
    def test_cast(self):
 
112
        curs = self.conn.cursor()
 
113
 
 
114
        self.assertEqual(42, curs.cast(20, '42'))
 
115
        self.assertAlmostEqual(3.14, curs.cast(700, '3.14'))
 
116
 
 
117
        try:
 
118
            from decimal import Decimal
 
119
        except ImportError:
 
120
            self.assertAlmostEqual(123.45, curs.cast(1700, '123.45'))
 
121
        else:
 
122
            self.assertEqual(Decimal('123.45'), curs.cast(1700, '123.45'))
 
123
 
 
124
        from datetime import date
 
125
        self.assertEqual(date(2011,1,2), curs.cast(1082, '2011-01-02'))
 
126
        self.assertEqual("who am i?", curs.cast(705, 'who am i?'))  # unknown
 
127
 
 
128
    def test_cast_specificity(self):
 
129
        curs = self.conn.cursor()
 
130
        self.assertEqual("foo", curs.cast(705, 'foo'))
 
131
 
 
132
        D = psycopg2.extensions.new_type((705,), "DOUBLING", lambda v, c: v * 2)
 
133
        psycopg2.extensions.register_type(D, self.conn)
 
134
        self.assertEqual("foofoo", curs.cast(705, 'foo'))
 
135
 
 
136
        T = psycopg2.extensions.new_type((705,), "TREBLING", lambda v, c: v * 3)
 
137
        psycopg2.extensions.register_type(T, curs)
 
138
        self.assertEqual("foofoofoo", curs.cast(705, 'foo'))
 
139
 
 
140
        curs2 = self.conn.cursor()
 
141
        self.assertEqual("foofoo", curs2.cast(705, 'foo'))
 
142
 
 
143
    def test_weakref(self):
 
144
        from weakref import ref
 
145
        curs = self.conn.cursor()
 
146
        w = ref(curs)
 
147
        del curs
 
148
        self.assert_(w() is None)
 
149
 
 
150
    def test_invalid_name(self):
 
151
        curs = self.conn.cursor()
 
152
        curs.execute("create temp table invname (data int);")
 
153
        for i in (10,20,30):
 
154
            curs.execute("insert into invname values (%s)", (i,))
 
155
        curs.close()
 
156
 
 
157
        curs = self.conn.cursor(r'1-2-3 \ "test"')
 
158
        curs.execute("select data from invname order by data")
 
159
        self.assertEqual(curs.fetchall(), [(10,), (20,), (30,)])
 
160
 
 
161
    @skip_before_postgres(8, 2)
 
162
    def test_iter_named_cursor_efficient(self):
 
163
        curs = self.conn.cursor('tmp')
 
164
        # if these records are fetched in the same roundtrip their
 
165
        # timestamp will not be influenced by the pause in Python world.
 
166
        curs.execute("""select clock_timestamp() from generate_series(1,2)""")
 
167
        i = iter(curs)
 
168
        t1 = (i.next())[0]  # the brackets work around a 2to3 bug
 
169
        time.sleep(0.2)
 
170
        t2 = (i.next())[0]
 
171
        self.assert_((t2 - t1).microseconds * 1e-6 < 0.1,
 
172
            "named cursor records fetched in 2 roundtrips (delta: %s)"
 
173
            % (t2 - t1))
 
174
 
 
175
    @skip_before_postgres(8, 0)
 
176
    def test_iter_named_cursor_default_itersize(self):
 
177
        curs = self.conn.cursor('tmp')
 
178
        curs.execute('select generate_series(1,50)')
 
179
        rv = [ (r[0], curs.rownumber) for r in curs ]
 
180
        # everything swallowed in one gulp
 
181
        self.assertEqual(rv, [(i,i) for i in range(1,51)])
 
182
 
 
183
    @skip_before_postgres(8, 0)
 
184
    def test_iter_named_cursor_itersize(self):
 
185
        curs = self.conn.cursor('tmp')
 
186
        curs.itersize = 30
 
187
        curs.execute('select generate_series(1,50)')
 
188
        rv = [ (r[0], curs.rownumber) for r in curs ]
 
189
        # everything swallowed in two gulps
 
190
        self.assertEqual(rv, [(i,((i - 1) % 30) + 1) for i in range(1,51)])
 
191
 
 
192
    @skip_if_no_namedtuple
 
193
    def test_namedtuple_description(self):
 
194
        curs = self.conn.cursor()
 
195
        curs.execute("""select
 
196
            3.14::decimal(10,2) as pi,
 
197
            'hello'::text as hi,
 
198
            '2010-02-18'::date as now;
 
199
            """)
 
200
        self.assertEqual(len(curs.description), 3)
 
201
        for c in curs.description:
 
202
            self.assertEqual(len(c), 7)  # DBAPI happy
 
203
            for a in ('name', 'type_code', 'display_size', 'internal_size',
 
204
                    'precision', 'scale', 'null_ok'):
 
205
                self.assert_(hasattr(c, a), a)
 
206
 
 
207
        c = curs.description[0]
 
208
        self.assertEqual(c.name, 'pi')
 
209
        self.assert_(c.type_code in psycopg2.extensions.DECIMAL.values)
 
210
        self.assert_(c.internal_size > 0)
 
211
        self.assertEqual(c.precision, 10)
 
212
        self.assertEqual(c.scale, 2)
 
213
 
 
214
        c = curs.description[1]
 
215
        self.assertEqual(c.name, 'hi')
 
216
        self.assert_(c.type_code in psycopg2.STRING.values)
 
217
        self.assert_(c.internal_size < 0)
 
218
        self.assertEqual(c.precision, None)
 
219
        self.assertEqual(c.scale, None)
 
220
 
 
221
        c = curs.description[2]
 
222
        self.assertEqual(c.name, 'now')
 
223
        self.assert_(c.type_code in psycopg2.extensions.DATE.values)
 
224
        self.assert_(c.internal_size > 0)
 
225
        self.assertEqual(c.precision, None)
 
226
        self.assertEqual(c.scale, None)
 
227
 
 
228
 
 
229
def test_suite():
 
230
    return unittest.TestLoader().loadTestsFromName(__name__)
 
231
 
 
232
if __name__ == "__main__":
 
233
    unittest.main()