Skip to content

Commit afa8470

Browse files
committed
refactoring so tests can be run for sqlite
1 parent 710bcad commit afa8470

File tree

14 files changed

+98
-109
lines changed

14 files changed

+98
-109
lines changed

docs/src/piccolo/engines/index.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,8 @@ variable accordingly.
103103
104104
DB = SQLiteEngine(path='my_test_db.sqlite')
105105
106+
.. hint:: You can also specify sub modules, like `my_module.piccolo_conf`.
107+
106108
.. _EngineTypes:
107109

108110
Engine types

piccolo/engine/finder.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,8 @@ def engine_finder(module_name: t.Optional[str] = None) -> t.Optional[Engine]:
4646
)
4747
elif not isinstance(engine, Engine):
4848
warnings.warn(
49-
f"{module_name} contains a {ENGINE_VAR} variable of the wrong type - it should be an Engine subclass."
49+
f"{module_name} contains a {ENGINE_VAR} variable of the wrong "
50+
"type - it should be an Engine subclass."
5051
)
5152

5253
return engine

piccolo/query/base.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,11 @@
1313

1414
class Query(object):
1515
def __init__(
16-
self, table: Table, base: QueryString = QueryString(""), *args, **kwargs
16+
self,
17+
table: Table,
18+
base: QueryString = QueryString(""),
19+
*args,
20+
**kwargs,
1721
) -> None:
1822
self.base = base
1923
self.table = table

piccolo/table.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from __future__ import annotations
22
import copy
33
import typing as t
4-
from functools import wraps
54

65
from piccolo.engine import Engine, engine_finder
76
from piccolo.columns import Column, PrimaryKey, ForeignKey
@@ -14,7 +13,6 @@
1413
Exists,
1514
Insert,
1615
Objects,
17-
Query,
1816
Raw,
1917
Select,
2018
TableExists,
@@ -42,6 +40,10 @@ def __new__(cls, name, bases, namespace, **kwds):
4240
if not tablename:
4341
table.Meta.tablename = _camel_to_snake(name)
4442

43+
db = getattr(Meta, "db", None) if Meta else None
44+
if not db:
45+
table.Meta.db = engine_finder()
46+
4547
columns = []
4648

4749
# In case super classes also have columns.
@@ -133,7 +135,9 @@ def save(self) -> t.Union[Insert, Update]:
133135

134136
if type(self.id) == int:
135137
# pre-existing row
136-
kwargs = {i: getattr(self, i._name, None) for i in cls.Meta.columns}
138+
kwargs = {
139+
i: getattr(self, i._name, None) for i in cls.Meta.columns
140+
}
137141
_id = kwargs.pop("id")
138142
return cls.update().values(kwargs).where(cls.id == _id)
139143
else:

test.sqlite

20 KB
Binary file not shown.

tests/base.py

Lines changed: 30 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import asyncio
22
from unittest import TestCase
33

4-
import asyncpg
4+
from piccolo.engine.finder import engine_finder
55

6-
from .example_project.tables import Band
6+
7+
ENGINE = engine_finder()
78

89

910
class DBTestCase(TestCase):
@@ -12,36 +13,38 @@ class DBTestCase(TestCase):
1213
"""
1314

1415
def run_sync(self, query):
15-
async def _run():
16-
connection = await asyncpg.connect(**Band.Meta.db.config)
17-
await connection.execute(query)
18-
await connection.close()
19-
20-
asyncio.run(_run())
16+
asyncio.run(ENGINE.run(query))
2117

2218
def create_table(self):
23-
self.run_sync('''
19+
self.run_sync(
20+
"""
2421
CREATE TABLE manager (
2522
id SERIAL PRIMARY KEY,
2623
name VARCHAR(50)
27-
);''')
24+
);"""
25+
)
2826

29-
self.run_sync('''
27+
self.run_sync(
28+
"""
3029
CREATE TABLE band (
3130
id SERIAL PRIMARY KEY,
3231
name VARCHAR(50),
3332
manager INTEGER REFERENCES manager,
3433
popularity SMALLINT
35-
);''')
34+
);"""
35+
)
3636

