This file is indexed.

/usr/lib/python2.7/dist-packages/twext/enterprise/dal/test/test_record.py is in python-twext 0.1.b2.dev15059-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
##
# Copyright (c) 2012-2015 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##

"""
Test cases for L{twext.enterprise.dal.record}.
"""

import datetime

from twisted.internet.defer import inlineCallbacks, gatherResults, returnValue
from twisted.trial.unittest import TestCase, SkipTest

from twext.enterprise.dal.record import (
    Record, fromTable, ReadOnly, NoSuchRecord,
    SerializableRecord)
from twext.enterprise.dal.test.test_parseschema import SchemaTestHelper
from twext.enterprise.dal.syntax import SchemaSyntax
from twext.enterprise.fixtures import buildConnectionPool

# from twext.enterprise.dal.syntax import


sth = SchemaTestHelper()
sth.id = lambda: __name__
schemaString = """
create table ALPHA (BETA integer primary key, GAMMA text);
create table DELTA (PHI integer primary key default (nextval('myseq')),
                    EPSILON text not null,
                    ZETA timestamp not null default '2012-12-12 12:12:12' );
"""

# sqlite can be made to support nextval() as a function, but 'create sequence'
# is syntax and can't.
parseableSchemaString = """
create sequence myseq;
""" + schemaString

try:
    testSchema = SchemaSyntax(sth.schemaFromString(parseableSchemaString))
except SkipTest as e:
    Alpha = Delta = object
    skip = e
else:
    Alpha = fromTable(testSchema.ALPHA)
    Delta = fromTable(testSchema.DELTA)
    skip = False



class TestRecord(Record, Alpha):
    """
    A sample test record.
    """



class TestSerializeRecord(SerializableRecord, Alpha):
    """
    A sample test serializable record with default values specified.
    """



class TestAutoRecord(Record, Delta):
    """
    A sample test record with default values specified.
    """



