source: branches/4.x/tests/test_tutorial.py @ 716

Last change on this file since 716 was 716, checked in by cito, 4 years ago

Add a "first steps" tutorial for PyGreSQL

In addition to the already existing tutorial for the PostgreSQL database.

Also added tests for all the steps in this tutorial.

  • Property svn:keywords set to Id
File size: 6.7 KB
Line 
1#! /usr/bin/python
2# -*- coding: utf-8 -*-
3
4try:
5    import unittest2 as unittest  # for Python < 2.7
6except ImportError:
7    import unittest
8
9try:
10    from collections import namedtuple
11except ImportError:  # Python < 2.6
12    namedtuple = None
13
14from pg import DB
15from pgdb import connect
16
17# We need a database to test against.  If LOCAL_PyGreSQL.py exists we will
18# get our information from that.  Otherwise we use the defaults.
19dbname = 'unittest'
20dbhost = None
21dbport = 5432
22
23try:
24    from LOCAL_PyGreSQL import *
25except ImportError:
26    pass
27
28
29class TestClassicTutorial(unittest.TestCase):
30    """Test the First Steps Tutorial for the classic interface."""
31
32    def setUp(self):
33        """Setup test tables or empty them if they already exist."""
34        db = DB(dbname=dbname, host=dbhost, port=dbport)
35        db.query("set datestyle to 'iso'")
36        db.query("set default_with_oids=false")
37        db.query("set standard_conforming_strings=false")
38        db.query("set client_min_messages=warning")
39        db.query("drop table if exists fruits cascade")
40        db.query("create table fruits(id serial primary key, name varchar)")
41        self.db = db
42
43    def tearDown(self):
44        db = self.db
45        db.query("drop table fruits")
46        db.close()
47
48    def test_all_steps(self):
49        db = self.db
50        r = db.get_tables()
51        self.assertIsInstance(r, list)
52        self.assertIn('public.fruits', r)
53        r = db.get_attnames('fruits')
54        self.assertIsInstance(r, dict)
55        self.assertEqual(r, {'id': 'int', 'name': 'text'})
56        r = db.has_table_privilege('fruits', 'insert')
57        self.assertTrue(r)
58        r = db.insert('fruits', name='apple')
59        self.assertIsInstance(r, dict)
60        self.assertEqual(r, {'name': 'apple', 'id': 1})
61        banana = r = db.insert('fruits', name='banana')
62        self.assertIsInstance(r, dict)
63        self.assertEqual(r, {'name': 'banana', 'id': 2})
64        more_fruits = 'cherimaya durian eggfruit fig grapefruit'.split()
65        if namedtuple:
66            data = list(enumerate(more_fruits, start=3))
67        else:  # Pyton < 2.6
68            data = [(n + 3, name) for n, name in enumerate(more_fruits)]
69        db.inserttable('fruits', data)
70        q = db.query('select * from fruits')
71        r = str(q).splitlines()
72        self.assertEqual(r[0], 'id|   name   ')
73        self.assertEqual(r[1], '--+----------')
74        self.assertEqual(r[2], ' 1|apple     ')
75        self.assertEqual(r[8], ' 7|grapefruit')
76        self.assertEqual(r[9], '(7 rows)')
77        q = db.query('select * from fruits')
78        r = q.getresult()
79        self.assertIsInstance(r, list)
80        self.assertIsInstance(r[0], tuple)
81        self.assertEqual(r[0], (1, 'apple'))
82        self.assertEqual(r[6], (7, 'grapefruit'))
83        r = q.dictresult()
84        self.assertIsInstance(r, list)
85        self.assertIsInstance(r[0], dict)
86        self.assertEqual(r[0], {'id': 1, 'name': 'apple'})
87        self.assertEqual(r[6], {'id': 7, 'name': 'grapefruit'})
88        try:
89            rows = r = q.namedresult()
90        except TypeError:  # Python < 2.6
91            self.assertIsNone(namedtuple)
92        else:
93            self.assertIsInstance(r, list)
94            self.assertIsInstance(r[0], tuple)
95            self.assertEqual(rows[3].name, 'durian')
96        r = db.update('fruits', banana, name=banana['name'].capitalize())
97        self.assertIsInstance(r, dict)
98        self.assertEqual(r, {'id': 2, 'name': 'Banana'})
99        q = db.query('select * from fruits where id between 1 and 3')
100        r = str(q).splitlines()
101        self.assertEqual(r[0], 'id|  name   ')
102        self.assertEqual(r[1], '--+---------')
103        self.assertEqual(r[2], ' 1|apple    ')
104        self.assertEqual(r[3], ' 2|Banana   ')
105        self.assertEqual(r[4], ' 3|cherimaya')
106        self.assertEqual(r[5], '(3 rows)')
107        r = db.query('update fruits set name=initcap(name)')
108        self.assertIsInstance(r, str)
109        self.assertEqual(r, '7')
110        r = db.delete('fruits', banana)
111        self.assertIsInstance(r, int)
112        self.assertEqual(r, 1)
113        r = db.delete('fruits', banana)
114        self.assertIsInstance(r, int)
115        self.assertEqual(r, 0)
116        r = db.insert('fruits', banana)
117        self.assertIsInstance(r, dict)
118        self.assertEqual(r, {'id': 2, 'name': 'Banana'})
119        apple = r = db.get('fruits', 1)
120        self.assertIsInstance(r, dict)
121        self.assertEqual(r, {'name': 'Apple', 'id': 1})
122        r = db.insert('fruits', apple, id=8)
123        self.assertIsInstance(r, dict)
124        self.assertEqual(r, {'id': 8, 'name': 'Apple'})
125        r = db.delete('fruits', id=8)
126        self.assertIsInstance(r, int)
127        self.assertEqual(r, 1)
128
129
130class TestDbApi20Tutorial(unittest.TestCase):
131    """Test the First Steps Tutorial for the DB-API 2.0 interface."""
132
133    def setUp(self):
134        """Setup test tables or empty them if they already exist."""
135        database = dbname
136        host = '%s:%d' % (dbhost or '', dbport or -1)
137        con = connect(database=database, host=host)
138        cur = con.cursor()
139        cur.execute("set datestyle to 'iso'")
140        cur.execute("set default_with_oids=false")
141        cur.execute("set standard_conforming_strings=false")
142        cur.execute("set client_min_messages=warning")
143        cur.execute("drop table if exists fruits cascade")
144        cur.execute("create table fruits(id serial primary key, name varchar)")
145        cur.close()
146        self.con = con
147
148    def tearDown(self):
149        con = self.con
150        cur = con.cursor()
151        cur.execute("drop table fruits")
152        cur.close()
153        con.close()
154
155    def test_all_steps(self):
156        con = self.con
157        cursor = con.cursor()
158        cursor.execute("insert into fruits (name) values ('apple')")
159        cursor.execute("insert into fruits (name) values (%s)", ('banana',))
160        more_fruits = 'cherimaya durian eggfruit fig grapefruit'.split()
161        parameters = [(name,) for name in more_fruits]
162        cursor.executemany("insert into fruits (name) values (%s)", parameters)
163        con.commit()
164        cursor.execute('select * from fruits where id=1')
165        r = cursor.fetchone()
166        self.assertIsInstance(r, list)
167        self.assertEqual(r, [1, 'apple'])
168        cursor.execute('select * from fruits')
169        r = cursor.fetchall()
170        self.assertIsInstance(r, list)
171        self.assertEqual(len(r), 7)
172        self.assertEqual(r[0], [1, 'apple'])
173        self.assertEqual(r[6], [7, 'grapefruit'])
174        cursor.execute('select * from fruits')
175        r = cursor.fetchmany(2)
176        self.assertIsInstance(r, list)
177        self.assertEqual(len(r), 2)
178        self.assertEqual(r[0], [1, 'apple'])
179        self.assertEqual(r[1], [2, 'banana'])
180       
181
182if __name__ == '__main__':
183    unittest.main()
Note: See TracBrowser for help on using the repository browser.