source: trunk/tests/test_tutorial.py @ 928

Last change on this file since 928 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.6 KB
Line 
1#! /usr/bin/python
2# -*- coding: utf-8 -*-
3
4from __future__ import print_function
5
6try:
7    import unittest2 as unittest  # for Python < 2.7
8except ImportError:
9    import unittest
10
11from pg import DB
12from pgdb import connect
13
14# We need a database to test against.  If LOCAL_PyGreSQL.py exists we will
15# get our information from that.  Otherwise we use the defaults.
16dbname = 'unittest'
17dbhost = None
18dbport = 5432
19
20try:
21    from .LOCAL_PyGreSQL import *
22except (ImportError, ValueError):
23    try:
24        from LOCAL_PyGreSQL import *
25    except 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        data = list(enumerate(more_fruits, start=3))
66        db.inserttable('fruits', data)
67        q = db.query('select * from fruits')
68        r = str(q).splitlines()
69        self.assertEqual(r[0], 'id|   name   ')
70        self.assertEqual(r[1], '--+----------')
71        self.assertEqual(r[2], ' 1|apple     ')
72        self.assertEqual(r[8], ' 7|grapefruit')
73        self.assertEqual(r[9], '(7 rows)')
74        q = db.query('select * from fruits')
75        r = q.getresult()
76        self.assertIsInstance(r, list)
77        self.assertIsInstance(r[0], tuple)
78        self.assertEqual(r[0], (1, 'apple'))
79        self.assertEqual(r[6], (7, 'grapefruit'))
80        r = q.dictresult()
81        self.assertIsInstance(r, list)
82        self.assertIsInstance(r[0], dict)
83        self.assertEqual(r[0], {'id': 1, 'name': 'apple'})
84        self.assertEqual(r[6], {'id': 7, 'name': 'grapefruit'})
85        rows = r = q.namedresult()
86        self.assertIsInstance(r, list)
87        self.assertIsInstance(r[0], tuple)
88        self.assertEqual(rows[3].name, 'durian')
89        r = db.update('fruits', banana, name=banana['name'].capitalize())
90        self.assertIsInstance(r, dict)
91        self.assertEqual(r, {'id': 2, 'name': 'Banana'})
92        q = db.query('select * from fruits where id between 1 and 3')
93        r = str(q).splitlines()
94        self.assertEqual(r[0], 'id|  name   ')
95        self.assertEqual(r[1], '--+---------')
96        self.assertEqual(r[2], ' 1|apple    ')
97        self.assertEqual(r[3], ' 2|Banana   ')
98        self.assertEqual(r[4], ' 3|cherimaya')
99        self.assertEqual(r[5], '(3 rows)')
100        r = db.query('update fruits set name=initcap(name)')
101        self.assertIsInstance(r, str)
102        self.assertEqual(r, '7')
103        r = db.delete('fruits', banana)
104        self.assertIsInstance(r, int)
105        self.assertEqual(r, 1)
106        r = db.delete('fruits', banana)
107        self.assertIsInstance(r, int)
108        self.assertEqual(r, 0)
109        r = db.insert('fruits', banana)
110        self.assertIsInstance(r, dict)
111        self.assertEqual(r, {'id': 2, 'name': 'Banana'})
112        apple = r = db.get('fruits', 1)
113        self.assertIsInstance(r, dict)
114        self.assertEqual(r, {'name': 'Apple', 'id': 1})
115        r = db.insert('fruits', apple, id=8)
116        self.assertIsInstance(r, dict)
117        self.assertEqual(r, {'id': 8, 'name': 'Apple'})
118        r = db.delete('fruits', id=8)
119        self.assertIsInstance(r, int)
120        self.assertEqual(r, 1)
121
122
123class TestDbApi20Tutorial(unittest.TestCase):
124    """Test the First Steps Tutorial for the DB-API 2.0 interface."""
125
126    def setUp(self):
127        """Setup test tables or empty them if they already exist."""
128        database = dbname
129        host = '%s:%d' % (dbhost or '', dbport or -1)
130        con = connect(database=database, host=host)
131        cur = con.cursor()
132        cur.execute("set datestyle to 'iso'")
133        cur.execute("set default_with_oids=false")
134        cur.execute("set standard_conforming_strings=false")
135        cur.execute("set client_min_messages=warning")
136        cur.execute("drop table if exists fruits cascade")
137        cur.execute("create table fruits(id serial primary key, name varchar)")
138        cur.close()
139        self.con = con
140
141    def tearDown(self):
142        con = self.con
143        cur = con.cursor()
144        cur.execute("drop table fruits")
145        cur.close()
146        con.close()
147
148    def test_all_steps(self):
149        con = self.con
150        cursor = con.cursor()
151        cursor.execute("insert into fruits (name) values ('apple')")
152        cursor.execute("insert into fruits (name) values (%s)", ('banana',))
153        more_fruits = 'cherimaya durian eggfruit fig grapefruit'.split()
154        parameters = [(name,) for name in more_fruits]
155        cursor.executemany("insert into fruits (name) values (%s)", parameters)
156        con.commit()
157        cursor.execute('select * from fruits where id=1')
158        r = cursor.fetchone()
159        self.assertIsInstance(r, tuple)
160        self.assertEqual(len(r), 2)
161        r = str(r)
162        self.assertEqual(r, "Row(id=1, name='apple')")
163        cursor.execute('select * from fruits')
164        r = cursor.fetchall()
165        self.assertIsInstance(r, list)
166        self.assertEqual(len(r), 7)
167        self.assertEqual(str(r[0]), "Row(id=1, name='apple')")
168        self.assertEqual(str(r[6]), "Row(id=7, name='grapefruit')")
169        cursor.execute('select * from fruits')
170        r = cursor.fetchmany(2)
171        self.assertIsInstance(r, list)
172        self.assertEqual(len(r), 2)
173        self.assertEqual(str(r[0]), "Row(id=1, name='apple')")
174        self.assertEqual(str(r[1]), "Row(id=2, name='banana')")
175
176
177if __name__ == '__main__':
178    unittest.main()
Note: See TracBrowser for help on using the repository browser.