337 lines
12 KiB
Python
Raw Normal View History

import os
2013-04-01 19:38:02 +02:00
import unittest
from datetime import datetime
try:
from collections import OrderedDict
except ImportError: # pragma: no cover
from ordereddict import OrderedDict # Python < 2.7 drop-in
2014-06-08 23:36:42 +02:00
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from dataset import connect
2013-04-05 00:47:40 +02:00
from dataset.util import DatasetException
from .sample_data import TEST_DATA, TEST_CITY_1
2013-04-01 19:38:02 +02:00
2013-04-05 11:46:45 +02:00
2013-04-01 19:38:02 +02:00
class DatabaseTestCase(unittest.TestCase):
def setUp(self):
os.environ.setdefault('DATABASE_URL', 'sqlite:///:memory:')
self.db = connect(os.environ['DATABASE_URL'])
2013-04-01 19:46:17 +02:00
self.tbl = self.db['weather']
for row in TEST_DATA:
self.tbl.insert(row)
2013-04-01 19:38:02 +02:00
2014-01-31 18:56:58 +01:00
def tearDown(self):
for table in self.db.tables:
self.db[table].drop()
def test_valid_database_url(self):
assert self.db.url, os.environ['DATABASE_URL']
def test_database_url_query_string(self):
db = connect('sqlite:///:memory:/?cached_statements=1')
assert 'cached_statements' in db.url, db.url
2013-04-01 22:09:16 +02:00
def test_tables(self):
2013-04-05 11:46:45 +02:00
assert self.db.tables == ['weather'], self.db.tables
2013-04-01 22:09:16 +02:00
2014-08-29 20:12:25 +02:00
def test_contains(self):
assert 'weather' in self.db, self.db.tables
2013-04-01 19:38:02 +02:00
def test_create_table(self):
table = self.db['foo']
assert table.table.exists()
assert len(table.table.columns) == 1, table.table.columns
2013-04-01 19:46:17 +02:00
assert 'id' in table.table.c, table.table.c
2013-09-08 17:35:43 +02:00
def test_create_table_custom_id1(self):
pid = "string_id"
table = self.db.create_table("foo2", pid, 'String')
2013-09-08 17:35:43 +02:00
assert table.table.exists()
assert len(table.table.columns) == 1, table.table.columns
assert pid in table.table.c, table.table.c
table.insert({
'string_id': 'foobar'})
2014-01-25 21:45:30 +01:00
assert table.find_one(string_id='foobar')['string_id'] == 'foobar'
2013-09-08 17:35:43 +02:00
def test_create_table_custom_id2(self):
pid = "string_id"
table = self.db.create_table("foo3", pid, 'String(50)')
assert table.table.exists()
assert len(table.table.columns) == 1, table.table.columns
assert pid in table.table.c, table.table.c
table.insert({
'string_id': 'foobar'})
2014-01-25 21:45:30 +01:00
assert table.find_one(string_id='foobar')['string_id'] == 'foobar'
def test_create_table_custom_id3(self):
2013-09-08 17:35:43 +02:00
pid = "int_id"
2014-01-25 21:45:30 +01:00
table = self.db.create_table("foo4", primary_id=pid)
2013-09-08 17:35:43 +02:00
assert table.table.exists()
assert len(table.table.columns) == 1, table.table.columns
assert pid in table.table.c, table.table.c
table.insert({'int_id': 123})
table.insert({'int_id': 124})
2014-01-25 21:45:30 +01:00
assert table.find_one(int_id=123)['int_id'] == 123
assert table.find_one(int_id=124)['int_id'] == 124
self.assertRaises(IntegrityError, lambda: table.insert({'int_id': 123}))
2013-09-08 17:35:43 +02:00
def test_create_table_shorthand1(self):
pid = "int_id"
table = self.db.get_table('foo5', pid)
assert table.table.exists
assert len(table.table.columns) == 1, table.table.columns
assert pid in table.table.c, table.table.c
table.insert({'int_id': 123})
table.insert({'int_id': 124})
2014-01-25 21:45:30 +01:00
assert table.find_one(int_id=123)['int_id'] == 123
assert table.find_one(int_id=124)['int_id'] == 124
self.assertRaises(IntegrityError, lambda: table.insert({'int_id': 123}))
def test_create_table_shorthand2(self):
pid = "string_id"
table = self.db.get_table('foo6', primary_id=pid, primary_type='String')
assert table.table.exists
assert len(table.table.columns) == 1, table.table.columns
assert pid in table.table.c, table.table.c
table.insert({
'string_id': 'foobar'})
2014-01-25 21:45:30 +01:00
assert table.find_one(string_id='foobar')['string_id'] == 'foobar'
def test_create_table_shorthand3(self):
pid = "string_id"
table = self.db.get_table('foo7', primary_id=pid, primary_type='String(20)')
assert table.table.exists
assert len(table.table.columns) == 1, table.table.columns
assert pid in table.table.c, table.table.c
table.insert({
'string_id': 'foobar'})
2014-01-25 21:45:30 +01:00
assert table.find_one(string_id='foobar')['string_id'] == 'foobar'
2014-06-08 23:36:42 +02:00
def test_with(self):
init_length = len(self.db['weather'])
with self.assertRaises(ValueError):
with self.db as tx:
tx['weather'].insert({'date': datetime(2011, 1, 1), 'temperature': 1, 'place': u'tmp_place'})
raise ValueError()
2014-06-08 23:36:42 +02:00
assert len(self.db['weather']) == init_length
def test_invalid_values(self):
if 'mysql.connector' in self.db.engine.dialect.dbapi.__name__:
# WARNING: mysql-connector seems to be doing some weird type casting upon insert.
# The mysql-python driver is not affected but it isn't compatible with Python 3
# Conclusion: use postgresql.
return
with self.assertRaises(SQLAlchemyError):
tbl = self.db['weather']
tbl.insert({'date': True, 'temperature': 'wrong_value', 'place': u'tmp_place'})
2013-04-01 19:46:17 +02:00
def test_load_table(self):
tbl = self.db.load_table('weather')
2013-04-05 11:46:45 +02:00
assert tbl.table == self.tbl.table
2013-04-01 19:46:17 +02:00
def test_query(self):
r = self.db.query('SELECT COUNT(*) AS num FROM weather').next()
2013-04-05 11:46:45 +02:00
assert r['num'] == len(TEST_DATA), r
2013-04-01 19:46:17 +02:00
def test_table_cache_updates(self):
tbl1 = self.db.get_table('people')
2014-02-18 12:59:12 +01:00
data = OrderedDict([('first_name', 'John'), ('last_name', 'Smith')])
tbl1.insert(data)
data['id'] = 1
tbl2 = self.db.get_table('people')
2014-02-18 12:59:12 +01:00
assert dict(tbl2.all().next()) == dict(data), (tbl2.all().next(), data)
2013-04-01 19:38:02 +02:00
2013-04-01 19:56:14 +02:00
class TableTestCase(unittest.TestCase):
def setUp(self):
2013-07-14 23:07:42 +02:00
self.db = connect('sqlite:///:memory:')
2013-04-01 19:56:14 +02:00
self.tbl = self.db['weather']
for row in TEST_DATA:
self.tbl.insert(row)
def test_insert(self):
2013-04-05 11:46:45 +02:00
assert len(self.tbl) == len(TEST_DATA), len(self.tbl)
2013-04-06 03:06:51 +02:00
last_id = self.tbl.insert({
'date': datetime(2011, 1, 2),
2013-04-01 19:56:14 +02:00
'temperature': -10,
'place': 'Berlin'}
2013-04-05 11:46:45 +02:00
)
2014-01-25 21:45:30 +01:00
assert len(self.tbl) == len(TEST_DATA) + 1, len(self.tbl)
2013-04-06 03:06:51 +02:00
assert self.tbl.find_one(id=last_id)['place'] == 'Berlin'
2013-04-01 19:56:14 +02:00
2013-04-01 22:03:01 +02:00
def test_upsert(self):
self.tbl.upsert({
'date': datetime(2011, 1, 2),
2013-04-01 22:03:01 +02:00
'temperature': -10,
'place': 'Berlin'},
['place']
2013-04-05 11:46:45 +02:00
)
2014-01-25 21:45:30 +01:00
assert len(self.tbl) == len(TEST_DATA) + 1, len(self.tbl)
2013-04-01 22:03:01 +02:00
self.tbl.upsert({
'date': datetime(2011, 1, 2),
2013-04-01 22:03:01 +02:00
'temperature': -10,
'place': 'Berlin'},
['place']
2013-04-05 11:46:45 +02:00
)
2014-01-25 21:45:30 +01:00
assert len(self.tbl) == len(TEST_DATA) + 1, len(self.tbl)
2013-04-01 22:03:01 +02:00
2013-06-27 14:13:28 +02:00
def test_upsert_all_key(self):
2014-01-25 21:45:30 +01:00
for i in range(0, 2):
2013-06-27 14:13:28 +02:00
self.tbl.upsert({
'date': datetime(2011, 1, 2),
2013-06-27 14:13:28 +02:00
'temperature': -10,
'place': 'Berlin'},
['date', 'temperature', 'place']
)
def test_update_while_iter(self):
for row in self.tbl:
row['foo'] = 'bar'
self.tbl.update(row, ['place', 'date'])
def test_weird_column_names(self):
with self.assertRaises(ValueError):
self.tbl.insert({
'date': datetime(2011, 1, 2),
'temperature': -10,
'foo.bar': 'Berlin',
'qux.bar': 'Huhu'
})
2013-04-01 22:03:01 +02:00
def test_delete(self):
self.tbl.insert({
'date': datetime(2011, 1, 2),
2013-04-01 22:03:01 +02:00
'temperature': -10,
'place': 'Berlin'}
2013-04-05 11:46:45 +02:00
)
2014-01-25 21:45:30 +01:00
assert len(self.tbl) == len(TEST_DATA) + 1, len(self.tbl)
2014-01-31 23:27:40 +01:00
assert self.tbl.delete(place='Berlin') is True, 'should return 1'
2013-04-05 11:46:45 +02:00
assert len(self.tbl) == len(TEST_DATA), len(self.tbl)
2014-01-31 23:27:40 +01:00
assert self.tbl.delete() is True, 'should return non zero'
2013-04-05 11:53:50 +02:00
assert len(self.tbl) == 0, len(self.tbl)
2013-04-01 22:03:01 +02:00
2014-02-03 22:52:00 +01:00
def test_repr(self):
assert repr(self.tbl) == '<Table(weather)>', 'the representation should be <Table(weather)>'
2014-01-31 23:27:40 +01:00
def test_delete_nonexist_entry(self):
assert self.tbl.delete(place='Berlin') is False, 'entry not exist, should fail to delete'
2013-04-01 22:03:01 +02:00
def test_find_one(self):
self.tbl.insert({
'date': datetime(2011, 1, 2),
2013-04-01 22:03:01 +02:00
'temperature': -10,
'place': 'Berlin'}
2013-04-05 11:46:45 +02:00
)
2013-04-01 22:03:01 +02:00
d = self.tbl.find_one(place='Berlin')
2013-04-05 11:46:45 +02:00
assert d['temperature'] == -10, d
2013-04-01 22:03:01 +02:00
d = self.tbl.find_one(place='Atlantis')
assert d is None, d
def test_count(self):
assert len(self.tbl) == 6, len(self.tbl)
l = self.tbl.count(place=TEST_CITY_1)
assert l == 3, l
2013-04-01 22:03:01 +02:00
def test_find(self):
ds = list(self.tbl.find(place=TEST_CITY_1))
2013-04-05 11:46:45 +02:00
assert len(ds) == 3, ds
ds = list(self.tbl.find(place=TEST_CITY_1, _limit=2))
2013-04-05 11:46:45 +02:00
assert len(ds) == 2, ds
ds = list(self.tbl.find(place=TEST_CITY_1, _limit=2, _step=1))
assert len(ds) == 2, ds
ds = list(self.tbl.find(place=TEST_CITY_1, _limit=1, _step=2))
assert len(ds) == 1, ds
ds = list(self.tbl.find(order_by=['temperature']))
assert ds[0]['temperature'] == -1, ds
ds = list(self.tbl.find(order_by=['-temperature']))
assert ds[0]['temperature'] == 8, ds
2014-01-31 21:52:57 +01:00
def test_offset(self):
ds = list(self.tbl.find(place=TEST_CITY_1, _offset=1))
assert len(ds) == 2, ds
ds = list(self.tbl.find(place=TEST_CITY_1, _limit=2, _offset=2))
assert len(ds) == 1, ds
2013-04-01 22:03:01 +02:00
2013-04-01 19:56:14 +02:00
def test_distinct(self):
x = list(self.tbl.distinct('place'))
2013-04-05 11:46:45 +02:00
assert len(x) == 2, x
2013-04-01 19:56:14 +02:00
x = list(self.tbl.distinct('place', 'date'))
2013-04-05 11:46:45 +02:00
assert len(x) == 6, x
2013-04-01 19:56:14 +02:00
def test_get_items(self):
x = list(self.tbl['place'])
y = list(self.tbl.distinct('place'))
assert x == y, (x, y)
x = list(self.tbl['place', 'date'])
y = list(self.tbl.distinct('place', 'date'))
assert x == y, (x, y)
2013-04-04 15:43:05 +02:00
def test_insert_many(self):
2013-12-18 11:50:34 +01:00
data = TEST_DATA * 100
self.tbl.insert_many(data, chunk_size=13)
2013-04-04 15:43:05 +02:00
assert len(self.tbl) == len(data) + 6
2013-04-05 00:47:40 +02:00
def test_drop_warning(self):
assert self.tbl._is_dropped is False, 'table shouldn\'t be dropped yet'
self.tbl.drop()
assert self.tbl._is_dropped is True, 'table should be dropped now'
try:
list(self.tbl.all())
except DatasetException:
pass
else:
assert False, 'we should not reach else block, no exception raised!'
2013-04-01 19:56:14 +02:00
2013-04-05 11:46:45 +02:00
def test_columns(self):
cols = self.tbl.columns
assert len(list(cols)) == 4, 'column count mismatch'
2013-04-05 11:46:45 +02:00
assert 'date' in cols and 'temperature' in cols and 'place' in cols
def test_iter(self):
c = 0
for row in self.tbl:
c += 1
assert c == len(self.tbl)
def test_update(self):
date = datetime(2011, 1, 2)
2013-04-05 11:50:50 +02:00
res = self.tbl.update({
'date': date,
2013-04-05 11:46:45 +02:00
'temperature': -10,
'place': TEST_CITY_1},
2013-04-05 11:50:50 +02:00
['place', 'date']
2013-04-05 11:46:45 +02:00
)
2013-04-05 11:50:50 +02:00
assert res, 'update should return True'
m = self.tbl.find_one(place=TEST_CITY_1, date=date)
2013-04-05 11:59:47 +02:00
assert m['temperature'] == -10, 'new temp. should be -10 but is %d' % m['temperature']
2013-04-01 19:38:02 +02:00
2013-04-05 11:58:16 +02:00
def test_create_column(self):
from sqlalchemy import FLOAT
tbl = self.tbl
tbl.create_column('foo', FLOAT)
assert 'foo' in tbl.table.c, tbl.table.c
assert isinstance(tbl.table.c['foo'].type, FLOAT), tbl.table.c['foo'].type
2013-04-05 11:58:16 +02:00
assert 'foo' in tbl.columns, tbl.columns
2013-12-19 23:46:10 +01:00
def test_key_order(self):
res = self.db.query('SELECT temperature, place FROM weather LIMIT 1')
2014-01-05 18:36:11 +01:00
keys = list(res.next().keys())
2013-12-19 23:46:10 +01:00
assert keys[0] == 'temperature'
assert keys[1] == 'place'
def test_empty_query(self):
m = self.tbl.find(place='not in data')
l = list(m) # exhaust iterator
assert len(l) == 0