-
Notifications
You must be signed in to change notification settings - Fork 28
/
test_suite.py
1548 lines (1296 loc) · 50.9 KB
/
test_suite.py
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# Copyright 2021 Google LLC
#
# 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
#
# https://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.
from datetime import timezone
import decimal
import operator
import os
import pkg_resources
import pytest
from unittest import mock
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import inspect
from sqlalchemy import testing
from sqlalchemy import ForeignKey
from sqlalchemy import MetaData
from sqlalchemy.schema import DDL
from sqlalchemy.testing import config
from sqlalchemy.testing import engines
from sqlalchemy.testing import eq_
from sqlalchemy.testing import provide_metadata, emits_warning
from sqlalchemy.testing import fixtures
from sqlalchemy.testing.provision import temp_table_keyword_args
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import Table
from sqlalchemy import literal_column
from sqlalchemy import select
from sqlalchemy import util
from sqlalchemy import event
from sqlalchemy import exists
from sqlalchemy import Boolean
from sqlalchemy import Float
from sqlalchemy import LargeBinary
from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relation
from sqlalchemy.orm import Session
from sqlalchemy.types import Integer
from sqlalchemy.types import Numeric
from sqlalchemy.types import Text
from sqlalchemy.testing import requires
from google.api_core.datetime_helpers import DatetimeWithNanoseconds
from google.cloud import spanner_dbapi
from sqlalchemy.testing.suite.test_cte import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_ddl import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_dialect import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_insert import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_reflection import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_results import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_select import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_sequence import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_update_delete import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_cte import CTETest as _CTETest
from sqlalchemy.testing.suite.test_ddl import TableDDLTest as _TableDDLTest
from sqlalchemy.testing.suite.test_ddl import (
LongNameBlowoutTest as _LongNameBlowoutTest,
)
from sqlalchemy.testing.suite.test_dialect import EscapingTest as _EscapingTest
from sqlalchemy.testing.suite.test_insert import (
InsertBehaviorTest as _InsertBehaviorTest,
)
from sqlalchemy.testing.suite.test_select import ( # noqa: F401, F403
CompoundSelectTest as _CompoundSelectTest,
ExistsTest as _ExistsTest,
IsOrIsNotDistinctFromTest as _IsOrIsNotDistinctFromTest,
LikeFunctionsTest as _LikeFunctionsTest,
OrderByLabelTest as _OrderByLabelTest,
)
from sqlalchemy.testing.suite.test_reflection import (
QuotedNameArgumentTest as _QuotedNameArgumentTest,
ComponentReflectionTest as _ComponentReflectionTest,
CompositeKeyReflectionTest as _CompositeKeyReflectionTest,
)
from sqlalchemy.testing.suite.test_results import RowFetchTest as _RowFetchTest
from sqlalchemy.testing.suite.test_types import ( # noqa: F401, F403
BooleanTest as _BooleanTest,
DateTest as _DateTest,
_DateFixture as _DateFixtureTest,
DateTimeHistoricTest,
DateTimeCoercedToDateTimeTest as _DateTimeCoercedToDateTimeTest,
DateTimeMicrosecondsTest as _DateTimeMicrosecondsTest,
DateTimeTest as _DateTimeTest,
IntegerTest as _IntegerTest,
_LiteralRoundTripFixture,
NumericTest as _NumericTest,
StringTest as _StringTest,
TextTest as _TextTest,
TimeTest as _TimeTest,
TimeMicrosecondsTest as _TimeMicrosecondsTest,
TimestampMicrosecondsTest,
UnicodeVarcharTest as _UnicodeVarcharTest,
UnicodeTextTest as _UnicodeTextTest,
_UnicodeFixture as _UnicodeFixtureTest,
)
config.test_schema = ""
class EscapingTest(_EscapingTest):
@provide_metadata
def test_percent_sign_round_trip(self):
"""Test that the DBAPI accommodates for escaped / nonescaped
percent signs in a way that matches the compiler
SPANNER OVERRIDE
Cloud Spanner supports tables with empty primary key, but
only single one row can be inserted into such a table -
following insertions will fail with `Row [] already exists".
Overriding the test to avoid the same failure.
"""
m = self.metadata
t = Table("t", m, Column("data", String(50)))
t.create(config.db)
with config.db.begin() as conn:
conn.execute(t.insert(), dict(data="some % value"))
eq_(
conn.scalar(
select([t.c.data]).where(
t.c.data == literal_column("'some % value'")
)
),
"some % value",
)
conn.execute(t.delete())
conn.execute(t.insert(), dict(data="some %% other value"))
eq_(
conn.scalar(
select([t.c.data]).where(
t.c.data == literal_column("'some %% other value'")
)
),
"some %% other value",
)
class CTETest(_CTETest):
@classmethod
def define_tables(cls, metadata):
"""
The original method creates a foreign key without a name,
which causes troubles on test cleanup. Overriding the
method to explicitly set a foreign key name.
"""
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String(50)),
Column("parent_id", ForeignKey("some_table.id", name="fk_some_table")),
)
Table(
"some_other_table",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String(50)),
Column("parent_id", Integer),
)
@pytest.mark.skip("INSERT from WITH subquery is not supported")
def test_insert_from_select_round_trip(self):
"""
The test checks if an INSERT can be done from a cte, like:
WITH some_cte AS (...)
INSERT INTO some_other_table (... SELECT * FROM some_cte)
Such queries are not supported by Spanner.
"""
pass
@pytest.mark.skip("DELETE from WITH subquery is not supported")
def test_delete_scalar_subq_round_trip(self):
"""
The test checks if a DELETE can be done from a cte, like:
WITH some_cte AS (...)
DELETE FROM some_other_table (... SELECT * FROM some_cte)
Such queries are not supported by Spanner.
"""
pass
@pytest.mark.skip("DELETE from WITH subquery is not supported")
def test_delete_from_round_trip(self):
"""
The test checks if a DELETE can be done from a cte, like:
WITH some_cte AS (...)
DELETE FROM some_other_table (... SELECT * FROM some_cte)
Such queries are not supported by Spanner.
"""
pass
@pytest.mark.skip("UPDATE from WITH subquery is not supported")
def test_update_from_round_trip(self):
"""
The test checks if an UPDATE can be done from a cte, like:
WITH some_cte AS (...)
UPDATE some_other_table
SET (... SELECT * FROM some_cte)
Such queries are not supported by Spanner.
"""
pass
@pytest.mark.skip("WITH RECURSIVE subqueries are not supported")
def test_select_recursive_round_trip(self):
pass
class BooleanTest(_BooleanTest):
def test_render_literal_bool(self):
"""
SPANNER OVERRIDE:
Cloud Spanner supports tables with an empty primary key, but
only a single row can be inserted into such a table -
following insertions will fail with `Row [] already exists".
Overriding the test to avoid the same failure.
"""
self._literal_round_trip(Boolean(), [True], [True])
self._literal_round_trip(Boolean(), [False], [False])
class ExistsTest(_ExistsTest):
def test_select_exists(self, connection):
"""
SPANNER OVERRIDE:
The original test is trying to execute a query like:
SELECT ...
WHERE EXISTS (SELECT ...)
SELECT WHERE without FROM clause is not supported by Spanner.
Rewriting the test to force it to generate a query like:
SELECT EXISTS (SELECT ...)
"""
stuff = self.tables.stuff
eq_(
connection.execute(
select((exists().where(stuff.c.data == "some data"),))
).fetchall(),
[(True,)],
)
def test_select_exists_false(self, connection):
"""
SPANNER OVERRIDE:
The original test is trying to execute a query like:
SELECT ...
WHERE EXISTS (SELECT ...)
SELECT WHERE without FROM clause is not supported by Spanner.
Rewriting the test to force it to generate a query like:
SELECT EXISTS (SELECT ...)
"""
stuff = self.tables.stuff
eq_(
connection.execute(
select((exists().where(stuff.c.data == "no data"),))
).fetchall(),
[(False,)],
)
class TableDDLTest(_TableDDLTest):
@pytest.mark.skip(
"Spanner table name must start with an uppercase or lowercase letter"
)
def test_underscore_names(self):
pass
@pytest.mark.skip("Max identifier length in Spanner is 128")
class LongNameBlowoutTest(_LongNameBlowoutTest):
pass
class DateFixtureTest(_DateFixtureTest):
@classmethod
def define_tables(cls, metadata):
"""
SPANNER OVERRIDE:
Cloud Spanner doesn't support auto incrementing ids feature,
which is used by the original test. Overriding the test data
creation method to disable autoincrement and make id column
nullable.
"""
Table(
"date_table",
metadata,
Column("id", Integer, primary_key=True, nullable=True),
Column("date_data", cls.datatype),
)
class DateTest(DateFixtureTest, _DateTest):
"""
SPANNER OVERRIDE:
DateTest tests used same class method to create table, so to avoid those failures
and maintain DRY concept just inherit the class to run tests successfully.
"""
@pytest.mark.skipif(
bool(os.environ.get("SPANNER_EMULATOR_HOST")), reason="Skipped on emulator"
)
def test_null_bound_comparison(self):
super().test_null_bound_comparison()
@pytest.mark.skipif(
bool(os.environ.get("SPANNER_EMULATOR_HOST")), reason="Skipped on emulator"
)
def test_null(self):
super().test_null()
class DateTimeMicrosecondsTest(_DateTimeMicrosecondsTest, DateTest):
def test_round_trip(self):
"""
SPANNER OVERRIDE:
Spanner converts timestamp into `%Y-%m-%dT%H:%M:%S.%fZ` format, so to avoid
assert failures convert datetime input to the desire timestamp format.
"""
date_table = self.tables.date_table
config.db.execute(date_table.insert(), {"date_data": self.data})
row = config.db.execute(select([date_table.c.date_data])).first()
compare = self.compare or self.data
compare = compare.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
eq_(row[0].rfc3339(), compare)
assert isinstance(row[0], DatetimeWithNanoseconds)
@pytest.mark.skipif(
bool(os.environ.get("SPANNER_EMULATOR_HOST")), reason="Skipped on emulator"
)
def test_null_bound_comparison(self):
super().test_null_bound_comparison()
@pytest.mark.skipif(
bool(os.environ.get("SPANNER_EMULATOR_HOST")), reason="Skipped on emulator"
)
def test_null(self):
super().test_null()
class DateTimeTest(_DateTimeTest, DateTimeMicrosecondsTest):
"""
SPANNER OVERRIDE:
DateTimeTest tests have the same failures same as DateTimeMicrosecondsTest tests,
so to avoid those failures and maintain DRY concept just inherit the class to run
tests successfully.
"""
@pytest.mark.skipif(
bool(os.environ.get("SPANNER_EMULATOR_HOST")), reason="Skipped on emulator"
)
def test_null_bound_comparison(self):
super().test_null_bound_comparison()
@pytest.mark.skipif(
bool(os.environ.get("SPANNER_EMULATOR_HOST")), reason="Skipped on emulator"
)
def test_null(self):
super().test_null()
@pytest.mark.skip("Spanner doesn't support Time data type.")
class TimeTests(_TimeMicrosecondsTest, _TimeTest):
pass
@pytest.mark.skip("Spanner doesn't coerce dates from datetime.")
class DateTimeCoercedToDateTimeTest(_DateTimeCoercedToDateTimeTest):
pass
class IntegerTest(_IntegerTest):
@provide_metadata
def _round_trip(self, datatype, data):
"""
SPANNER OVERRIDE:
This is the helper method for integer class tests which creates a table and
performs an insert operation.
Cloud Spanner supports tables with an empty primary key, but only one
row can be inserted into such a table - following insertions will fail with
`400 id must not be NULL in table date_table`.
Overriding the tests and adding a manual primary key value to avoid the same
failures.
"""
metadata = self.metadata
int_table = Table(
"integer_table",
metadata,
Column("id", Integer, primary_key=True, test_needs_autoincrement=True),
Column("integer_data", datatype),
)
metadata.create_all(config.db)
config.db.execute(int_table.insert(), {"id": 1, "integer_data": data})
row = config.db.execute(select([int_table.c.integer_data])).first()
eq_(row, (data,))
if util.py3k:
assert isinstance(row[0], int)
else:
assert isinstance(row[0], (long, int)) # noqa
class UnicodeFixtureTest(_UnicodeFixtureTest):
@classmethod
def define_tables(cls, metadata):
"""
SPANNER OVERRIDE:
Cloud Spanner doesn't support auto incrementing ids feature,
which is used by the original test. Overriding the test data
creation method to disable autoincrement and make id column
nullable.
"""
Table(
"unicode_table",
metadata,
Column("id", Integer, primary_key=True, nullable=True),
Column("unicode_data", cls.datatype),
)
def test_round_trip_executemany(self):
"""
SPANNER OVERRIDE
Cloud Spanner supports tables with empty primary key, but
only single one row can be inserted into such a table -
following insertions will fail with `Row [] already exists".
Overriding the test to avoid the same failure.
"""
unicode_table = self.tables.unicode_table
config.db.execute(
unicode_table.insert(),
[{"id": i, "unicode_data": self.data} for i in range(3)],
)
rows = config.db.execute(select([unicode_table.c.unicode_data])).fetchall()
eq_(rows, [(self.data,) for i in range(3)])
for row in rows:
assert isinstance(row[0], util.text_type)
@pytest.mark.skip("Spanner doesn't support non-ascii characters")
def test_literal(self):
pass
@pytest.mark.skip("Spanner doesn't support non-ascii characters")
def test_literal_non_ascii(self):
pass
class UnicodeVarcharTest(UnicodeFixtureTest, _UnicodeVarcharTest):
"""
SPANNER OVERRIDE:
UnicodeVarcharTest class inherits the _UnicodeFixtureTest class's tests,
so to avoid those failures and maintain DRY concept just inherit the class to run
tests successfully.
"""
pass
class UnicodeTextTest(UnicodeFixtureTest, _UnicodeTextTest):
"""
SPANNER OVERRIDE:
UnicodeTextTest class inherits the _UnicodeFixtureTest class's tests,
so to avoid those failures and maintain DRY concept just inherit the class to run
tests successfully.
"""
pass
class ComponentReflectionTest(_ComponentReflectionTest):
@classmethod
def define_reflected_tables(cls, metadata, schema):
if schema:
schema_prefix = schema + "."
else:
schema_prefix = ""
if testing.requires.self_referential_foreign_keys.enabled:
users = Table(
"users",
metadata,
Column("user_id", sqlalchemy.INT, primary_key=True),
Column("test1", sqlalchemy.CHAR(5), nullable=False),
Column("test2", sqlalchemy.Float(5), nullable=False),
Column(
"parent_user_id",
sqlalchemy.Integer,
sqlalchemy.ForeignKey(
"%susers.user_id" % schema_prefix, name="user_id_fk"
),
),
schema=schema,
test_needs_fk=True,
)
else:
users = Table(
"users",
metadata,
Column("user_id", sqlalchemy.INT, primary_key=True),
Column("test1", sqlalchemy.CHAR(5), nullable=False),
Column("test2", sqlalchemy.Float(5), nullable=False),
schema=schema,
test_needs_fk=True,
)
Table(
"dingalings",
metadata,
Column("dingaling_id", sqlalchemy.Integer, primary_key=True),
Column(
"address_id",
sqlalchemy.Integer,
sqlalchemy.ForeignKey("%semail_addresses.address_id" % schema_prefix),
),
Column("data", sqlalchemy.String(30)),
schema=schema,
test_needs_fk=True,
)
Table(
"email_addresses",
metadata,
Column("address_id", sqlalchemy.Integer, primary_key=True),
Column(
"remote_user_id",
sqlalchemy.Integer,
sqlalchemy.ForeignKey(users.c.user_id),
),
Column("email_address", sqlalchemy.String(20)),
sqlalchemy.PrimaryKeyConstraint("address_id", name="email_ad_pk"),
schema=schema,
test_needs_fk=True,
)
Table(
"comment_test",
metadata,
Column("id", sqlalchemy.Integer, primary_key=True, comment="id comment"),
Column("data", sqlalchemy.String(20), comment="data % comment"),
Column(
"d2",
sqlalchemy.String(20),
comment=r"""Comment types type speedily ' " \ '' Fun!""",
),
schema=schema,
comment=r"""the test % ' " \ table comment""",
)
if testing.requires.cross_schema_fk_reflection.enabled:
if schema is None:
Table(
"local_table",
metadata,
Column("id", sqlalchemy.Integer, primary_key=True),
Column("data", sqlalchemy.String(20)),
Column(
"remote_id",
ForeignKey("%s.remote_table_2.id" % testing.config.test_schema),
),
test_needs_fk=True,
schema=config.db.dialect.default_schema_name,
)
else:
Table(
"remote_table",
metadata,
Column("id", sqlalchemy.Integer, primary_key=True),
Column(
"local_id",
ForeignKey(
"%s.local_table.id" % config.db.dialect.default_schema_name
),
),
Column("data", sqlalchemy.String(20)),
schema=schema,
test_needs_fk=True,
)
Table(
"remote_table_2",
metadata,
Column("id", sqlalchemy.Integer, primary_key=True),
Column("data", sqlalchemy.String(20)),
schema=schema,
test_needs_fk=True,
)
if testing.requires.index_reflection.enabled:
cls.define_index(metadata, users)
if not schema:
# test_needs_fk is at the moment to force MySQL InnoDB
noncol_idx_test_nopk = Table(
"noncol_idx_test_nopk",
metadata,
Column("id", sqlalchemy.Integer, primary_key=True),
Column("q", sqlalchemy.String(5)),
test_needs_fk=True,
)
noncol_idx_test_pk = Table(
"noncol_idx_test_pk",
metadata,
Column("id", sqlalchemy.Integer, primary_key=True),
Column("q", sqlalchemy.String(5)),
test_needs_fk=True,
)
if testing.requires.indexes_with_ascdesc.enabled:
sqlalchemy.Index("noncol_idx_nopk", noncol_idx_test_nopk.c.q.desc())
sqlalchemy.Index("noncol_idx_pk", noncol_idx_test_pk.c.q.desc())
if testing.requires.view_column_reflection.enabled:
cls.define_views(metadata, schema)
if not schema and testing.requires.temp_table_reflection.enabled:
cls.define_temp_tables(metadata)
@classmethod
def define_temp_tables(cls, metadata):
"""
SPANNER OVERRIDE:
In Cloud Spanner unique indexes are used instead of directly
creating unique constraints. Overriding the test to replace
constraints with indexes in testing data.
"""
kw = temp_table_keyword_args(config, config.db)
user_tmp = Table(
"user_tmp",
metadata,
Column("id", sqlalchemy.INT, primary_key=True),
Column("name", sqlalchemy.VARCHAR(50)),
Column("foo", sqlalchemy.INT),
sqlalchemy.Index("user_tmp_uq", "name", unique=True),
sqlalchemy.Index("user_tmp_ix", "foo"),
**kw
)
if (
testing.requires.view_reflection.enabled
and testing.requires.temporary_views.enabled
):
event.listen(
user_tmp,
"after_create",
DDL("create temporary view user_tmp_v as " "select * from user_tmp"),
)
event.listen(user_tmp, "before_drop", DDL("drop view user_tmp_v"))
@testing.provide_metadata
def test_reflect_string_column_max_len(self):
"""
SPANNER SPECIFIC TEST:
In Spanner column of the STRING type can be
created with size defined as MAX. The test
checks that such a column is correctly reflected.
"""
Table("text_table", self.metadata, Column("TestColumn", Text, nullable=False))
self.metadata.create_all()
Table("text_table", MetaData(bind=self.bind), autoload=True)
@testing.provide_metadata
def test_reflect_bytes_column_max_len(self):
"""
SPANNER SPECIFIC TEST:
In Spanner column of the BYTES type can be
created with size defined as MAX. The test
checks that such a column is correctly reflected.
"""
Table(
"bytes_table",
self.metadata,
Column("TestColumn", LargeBinary, nullable=False),
)
self.metadata.create_all()
Table("bytes_table", MetaData(bind=self.bind), autoload=True)
@testing.provide_metadata
def _test_get_unique_constraints(self, schema=None):
"""
SPANNER OVERRIDE:
In Cloud Spanner unique indexes are used instead of directly
creating unique constraints. Overriding the test to replace
constraints with indexes in testing data.
"""
# SQLite dialect needs to parse the names of the constraints
# separately from what it gets from PRAGMA index_list(), and
# then matches them up. so same set of column_names in two
# constraints will confuse it. Perhaps we should no longer
# bother with index_list() here since we have the whole
# CREATE TABLE?
uniques = sorted(
[
{"name": "unique_a", "column_names": ["a"]},
{"name": "unique_a_b_c", "column_names": ["a", "b", "c"]},
{"name": "unique_c_a_b", "column_names": ["c", "a", "b"]},
{"name": "unique_asc_key", "column_names": ["asc", "key"]},
{"name": "i.have.dots", "column_names": ["b"]},
{"name": "i have spaces", "column_names": ["c"]},
],
key=operator.itemgetter("name"),
)
orig_meta = self.metadata
Table(
"testtbl",
orig_meta,
Column("id", sqlalchemy.Integer, primary_key=True),
Column("a", sqlalchemy.String(20)),
Column("b", sqlalchemy.String(30)),
Column("c", sqlalchemy.Integer),
# reserved identifiers
Column("asc", sqlalchemy.String(30)),
Column("key", sqlalchemy.String(30)),
sqlalchemy.Index("unique_a", "a", unique=True),
sqlalchemy.Index("unique_a_b_c", "a", "b", "c", unique=True),
sqlalchemy.Index("unique_c_a_b", "c", "a", "b", unique=True),
sqlalchemy.Index("unique_asc_key", "asc", "key", unique=True),
schema=schema,
)
orig_meta.create_all()
inspector = inspect(orig_meta.bind)
reflected = sorted(
inspector.get_unique_constraints("testtbl", schema=schema),
key=operator.itemgetter("name"),
)
names_that_duplicate_index = set()
for orig, refl in zip(uniques, reflected):
# Different dialects handle duplicate index and constraints
# differently, so ignore this flag
dupe = refl.pop("duplicates_index", None)
if dupe:
names_that_duplicate_index.add(dupe)
eq_(orig, refl)
reflected_metadata = MetaData()
reflected = Table(
"testtbl", reflected_metadata, autoload_with=orig_meta.bind, schema=schema,
)
# test "deduplicates for index" logic. MySQL and Oracle
# "unique constraints" are actually unique indexes (with possible
# exception of a unique that is a dupe of another one in the case
# of Oracle). make sure # they aren't duplicated.
idx_names = set([idx.name for idx in reflected.indexes])
uq_names = set(
[
uq.name
for uq in reflected.constraints
if isinstance(uq, sqlalchemy.UniqueConstraint)
]
).difference(["unique_c_a_b"])
assert not idx_names.intersection(uq_names)
if names_that_duplicate_index:
eq_(names_that_duplicate_index, idx_names)
eq_(uq_names, set())
@testing.provide_metadata
def test_unique_constraint_raises(self):
"""
Checking that unique constraint creation
fails due to a ProgrammingError.
"""
Table(
"user_tmp_failure",
self.metadata,
Column("id", sqlalchemy.INT, primary_key=True),
Column("name", sqlalchemy.VARCHAR(50)),
sqlalchemy.UniqueConstraint("name", name="user_tmp_uq"),
)
with pytest.raises(spanner_dbapi.exceptions.ProgrammingError):
self.metadata.create_all()
@testing.provide_metadata
def _test_get_table_names(self, schema=None, table_type="table", order_by=None):
"""
SPANNER OVERRIDE:
Spanner doesn't support temporary tables, so real tables are
used for testing. As the original test expects only real
tables to be read, and in Spanner all the tables are real,
expected results override is required.
"""
_ignore_tables = [
"comment_test",
"noncol_idx_test_pk",
"noncol_idx_test_nopk",
"local_table",
"remote_table",
"remote_table_2",
]
meta = self.metadata
insp = inspect(meta.bind)
if table_type == "view":
table_names = insp.get_view_names(schema)
table_names.sort()
answer = ["email_addresses_v", "users_v"]
eq_(sorted(table_names), answer)
else:
if order_by:
tables = [
rec[0]
for rec in insp.get_sorted_table_and_fkc_names(schema)
if rec[0]
]
else:
tables = insp.get_table_names(schema)
table_names = [t for t in tables if t not in _ignore_tables]
if order_by == "foreign_key":
answer = {"dingalings", "email_addresses", "user_tmp", "users"}
eq_(set(table_names), answer)
else:
answer = ["dingalings", "email_addresses", "user_tmp", "users"]
eq_(sorted(table_names), answer)
@pytest.mark.skip("Spanner doesn't support temporary tables")
def test_get_temp_table_indexes(self):
pass
@pytest.mark.skip("Spanner doesn't support temporary tables")
def test_get_temp_table_unique_constraints(self):
pass
@testing.requires.table_reflection
def test_numeric_reflection(self):
"""
SPANNER OVERRIDE:
Spanner defines NUMERIC type with the constant precision=38
and scale=9. Overriding the test to check if the NUMERIC
column is successfully created and has dimensions
correct for Cloud Spanner.
"""
for typ in self._type_round_trip(Numeric(18, 5)):
assert isinstance(typ, Numeric)
eq_(typ.precision, 38)
eq_(typ.scale, 9)
@testing.requires.table_reflection
def test_binary_reflection(self):
"""
Check that a BYTES column with an explicitly
set size is correctly reflected.
"""
for typ in self._type_round_trip(LargeBinary(20)):
assert isinstance(typ, LargeBinary)
eq_(typ.length, 20)
class CompositeKeyReflectionTest(_CompositeKeyReflectionTest):
@testing.requires.foreign_key_constraint_reflection
@testing.provide_metadata
def test_fk_column_order(self):
"""
SPANNER OVERRIDE:
Spanner column usage reflection doesn't support determenistic
ordering. Overriding the test to check that columns are
reflected correctly, without considering their order.
"""
# test for issue #5661
meta = self.metadata
insp = inspect(meta.bind)
foreign_keys = insp.get_foreign_keys(self.tables.tb2.name)
eq_(len(foreign_keys), 1)
fkey1 = foreign_keys[0]
eq_(set(fkey1.get("referred_columns")), {"name", "id", "attr"})
eq_(set(fkey1.get("constrained_columns")), {"pname", "pid", "pattr"})
class RowFetchTest(_RowFetchTest):
def test_row_w_scalar_select(self):
"""
SPANNER OVERRIDE:
Cloud Spanner returns a DatetimeWithNanoseconds() for date
data types. Overriding the test to use a DatetimeWithNanoseconds
type value as an expected result.
--------------
test that a scalar select as a column is returned as such
and that type conversion works OK.
(this is half a SQLAlchemy Core test and half to catch database
backends that may have unusual behavior with scalar selects.)
"""
datetable = self.tables.has_dates
s = select([datetable.alias("x").c.today]).as_scalar()
s2 = select([datetable.c.id, s.label("somelabel")])
row = config.db.execute(s2).first()
eq_(
row["somelabel"],
DatetimeWithNanoseconds(2006, 5, 12, 12, 0, 0, tzinfo=timezone.utc),
)
class InsertBehaviorTest(_InsertBehaviorTest):
@pytest.mark.skip("Spanner doesn't support empty inserts")
def test_empty_insert(self):
pass
@pytest.mark.skip("Spanner doesn't support auto increment")
def test_insert_from_select_autoinc(self):
pass
@pytest.mark.skip("Spanner doesn't support default column values")
def test_insert_from_select_with_defaults(self):
pass
def test_autoclose_on_insert(self):
"""
SPANNER OVERRIDE:
Cloud Spanner doesn't support tables with an auto increment primary key,
following insertions will fail with `400 id must not be NULL in table
autoinc_pk`.
Overriding the tests and adding a manual primary key value to avoid the same
failures.
"""
if config.requirements.returning.enabled:
engine = engines.testing_engine(options={"implicit_returning": False})
else:
engine = config.db
with engine.begin() as conn:
r = conn.execute(
self.tables.autoinc_pk.insert(), dict(id=1, data="some data")
)
assert r._soft_closed
assert not r.closed
assert r.is_insert
assert not r.returns_rows
class BytesTest(_LiteralRoundTripFixture, fixtures.TestBase):
__backend__ = True
def test_nolength_binary(self):
metadata = MetaData()
foo = Table("foo", metadata, Column("one", LargeBinary))
foo.create(config.db)