class TestCRUD(TestCase):
    """
    Tests for creation, mutation, and deletion operations.
    """

    def setUp(self):
        self.pool = buildConnectionPool(self, schemaString)


    @inlineCallbacks
    def test_simpleLoad(self):
        """
        Loading an existing row from the database by its primary key will
        populate its attributes from columns of the corresponding row in the
        database.
        """
        txn = self.pool.connection()
        yield txn.execSQL("insert into ALPHA values (:1, :2)", [234, "one"])
        yield txn.execSQL("insert into ALPHA values (:1, :2)", [456, "two"])

        rec = yield TestRecord.load(txn, 456)
        self.assertIsInstance(rec, TestRecord)
        self.assertEquals(rec.beta, 456)
        self.assertEquals(rec.gamma, "two")

        rec2 = yield TestRecord.load(txn, 234)
        self.assertIsInstance(rec2, TestRecord)
        self.assertEqual(rec2.beta, 234)
        self.assertEqual(rec2.gamma, "one")


    @inlineCallbacks
    def test_missingLoad(self):
        """
        Try loading an row which doesn't exist
        """
        txn = self.pool.connection()
        yield txn.execSQL("insert into ALPHA values (:1, :2)", [234, "one"])
        yield self.assertFailure(TestRecord.load(txn, 456), NoSuchRecord)


    @inlineCallbacks
    def test_simpleCreate(self):
        """
        When a record object is created, a row with matching column values will
        be created in the database.
        """
        txn = self.pool.connection()

        rec = yield TestRecord.create(txn, beta=3, gamma=u'epsilon')
        self.assertEquals(rec.beta, 3)
        self.assertEqual(rec.gamma, u'epsilon')

        rows = yield txn.execSQL("select BETA, GAMMA from ALPHA")
        self.assertEqual(rows, [tuple([3, u'epsilon'])])


    @inlineCallbacks
    def test_simpleDelete(self):
        """
        When a record object is deleted, a row with a matching primary key will
        be deleted in the database.
        """
        txn = self.pool.connection()

        def mkrow(beta, gamma):
            return txn.execSQL("insert into ALPHA values (:1, :2)",
                               [beta, gamma])

        yield gatherResults(
            [mkrow(123, u"one"), mkrow(234, u"two"), mkrow(345, u"three")]
        )
        tr = yield TestRecord.load(txn, 234)
        yield tr.delete()
        rows = yield txn.execSQL("select BETA, GAMMA from ALPHA order by BETA")
        self.assertEqual(rows, [(123, u"one"), (345, u"three")])


    @inlineCallbacks
    def oneRowCommitted(self, beta=123, gamma=u'456'):
        """
        Create, commit, and return one L{TestRecord}.
        """
        txn = self.pool.connection(self.id())
        row = yield TestRecord.create(txn, beta=beta, gamma=gamma)
        yield txn.commit()
        returnValue(row)


    @inlineCallbacks
    def test_deleteWhenDeleted(self):
        """
        When a record object is deleted, if it's already been deleted, it will
        raise L{NoSuchRecord}.
        """
        row = yield self.oneRowCommitted()
        txn = self.pool.connection(self.id())
        newRow = yield TestRecord.load(txn, row.beta)
        yield newRow.delete()
        yield self.assertFailure(newRow.delete(), NoSuchRecord)


    @inlineCallbacks
    def test_cantCreateWithoutRequiredValues(self):
        """
        When a L{Record} object is created without required values, it raises a
        L{TypeError}.
        """
        txn = self.pool.connection()
        te = yield self.assertFailure(TestAutoRecord.create(txn), TypeError)
        self.assertIn("required attribute 'epsilon' not passed", str(te))


    @inlineCallbacks
    def test_datetimeType(self):
        """
        When a L{Record} references a timestamp column, it retrieves the date
        as UTC.
        """
        txn = self.pool.connection()
        # Create ...
        rec = yield TestAutoRecord.create(txn, epsilon=1)
        self.assertEquals(
            rec.zeta,
            datetime.datetime(2012, 12, 12, 12, 12, 12)
        )
        yield txn.commit()
        # ... should have the same effect as loading.

        txn = self.pool.connection()
        rec = (yield TestAutoRecord.all(txn))[0]
        self.assertEquals(
            rec.zeta,
            datetime.datetime(2012, 12, 12, 12, 12, 12)
        )


    @inlineCallbacks
    def test_tooManyAttributes(self):
        """
        When a L{Record} object is created with unknown attributes (those which
        don't map to any column), it raises a L{TypeError}.
        """
        txn = self.pool.connection()
        te = yield self.assertFailure(
            TestRecord.create(
                txn, beta=3, gamma=u'three',
                extraBonusAttribute=u'nope',
                otherBonusAttribute=4321,
            ),
            TypeError
        )
        self.assertIn("extraBonusAttribute, otherBonusAttribute", str(te))


    @inlineCallbacks
    def test_createFillsInPKey(self):
        """
        If L{Record.create} is called without an auto-generated primary key
        value for its row, that value will be generated and set on the returned
        object.
        """
        txn = self.pool.connection()
        tr = yield TestAutoRecord.create(txn, epsilon=u'specified')
        tr2 = yield TestAutoRecord.create(txn, epsilon=u'also specified')
        self.assertEquals(tr.phi, 1)
        self.assertEquals(tr2.phi, 2)


    @inlineCallbacks
    def test_attributesArentMutableYet(self):
        """
        Changing attributes on a database object is not supported yet, because
        it's not entirely clear when to flush the SQL to the database.
        Instead, for the time being, use C{.update}.  When you attempt to set
        an attribute, an error will be raised informing you of this fact, so
        that the error is clear.
        """
        txn = self.pool.connection()
        rec = yield TestRecord.create(txn, beta=7, gamma=u'what')

        def setit():
            rec.beta = 12

        ro = self.assertRaises(ReadOnly, setit)
        self.assertEqual(rec.beta, 7)
        self.assertIn("SQL-backed attribute 'TestRecord.beta' is read-only. "
                      "Use '.update(...)' to modify attributes.", str(ro))


    @inlineCallbacks
    def test_simpleUpdate(self):
        """
        L{Record.update} will change the values on the record and in te
        database.
        """
        txn = self.pool.connection()
        rec = yield TestRecord.create(txn, beta=3, gamma=u'epsilon')
        yield rec.update(gamma=u'otherwise')
        self.assertEqual(rec.gamma, u'otherwise')
        yield txn.commit()
        # Make sure that it persists.
        txn = self.pool.connection()
        rec = yield TestRecord.load(txn, 3)
        self.assertEqual(rec.gamma, u'otherwise')


    @inlineCallbacks
    def test_simpleQuery(self):
        """
        L{Record.query} will allow you to query for a record by its class
        attributes as columns.
        """
        txn = self.pool.connection()
        for beta, gamma in [(123, u"one"), (234, u"two"), (345, u"three"),
                            (356, u"three"), (456, u"four")]:
            yield txn.execSQL("insert into ALPHA values (:1, :2)",
                              [beta, gamma])
        records = yield TestRecord.query(txn, TestRecord.gamma == u"three")
        self.assertEqual(len(records), 2)
        records.sort(key=lambda x: x.beta)
        self.assertEqual(records[0].beta, 345)
        self.assertEqual(records[1].beta, 356)


    @inlineCallbacks
    def test_querySimple(self):
        """
        L{Record.querysimple} will allow you to query for a record by its class
        attributes as columns.
        """
        txn = self.pool.connection()
        for beta, gamma in [(123, u"one"), (234, u"two"), (345, u"three"),
                            (356, u"three"), (456, u"four")]:
            yield txn.execSQL("insert into ALPHA values (:1, :2)",
                              [beta, gamma])
        records = yield TestRecord.querysimple(txn, gamma=u"three")
        self.assertEqual(len(records), 2)
        records.sort(key=lambda x: x.beta)
        self.assertEqual(records[0].beta, 345)
        self.assertEqual(records[1].beta, 356)


    @inlineCallbacks
    def test_eq(self):
        """
        L{Record.__eq__} works.
        """
        txn = self.pool.connection()
        data = [(123, u"one"), (456, u"four"), (345, u"three"),
                (234, u"two"), (356, u"three")]
        for beta, gamma in data:
            yield txn.execSQL("insert into ALPHA values (:1, :2)",
                              [beta, gamma])

        one = yield TestRecord.load(txn, 123)
        one_copy = yield TestRecord.load(txn, 123)
        two = yield TestRecord.load(txn, 234)

        self.assertTrue(one == one_copy)
        self.assertFalse(one == two)


    @inlineCallbacks
    def test_all(self):
        """
        L{Record.all} will return all instances of the record, sorted by
        primary key.
        """
        txn = self.pool.connection()
        data = [(123, u"one"), (456, u"four"), (345, u"three"),
                (234, u"two"), (356, u"three")]
        for beta, gamma in data:
            yield txn.execSQL("insert into ALPHA values (:1, :2)",
                              [beta, gamma])
        self.assertEqual(
            [(x.beta, x.gamma) for x in (yield TestRecord.all(txn))],
            sorted(data)
        )


    @inlineCallbacks
    def test_updatesome(self):
        """
        L{Record.updatesome} will update all instances of the matching records.
        """
        txn = self.pool.connection()
        data = [(123, u"one"), (456, u"four"), (345, u"three"),
                (234, u"two"), (356, u"three")]
        for beta, gamma in data:
            yield txn.execSQL("insert into ALPHA values (:1, :2)",
                              [beta, gamma])

        yield TestRecord.updatesome(txn, where=(TestRecord.beta == 123), gamma=u"changed")
        yield txn.commit()

        txn = self.pool.connection()
        records = yield TestRecord.all(txn)
        self.assertEqual(
            set([(record.beta, record.gamma,) for record in records]),
            set([
                (123, u"changed"), (456, u"four"), (345, u"three"),
                (234, u"two"), (356, u"three")
            ])
        )

        yield TestRecord.updatesome(txn, where=(TestRecord.beta.In((234, 345,))), gamma=u"changed-2")
        yield txn.commit()

        txn = self.pool.connection()
        records = yield TestRecord.all(txn)
        self.assertEqual(
            set([(record.beta, record.gamma,) for record in records]),
            set([
                (123, u"changed"), (456, u"four"), (345, u"changed-2"),
                (234, u"changed-2"), (356, u"three")
            ])
        )


    @inlineCallbacks
    def test_deleteall(self):
        """
        L{Record.deleteall} will delete all instances of the record.
        """
        txn = self.pool.connection()
        data = [(123, u"one"), (456, u"four"), (345, u"three"),
                (234, u"two"), (356, u"three")]
        for beta, gamma in data:
            yield txn.execSQL("insert into ALPHA values (:1, :2)",
                              [beta, gamma])

        yield TestRecord.deleteall(txn)
        all = yield TestRecord.all(txn)
        self.assertEqual(len(all), 0)


    @inlineCallbacks
    def test_deletesome(self):
        """
        L{Record.deletesome} will delete all instances of the matching records.
        """
        txn = self.pool.connection()
        data = [(123, u"one"), (456, u"four"), (345, u"three"),
                (234, u"two"), (356, u"three")]
        for beta, gamma in data:
            yield txn.execSQL("insert into ALPHA values (:1, :2)",
                              [beta, gamma])

        yield TestRecord.deletesome(txn, TestRecord.gamma == u"three")
        all = yield TestRecord.all(txn)
        self.assertEqual(set([record.beta for record in all]), set((123, 456, 234,)))

        yield TestRecord.deletesome(txn, (TestRecord.gamma == u"one").Or(TestRecord.gamma == u"two"))
        all = yield TestRecord.all(txn)
        self.assertEqual(set([record.beta for record in all]), set((456,)))


    @inlineCallbacks
    def test_deletesimple(self):
        """
        L{Record.deletesimple} will delete all instances of the matching records.
        """
        txn = self.pool.connection()
        data = [(123, u"one"), (456, u"four"), (345, u"three"),
                (234, u"two"), (356, u"three")]
        for beta, gamma in data:
            yield txn.execSQL("insert into ALPHA values (:1, :2)",
                              [beta, gamma])

        yield TestRecord.deletesimple(txn, gamma=u"three")
        all = yield TestRecord.all(txn)
        self.assertEqual(set([record.beta for record in all]), set((123, 456, 234,)))

        yield TestRecord.deletesimple(txn, beta=123, gamma=u"one")
        all = yield TestRecord.all(txn)
        self.assertEqual(set([record.beta for record in all]), set((456, 234)))


    @inlineCallbacks
    def test_repr(self):
        """
        The C{repr} of a L{Record} presents all its values.
        """
        txn = self.pool.connection()
        yield txn.execSQL("insert into ALPHA values (:1, :2)", [789, u'nine'])
        rec = list((yield TestRecord.all(txn)))[0]
        self.assertIn(" beta=789", repr(rec))
        self.assertIn(" gamma=u'nine'", repr(rec))


    @inlineCallbacks
    def test_orderedQuery(self):
        """
        L{Record.query} takes an 'order' argument which will allow the objects
        returned to be ordered.
        """
        txn = self.pool.connection()
        for beta, gamma in [(123, u"one"), (234, u"two"), (345, u"three"),
                            (356, u"three"), (456, u"four")]:
            yield txn.execSQL("insert into ALPHA values (:1, :2)",
                              [beta, gamma])

        records = yield TestRecord.query(
            txn, TestRecord.gamma == u"three", TestRecord.beta
        )
        self.assertEqual([record.beta for record in records], [345, 356])

        records = yield TestRecord.query(
            txn, TestRecord.gamma == u"three", TestRecord.beta, ascending=False
        )
        self.assertEqual([record.beta for record in records], [356, 345])


    @inlineCallbacks
    def test_pop(self):
        """
        A L{Record} may be loaded and deleted atomically, with L{Record.pop}.
        """
        txn = self.pool.connection()
        for beta, gamma in [
            (123, u"one"),
            (234, u"two"),
            (345, u"three"),
            (356, u"three"),
            (456, u"four"),
        ]:
            yield txn.execSQL(
                "insert into ALPHA values (:1, :2)", [beta, gamma]
            )

        rec = yield TestRecord.pop(txn, 234)
        self.assertEqual(rec.gamma, u'two')
        self.assertEqual(
            (yield txn.execSQL(
                "select count(*) from ALPHA where BETA = :1", [234]
            )),
            [tuple([0])]
        )
        yield self.assertFailure(TestRecord.pop(txn, 234), NoSuchRecord)


    def test_columnNamingConvention(self):
        """
        The naming convention maps columns C{LIKE_THIS} to be attributes
        C{likeThis}.
        """
        self.assertEqual(
            Record.namingConvention(u"like_this"),
            "likeThis"
        )
        self.assertEqual(
            Record.namingConvention(u"LIKE_THIS"),
            "likeThis"
        )
        self.assertEqual(
            Record.namingConvention(u"LIKE_THIS_ID"),
            "likeThisID"
        )


    @inlineCallbacks
    def test_lock(self):
        """
        A L{Record} may be locked, with L{Record.lock}.
        """
        txn = self.pool.connection()
        for beta, gamma in [
            (123, u"one"),
            (234, u"two"),
            (345, u"three"),
            (356, u"three"),
            (456, u"four"),
        ]:
            yield txn.execSQL(
                "insert into ALPHA values (:1, :2)", [beta, gamma]
            )

        rec = yield TestRecord.load(txn, 234)
        yield rec.lock()
        self.assertEqual(rec.gamma, u'two')


    @inlineCallbacks
    def test_trylock(self):
        """
        A L{Record} may be locked, with L{Record.trylock}.
        """
        txn = self.pool.connection()
        for beta, gamma in [
            (123, u"one"),
            (234, u"two"),
            (345, u"three"),
            (356, u"three"),
            (456, u"four"),
        ]:
            yield txn.execSQL(
                "insert into ALPHA values (:1, :2)", [beta, gamma]
            )

        rec = yield TestRecord.load(txn, 234)
        result = yield rec.trylock()
        self.assertTrue(result)


    @inlineCallbacks
    def test_serialize(self):
        """
        A L{SerializableRecord} may be serialized.
        """
        txn = self.pool.connection()
        for beta, gamma in [
            (123, u"one"),
            (234, u"two"),
            (345, u"three"),
            (356, u"three"),
            (456, u"four"),
        ]:
            yield txn.execSQL(
                "insert into ALPHA values (:1, :2)", [beta, gamma]
            )

        rec = yield TestSerializeRecord.load(txn, 234)
        result = rec.serialize()
        self.assertEqual(result, {"beta": 234, "gamma": u"two"})


    @inlineCallbacks
    def test_deserialize(self):
        """
        A L{SerializableRecord} may be deserialized.
        """
        txn = self.pool.connection()

        rec = yield TestSerializeRecord.deserialize({"beta": 234, "gamma": u"two"})
        yield rec.insert(txn)
        yield txn.commit()

        txn = self.pool.connection()
        rec = yield TestSerializeRecord.query(txn, TestSerializeRecord.beta == 234)
        self.assertEqual(len(rec), 1)
        self.assertEqual(rec[0].gamma, u"two")
        yield txn.commit()

        # Check that attributes can be changed prior to insert, and not after
        txn = self.pool.connection()
        rec = yield TestSerializeRecord.deserialize({"beta": 456, "gamma": u"one"})
        rec.gamma = u"four"
        yield rec.insert(txn)
        def _raise():
            rec.gamma = u"five"
        self.assertRaises(ReadOnly, _raise)
        yield txn.commit()

        txn = self.pool.connection()
        rec = yield TestSerializeRecord.query(txn, TestSerializeRecord.beta == 456)
        self.assertEqual(len(rec), 1)
        self.assertEqual(rec[0].gamma, u"four")
        yield txn.commit()