File: test_dynamodb_exceptions.py

package info (click to toggle)
python-moto 5.1.18-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,520 kB
  • sloc: python: 636,725; javascript: 181; makefile: 39; sh: 3
file content (2066 lines) | stat: -rw-r--r-- 78,035 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
from decimal import Decimal
from unittest import SkipTest
from uuid import uuid4

import boto3
import botocore
import pytest
from boto3.dynamodb.conditions import Key
from botocore.exceptions import ClientError

from moto import mock_aws, settings
from tests import allow_aws_request
from tests.test_dynamodb import dynamodb_aws_verified

table_schema = {
    "KeySchema": [{"AttributeName": "partitionKey", "KeyType": "HASH"}],
    "GlobalSecondaryIndexes": [
        {
            "IndexName": "GSI-K1",
            "KeySchema": [
                {"AttributeName": "gsiK1PartitionKey", "KeyType": "HASH"},
                {"AttributeName": "gsiK1SortKey", "KeyType": "RANGE"},
            ],
            "Projection": {"ProjectionType": "KEYS_ONLY"},
        }
    ],
    "AttributeDefinitions": [
        {"AttributeName": "partitionKey", "AttributeType": "S"},
        {"AttributeName": "gsiK1PartitionKey", "AttributeType": "S"},
        {"AttributeName": "gsiK1SortKey", "AttributeType": "S"},
    ],
}


class BaseTest:
    @classmethod
    def setup_class(cls, add_range=False):
        if not allow_aws_request():
            cls.mock = mock_aws()
            cls.mock.start()
        cls.client = boto3.client("dynamodb", region_name="us-east-1")
        cls.table_name = "T" + str(uuid4())
        cls.has_range_key = add_range

        dynamodb = boto3.resource("dynamodb", region_name="us-east-1")

        # Create the DynamoDB table.
        schema = [{"AttributeName": "pk", "KeyType": "HASH"}]
        defs = [{"AttributeName": "pk", "AttributeType": "S"}]
        if add_range:
            schema.append({"AttributeName": "rk", "KeyType": "RANGE"})
            defs.append({"AttributeName": "rk", "AttributeType": "S"})
        dynamodb.create_table(
            TableName=cls.table_name,
            KeySchema=schema,
            AttributeDefinitions=defs,
            ProvisionedThroughput={"ReadCapacityUnits": 5, "WriteCapacityUnits": 5},
        )
        waiter = cls.client.get_waiter("table_exists")
        waiter.wait(TableName=cls.table_name)
        cls.table = dynamodb.Table(cls.table_name)

    @classmethod
    def empty_table(self):
        # Empty table between runs
        items = self.table.scan()["Items"]
        for item in items:
            if self.has_range_key:
                self.table.delete_item(Key={"pk": item["pk"], "rk": item["rk"]})
            else:
                self.table.delete_item(Key={"pk": item["pk"]})

    @classmethod
    def teardown_class(cls):
        cls.client.delete_table(TableName=cls.table_name)
        if not allow_aws_request():
            cls.mock.stop()


@mock_aws
def test_query_gsi_with_wrong_key_attribute_names_throws_exception():
    item = {
        "partitionKey": "pk-1",
        "gsiK1PartitionKey": "gsi-pk",
        "gsiK1SortKey": "gsi-sk",
        "someAttribute": "lore ipsum",
    }

    dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
    table = dynamodb.create_table(
        TableName=f"T{uuid4()}", BillingMode="PAY_PER_REQUEST", **table_schema
    )
    table.put_item(Item=item)

    # check using wrong name for sort key throws exception
    with pytest.raises(ClientError) as exc:
        table.query(
            KeyConditionExpression="gsiK1PartitionKey = :pk AND wrongName = :sk",
            ExpressionAttributeValues={":pk": "gsi-pk", ":sk": "gsi-sk"},
            IndexName="GSI-K1",
        )["Items"]
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert err["Message"] == "Query condition missed key schema element: gsiK1SortKey"

    # check using wrong name for partition key throws exception
    with pytest.raises(ClientError) as exc:
        table.query(
            KeyConditionExpression="wrongName = :pk AND gsiK1SortKey = :sk",
            ExpressionAttributeValues={":pk": "gsi-pk", ":sk": "gsi-sk"},
            IndexName="GSI-K1",
        )["Items"]
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"] == "Query condition missed key schema element: gsiK1PartitionKey"
    )

    # verify same behaviour for begins_with
    with pytest.raises(ClientError) as exc:
        table.query(
            KeyConditionExpression="gsiK1PartitionKey = :pk AND begins_with ( wrongName , :sk )",
            ExpressionAttributeValues={":pk": "gsi-pk", ":sk": "gsi-sk"},
            IndexName="GSI-K1",
        )["Items"]
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert err["Message"] == "Query condition missed key schema element: gsiK1SortKey"

    # verify same behaviour for between
    with pytest.raises(ClientError) as exc:
        table.query(
            KeyConditionExpression="gsiK1PartitionKey = :pk AND wrongName BETWEEN :sk1 and :sk2",
            ExpressionAttributeValues={
                ":pk": "gsi-pk",
                ":sk1": "gsi-sk",
                ":sk2": "gsi-sk2",
            },
            IndexName="GSI-K1",
        )["Items"]
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert err["Message"] == "Query condition missed key schema element: gsiK1SortKey"


