File: test_productspec.py

package info (click to toggle)
sqlalchemy 2.0.40%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 26,404 kB
  • sloc: python: 410,002; makefile: 230; sh: 7
file content (481 lines) | stat: -rw-r--r-- 15,833 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
from datetime import datetime

from sqlalchemy import DateTime
from sqlalchemy import Float
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import LargeBinary
from sqlalchemy import String
from sqlalchemy.orm import backref
from sqlalchemy.orm import deferred
from sqlalchemy.orm import relationship
from sqlalchemy.testing import fixtures
from sqlalchemy.testing.fixtures import fixture_session
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import Table


class InheritTest(fixtures.MappedTest):
    """tests some various inheritance round trips involving a particular set of
    polymorphic inheritance relationships"""

    @classmethod
    def define_tables(cls, metadata):
        global products_table, specification_table, documents_table
        global Product, Detail, Assembly, SpecLine, Document, RasterDocument

        products_table = Table(
            "products",
            metadata,
            Column(
                "product_id",
                Integer,
                primary_key=True,
                test_needs_autoincrement=True,
            ),
            Column("product_type", String(128)),
            Column("name", String(128)),
            Column("mark", String(128)),
        )

        specification_table = Table(
            "specification",
            metadata,
            Column(
                "spec_line_id",
                Integer,
                primary_key=True,
                test_needs_autoincrement=True,
            ),
            Column(
                "leader_id",
                Integer,
                ForeignKey("products.product_id"),
                nullable=True,
            ),
            Column(
                "follower_id",
                Integer,
                ForeignKey("products.product_id"),
                nullable=True,
            ),
            Column("quantity", Float, default=1.0),
        )

        documents_table = Table(
            "documents",
            metadata,
            Column(
                "document_id",
                Integer,
                primary_key=True,
                test_needs_autoincrement=True,
            ),
            Column("document_type", String(128)),
            Column("product_id", Integer, ForeignKey("products.product_id")),
            Column("create_date", DateTime, default=lambda: datetime.now()),
            Column(
                "last_updated",
                DateTime,
                default=lambda: datetime.now(),
                onupdate=lambda: datetime.now(),
            ),
            Column("name", String(128)),
            Column("data", LargeBinary),
            Column("size", Integer, default=0),
        )

        class Product:
            def __init__(self, name, mark=""):
                self.name = name
                self.mark = mark

            def __repr__(self):
                return "<%s %s>" % (self.__class__.__name__, self.name)

        class Detail(Product):
            def __init__(self, name):
                self.name = name

        class Assembly(Product):
            def __repr__(self):
                return (
                    Product.__repr__(self)
                    + " "
                    + " ".join(
                        [
                            x + "=" + repr(getattr(self, x, None))
                            for x in ["specification", "documents"]
                        ]
                    )
                )

        class SpecLine:
            def __init__(self, leader=None, follower=None, quantity=1):
                self.leader = leader
                self.follower = follower
                self.quantity = quantity

            def __repr__(self):
                return "<%s %.01f %s>" % (
                    self.__class__.__name__,
                    self.quantity or 0.0,
                    repr(self.follower),
                )

        class Document:
            def __init__(self, name, data=None):
                self.name = name
                self.data = data

            def __repr__(self):
                return "<%s %s>" % (self.__class__.__name__, self.name)

        class RasterDocument(Document):
            pass

    def test_one(self):
        product_mapper = self.mapper_registry.map_imperatively(
            Product,
            products_table,
            polymorphic_on=products_table.c.product_type,
            polymorphic_identity="product",
        )

        self.mapper_registry.map_imperatively(
            Detail, inherits=product_mapper, polymorphic_identity="detail"
        )

        self.mapper_registry.map_imperatively(
            Assembly, inherits=product_mapper, polymorphic_identity="assembly"
        )

        self.mapper_registry.map_imperatively(
            SpecLine,
            specification_table,
            properties=dict(
                leader=relationship(
                    Assembly,
                    foreign_keys=[specification_table.c.leader_id],
                    primaryjoin=specification_table.c.leader_id
                    == products_table.c.product_id,
                    lazy="select",
                    backref=backref("specification"),
                    uselist=False,
                ),
                follower=relationship(
                    Product,
                    foreign_keys=[specification_table.c.follower_id],
                    primaryjoin=specification_table.c.follower_id
                    == products_table.c.product_id,
                    lazy="select",
                    uselist=False,
                ),
                quantity=specification_table.c.quantity,
            ),
        )

        session = fixture_session()

        a1 = Assembly(name="a1")

        p1 = Product(name="p1")
        a1.specification.append(SpecLine(follower=p1))

        d1 = Detail(name="d1")
        a1.specification.append(SpecLine(follower=d1))

        session.add(a1)
        orig = repr(a1)
        session.flush()
        session.expunge_all()

        a1 = session.query(Product).filter_by(name="a1").one()
        new = repr(a1)
        print(orig)
        print(new)
        assert (
            orig == new == "<Assembly a1> specification=[<SpecLine 1.0 "
            "<Product p1>>, <SpecLine 1.0 <Detail d1>>] documents=None"
        )

    def test_two(self):
        product_mapper = self.mapper_registry.map_imperatively(
            Product,
            products_table,
            polymorphic_on=products_table.c.product_type,
            polymorphic_identity="product",
        )

        self.mapper_registry.map_imperatively(
            Detail, inherits=product_mapper, polymorphic_identity="detail"
        )

        self.mapper_registry.map_imperatively(
            SpecLine,
            specification_table,
            properties=dict(
                follower=relationship(
                    Product,
                    foreign_keys=[specification_table.c.follower_id],
                    primaryjoin=specification_table.c.follower_id
                    == products_table.c.product_id,
                    lazy="select",
                    uselist=False,
                )
            ),
        )

        session = fixture_session()

        s = SpecLine(follower=Product(name="p1"))
        s2 = SpecLine(follower=Detail(name="d1"))
        session.add(s)
        session.add(s2)
        orig = repr([s, s2])
        session.flush()
        session.expunge_all()
        new = repr(session.query(SpecLine).all())
        print(orig)
        print(new)
        assert (
            orig == new == "[<SpecLine 1.0 <Product p1>>, "
            "<SpecLine 1.0 <Detail d1>>]"
        )

    def test_three(self):
        product_mapper = self.mapper_registry.map_imperatively(
            Product,
            products_table,
            polymorphic_on=products_table.c.product_type,
            polymorphic_identity="product",
        )
        self.mapper_registry.map_imperatively(
            Detail, inherits=product_mapper, polymorphic_identity="detail"
        )
        self.mapper_registry.map_imperatively(
            Assembly, inherits=product_mapper, polymorphic_identity="assembly"
        )

        self.mapper_registry.map_imperatively(
            SpecLine,
            specification_table,
            properties=dict(
                leader=relationship(
                    Assembly,
                    lazy="joined",
                    uselist=False,
                    foreign_keys=[specification_table.c.leader_id],
                    primaryjoin=specification_table.c.leader_id
                    == products_table.c.product_id,
                    backref=backref(
                        "specification", cascade="all, delete-orphan"
                    ),
                ),
                follower=relationship(
                    Product,
                    lazy="joined",
                    uselist=False,
                    foreign_keys=[specification_table.c.follower_id],
                    primaryjoin=specification_table.c.follower_id
                    == products_table.c.product_id,
                ),
                quantity=specification_table.c.quantity,
            ),
        )

        document_mapper = self.mapper_registry.map_imperatively(
            Document,
            documents_table,
            polymorphic_on=documents_table.c.document_type,
            polymorphic_identity="document",
            properties=dict(
                name=documents_table.c.name,
                data=deferred(documents_table.c.data),
                product=relationship(
                    Product,
                    lazy="select",
                    backref=backref("documents", cascade="all, delete-orphan"),
                ),
            ),
        )
        self.mapper_registry.map_imperatively(
            RasterDocument,
            inherits=document_mapper,
            polymorphic_identity="raster_document",
        )

        session = fixture_session()

        a1 = Assembly(name="a1")
        a1.specification.append(SpecLine(follower=Detail(name="d1")))
        a1.documents.append(Document("doc1"))
        a1.documents.append(RasterDocument("doc2"))
        session.add(a1)
        orig = repr(a1)
        session.flush()
        session.expunge_all()

        a1 = session.query(Product).filter_by(name="a1").one()
        new = repr(a1)
        print(orig)
        print(new)
        assert (
            orig == new == "<Assembly a1> specification="
            "[<SpecLine 1.0 <Detail d1>>] "
            "documents=[<Document doc1>, <RasterDocument doc2>]"
        )

    def test_four(self):
        """this tests the RasterDocument being attached to the Assembly, but
        *not* the Document.  this means only a "sub-class" task, i.e.
        corresponding to an inheriting mapper but not the base mapper,
        is created."""

        product_mapper = self.mapper_registry.map_imperatively(
            Product,
            products_table,
            polymorphic_on=products_table.c.product_type,
            polymorphic_identity="product",
        )
        self.mapper_registry.map_imperatively(
            Detail, inherits=product_mapper, polymorphic_identity="detail"
        )
        self.mapper_registry.map_imperatively(
            Assembly, inherits=product_mapper, polymorphic_identity="assembly"
        )

        document_mapper = self.mapper_registry.map_imperatively(
            Document,
            documents_table,
            polymorphic_on=documents_table.c.document_type,
            polymorphic_identity="document",
            properties=dict(
                name=documents_table.c.name,
                data=deferred(documents_table.c.data),
                product=relationship(
                    Product,
                    lazy="select",
                    backref=backref("documents", cascade="all, delete-orphan"),
                ),
            ),
        )
        self.mapper_registry.map_imperatively(
            RasterDocument,
            inherits=document_mapper,
            polymorphic_identity="raster_document",
        )

        session = fixture_session()

        a1 = Assembly(name="a1")
        a1.documents.append(RasterDocument("doc2"))
        session.add(a1)
        orig = repr(a1)
        session.flush()
        session.expunge_all()

        a1 = session.query(Product).filter_by(name="a1").one()
        new = repr(a1)
        print(orig)
        print(new)
        assert (
            orig == new == "<Assembly a1> specification=None documents="
            "[<RasterDocument doc2>]"
        )

        del a1.documents[0]
        session.flush()
        session.expunge_all()

        a1 = session.query(Product).filter_by(name="a1").one()
        assert len(session.query(Document).all()) == 0

    def test_five(self):
        """tests the late compilation of mappers"""

        self.mapper_registry.map_imperatively(
            SpecLine,
            specification_table,
            properties=dict(
                leader=relationship(
                    Assembly,
                    lazy="joined",
                    uselist=False,
                    foreign_keys=[specification_table.c.leader_id],
                    primaryjoin=specification_table.c.leader_id
                    == products_table.c.product_id,
                    backref=backref("specification"),
                ),
                follower=relationship(
                    Product,
                    lazy="joined",
                    uselist=False,
                    foreign_keys=[specification_table.c.follower_id],
                    primaryjoin=specification_table.c.follower_id
                    == products_table.c.product_id,
                ),
                quantity=specification_table.c.quantity,
            ),
        )

        self.mapper_registry.map_imperatively(
            Product,
            products_table,
            polymorphic_on=products_table.c.product_type,
            polymorphic_identity="product",
            properties={
                "documents": relationship(
                    Document,
                    lazy="select",
                    backref="product",
                    cascade="all, delete-orphan",
                )
            },
        )

        self.mapper_registry.map_imperatively(
            Detail, inherits=Product, polymorphic_identity="detail"
        )

        self.mapper_registry.map_imperatively(
            Document,
            documents_table,
            polymorphic_on=documents_table.c.document_type,
            polymorphic_identity="document",
            properties=dict(
                name=documents_table.c.name,
                data=deferred(documents_table.c.data),
            ),
        )

        self.mapper_registry.map_imperatively(
            RasterDocument,
            inherits=Document,
            polymorphic_identity="raster_document",
        )

        self.mapper_registry.map_imperatively(
            Assembly, inherits=Product, polymorphic_identity="assembly"
        )

        session = fixture_session()

        a1 = Assembly(name="a1")
        a1.specification.append(SpecLine(follower=Detail(name="d1")))
        a1.documents.append(Document("doc1"))
        a1.documents.append(RasterDocument("doc2"))
        session.add(a1)
        orig = repr(a1)
        session.flush()
        session.expunge_all()

        a1 = session.query(Product).filter_by(name="a1").one()
        new = repr(a1)
        print(orig)
        print(new)
        assert (
            orig == new == "<Assembly a1> specification="
            "[<SpecLine 1.0 <Detail d1>>] documents=[<Document doc1>, "
            "<RasterDocument doc2>]"
        )