3737
def insert_row(self):
38-
self.run_sync('''
38+
self.run_sync(
39+
"""
3940
INSERT INTO manager (
4041
name
4142
) VALUES (
4243
'Guido'
43-
);''')
44-
self.run_sync('''
44+
);"""
45+
)
46+
self.run_sync(
47+
"""
4548
INSERT INTO band (
4649
name,
4750
manager,
@@ -50,10 +53,12 @@ def insert_row(self):
5053
'Pythonistas',
5154
1,
5255
1000
53-
);''')
56+
);"""
57+
)
5458

5559
def insert_rows(self):
56-
self.run_sync('''
60+
self.run_sync(
61+
"""
5762
INSERT INTO manager (
5863
name
5964
) VALUES (
@@ -62,8 +67,10 @@ def insert_rows(self):
6267
'Graydon'
6368
),(
6469
'Mads'
65-
);''')
66-
self.run_sync('''
70+
);"""
71+
)
72+
self.run_sync(
73+
"""
6774
INSERT INTO band (
6875
name,
6976
manager,
@@ -80,11 +87,12 @@ def insert_rows(self):
8087
'CSharps',
8188
3,
8289
10
83-
);''')
90+
);"""
91+
)
8492

8593
def drop_table(self):
86-
self.run_sync('DROP TABLE band;')
87-
self.run_sync('DROP TABLE manager;')
94+
self.run_sync("DROP TABLE band;")
95+
self.run_sync("DROP TABLE manager;")
8896

8997
def setUp(self):
9098
self.create_table()

tests/conftest.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,28 @@
11
import asyncio
22

3-
import asyncpg
4-
import pytest
3+
from piccolo.engine.finder import engine_finder
54

6-
from .example_project.tables import DB
75

6+
ENGINE = engine_finder()
87

9-
async def drop_tables():
10-
connection = await asyncpg.connect(**DB.config)
11-
for table in ['venue', 'concert', 'band', 'manager', 'migration']:
12-
await connection.execute(f'DROP TABLE IF EXISTS {table}')
138

14-
await connection.close()
9+
async def drop_tables():
10+
for table in ["venue", "concert", "band", "manager", "migration"]:
11+
await ENGINE.run(f"DROP TABLE IF EXISTS {table}")
1512

1613

1714
def pytest_sessionstart(session):
1815
"""
16+
Make sure all the tables have been dropped.
17+
1918
https://docs.pytest.org/en/latest/reference.html#_pytest.hookspec.pytest_configure
2019
"""
21-
print('Session starting')
20+
print("Session starting")
2221
asyncio.run(drop_tables())
2322

2423

25-
# def pytest_sessionfinish(session, exitstatus):
26-
# """
27-
# https://docs.pytest.org/en/latest/reference.html#_pytest.hookspec.pytest_sessionfinish
28-
# """
29-
# print('Session finishing')
24+
def pytest_sessionfinish(session, exitstatus):
25+
"""
26+
https://docs.pytest.org/en/latest/reference.html#_pytest.hookspec.pytest_sessionfinish
27+
"""
28+
print("Session finishing")

tests/example_project/tables.py

Lines changed: 2 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,31 @@
11
from piccolo import table
22
from piccolo import columns
3-
from piccolo.engine import PostgresEngine
4-
5-
6-
DB = PostgresEngine({
7-
'host': 'localhost',
8-
'database': 'piccolo',
9-
'user': 'piccolo',
10-
'password': 'piccolo'
11-
})
123

134

145
###############################################################################
156
# Simple example
167

8+
179
class Manager(table.Table):
1810
name = columns.Varchar(length=50)
1911

20-
class Meta():
21-
db = DB
22-
2312

2413
class Band(table.Table):
2514
name = columns.Varchar(length=50)
2615
manager = columns.ForeignKey(Manager)
2716
popularity = columns.Integer()
2817

29-
class Meta():
30-
db = DB
31-
3218

3319
###############################################################################
3420
# More complex
3521

22+
3623
class Venue(table.Table):
3724
name = columns.Varchar(length=100)
3825
capacity = columns.Integer()
3926

40-
class Meta():
41-
db = DB
42-
4327

4428
class Concert(table.Table):
4529
band_1 = columns.ForeignKey(Band)
4630
band_2 = columns.ForeignKey(Band)
4731
venue = columns.ForeignKey(Venue)
48-
49-
class Meta():
50-
db = DB

tests/extensions/test_user.py

Lines changed: 11 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,20 @@
22
from unittest import TestCase
33

44
from piccolo.extensions.user import BaseUser
5-
from ..example_project.tables import DB
6-
7-
8-
class User(BaseUser):
9-
class Meta():
10-
db = DB
11-
tablename = 'custom_user'
125

136

147
class TestCreateUserTable(TestCase):
15-
168
def test_create_user_table(self):
179
"""
1810
Make sure the table can be created.
1911
"""
2012
exception = None
2113
try:
22-
User.create().run_sync()
14+
BaseUser.create().run_sync()
2315
except Exception as e:
2416
exception = e
2517
else:
26-
User.drop().run_sync()
18+
BaseUser.drop().run_sync()
2719

2820
if exception:
2921
raise exception
@@ -32,60 +24,46 @@ def test_create_user_table(self):
3224

3325

3426
class TestHashPassword(TestCase):
35-
3627
def test_hash_password(self):
3728
pass
3829

3930

4031
class TestLogin(TestCase):
41-
4232
def setUp(self):
43-
User.create().run_sync()
33+
BaseUser.create().run_sync()
4434

4535
def tearDown(self):
46-
User.drop().run_sync()
36+
BaseUser.drop().run_sync()
4737

4838
def test_login(self):
4939
username = "bob"
5040
password = "Bob123$$$"
5141
email = "bob@bob.com"
5242

53-
user = User(
54-
username=username,
55-
password=password,
56-
email=email
57-
)
43+
user = BaseUser(username=username, password=password, email=email)
5844

5945
save_query = user.save()
6046

6147
save_query.run_sync()
6248

63-
authenticated = asyncio.run(
64-
User.login(username, password)
65-
)
49+
authenticated = asyncio.run(BaseUser.login(username, password))
6650
self.assertTrue(authenticated is not None)
6751

68-
authenticated = asyncio.run(
69-
User.login(username, 'blablabla')
70-
)
52+
authenticated = asyncio.run(BaseUser.login(username, "blablabla"))
7153
self.assertTrue(not authenticated)
7254

7355
def test_update_password(self):
7456
username = "bob"
7557
password = "Bob123$$$"
7658
email = "bob@bob.com"
7759

78-
user = User(
79-
username=username,
80-
password=password,
81-
email=email
82-
)
60+
user = BaseUser(username=username, password=password, email=email)
8361
user.save().run_sync()
8462

85-
authenticated = User.login_sync(username, password)
63+
authenticated = BaseUser.login_sync(username, password)
8664
self.assertTrue(authenticated is not None)
8765

8866
new_password = "XXX111"
89-
User.update_password_sync(username, new_password)
90-
authenticated = User.login_sync(username, new_password)
67+
BaseUser.update_password_sync(username, new_password)
68+
authenticated = BaseUser.login_sync(username, new_password)
9169
self.assertTrue(authenticated is not None)

tests/postgres_conf.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from piccolo.engine.postgres import PostgresEngine
2+
3+
4+
DB = PostgresEngine(
5+
{
6+
"host": "localhost",
7+
"database": "piccolo",
8+
"user": "piccolo",
9+
"password": "piccolo",
10+
}
11+
)

0 commit comments

Comments
 (0)