@pytest.mark.aws_verified
@dynamodb_aws_verified(add_range=True, add_gsi=True)
def test_query_table_with_wrong_attrs_used_in_key_condition_expression(table_name=None):
    dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
    table = dynamodb.Table(table_name)

    # check using wrong name for sort key throws exception
    with pytest.raises(ClientError) as exc:
        table.query(
            KeyConditionExpression="wrongName = :pk",
            ExpressionAttributeValues={":pk": "pk"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert err["Message"] == "Query condition missed key schema element: pk"

    # Using PK of Index when querying Table is wrong
    with pytest.raises(ClientError) as exc:
        table.query(
            KeyConditionExpression="gsi_pk = :pk",
            ExpressionAttributeValues={":pk": "pk"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert err["Message"] == "Query condition missed key schema element: pk"

    # Using PK of Table when querying Index is actually correct
    with pytest.raises(ClientError) as exc:
        table.query(
            IndexName="test_gsi",
            KeyConditionExpression="pk = :pk",
            ExpressionAttributeValues={":pk": "pk"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert err["Message"] == "Query condition missed key schema element: gsi_pk"

    # Using both PK and SK is acceptable
    items = table.query(
        KeyConditionExpression="pk = :pk AND sk = :sk",
        ExpressionAttributeValues={":pk": "pk", ":sk": "sk"},
    )["Items"]
    assert items == []

    # Using PK and SK on the Index is wrong
    with pytest.raises(ClientError) as exc:
        table.query(
            IndexName="test_gsi",
            KeyConditionExpression="pk = :pk AND sk = :sk",
            ExpressionAttributeValues={":pk": "pk", ":sk": "sk"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"

    # Using GSI PK and SK on the Index is wrong
    with pytest.raises(ClientError) as exc:
        table.query(
            IndexName="test_gsi",
            KeyConditionExpression="gsi_pk = :pk AND sk = :sk",
            ExpressionAttributeValues={":pk": "pk", ":sk": "sk"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert err["Message"] == "Query key condition not supported"

    # Using GSI PK and SK on the Table is wrong
    with pytest.raises(ClientError) as exc:
        table.query(
            KeyConditionExpression="gsi_pk = :pk AND sk = :sk",
            ExpressionAttributeValues={":pk": "pk", ":sk": "sk"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert err["Message"] == "Query condition missed key schema element: pk"


@pytest.mark.aws_verified
@dynamodb_aws_verified()
def test_empty_expressionattributenames(table_name=None):
    ddb = boto3.resource("dynamodb", region_name="us-east-1")
    table = ddb.Table(table_name)
    with pytest.raises(ClientError) as exc:
        # Note: provided key is wrong. Expression doesn't exist either.
        # Whether we can supply ExpressionAttributeName in the first place, that's what we're validating here
        table.get_item(Key={"id": "my_id"}, ExpressionAttributeNames={"#a": "b"})
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "ExpressionAttributeNames can only be specified when using expressions"
    )


@mock_aws
def test_empty_expressionattributenames_with_empty_projection():
    ddb = boto3.resource("dynamodb", region_name="us-east-1")
    table = ddb.create_table(
        TableName=f"T{uuid4()}", BillingMode="PAY_PER_REQUEST", **table_schema
    )
    with pytest.raises(ClientError) as exc:
        table.get_item(
            Key={"id": "my_id"}, ProjectionExpression="a", ExpressionAttributeNames={}
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert err["Message"] == "ExpressionAttributeNames must not be empty"


@mock_aws
def test_empty_expressionattributenames_with_projection():
    ddb = boto3.resource("dynamodb", region_name="us-east-1")
    table = ddb.create_table(
        TableName=f"T{uuid4()}", BillingMode="PAY_PER_REQUEST", **table_schema
    )
    with pytest.raises(ClientError) as exc:
        table.get_item(
            Key={"id": "my_id"}, ProjectionExpression="id", ExpressionAttributeNames={}
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert err["Message"] == "ExpressionAttributeNames must not be empty"


@pytest.mark.aws_verified
class TestUpdateExpressionClausesWithClashingExpressions(BaseTest):
    def test_multiple_add_clauses(self):
        with pytest.raises(ClientError) as exc:
            self.table.update_item(
                Key={"pk": "the-key"},
                UpdateExpression="ADD x :one SET a = :a ADD y :one",
                ExpressionAttributeValues={":one": 1, ":a": "lore ipsum"},
            )
        err = exc.value.response["Error"]
        assert err["Code"] == "ValidationException"
        assert (
            err["Message"]
            == 'Invalid UpdateExpression: The "ADD" section can only be used once in an update expression;'
        )

    def test_multiple_remove_clauses(self):
        with pytest.raises(ClientError) as exc:
            self.table.update_item(
                Key={"pk": "the-key"},
                UpdateExpression="REMOVE #ulist[0] SET current_user = :current_user REMOVE some_param",
                ExpressionAttributeNames={"#ulist": "user_list"},
                ExpressionAttributeValues={":current_user": {"name": "Jane"}},
            )
        err = exc.value.response["Error"]
        assert err["Code"] == "ValidationException"
        assert (
            err["Message"]
            == 'Invalid UpdateExpression: The "REMOVE" section can only be used once in an update expression;'
        )

    def test_multiple_set_clauses(self):
        with pytest.raises(ClientError) as exc:
            self.table.update_item(
                Key={"pk": "the-key"},
                UpdateExpression="SET current_user = :current_user SET some_param = :current_user",
                ExpressionAttributeValues={":current_user": {"name": "Jane"}},
            )
        err = exc.value.response["Error"]
        assert err["Code"] == "ValidationException"
        assert (
            err["Message"]
            == 'Invalid UpdateExpression: The "SET" section can only be used once in an update expression;'
        )

    def test_delete_and_add_on_same_set(self):
        with pytest.raises(ClientError) as exc:
            self.table.update_item(
                Key={"pk": "foo"},
                UpdateExpression="ADD #stringSet :addSet DELETE #stringSet :deleteSet",
                ExpressionAttributeNames={"#stringSet": "string_set"},
                ExpressionAttributeValues={":addSet": {"c"}, ":deleteSet": {"a"}},
            )
        assert exc.value.response["Error"]["Code"] == "ValidationException"
        assert exc.value.response["Error"]["Message"].startswith(
            "Invalid UpdateExpression: Two document paths overlap with each other;"
        )

    def test_remove_and_add_on_same_set(self):
        with pytest.raises(ClientError) as exc:
            self.table.update_item(
                Key={"pk": "foo"},
                UpdateExpression="ADD #stringSet :addSet REMOVE #stringSet",
                ExpressionAttributeNames={"#stringSet": "string_set.nested"},
                ExpressionAttributeValues={":addSet": {"c"}},
            )
        assert exc.value.response["Error"]["Code"] == "ValidationException"
        assert exc.value.response["Error"]["Message"].startswith(
            "Invalid UpdateExpression: Two document paths overlap with each other;"
        )

    def test_set_and_remove_on_overlapping_paths(self):
        with pytest.raises(ClientError) as exc:
            self.table.update_item(
                Key={"pk": "foo"},
                UpdateExpression="REMOVE string_set SET string_set.nested = :h",
                ExpressionAttributeValues={":h": "H"},
            )
        assert exc.value.response["Error"]["Code"] == "ValidationException"
        assert exc.value.response["Error"]["Message"].startswith(
            "Invalid UpdateExpression: Two document paths overlap with each other;"
        )

    def test_set_path_overlap(self):
        with pytest.raises(ClientError) as exc:
            self.table.update_item(
                Key={"pk": "foo"},
                UpdateExpression="SET string_set = :h, string_set.nested = :h",
                ExpressionAttributeValues={":h": "H"},
            )
        assert exc.value.response["Error"]["Code"] == "ValidationException"
        assert exc.value.response["Error"]["Message"].startswith(
            "Invalid UpdateExpression: Two document paths overlap with each other;"
        )

    def test_path_overlap_error_uses_expression_attribute_name(self):
        with pytest.raises(ClientError) as exc:
            self.table.update_item(
                Key={"pk": "foo"},
                UpdateExpression="SET #stringSet = :h, #stringSet = :h",
                ExpressionAttributeNames={"#stringSet": "string_set"},
                ExpressionAttributeValues={":h": "H"},
            )
        assert exc.value.response["Error"]["Code"] == "ValidationException"
        assert (
            exc.value.response["Error"]["Message"]
            == "Invalid UpdateExpression: Two document paths overlap with each other; must remove or rewrite one of these paths; path one: [string_set], path two: [string_set]"
        )

    def test_path_overlap_error_splits_paths(self):
        with pytest.raises(ClientError) as exc:
            self.table.update_item(
                Key={"pk": "foo"},
                UpdateExpression="SET string_set.nested = :h, string_set.nested = :h",
                ExpressionAttributeValues={":h": "H"},
            )
        assert exc.value.response["Error"]["Code"] == "ValidationException"
        assert (
            exc.value.response["Error"]["Message"]
            == "Invalid UpdateExpression: Two document paths overlap with each other; must remove or rewrite one of these paths; path one: [string_set, nested], path two: [string_set, nested]"
        )

    # pretty weird AWS behavior with the next two tests, seems like a bug
    def test_no_overlapping_paths_error_if_one_of_the_overlapping_paths_is_an_expression_attribute_name(
        self,
    ):
        self.table.update_item(
            Key={"pk": "foo"},
            UpdateExpression="SET string_set = :h, #nested = :h",
            ExpressionAttributeNames={"#nested": "string_set.nested"},
            ExpressionAttributeValues={":h": "H"},
        )

    def test_overlapping_paths_error_if_identical_paths_are_expression_attribute_names(
        self,
    ):
        with pytest.raises(ClientError) as exc:
            self.table.update_item(
                Key={"pk": "foo"},
                UpdateExpression="SET #stringSet = :h, #nested = :h",
                ExpressionAttributeNames={
                    "#stringSet": "string_set",
                    "#nested": "string_set",
                },
                ExpressionAttributeValues={":h": "H"},
            )
        assert exc.value.response["Error"]["Code"] == "ValidationException"
        assert exc.value.response["Error"]["Message"].startswith(
            "Invalid UpdateExpression: Two document paths overlap with each other;"
        )

    def test_update_item_with_shared_root_but_different_overall(self):
        # Can update an item where the first part of the expressions is duplicate but not the rest
        nested = {"key1": "value1", "key2": "value2", "key3": "value3"}
        item = {"pk": "1", "name": "test", "nested": nested}
        self.table.put_item(Item=item)
        self.table.update_item(
            Key={"pk": "1"},
            UpdateExpression="SET #root.#child1=:key1,#root.#child2=:key2",
            ExpressionAttributeNames={
                "#root": "nested",
                "#child1": "key1",
                "#child2": "key2",
            },
            ExpressionAttributeValues={":key1": "new value1", ":key2": "new value2"},
        )
        item = self.table.get_item(Key={"pk": "1"})["Item"]
        assert item["nested"] == {
            "key1": "new value1",
            "key2": "new value2",
            "key3": "value3",
        }

    def test_delete_and_add_on_different_set(self):
        self.table.update_item(
            Key={"pk": "the-key"},
            UpdateExpression="ADD #stringSet1 :addSet DELETE #stringSet2 :deleteSet",
            ExpressionAttributeNames={"#stringSet1": "ss1", "#stringSet2": "ss2"},
            ExpressionAttributeValues={":addSet": {"c"}, ":deleteSet": {"a"}},
        )


@pytest.mark.aws_verified
@dynamodb_aws_verified()
def test_update_item_unused_attributes(table_name=None):
    ddb = boto3.resource("dynamodb", region_name="us-east-1")

    # Create the DynamoDB table.
    table = ddb.Table(table_name)
    table.put_item(Item={"pk": "pk1", "spec": {}, "am": 0, "test": "text"})

    # Unused Name (count), in addition to Used Name (limit)
    with pytest.raises(ClientError) as exc:
        table.update_item(
            Key={"pk": "pk1"},
            UpdateExpression="SET spec.#limit = :limit",
            ExpressionAttributeNames={"#count": "count", "#limit": "limit"},
            ExpressionAttributeValues={":countChange": 1, ":limit": "limit"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "Value provided in ExpressionAttributeNames unused in expressions: keys: {#count}"
    )

    # Unused Name (count) only
    with pytest.raises(ClientError) as exc:
        table.update_item(
            Key={"pk": "pk1"},
            UpdateExpression="ADD am :limit",
            ExpressionAttributeNames={"#count": "count"},
            ExpressionAttributeValues={":limit": 2},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "Value provided in ExpressionAttributeNames unused in expressions: keys: {#count}"
    )

    # Unused Value (countChange)
    with pytest.raises(ClientError) as exc:
        table.update_item(
            Key={"pk": "pk1"},
            UpdateExpression="SET spec.#limit = :limit",
            ExpressionAttributeNames={"#limit": "limit"},
            ExpressionAttributeValues={":countChange": 1, ":limit": "limit"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "Value provided in ExpressionAttributeValues unused in expressions: keys: {:countChange}"
    )

    # Used value in ConditionExpression
    table.update_item(
        Key={"pk": "pk1"},
        UpdateExpression="SET spec.#limit = :limit",
        ConditionExpression="begins_with(test, :t)",
        ExpressionAttributeNames={"#limit": "limit"},
        ExpressionAttributeValues={":t": "t", ":limit": "limit"},
    )
    item = table.get_item(Key={"pk": "pk1"})["Item"]
    assert item == {
        "spec": {"limit": "limit"},
        "pk": "pk1",
        "am": Decimal("0"),
        "test": "text",
    }

    # Used ExpressionAttributeValue, but with invalid value
    with pytest.raises(ClientError) as exc:
        table.update_item(
            Key={"pk": "pk1"},
            UpdateExpression="SET x = :one",
            ExpressionAttributeValues={":one": set()},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "ExpressionAttributeValues contains invalid value: One or more parameter values were invalid: An number set  may not be empty for key :one"
    )


@pytest.mark.aws_verified
@dynamodb_aws_verified()
def test_put_item_unused_attributes(table_name=None):
    ddb = boto3.resource("dynamodb", region_name="us-east-1")

    table = ddb.Table(table_name)

    with pytest.raises(ClientError) as exc:
        table.put_item(
            Item={"pk": "pk1", "spec": {}, "am": 0},
            ConditionExpression="attribute_not_exists(body)",
            ExpressionAttributeNames={"#count": "count"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "Value provided in ExpressionAttributeNames unused in expressions: keys: {#count}"
    )


@pytest.mark.aws_verified
@dynamodb_aws_verified()
def test_get_item_unused_attribute_name(table_name=None):
    ddb = boto3.resource("dynamodb", region_name="us-east-1")

    table = ddb.Table(table_name)

    with pytest.raises(ClientError) as exc:
        table.get_item(
            Key={"pk": "example_id"},
            ProjectionExpression="pk",
            ExpressionAttributeNames={"#count": "count"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "Value provided in ExpressionAttributeNames unused in expressions: keys: {#count}"
    )


@pytest.mark.aws_verified
@dynamodb_aws_verified()
def test_query_unused_attribute_name(table_name=None):
    ddb = boto3.resource("dynamodb", region_name="us-east-1")

    table = ddb.Table(table_name)

    with pytest.raises(ClientError) as exc:
        table.query(
            KeyConditionExpression="(#0 = x)",
            ExpressionAttributeNames={"#0": "pk", "#count": "count"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    # Moto will always complain about the fact that #count is unused
    # AWS will usually complain about that
    # Sometimes (1 in 10 times, maybe?) it will complain about multiple attribute names are used in one condition
    # Which is interesting, as there is obviously some async error handling going on. Whichever error is found first, 'wins'
    assert err["Message"] in [
        "Value provided in ExpressionAttributeNames unused in expressions: keys: {#count}",
        "Invalid KeyConditionExpression: Invalid condition in KeyConditionExpression: Multiple attribute names used in one condition",
    ]


@pytest.mark.aws_verified
@dynamodb_aws_verified()
def test_scan_unused_attribute_name(table_name=None):
    ddb = boto3.resource("dynamodb", region_name="us-east-1")

    table = ddb.Table(table_name)

    with pytest.raises(ClientError) as exc:
        table.scan(
            TableName=table_name,
            FilterExpression="#h = :h",
            ExpressionAttributeNames={"#h": "pk", "#count": "count"},
            ExpressionAttributeValues={":h": {"S": "hash_value"}},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "Value provided in ExpressionAttributeNames unused in expressions: keys: {#count}"
    )


@pytest.mark.aws_verified
@dynamodb_aws_verified()
def test_delete_unused_attribute_name(table_name=None):
    ddb = boto3.resource("dynamodb", region_name="us-east-1")

    table = ddb.Table(table_name)

    with pytest.raises(ClientError) as exc:
        table.delete_item(
            Key={"pk": "pk1"},
            ConditionExpression="attribute_not_exists(body)",
            ExpressionAttributeNames={"#count": "count"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "Value provided in ExpressionAttributeNames unused in expressions: keys: {#count}"
    )


@pytest.mark.aws_verified
@dynamodb_aws_verified()
def test_batch_get_item_unused_attribute_name(table_name=None):
    ddb = boto3.resource("dynamodb", region_name="us-east-1")

    with pytest.raises(ClientError) as exc:
        ddb.batch_get_item(
            RequestItems={
                "users": {
                    "Keys": [
                        {"username": {"S": "user0"}},
                        {"username": {"S": "user1"}},
                        {"username": {"S": "user2"}},
                        {"username": {"S": "user3"}},
                    ],
                    "ConsistentRead": True,
                    "ProjectionExpression": "#rl",
                    "ExpressionAttributeNames": {"#rl": "username", "#count": "count"},
                }
            }
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "Value provided in ExpressionAttributeNames unused in expressions: keys: {#count}"
    )


@pytest.mark.aws_verified
@dynamodb_aws_verified()
def test_transact_write_item_put_unused_attribute_name(table_name=None):
    ddb = boto3.client("dynamodb", region_name="us-east-1")

    with pytest.raises(ClientError) as exc:
        ddb.transact_write_items(
            TransactItems=[
                {
                    "Put": {
                        "Item": {
                            "pk": {"S": "foo"},
                            "foo": {"S": "bar"},
                        },
                        "TableName": table_name,
                        "ConditionExpression": "#i <> foo",
                        "ExpressionAttributeNames": {"#i": "pk", "#count": "count"},
                    },
                }
            ]
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "Value provided in ExpressionAttributeNames unused in expressions: keys: {#count}"
    )


@pytest.mark.aws_verified
@dynamodb_aws_verified()
def test_transact_write_item_update_unused_attribute_name(table_name=None):
    ddb = boto3.client("dynamodb", region_name="us-east-1")

    with pytest.raises(ClientError) as exc:
        ddb.transact_write_items(
            TransactItems=[
                {
                    "Update": {
                        "Key": {"id": {"S": "foo"}},
                        "TableName": table_name,
                        "UpdateExpression": "SET #e = test",
                        "ExpressionAttributeNames": {
                            "#e": "email_address",
                            "#count": "count",
                        },
                    }
                }
            ]
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "Value provided in ExpressionAttributeNames unused in expressions: keys: {#count}"
    )


@pytest.mark.aws_verified
@dynamodb_aws_verified()
def test_transact_write_item_delete_unused_attribute_name(table_name=None):
    ddb = boto3.client("dynamodb", region_name="us-east-1")

    with pytest.raises(ClientError) as exc:
        ddb.transact_write_items(
            TransactItems=[
                {
                    "Delete": {
                        "Key": {
                            "pk": {"S": "foo"},
                            "foo": {"S": "bar"},
                        },
                        "TableName": table_name,
                        "ConditionExpression": "#i <> foo",
                        "ExpressionAttributeNames": {"#i": "pk", "#count": "count"},
                    },
                }
            ]
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "Value provided in ExpressionAttributeNames unused in expressions: keys: {#count}"
    )


@pytest.mark.aws_verified
@dynamodb_aws_verified()
def test_transact_write_item_unused_attribute_name_in_condition_check(table_name=None):
    ddb = boto3.client("dynamodb", region_name="us-east-1")

    with pytest.raises(ClientError) as exc:
        ddb.transact_write_items(
            TransactItems=[
                {
                    "ConditionCheck": {
                        "Key": {"id": {"S": "foo"}},
                        "TableName": table_name,
                        "ConditionExpression": "attribute_exists(#e)",
                        "ExpressionAttributeNames": {
                            "#e": "email_address",
                            "#count": "count",
                        },
                    }
                },
                {
                    "Put": {
                        "Item": {
                            "id": {"S": "bar"},
                            "email_address": {"S": "bar@moto.com"},
                        },
                        "TableName": table_name,
                    }
                },
            ]
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "Value provided in ExpressionAttributeNames unused in expressions: keys: {#count}"
    )


@mock_aws
def test_batch_get_item_non_existing_table():
    client = boto3.client("dynamodb", region_name="us-west-2")

    with pytest.raises(client.exceptions.ResourceNotFoundException) as exc:
        client.batch_get_item(RequestItems={"my-table": {"Keys": [{"id": {"N": "0"}}]}})
    err = exc.value.response["Error"]
    assert err["Code"] == "ResourceNotFoundException"
    assert err["Message"] == "Requested resource not found"


@mock_aws
def test_batch_write_item_non_existing_table():
    client = boto3.client("dynamodb", region_name="us-west-2")

    with pytest.raises(client.exceptions.ResourceNotFoundException) as exc:
        # Table my-table does not exist
        client.batch_write_item(
            RequestItems={"my-table": [{"PutRequest": {"Item": {}}}]}
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ResourceNotFoundException"
    assert err["Message"] == "Requested resource not found"


@mock_aws
def test_create_table_with_redundant_attributes():
    dynamodb = boto3.client("dynamodb", region_name="us-east-1")

    with pytest.raises(ClientError) as exc:
        dynamodb.create_table(
            TableName=f"T{uuid4()}",
            AttributeDefinitions=[
                {"AttributeName": "id", "AttributeType": "S"},
                {"AttributeName": "created_at", "AttributeType": "N"},
            ],
            KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
            BillingMode="PAY_PER_REQUEST",
        )

    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "One or more parameter values were invalid: Number of attributes in KeySchema does not exactly match number of attributes defined in AttributeDefinitions"
    )

    with pytest.raises(ClientError) as exc:
        dynamodb.create_table(
            TableName=f"T{uuid4()}",
            AttributeDefinitions=[
                {"AttributeName": "id", "AttributeType": "S"},
                {"AttributeName": "user", "AttributeType": "S"},
                {"AttributeName": "created_at", "AttributeType": "N"},
            ],
            KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
            GlobalSecondaryIndexes=[
                {
                    "IndexName": "gsi_user-items",
                    "KeySchema": [{"AttributeName": "user", "KeyType": "HASH"}],
                    "Projection": {"ProjectionType": "ALL"},
                }
            ],
            BillingMode="PAY_PER_REQUEST",
        )

    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "One or more parameter values were invalid: Some AttributeDefinitions are not used. AttributeDefinitions: [created_at, id, user], keys used: [id, user]"
    )


@mock_aws
def test_create_table_with_missing_attributes():
    dynamodb = boto3.client("dynamodb", region_name="us-east-1")

    with pytest.raises(ClientError) as exc:
        dynamodb.create_table(
            TableName=f"T{uuid4()}",
            AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
            KeySchema=[
                {"AttributeName": "id", "KeyType": "HASH"},
                {"AttributeName": "created_at", "KeyType": "RANGE"},
            ],
            BillingMode="PAY_PER_REQUEST",
        )

    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "Invalid KeySchema: Some index key attribute have no definition"
    )

    with pytest.raises(ClientError) as exc:
        dynamodb.create_table(
            TableName=f"T{uuid4()}",
            AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
            KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
            GlobalSecondaryIndexes=[
                {
                    "IndexName": "gsi_user-items",
                    "KeySchema": [{"AttributeName": "user", "KeyType": "HASH"}],
                    "Projection": {"ProjectionType": "ALL"},
                }
            ],
            BillingMode="PAY_PER_REQUEST",
        )

    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "One or more parameter values were invalid: Some index key attributes are not defined in AttributeDefinitions. Keys: [user], AttributeDefinitions: [id]"
    )


@mock_aws
def test_create_table_with_redundant_and_missing_attributes():
    dynamodb = boto3.client("dynamodb", region_name="us-east-1")

    with pytest.raises(ClientError) as exc:
        dynamodb.create_table(
            TableName=f"T{uuid4()}",
            AttributeDefinitions=[
                {"AttributeName": "created_at", "AttributeType": "N"}
            ],
            KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
            BillingMode="PAY_PER_REQUEST",
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "One or more parameter values were invalid: Some index key attributes are not defined in AttributeDefinitions. Keys: [id], AttributeDefinitions: [created_at]"
    )

    with pytest.raises(ClientError) as exc:
        dynamodb.create_table(
            TableName=f"T{uuid4()}",
            AttributeDefinitions=[
                {"AttributeName": "id", "AttributeType": "S"},
                {"AttributeName": "created_at", "AttributeType": "N"},
            ],
            KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
            GlobalSecondaryIndexes=[
                {
                    "IndexName": "gsi_user-items",
                    "KeySchema": [{"AttributeName": "user", "KeyType": "HASH"}],
                    "Projection": {"ProjectionType": "ALL"},
                }
            ],
            BillingMode="PAY_PER_REQUEST",
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "One or more parameter values were invalid: Some index key attributes are not defined in AttributeDefinitions. Keys: [user], AttributeDefinitions: [created_at, id]"
    )


@mock_aws
def test_put_item_wrong_attribute_type():
    dynamodb = boto3.client("dynamodb", region_name="us-east-1")
    table_name = f"T{uuid4()}"

    dynamodb.create_table(
        TableName=table_name,
        AttributeDefinitions=[
            {"AttributeName": "id", "AttributeType": "S"},
            {"AttributeName": "created_at", "AttributeType": "N"},
        ],
        KeySchema=[
            {"AttributeName": "id", "KeyType": "HASH"},
            {"AttributeName": "created_at", "KeyType": "RANGE"},
        ],
        BillingMode="PAY_PER_REQUEST",
    )

    item = {
        "id": {"N": "1"},  # should be a string
        "created_at": {"N": "2"},
        "someAttribute": {"S": "lore ipsum"},
    }

    with pytest.raises(ClientError) as exc:
        dynamodb.put_item(TableName=table_name, Item=item)
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "One or more parameter values were invalid: Type mismatch for key id expected: S actual: N"
    )

    item = {
        "id": {"S": "some id"},
        "created_at": {"S": "should be date not string"},
        "someAttribute": {"S": "lore ipsum"},
    }

    with pytest.raises(ClientError) as exc:
        dynamodb.put_item(TableName=table_name, Item=item)
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "One or more parameter values were invalid: Type mismatch for key created_at expected: N actual: S"
    )


@mock_aws
# https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html#DDB-Query-request-KeyConditionExpression
def test_hash_key_cannot_use_begins_with_operations():
    dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
    table = dynamodb.create_table(
        TableName=f"T{uuid4()}",
        KeySchema=[{"AttributeName": "key", "KeyType": "HASH"}],
        AttributeDefinitions=[{"AttributeName": "key", "AttributeType": "S"}],
        ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1},
    )

    items = [
        {"key": "prefix-$LATEST", "value": "$LATEST"},
        {"key": "prefix-DEV", "value": "DEV"},
        {"key": "prefix-PROD", "value": "PROD"},
    ]

    with table.batch_writer() as batch:
        for item in items:
            batch.put_item(Item=item)

    with pytest.raises(ClientError) as ex:
        table.query(KeyConditionExpression=Key("key").begins_with("prefix-"))
    assert ex.value.response["Error"]["Code"] == "ValidationException"
    assert ex.value.response["Error"]["Message"] == "Query key condition not supported"


# Test this again, but with manually supplying an operator
@mock_aws
@pytest.mark.parametrize("operator", ["<", "<=", ">", ">="])
def test_hash_key_can_only_use_equals_operations(operator):
    dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
    table = dynamodb.create_table(
        TableName=f"T{uuid4()}",
        KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
        AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
        ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1},
    )

    with pytest.raises(ClientError) as exc:
        table.query(
            KeyConditionExpression=f"pk {operator} :pk",
            ExpressionAttributeValues={":pk": "p"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert err["Message"] == "Query key condition not supported"


@mock_aws
def test_creating_table_with_0_local_indexes():
    dynamodb = boto3.resource("dynamodb", region_name="us-east-1")

    with pytest.raises(ClientError) as exc:
        dynamodb.create_table(
            TableName=f"T{uuid4()}",
            KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
            AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
            ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1},
            LocalSecondaryIndexes=[],
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "One or more parameter values were invalid: List of LocalSecondaryIndexes is empty"
    )


@mock_aws
def test_creating_table_with_0_global_indexes():
    dynamodb = boto3.resource("dynamodb", region_name="us-east-1")

    with pytest.raises(ClientError) as exc:
        dynamodb.create_table(
            TableName=f"T{uuid4()}",
            KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
            AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
            ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1},
            GlobalSecondaryIndexes=[],
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "One or more parameter values were invalid: List of GlobalSecondaryIndexes is empty"
    )


@mock_aws
def test_multiple_transactions_on_same_item():
    table_name = f"T{uuid4()}"
    schema = {
        "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}],
        "AttributeDefinitions": [{"AttributeName": "id", "AttributeType": "S"}],
    }
    dynamodb = boto3.client("dynamodb", region_name="us-east-1")
    dynamodb.create_table(TableName=table_name, BillingMode="PAY_PER_REQUEST", **schema)
    # Insert an item
    dynamodb.put_item(TableName=table_name, Item={"id": {"S": "foo"}})

    def update_email_transact(email):
        return {
            "Update": {
                "Key": {"id": {"S": "foo"}},
                "TableName": table_name,
                "UpdateExpression": "SET #e = :v",
                "ExpressionAttributeNames": {"#e": "email_address"},
                "ExpressionAttributeValues": {":v": {"S": email}},
            }
        }

    with pytest.raises(ClientError) as exc:
        dynamodb.transact_write_items(
            TransactItems=[
                update_email_transact("test1@moto.com"),
                update_email_transact("test2@moto.com"),
            ]
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "Transaction request cannot include multiple operations on one item"
    )


@mock_aws
def test_transact_write_items__too_many_transactions():
    table_name = f"T{uuid4()}"
    schema = {
        "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
        "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
    }
    dynamodb = boto3.client("dynamodb", region_name="us-east-1")
    dynamodb.create_table(TableName=table_name, BillingMode="PAY_PER_REQUEST", **schema)

    def update_email_transact(email):
        return {
            "Put": {
                "TableName": table_name,
                "Item": {"pk": {"S": ":v"}},
                "ExpressionAttributeValues": {":v": {"S": email}},
            }
        }

    update_email_transact("test1@moto.com")
    with pytest.raises(ClientError) as exc:
        dynamodb.transact_write_items(
            TransactItems=[
                update_email_transact(f"test{idx}@moto.com") for idx in range(101)
            ]
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "1 validation error detected at 'transactItems' failed to satisfy constraint: Member must have length less than or equal to 100."
    )


@mock_aws
def test_update_item_non_existent_table():
    client = boto3.client("dynamodb", region_name="us-west-2")
    with pytest.raises(client.exceptions.ResourceNotFoundException) as exc:
        client.update_item(
            TableName="non-existent",
            Key={"forum_name": {"S": "LOLCat Forum"}},
            UpdateExpression="set Body=:Body",
            ExpressionAttributeValues={":Body": {"S": ""}},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ResourceNotFoundException"
    assert err["Message"] == "Requested resource not found"


@pytest.mark.aws_verified
class TestDuplicateProjectionExpressions(BaseTest):
    def test_query_item_with_duplicate_path_in_projection_expressions(self):
        with pytest.raises(ClientError) as exc:
            TestDuplicateProjectionExpressions.table.query(
                KeyConditionExpression=Key("pk").eq("the-key"),
                ProjectionExpression="body, subject, body",  # duplicate body
            )
        self._validate(exc)

    def test_get_item_with_duplicate_path_in_projection_expressions(self):
        with pytest.raises(ClientError) as exc:
            TestDuplicateProjectionExpressions.table.get_item(
                Key={"pk": "the-key"},
                ProjectionExpression="#rl, #rt, subject, subject",  # duplicate subject
                ExpressionAttributeNames={"#rl": "body", "#rt": "attachment"},
            )
        self._validate(exc)

    def test_scan_with_duplicate_path_in_projection_expressions(self):
        with pytest.raises(ClientError) as exc:
            TestDuplicateProjectionExpressions.table.scan(
                FilterExpression=Key("forum_name").eq("the-key"),
                ProjectionExpression="#rl, #rt, subject, subject",  # duplicate subject
                ExpressionAttributeNames={"#rl": "body", "#rt": "attachment"},
            )
        self._validate(exc)

    def _validate(self, exc):
        err = exc.value.response["Error"]
        assert err["Code"] == "ValidationException"
        assert "Invalid ProjectionExpression: " in err["Message"]
        assert (
            "Two document paths overlap with each other; must remove or rewrite one of these paths"
            in err["Message"]
        )


@mock_aws
def test_put_item_wrong_datatype():
    if settings.TEST_SERVER_MODE:
        raise SkipTest("Unable to mock a session with Config in ServerMode")
    session = botocore.session.Session()
    config = botocore.client.Config(parameter_validation=False)
    table_name = f"T{uuid4()}"
    client = session.create_client("dynamodb", region_name="us-east-1", config=config)
    client.create_table(
        TableName=table_name,
        KeySchema=[{"AttributeName": "mykey", "KeyType": "HASH"}],
        AttributeDefinitions=[{"AttributeName": "mykey", "AttributeType": "N"}],
        BillingMode="PAY_PER_REQUEST",
    )
    with pytest.raises(ClientError) as exc:
        client.put_item(TableName=table_name, Item={"mykey": {"N": 123}})
    err = exc.value.response["Error"]
    assert err["Code"] == "SerializationException"
    assert err["Message"] == "NUMBER_VALUE cannot be converted to String"

    # Same thing - but with a non-key, and nested
    with pytest.raises(ClientError) as exc:
        client.put_item(
            TableName=table_name,
            Item={"mykey": {"N": "123"}, "nested": {"M": {"sth": {"N": 5}}}},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "SerializationException"
    assert err["Message"] == "NUMBER_VALUE cannot be converted to String"


@dynamodb_aws_verified()
@pytest.mark.aws_verified
def test_put_item_empty_set(table_name=None):
    client = boto3.client("dynamodb", region_name="us-east-1")
    dynamodb = boto3.resource("dynamodb", region_name="us-east-1")

    table = dynamodb.Table(table_name)
    with pytest.raises(ClientError) as exc:
        table.put_item(Item={"pk": "some-irrelevant_key", "attr2": {"SS": set()}})
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "One or more parameter values were invalid: An number set  may not be empty"
    )

    with pytest.raises(ClientError) as exc:
        client.put_item(
            TableName=table_name, Item={"pk": {"S": "foo"}, "stringSet": {"SS": []}}
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "One or more parameter values were invalid: An string set  may not be empty"
    )


@mock_aws
def test_update_expression_with_trailing_comma():
    resource = boto3.resource(service_name="dynamodb", region_name="us-east-1")
    table = resource.create_table(
        TableName=f"T{uuid4()}",
        KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
        AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
        ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1},
    )
    table.put_item(Item={"pk": "key", "attr2": 2})

    with pytest.raises(ClientError) as exc:
        table.update_item(
            Key={"pk": "key"},
            # Trailing comma should be invalid
            UpdateExpression="SET #attr1 = :val1, #attr2 = :val2,",
            ExpressionAttributeNames={"#attr1": "attr1", "#attr2": "attr2"},
            ExpressionAttributeValues={":val1": 3, ":val2": 4},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == 'Invalid UpdateExpression: Syntax error; token: "<EOF>", near: ","'
    )


@mock_aws
def test_batch_items_should_throw_exception_for_duplicate_request(
    ddb_resource, user_table
):
    # Setup
    test_item = {"forum_name": "test_dupe", "subject": "test1"}

    # Execute
    with pytest.raises(ClientError) as ex:
        with user_table.batch_writer() as batch:
            batch.put_item(Item=test_item)
            batch.put_item(Item=test_item)

    with pytest.raises(ClientError) as ex2:
        with user_table.batch_writer() as batch:
            batch.delete_item(Key=test_item)
            batch.delete_item(Key=test_item)

    # Verify
    err = ex.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert err["Message"] == "Provided list of item keys contains duplicates"

    err2 = ex2.value.response["Error"]
    assert err2["Code"] == "ValidationException"
    assert err2["Message"] == "Provided list of item keys contains duplicates"


@mock_aws
def test_batch_put_item_with_empty_value():
    ddb = boto3.resource("dynamodb", region_name="us-east-1")
    table = ddb.create_table(
        AttributeDefinitions=[
            {"AttributeName": "pk", "AttributeType": "S"},
            {"AttributeName": "sk", "AttributeType": "S"},
        ],
        TableName=f"T{uuid4()}",
        KeySchema=[
            {"AttributeName": "pk", "KeyType": "HASH"},
            {"AttributeName": "sk", "KeyType": "RANGE"},
        ],
        ProvisionedThroughput={"ReadCapacityUnits": 5, "WriteCapacityUnits": 5},
    )

    # Empty Partition Key throws an error
    with pytest.raises(botocore.exceptions.ClientError) as exc:
        with table.batch_writer() as batch:
            batch.put_item(Item={"pk": "", "sk": "sth"})
    err = exc.value.response["Error"]
    assert (
        err["Message"]
        == "One or more parameter values are not valid. The AttributeValue for a key attribute cannot contain an empty string value. Key: pk"
    )
    assert err["Code"] == "ValidationException"

    # Empty SortKey throws an error
    with pytest.raises(botocore.exceptions.ClientError) as exc:
        with table.batch_writer() as batch:
            batch.put_item(Item={"pk": "sth", "sk": ""})
    err = exc.value.response["Error"]
    assert (
        err["Message"]
        == "One or more parameter values are not valid. The AttributeValue for a key attribute cannot contain an empty string value. Key: sk"
    )
    assert err["Code"] == "ValidationException"

    # Empty regular parameter workst just fine though
    with table.batch_writer() as batch:
        batch.put_item(Item={"pk": "sth", "sk": "else", "par": ""})


@mock_aws
def test_query_begins_with_without_brackets():
    client = boto3.client("dynamodb", region_name="us-east-1")
    table_name = f"T{uuid4()}"
    client.create_table(
        TableName=table_name,
        AttributeDefinitions=[
            {"AttributeName": "pk", "AttributeType": "S"},
            {"AttributeName": "sk", "AttributeType": "S"},
        ],
        KeySchema=[
            {"AttributeName": "pk", "KeyType": "HASH"},
            {"AttributeName": "sk", "KeyType": "RANGE"},
        ],
        ProvisionedThroughput={"ReadCapacityUnits": 123, "WriteCapacityUnits": 123},
    )
    with pytest.raises(ClientError) as exc:
        client.query(
            TableName=table_name,
            KeyConditionExpression="pk=:pk AND begins_with sk, :sk ",
            ExpressionAttributeValues={":pk": {"S": "test1"}, ":sk": {"S": "test2"}},
        )
    err = exc.value.response["Error"]
    assert err["Message"] == 'Invalid KeyConditionExpression: Syntax error; token: "sk"'
    assert err["Code"] == "ValidationException"


@mock_aws
def test_transact_write_items_multiple_operations_fail():
    # Setup
    schema = {
        "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}],
        "AttributeDefinitions": [{"AttributeName": "id", "AttributeType": "S"}],
    }
    dynamodb = boto3.client("dynamodb", region_name="us-east-1")
    table_name = f"T{uuid4()}"
    dynamodb.create_table(TableName=table_name, BillingMode="PAY_PER_REQUEST", **schema)

    # Execute
    with pytest.raises(ClientError) as exc:
        dynamodb.transact_write_items(
            TransactItems=[
                {
                    "Put": {
                        "Item": {"id": {"S": "test"}},
                        "TableName": table_name,
                    },
                    "Delete": {
                        "Key": {"id": {"S": "test"}},
                        "TableName": table_name,
                    },
                }
            ]
        )
    # Verify
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "TransactItems can only contain one of Check, Put, Update or Delete"
    )


@mock_aws
def test_transact_write_items_with_empty_gsi_key():
    client = boto3.client("dynamodb", "us-east-2")
    table_name = f"T{uuid4()}"

    client.create_table(
        TableName=table_name,
        KeySchema=[{"AttributeName": "unique_code", "KeyType": "HASH"}],
        AttributeDefinitions=[
            {"AttributeName": "unique_code", "AttributeType": "S"},
            {"AttributeName": "unique_id", "AttributeType": "S"},
        ],
        GlobalSecondaryIndexes=[
            {
                "IndexName": "gsi_index",
                "KeySchema": [{"AttributeName": "unique_id", "KeyType": "HASH"}],
                "Projection": {"ProjectionType": "ALL"},
            }
        ],
        ProvisionedThroughput={"ReadCapacityUnits": 5, "WriteCapacityUnits": 5},
    )

    transact_items = [
        {
            "Put": {
                "Item": {"unique_code": {"S": "some code"}, "unique_id": {"S": ""}},
                "TableName": table_name,
            }
        }
    ]

    with pytest.raises(ClientError) as exc:
        client.transact_write_items(TransactItems=transact_items)
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "One or more parameter values are not valid. A value specified for a secondary index key is not supported. The AttributeValue for a key attribute cannot contain an empty string value. IndexName: gsi_index, IndexKey: unique_id"
    )


@mock_aws
def test_update_primary_key_with_sortkey():
    dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
    schema = {
        "KeySchema": [
            {"AttributeName": "pk", "KeyType": "HASH"},
            {"AttributeName": "sk", "KeyType": "RANGE"},
        ],
        "AttributeDefinitions": [
            {"AttributeName": "pk", "AttributeType": "S"},
            {"AttributeName": "sk", "AttributeType": "S"},
        ],
    }
    table = dynamodb.create_table(
        TableName=f"T{uuid4()}", BillingMode="PAY_PER_REQUEST", **schema
    )

    base_item = {"pk": "testchangepk", "sk": "else"}
    table.put_item(Item=base_item)

    with pytest.raises(ClientError) as exc:
        table.update_item(
            Key={"pk": "n/a", "sk": "else"},
            UpdateExpression="SET #attr1 = :val1",
            ExpressionAttributeNames={"#attr1": "pk"},
            ExpressionAttributeValues={":val1": "different"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "One or more parameter values were invalid: Cannot update attribute pk. This attribute is part of the key"
    )

    item = table.get_item(Key={"pk": "testchangepk", "sk": "else"})["Item"]
    assert item == {"pk": "testchangepk", "sk": "else"}


@mock_aws
def test_update_primary_key():
    dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
    schema = {
        "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
        "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
    }
    table = dynamodb.create_table(
        TableName=f"T{uuid4()}", BillingMode="PAY_PER_REQUEST", **schema
    )

    base_item = {"pk": "testchangepk"}
    table.put_item(Item=base_item)

    with pytest.raises(ClientError) as exc:
        table.update_item(
            Key={"pk": "n/a"},
            UpdateExpression="SET #attr1 = :val1",
            ExpressionAttributeNames={"#attr1": "pk"},
            ExpressionAttributeValues={":val1": "different"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "One or more parameter values were invalid: Cannot update attribute pk. This attribute is part of the key"
    )

    item = table.get_item(Key={"pk": "testchangepk"})["Item"]
    assert item == {"pk": "testchangepk"}


@mock_aws
def test_put_item__string_as_integer_value():
    if settings.TEST_SERVER_MODE:
        raise SkipTest("Unable to mock a session with Config in ServerMode")
    config = botocore.client.Config(parameter_validation=False)
    client = boto3.client("dynamodb", region_name="us-east-1", config=config)
    table_name = f"T{uuid4()}"
    client.create_table(
        TableName=table_name,
        KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
        AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
        ProvisionedThroughput={"ReadCapacityUnits": 10, "WriteCapacityUnits": 10},
    )
    with pytest.raises(ClientError) as exc:
        client.put_item(TableName=table_name, Item={"pk": {"S": 123}})
    err = exc.value.response["Error"]
    assert err["Code"] == "SerializationException"
    assert err["Message"] == "NUMBER_VALUE cannot be converted to String"

    # A primary key cannot be of type S, but then point to a dictionary
    with pytest.raises(ClientError) as exc:
        client.put_item(TableName=table_name, Item={"pk": {"S": {"S": "asdf"}}})
    err = exc.value.response["Error"]
    assert err["Code"] == "SerializationException"
    assert err["Message"] == "Start of structure or map found where not expected"

    # Note that a normal attribute name can be an 'S', which follows the same pattern
    # Nested 'S'-s like this are allowed for non-key attributes
    client.put_item(TableName=table_name, Item={"pk": {"S": "val"}, "S": {"S": "asdf"}})
    item = client.get_item(TableName=table_name, Key={"pk": {"S": "val"}})["Item"]
    assert item == {"pk": {"S": "val"}, "S": {"S": "asdf"}}


@mock_aws
def test_gsi_key_cannot_be_empty():
    dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
    hello_index = {
        "IndexName": "hello-index",
        "KeySchema": [{"AttributeName": "hello", "KeyType": "HASH"}],
        "Projection": {"ProjectionType": "ALL"},
    }
    table_name = f"T{uuid4()}"

    # Let's create a table with [id: str, hello: str], with an index to hello
    dynamodb.create_table(
        TableName=table_name,
        KeySchema=[
            {"AttributeName": "id", "KeyType": "HASH"},
        ],
        AttributeDefinitions=[
            {"AttributeName": "id", "AttributeType": "S"},
            {"AttributeName": "hello", "AttributeType": "S"},
        ],
        GlobalSecondaryIndexes=[hello_index],
        BillingMode="PAY_PER_REQUEST",
    )

    table = dynamodb.Table(table_name)
    with pytest.raises(ClientError) as exc:
        table.put_item(
            TableName=table_name,
            Item={
                "id": "woop",
                "hello": None,
            },
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "One or more parameter values were invalid: Type mismatch for Index Key hello Expected: S Actual: NULL IndexName: hello-index"
    )


@mock_aws
def test_list_append_errors_for_unknown_attribute_value():
    # Verify whether the list_append operation works as expected
    client = boto3.client("dynamodb", region_name="us-east-1")
    table_name = f"T{uuid4()}"

    client.create_table(
        AttributeDefinitions=[{"AttributeName": "key", "AttributeType": "S"}],
        TableName=table_name,
        KeySchema=[{"AttributeName": "key", "KeyType": "HASH"}],
        ProvisionedThroughput={"ReadCapacityUnits": 5, "WriteCapacityUnits": 5},
    )
    client.put_item(
        TableName=table_name,
        Item={"key": {"S": "sha-of-file"}, "crontab": {"L": [{"S": "bar1"}]}},
    )

    # append to unknown list directly
    with pytest.raises(ClientError) as exc:
        client.update_item(
            TableName=table_name,
            Key={"key": {"S": "sha-of-file"}},
            UpdateExpression="SET uk = list_append(uk, :i)",
            ExpressionAttributeValues={":i": {"L": [{"S": "bar2"}]}},
            ReturnValues="UPDATED_NEW",
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "The provided expression refers to an attribute that does not exist in the item"
    )

    # append to unknown list via ExpressionAttributeNames
    with pytest.raises(ClientError) as exc:
        client.update_item(
            TableName=table_name,
            Key={"key": {"S": "sha-of-file"}},
            UpdateExpression="SET #0 = list_append(#0, :i)",
            ExpressionAttributeNames={"#0": "uk"},
            ExpressionAttributeValues={":i": {"L": [{"S": "bar2"}]}},
            ReturnValues="UPDATED_NEW",
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "The provided expression refers to an attribute that does not exist in the item"
    )

    # append to unknown list, even though end result is known
    with pytest.raises(ClientError) as exc:
        client.update_item(
            TableName=table_name,
            Key={"key": {"S": "sha-of-file"}},
            UpdateExpression="SET crontab = list_append(uk, :i)",
            ExpressionAttributeValues={":i": {"L": [{"S": "bar2"}]}},
            ReturnValues="UPDATED_NEW",
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "The provided expression refers to an attribute that does not exist in the item"
    )

    # We can append to a known list, into an unknown/new list
    client.update_item(
        TableName=table_name,
        Key={"key": {"S": "sha-of-file"}},
        UpdateExpression="SET uk = list_append(crontab, :i)",
        ExpressionAttributeValues={":i": {"L": [{"S": "bar2"}]}},
        ReturnValues="UPDATED_NEW",
    )


@mock_aws
def test_query_with_empty_filter_expression():
    ddb = boto3.resource("dynamodb", region_name="us-east-1")
    table = ddb.create_table(
        TableName=f"T{uuid4()}", BillingMode="PAY_PER_REQUEST", **table_schema
    )
    with pytest.raises(ClientError) as exc:
        table.query(
            KeyConditionExpression="partitionKey = sth", ProjectionExpression=""
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "Invalid ProjectionExpression: The expression can not be empty;"
    )

    with pytest.raises(ClientError) as exc:
        table.query(KeyConditionExpression="partitionKey = sth", FilterExpression="")
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"] == "Invalid FilterExpression: The expression can not be empty;"
    )


@mock_aws
def test_query_with_missing_expression_attribute():
    ddb = boto3.resource("dynamodb", region_name="us-west-2")
    table_name = f"T{uuid4()}"
    ddb.create_table(
        TableName=table_name, BillingMode="PAY_PER_REQUEST", **table_schema
    )
    client = boto3.client("dynamodb", region_name="us-west-2")
    with pytest.raises(ClientError) as exc:
        client.query(
            TableName=table_name,
            KeyConditionExpression="#part_key=some_value",
            ExpressionAttributeNames={"#part_key": "partitionKey"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == "Invalid condition in KeyConditionExpression: Multiple attribute names used in one condition"
    )


@pytest.mark.aws_verified
class TestReturnValuesOnConditionCheckFailure(BaseTest):
    def setup_method(self):
        self.table.put_item(
            Item={"pk": "the-key", "subject": "123", "body": "some test msg"}
        )

    def test_put_item_does_not_return_old_item(self):
        with pytest.raises(ClientError) as exc:
            self.table.put_item(
                Item={"pk": "the-key", "bar": "quuz"},
                ConditionExpression="attribute_not_exists(body)",
            )
        self._assert_without_return_values(exc)

    def test_put_item_returns_old_item(self):
        with pytest.raises(ClientError) as exc:
            self.table.put_item(
                Item={"pk": "the-key", "bar": "quuz"},
                ReturnValuesOnConditionCheckFailure="ALL_OLD",
                ConditionExpression="attribute_not_exists(body)",
            )
        self._assert_with_return_values(exc)

    def test_update_item_does_not_return_old_item(self):
        with pytest.raises(ClientError) as exc:
            self.table.update_item(
                Key={"pk": "the-key"},
                UpdateExpression="set #lock = :lock",
                ExpressionAttributeNames={"#lock": "lock"},
                ExpressionAttributeValues={":lock": "sth"},
                ConditionExpression="attribute_exists(#lock)",
            )
        self._assert_without_return_values(exc)

    def test_update_item_returns_old_item(self):
        with pytest.raises(ClientError) as exc:
            self.table.update_item(
                Key={"pk": "the-key"},
                UpdateExpression="set #lock = :lock",
                ExpressionAttributeNames={"#lock": "lock"},
                ExpressionAttributeValues={":lock": "sth"},
                ReturnValuesOnConditionCheckFailure="ALL_OLD",
                ConditionExpression="attribute_exists(#lock)",
            )
        self._assert_with_return_values(exc)

    def test_delete_item_does_not_return_old_item(self):
        with pytest.raises(ClientError) as exc:
            self.table.delete_item(
                Key={"pk": "the-key"},
                ExpressionAttributeNames={"#lock": "lock"},
                ConditionExpression="attribute_exists(#lock)",
            )
        self._assert_without_return_values(exc)

    def test_delete_item_returns_old_item(self):
        with pytest.raises(ClientError) as exc:
            self.table.delete_item(
                Key={"pk": "the-key"},
                ExpressionAttributeNames={"#lock": "lock"},
                ReturnValuesOnConditionCheckFailure="ALL_OLD",
                ConditionExpression="attribute_exists(#lock)",
            )
        self._assert_with_return_values(exc)

    def _assert_without_return_values(self, exc):
        resp = exc.value.response
        assert resp["Error"] == {
            "Message": "The conditional request failed",
            "Code": "ConditionalCheckFailedException",
        }
        assert resp["message"] == "The conditional request failed"
        assert "Item" not in resp

    def _assert_with_return_values(self, exc):
        resp = exc.value.response
        assert resp["Error"] == {
            "Message": "The conditional request failed",
            "Code": "ConditionalCheckFailedException",
        }
        assert "message" not in resp
        assert resp["Item"] == {
            "pk": {"S": "the-key"},
            "body": {"S": "some test msg"},
            "subject": {"S": "123"},
        }


@pytest.mark.aws_verified
@dynamodb_aws_verified()
def test_delete_item_returns_old_item(table_name=None):
    dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
    table = dynamodb.Table(table_name)
    table.put_item(Item={"pk": "mark", "lock": {"acquired_at": 123}})


@pytest.mark.aws_verified
@dynamodb_aws_verified()
def test_scan_with_missing_value(table_name=None):
    dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
    table = dynamodb.Table(table_name)

    with pytest.raises(ClientError) as exc:
        table.scan(
            FilterExpression="attr = loc",
            # Missing ':'
            ExpressionAttributeValues={"loc": "sth"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == 'ExpressionAttributeValues contains invalid key: Syntax error; key: "loc"'
    )

    with pytest.raises(ClientError) as exc:
        table.query(
            KeyConditionExpression="attr = loc",
            # Missing ':'
            ExpressionAttributeValues={"loc": "sth"},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert (
        err["Message"]
        == 'ExpressionAttributeValues contains invalid key: Syntax error; key: "loc"'
    )


@mock_aws
def test_too_many_key_schema_attributes():
    ddb = boto3.resource("dynamodb", "us-east-1")
    TableName = "my_test_"

    AttributeDefinitions = [
        {"AttributeName": "UUID", "AttributeType": "S"},
        {"AttributeName": "ComicBook", "AttributeType": "S"},
    ]

    KeySchema = [
        {"AttributeName": "UUID", "KeyType": "HASH"},
        {"AttributeName": "ComicBook", "KeyType": "RANGE"},
        {"AttributeName": "Creator", "KeyType": "RANGE"},
    ]

    ProvisionedThroughput = {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}

    expected_err = "1 validation error detected: Value '[KeySchemaElement(attributeName=UUID, keyType=HASH), KeySchemaElement(attributeName=ComicBook, keyType=RANGE), KeySchemaElement(attributeName=Creator, keyType=RANGE)]' at 'keySchema' failed to satisfy constraint: Member must have length less than or equal to 2"
    with pytest.raises(ClientError) as exc:
        ddb.create_table(
            TableName=TableName,
            KeySchema=KeySchema,
            AttributeDefinitions=AttributeDefinitions,
            ProvisionedThroughput=ProvisionedThroughput,
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert err["Message"] == expected_err


@mock_aws
def test_cannot_query_gsi_with_consistent_read():
    dynamodb = boto3.client("dynamodb", region_name="us-east-1")
    table_name = f"T{uuid4()}"
    dynamodb.create_table(
        TableName=table_name,
        KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
        AttributeDefinitions=[
            {"AttributeName": "id", "AttributeType": "S"},
            {"AttributeName": "gsi_hash_key", "AttributeType": "S"},
            {"AttributeName": "gsi_range_key", "AttributeType": "S"},
        ],
        ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1},
        GlobalSecondaryIndexes=[
            {
                "IndexName": "test_gsi",
                "KeySchema": [
                    {"AttributeName": "gsi_hash_key", "KeyType": "HASH"},
                    {"AttributeName": "gsi_range_key", "KeyType": "RANGE"},
                ],
                "Projection": {"ProjectionType": "ALL"},
                "ProvisionedThroughput": {
                    "ReadCapacityUnits": 1,
                    "WriteCapacityUnits": 1,
                },
            }
        ],
    )

    with pytest.raises(ClientError) as exc:
        dynamodb.query(
            TableName=table_name,
            IndexName="test_gsi",
            KeyConditionExpression="gsi_hash_key = :gsi_hash_key and gsi_range_key = :gsi_range_key",
            ExpressionAttributeValues={
                ":gsi_hash_key": {"S": "key1"},
                ":gsi_range_key": {"S": "range1"},
            },
            ConsistentRead=True,
        )

    assert exc.value.response["Error"] == {
        "Code": "ValidationException",
        "Message": "Consistent reads are not supported on global secondary indexes",
    }


@mock_aws
def test_cannot_scan_gsi_with_consistent_read():
    dynamodb = boto3.client("dynamodb", region_name="us-east-1")
    table_name = f"T{uuid4()}"
    dynamodb.create_table(
        TableName=table_name,
        KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
        AttributeDefinitions=[
            {"AttributeName": "id", "AttributeType": "S"},
            {"AttributeName": "gsi_hash_key", "AttributeType": "S"},
            {"AttributeName": "gsi_range_key", "AttributeType": "S"},
        ],
        ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1},
        GlobalSecondaryIndexes=[
            {
                "IndexName": "test_gsi",
                "KeySchema": [
                    {"AttributeName": "gsi_hash_key", "KeyType": "HASH"},
                    {"AttributeName": "gsi_range_key", "KeyType": "RANGE"},
                ],
                "Projection": {"ProjectionType": "ALL"},
                "ProvisionedThroughput": {
                    "ReadCapacityUnits": 1,
                    "WriteCapacityUnits": 1,
                },
            }
        ],
    )

    with pytest.raises(ClientError) as exc:
        dynamodb.scan(
            TableName=table_name,
            IndexName="test_gsi",
            ConsistentRead=True,
        )

    assert exc.value.response["Error"] == {
        "Code": "ValidationException",
        "Message": "Consistent reads are not supported on global secondary indexes",
    }


@mock_aws
def test_delete_table():
    client = boto3.client("dynamodb", region_name="us-east-1")
    table_name = f"T{uuid4()}"

    # Create the DynamoDB table.
    client.create_table(
        TableName=table_name,
        AttributeDefinitions=[
            {"AttributeName": "client", "AttributeType": "S"},
            {"AttributeName": "app", "AttributeType": "S"},
        ],
        KeySchema=[
            {"AttributeName": "client", "KeyType": "HASH"},
            {"AttributeName": "app", "KeyType": "RANGE"},
        ],
        ProvisionedThroughput={"ReadCapacityUnits": 123, "WriteCapacityUnits": 123},
        DeletionProtectionEnabled=True,
    )

    with pytest.raises(ClientError) as err:
        client.delete_table(TableName=table_name)
    assert err.value.response["Error"]["Code"] == "ValidationException"
    assert (
        err.value.response["Error"]["Message"]
        == f"1 validation error detected: Table '{table_name}' can't be deleted while DeletionProtectionEnabled is set to True"
    )


@pytest.mark.aws_verified
@dynamodb_aws_verified(add_range=False)
def test_provide_range_key_against_table_without_range_key(table_name=None):
    ddb_client = boto3.client("dynamodb", "us-east-1")
    with pytest.raises(ClientError) as exc:
        ddb_client.get_item(
            TableName=table_name, Key={"pk": {"S": "pk"}, "sk": {"S": "sk"}}
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert err["Message"] == "The provided key element does not match the schema"

    with pytest.raises(ClientError) as exc:
        ddb_client.delete_item(
            TableName=table_name, Key={"pk": {"S": "pk"}, "sk": {"S": "sk"}}
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert err["Message"] == "The provided key element does not match the schema"

    with pytest.raises(ClientError) as exc:
        ddb_client.update_item(
            TableName=table_name,
            Key={
                "pk": {"S": "x"},
                "ReceivedTime": {"S": "12/9/2011 11:36:03 PM"},
            },
            UpdateExpression="set body=:New",
            ExpressionAttributeValues={":New": {"S": "hello"}},
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"
    assert err["Message"] == "The provided key element does not match the schema"