File: test_dynamodb_export_table.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 (297 lines) | stat: -rw-r--r-- 10,355 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
import gzip
import json
import os
from time import sleep
from unittest import SkipTest, mock
from uuid import uuid4

import boto3
import pytest
from botocore.exceptions import ClientError

from moto import settings
from moto.dynamodb.models import TableExport
from tests.test_s3 import s3_aws_verified

from . import dynamodb_aws_verified


@pytest.mark.aws_verified
@dynamodb_aws_verified(create_table=False)
@s3_aws_verified
def test_export_from_missing_table(table_name=None, bucket_name=None):
    client = boto3.client("dynamodb", region_name="us-east-1")
    sts = boto3.client("sts", "us-east-1")

    account_id = sts.get_caller_identity()["Account"]

    s3_prefix = "prefix"
    table_arn = f"arn:aws:dynamodb:us-east-1:{account_id}:table/{str(uuid4())}"

    with pytest.raises(ClientError) as exc:
        client.export_table_to_point_in_time(
            TableArn=table_arn,
            ExportFormat="DYNAMODB_JSON",
            S3Bucket=bucket_name,
            S3Prefix=s3_prefix,
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "TableNotFoundException"
    assert err["Message"] == f"Table not found: {table_arn}"


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

    table_arn = client.describe_table(TableName=table_name)["Table"]["TableArn"]

    client.update_continuous_backups(
        TableName=table_name,
        PointInTimeRecoverySpecification={"PointInTimeRecoveryEnabled": True},
    )

    export_description = client.export_table_to_point_in_time(
        TableArn=table_arn,
        ExportFormat="DYNAMODB_JSON",
        S3Bucket=f"inttest{uuid4()}",
        S3Prefix="prefix",
    )["ExportDescription"]

    export_details = wait_for_export(client, export_description)

    assert export_details["ExportStatus"] == "FAILED"
    assert export_details["FailureCode"] == "S3NoSuchBucket"
    assert "The specified bucket does not exist" in export_details["FailureMessage"]


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

    table_arn = client.describe_table(TableName=table_name)["Table"]["TableArn"]

    with pytest.raises(ClientError) as exc:
        client.export_table_to_point_in_time(
            TableArn=table_arn,
            ExportFormat="DYNAMODB_JSON",
            S3Bucket=bucket_name,
            S3Prefix="prefix",
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "PointInTimeRecoveryUnavailableException"
    assert (
        err["Message"]
        == f"Point in time recovery is not enabled for table '{table_name}'"
    )


@dynamodb_aws_verified()
@s3_aws_verified
@mock.patch.object(TableExport, "_backup_to_s3_file", mock.Mock(side_effect=Exception))
def test_export_backup_to_s3_error(table_name=None, bucket_name=None):
    aws_request = (
        os.environ.get("MOTO_TEST_ALLOW_AWS_REQUEST", "false").lower() == "true"
    )
    if not settings.TEST_DECORATOR_MODE or aws_request:
        raise SkipTest("Can't mock backup to s3 error in ServerMode/against AWS")

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

    table_arn = client.describe_table(TableName=table_name)["Table"]["TableArn"]
    client.update_continuous_backups(
        TableName=table_name,
        PointInTimeRecoverySpecification={"PointInTimeRecoveryEnabled": True},
    )

    export_description = client.export_table_to_point_in_time(
        TableArn=table_arn,
        ExportFormat="DYNAMODB_JSON",
        S3Bucket=bucket_name,
        S3Prefix="prefix",
    )["ExportDescription"]

    export_details = wait_for_export(client, export_description)

    assert export_details["ExportStatus"] == "FAILED"
    assert export_details["FailureCode"] == "UNKNOWN"


@pytest.mark.aws_verified
@dynamodb_aws_verified()
@s3_aws_verified
def test_export_empty_table(table_name=None, bucket_name=None):
    client = boto3.client("dynamodb", region_name="us-east-1")
    s3 = boto3.client("s3", region_name="us-east-1")

    prefix = "prefix"

    table_arn = client.describe_table(TableName=table_name)["Table"]["TableArn"]

    client.update_continuous_backups(
        TableName=table_name,
        PointInTimeRecoverySpecification={"PointInTimeRecoveryEnabled": True},
    )

    export_description = client.export_table_to_point_in_time(
        TableArn=table_arn,
        ExportFormat="DYNAMODB_JSON",
        S3Bucket=bucket_name,
        S3Prefix=prefix,
    )["ExportDescription"]

    export_details = wait_for_export(client, export_description)

    assert export_details["BilledSizeBytes"] == 0
    assert export_details["ExportStatus"] == "COMPLETED"
    assert export_details["ItemCount"] == 0
    assert export_details["ExportFormat"] == "DYNAMODB_JSON"

    s3_files = s3.list_objects(Bucket=bucket_name, Prefix=prefix)["Contents"]
    for file in s3_files:
        # AWS creates other files as well
        # {prefix}/AWSDynamoDB/_started
        # {prefix}/AWSDynamoDB/{number}/data/random.json.gz
        # {prefix}/AWSDynamoDB/{number}/manifest-files.json
        # {prefix}/AWSDynamoDB/{number}/manifest-files.md5
        # {prefix}/AWSDynamoDB/{number}/manifest-summary.json
        # {prefix}/AWSDynamoDB/{number}/manifest-summary.md5
        if "/data/" in file["Key"]:
            s3_object = s3.get_object(Bucket=bucket_name, Key=file["Key"])

            compressed_backup = s3_object["Body"].read()
            file_contents = gzip.decompress(compressed_backup)
            assert file_contents == b""


@pytest.mark.aws_verified
@dynamodb_aws_verified()
@s3_aws_verified
def test_export_table(table_name=None, bucket_name=None):
    client = boto3.client("dynamodb", region_name="us-east-1")
    s3 = boto3.client("s3", region_name="us-east-1")

    s3_prefix = "prefix"

    table_arn = client.describe_table(TableName=table_name)["Table"]["TableArn"]

    client.update_continuous_backups(
        TableName=table_name,
        PointInTimeRecoverySpecification={"PointInTimeRecoveryEnabled": True},
    )

    client.put_item(
        TableName=table_name, Item={"pk": {"S": "user1"}, "binaryfoo": {"B": b"bar"}}
    )
    client.put_item(
        TableName=table_name, Item={"pk": {"S": "user2"}, "foo": {"S": "bar"}}
    )
    client.put_item(
        TableName=table_name, Item={"pk": {"S": "user3"}, "foo": {"S": "bar"}}
    )

    export_description = client.export_table_to_point_in_time(
        TableArn=table_arn,
        ExportFormat="DYNAMODB_JSON",
        S3Bucket=bucket_name,
        S3Prefix=s3_prefix,
    )["ExportDescription"]

    export_details = wait_for_export(client, export_description)
    assert export_details["ExportStatus"] == "COMPLETED"
    assert export_details["ItemCount"] == 3
    assert export_details["ExportFormat"] == "DYNAMODB_JSON"

    s3_files = s3.list_objects(Bucket=bucket_name, Prefix=s3_prefix)["Contents"]
    for file in s3_files:
        # AWS creates other files as well
        # {prefix}/AWSDynamoDB/_started
        # {prefix}/AWSDynamoDB/{number}/data/random.json.gz
        # {prefix}/AWSDynamoDB/{number}/manifest-files.json
        # {prefix}/AWSDynamoDB/{number}/manifest-files.md5
        # {prefix}/AWSDynamoDB/{number}/manifest-summary.json
        # {prefix}/AWSDynamoDB/{number}/manifest-summary.md5
        if "/data/" in file["Key"]:
            s3_object = s3.get_object(Bucket=bucket_name, Key=file["Key"])

            compressed_backup = s3_object["Body"].read()
            file_contents = gzip.decompress(compressed_backup).decode("utf-8")
            rows = [json.loads(r) for r in file_contents.split("\n") if r]

            assert {"Item": {"pk": {"S": "user1"}, "binaryfoo": {"B": "YmFy"}}} in rows
            assert {"Item": {"pk": {"S": "user2"}, "foo": {"S": "bar"}}} in rows
            assert {"Item": {"pk": {"S": "user3"}, "foo": {"S": "bar"}}} in rows


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

    s3_prefix = "prefix"

    table_arn = client.describe_table(TableName=table_name)["Table"]["TableArn"]

    client.update_continuous_backups(
        TableName=table_name,
        PointInTimeRecoverySpecification={"PointInTimeRecoveryEnabled": True},
    )

    client.put_item(
        TableName=table_name, Item={"pk": {"S": "user1"}, "binaryfoo": {"B": b"bar"}}
    )
    client.put_item(
        TableName=table_name, Item={"pk": {"S": "user2"}, "foo": {"S": "bar"}}
    )
    client.put_item(
        TableName=table_name, Item={"pk": {"S": "user3"}, "foo": {"S": "bar"}}
    )

    export_description = client.export_table_to_point_in_time(
        TableArn=table_arn,
        ExportFormat="DYNAMODB_JSON",
        S3Bucket=bucket_name,
        S3Prefix=s3_prefix,
    )["ExportDescription"]

    export_details_1 = wait_for_export(client, export_description)
    assert export_details_1["ExportStatus"] == "COMPLETED"
    export_description = client.export_table_to_point_in_time(
        TableArn=table_arn,
        ExportFormat="DYNAMODB_JSON",
        S3Bucket=bucket_name,
        S3Prefix=s3_prefix,
    )["ExportDescription"]

    export_details_2 = wait_for_export(client, export_description)
    assert export_details_2["ExportStatus"] == "COMPLETED"
    exports = client.list_exports(TableArn=table_arn)["ExportSummaries"]
    assert len(exports) == 2

    export_arn1 = export_details_1["ExportArn"]
    export_arn2 = export_details_1["ExportArn"]
    assert {
        "ExportArn": export_arn1,
        "ExportStatus": "COMPLETED",
        "ExportType": "FULL_EXPORT",
    } in exports
    assert {
        "ExportArn": export_arn2,
        "ExportStatus": "COMPLETED",
        "ExportType": "FULL_EXPORT",
    } in exports


def wait_for_export(client, export_description):
    status = "IN_PROGRESS"
    while status == "IN_PROGRESS":
        export_details = client.describe_export(
            ExportArn=export_description["ExportArn"]
        )
        status = export_details["ExportDescription"]["ExportStatus"]
        sleep(0.1)
    return export_details["ExportDescription"]