Skip to content

Commit fe40806

Browse files
authored
Merge pull request piccolo-orm#68 from piccolo-orm/test_inheritance
Test inheritance
2 parents a282883 + acaee23 commit fe40806

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

docs/src/piccolo/schema/advanced.rst

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,24 @@ for example with ``table_finder`` (see :ref:`TableFinder`).
6262
6363
class Band(Table, tags=["music"]):
6464
name = Varchar(length=100)
65+
66+
-------------------------------------------------------------------------------
67+
68+
Mixins
69+
------
70+
71+
If you're frequently defining the same columns over and over again, you can
72+
use mixins to reduce the amount of repetition.
73+
74+
.. code-block:: python
75+
76+
from piccolo.columns import Varchar, Boolean
77+
from piccolo.table import Table
78+
79+
80+
class FavouriteMixin:
81+
favourite = Boolean(default=False)
82+
83+
84+
class Manager(FavouriteMixin, Table):
85+
name = Varchar()

tests/table/test_inheritance.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import datetime
2+
from unittest import TestCase
3+
4+
from piccolo.columns import Varchar, Timestamp, Boolean
5+
from piccolo.table import Table
6+
7+
8+
class StartedOnMixin(Table):
9+
"""
10+
A mixin which inherits from Table.
11+
"""
12+
13+
started_on = Timestamp()
14+
15+
16+
class FavouriteMixin:
17+
"""
18+
A mixin which deliberately doesn't inherit from Table.
19+
"""
20+
21+
favourite = Boolean()
22+
23+
24+
class Manager(StartedOnMixin, FavouriteMixin, Table):
25+
name = Varchar()
26+
27+
28+
class TestInheritance(TestCase):
29+
"""
30+
Make sure columns can be inheritted from parent classes.
31+
"""
32+
33+
def setUp(self):
34+
Manager.create_table().run_sync()
35+
36+
def tearDown(self):
37+
Manager.alter().drop_table().run_sync()
38+
39+
def test_inheritance(self):
40+
"""
41+
Test that a table created via inheritance works as expected.
42+
"""
43+
# Make sure both columns can be retrieved:
44+
for column_name in ("started_on", "name", "favourite"):
45+
Manager._meta.get_column_by_name(column_name)
46+
47+
# Test saving and retrieving data:
48+
started_on = datetime.datetime(year=1989, month=12, day=1)
49+
name = "Guido"
50+
favourite = True
51+
Manager(
52+
name=name, started_on=started_on, favourite=favourite
53+
).save().run_sync()
54+
55+
response = Manager.select().first().run_sync()
56+
self.assertEqual(response["started_on"], started_on)
57+
self.assertEqual(response["name"], name)
58+
self.assertEqual(response["favourite"], favourite)

0 commit comments

Comments
 (0)