File: test_dhcp_options.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 (494 lines) | stat: -rw-r--r-- 17,661 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
import random
import uuid
from unittest import SkipTest

import boto3
import pytest
from botocore.exceptions import ClientError

from moto import mock_aws, settings

SAMPLE_DOMAIN_NAME = "example.com"
SAMPLE_NAME_SERVERS = ["10.0.0.6", "10.0.0.7"]


@mock_aws
def test_dhcp_options_associate():
    """associate dhcp option"""
    ec2 = boto3.resource("ec2", region_name="us-west-1")
    client = boto3.client("ec2", region_name="us-west-1")

    dhcp_options = ec2.create_dhcp_options(
        DhcpConfigurations=[
            {"Key": "domain-name", "Values": [SAMPLE_DOMAIN_NAME]},
            {"Key": "domain-name-servers", "Values": SAMPLE_NAME_SERVERS},
        ]
    )
    vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")

    client.associate_dhcp_options(DhcpOptionsId=dhcp_options.id, VpcId=vpc.id)
    #
    vpc.reload()
    assert vpc.dhcp_options_id == dhcp_options.id


@mock_aws
def test_dhcp_options_associate_invalid_dhcp_id():
    """associate dhcp option bad dhcp options id"""
    ec2 = boto3.resource("ec2", region_name="us-west-1")
    client = boto3.client("ec2", region_name="us-west-1")
    vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")

    with pytest.raises(ClientError) as ex:
        client.associate_dhcp_options(DhcpOptionsId="foo", VpcId=vpc.id)
    assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
    assert "RequestId" in ex.value.response["ResponseMetadata"]
    assert ex.value.response["Error"]["Code"] == "InvalidDhcpOptionID.NotFound"


@mock_aws
def test_dhcp_options_associate_invalid_vpc_id():
    """associate dhcp option invalid vpc id"""
    ec2 = boto3.resource("ec2", region_name="us-west-1")
    client = boto3.client("ec2", region_name="us-west-1")
    dhcp_options = ec2.create_dhcp_options(
        DhcpConfigurations=[
            {"Key": "domain-name", "Values": [SAMPLE_DOMAIN_NAME]},
            {"Key": "domain-name-servers", "Values": SAMPLE_NAME_SERVERS},
        ]
    )

    with pytest.raises(ClientError) as ex:
        client.associate_dhcp_options(DhcpOptionsId=dhcp_options.id, VpcId="foo")
    assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
    assert "RequestId" in ex.value.response["ResponseMetadata"]
    assert ex.value.response["Error"]["Code"] == "InvalidVpcID.NotFound"


@mock_aws
def test_dhcp_options_disassociation():
    """Ensure that VPCs can be set to the 'default' DHCP options set for disassociation."""
    ec2 = boto3.resource("ec2", region_name="us-west-1")
    client = boto3.client("ec2", region_name="us-west-1")
    dhcp_options = ec2.create_dhcp_options(
        DhcpConfigurations=[
            {"Key": "domain-name", "Values": [SAMPLE_DOMAIN_NAME]},
            {"Key": "domain-name-servers", "Values": SAMPLE_NAME_SERVERS},
        ]
    )
    vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")

    # Ensure newly created VPCs without any DHCP options can be disassociated
    client.associate_dhcp_options(DhcpOptionsId="default", VpcId=vpc.id)
    vpc.reload()
    assert vpc.dhcp_options_id == "default"

    client.associate_dhcp_options(DhcpOptionsId=dhcp_options.id, VpcId=vpc.id)
    vpc.reload()
    assert vpc.dhcp_options_id == dhcp_options.id

    # Ensure VPCs with already associated DHCP options can be disassociated
    client.associate_dhcp_options(DhcpOptionsId="default", VpcId=vpc.id)
    vpc.reload()
    assert vpc.dhcp_options_id == "default"


@mock_aws
def test_dhcp_options_delete_with_vpc():
    """Test deletion of dhcp options with vpc"""
    ec2 = boto3.resource("ec2", region_name="us-west-1")
    client = boto3.client("ec2", region_name="us-west-1")
    dhcp_options = ec2.create_dhcp_options(
        DhcpConfigurations=[
            {"Key": "domain-name", "Values": [SAMPLE_DOMAIN_NAME]},
            {"Key": "domain-name-servers", "Values": SAMPLE_NAME_SERVERS},
        ]
    )
    vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")

    client.associate_dhcp_options(DhcpOptionsId=dhcp_options.id, VpcId=vpc.id)

    with pytest.raises(ClientError) as ex:
        client.delete_dhcp_options(DhcpOptionsId=dhcp_options.id)
    assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
    assert "RequestId" in ex.value.response["ResponseMetadata"]
    assert ex.value.response["Error"]["Code"] == "DependencyViolation"

    vpc.delete()

    with pytest.raises(ClientError) as ex:
        client.describe_dhcp_options(DhcpOptionsIds=[dhcp_options.id])
    assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
    assert "RequestId" in ex.value.response["ResponseMetadata"]
    assert ex.value.response["Error"]["Code"] == "InvalidDhcpOptionID.NotFound"


@mock_aws
def test_create_dhcp_options():
    """Create most basic dhcp option"""
    ec2 = boto3.resource("ec2", region_name="us-west-1")

    dhcp_options = ec2.create_dhcp_options(
        DhcpConfigurations=[
            {"Key": "domain-name", "Values": [SAMPLE_DOMAIN_NAME]},
            {"Key": "domain-name-servers", "Values": SAMPLE_NAME_SERVERS},
        ]
    )
    config = dhcp_options.dhcp_configurations
    assert len(config) == 2
    assert {
        "Key": "domain-name-servers",
        "Values": [{"Value": ip} for ip in SAMPLE_NAME_SERVERS],
    } in config

    assert {"Key": "domain-name", "Values": [{"Value": SAMPLE_DOMAIN_NAME}]} in config


@mock_aws
def test_create_dhcp_options_invalid_options():
    """Create invalid dhcp options"""
    ec2 = boto3.resource("ec2", region_name="us-west-1")
    servers = ["f", "f", "f", "f", "f"]

    with pytest.raises(ClientError) as ex:
        ec2.create_dhcp_options(
            DhcpConfigurations=[{"Key": "ntp-servers", "Values": servers}]
        )
    assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
    assert "RequestId" in ex.value.response["ResponseMetadata"]
    assert ex.value.response["Error"]["Code"] == "InvalidParameterValue"

    with pytest.raises(ClientError) as ex:
        ec2.create_dhcp_options(
            DhcpConfigurations=[{"Key": "netbios-node-type", "Values": ["0"]}]
        )
    assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
    assert "RequestId" in ex.value.response["ResponseMetadata"]
    assert ex.value.response["Error"]["Code"] == "InvalidParameterValue"


@mock_aws
def test_describe_dhcp_options():
    """Test dhcp options lookup by id"""
    ec2 = boto3.resource("ec2", region_name="us-west-1")
    client = boto3.client("ec2", region_name="us-west-1")

    dhcp_options = ec2.create_dhcp_options(
        DhcpConfigurations=[
            {"Key": "domain-name", "Values": [SAMPLE_DOMAIN_NAME]},
            {"Key": "domain-name-servers", "Values": SAMPLE_NAME_SERVERS},
        ]
    )
    all_options = client.describe_dhcp_options(DhcpOptionsIds=[dhcp_options.id])[
        "DhcpOptions"
    ]
    assert len(all_options) == 1

    all_options = client.describe_dhcp_options()["DhcpOptions"]
    assert len(all_options) >= 1, "Should have recently created DHCP option"
    recently_created = [
        o for o in all_options if o["DhcpOptionsId"] == dhcp_options.id
    ][0]
    assert recently_created["DhcpOptionsId"] == dhcp_options.id
    config = recently_created["DhcpConfigurations"]
    assert len(config) == 2
    assert {
        "Key": "domain-name-servers",
        "Values": [{"Value": ip} for ip in SAMPLE_NAME_SERVERS],
    } in config
    assert {"Key": "domain-name", "Values": [{"Value": SAMPLE_DOMAIN_NAME}]} in config


@mock_aws
def test_describe_dhcp_options_invalid_id():
    """get error on invalid dhcp_option_id lookup"""
    client = boto3.client("ec2", region_name="us-west-1")

    with pytest.raises(ClientError) as ex:
        client.describe_dhcp_options(DhcpOptionsIds=["1"])
    assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
    assert "RequestId" in ex.value.response["ResponseMetadata"]
    assert ex.value.response["Error"]["Code"] == "InvalidDhcpOptionID.NotFound"


@mock_aws
def test_delete_dhcp_options():
    """delete dhcp option"""
    ec2 = boto3.resource("ec2", region_name="us-west-1")
    client = boto3.client("ec2", region_name="us-west-1")

    dhcp_option = ec2.create_dhcp_options(
        DhcpConfigurations=[
            {"Key": "domain-name", "Values": [SAMPLE_DOMAIN_NAME]},
            {"Key": "domain-name-servers", "Values": SAMPLE_NAME_SERVERS},
        ]
    )

    client.delete_dhcp_options(DhcpOptionsId=dhcp_option.id)

    with pytest.raises(ClientError) as ex:
        client.describe_dhcp_options(DhcpOptionsIds=[dhcp_option.id])
    assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
    assert "RequestId" in ex.value.response["ResponseMetadata"]
    assert ex.value.response["Error"]["Code"] == "InvalidDhcpOptionID.NotFound"


@mock_aws
def test_delete_dhcp_options_invalid_id():
    client = boto3.client("ec2", region_name="us-west-1")

    with pytest.raises(ClientError) as ex:
        client.delete_dhcp_options(DhcpOptionsId="dopt-abcd1234")
    assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
    assert "RequestId" in ex.value.response["ResponseMetadata"]
    assert ex.value.response["Error"]["Code"] == "InvalidDhcpOptionID.NotFound"


@mock_aws
def test_delete_dhcp_options_malformed_id():
    client = boto3.client("ec2", region_name="us-west-1")

    with pytest.raises(ClientError) as ex:
        client.delete_dhcp_options(DhcpOptionsId="foo-abcd1234")
    assert ex.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
    assert "RequestId" in ex.value.response["ResponseMetadata"]
    assert ex.value.response["Error"]["Code"] == "InvalidDhcpOptionsId.Malformed"


@mock_aws
def test_dhcp_tagging():
    ec2 = boto3.resource("ec2", region_name="us-west-1")
    client = boto3.client("ec2", region_name="us-west-1")

    dhcp_option = ec2.create_dhcp_options(
        DhcpConfigurations=[
            {"Key": "domain-name", "Values": [SAMPLE_DOMAIN_NAME]},
            {"Key": "domain-name-servers", "Values": SAMPLE_NAME_SERVERS},
        ]
    )

    tag_value = str(uuid.uuid4())
    dhcp_option.create_tags(Tags=[{"Key": "a tag", "Value": tag_value}])

    tag = client.describe_tags(
        Filters=[{"Name": "resource-id", "Values": [dhcp_option.id]}]
    )["Tags"][0]
    assert tag["ResourceId"] == dhcp_option.id
    assert tag["ResourceType"] == "dhcp-options"
    assert tag["Key"] == "a tag"
    assert tag["Value"] == tag_value

    # Refresh the DHCP options
    dhcp_option = client.describe_dhcp_options(DhcpOptionsIds=[dhcp_option.id])[
        "DhcpOptions"
    ][0]
    assert dhcp_option["Tags"] == [{"Key": "a tag", "Value": tag_value}]


@mock_aws
def test_dhcp_options_get_by_tag():
    ec2 = boto3.resource("ec2", region_name="us-west-1")
    client = boto3.client("ec2", region_name="us-west-1")

    dhcp_tag_value = str(uuid.uuid4())

    dhcp1 = ec2.create_dhcp_options(
        DhcpConfigurations=[
            {"Key": "domain-name", "Values": ["example.com"]},
            {"Key": "domain-name-servers", "Values": ["10.0.10.2"]},
        ]
    )
    dhcp1_tag_name = str(uuid.uuid4())
    dhcp1.create_tags(
        Tags=[
            {"Key": "Name", "Value": dhcp1_tag_name},
            {"Key": "test-tag", "Value": dhcp_tag_value},
        ]
    )

    dhcp2 = ec2.create_dhcp_options(
        DhcpConfigurations=[
            {"Key": "domain-name", "Values": ["example.com"]},
            {"Key": "domain-name-servers", "Values": ["10.0.20.2"]},
        ]
    )
    dhcp2_tag_name = str(uuid.uuid4())
    dhcp2.create_tags(
        Tags=[
            {"Key": "Name", "Value": dhcp2_tag_name},
            {"Key": "test-tag", "Value": dhcp_tag_value},
        ]
    )

    dhcp_options_sets = client.describe_dhcp_options(
        Filters=[
            {"Name": "tag:Name", "Values": [dhcp1_tag_name]},
            {"Name": "tag:test-tag", "Values": [dhcp_tag_value]},
        ]
    )["DhcpOptions"]

    assert len(dhcp_options_sets) == 1
    config = dhcp_options_sets[0]["DhcpConfigurations"]
    assert len(config) == 2
    assert {"Key": "domain-name", "Values": [{"Value": "example.com"}]} in config
    assert {"Key": "domain-name-servers", "Values": [{"Value": "10.0.10.2"}]} in config
    tags = dhcp_options_sets[0]["Tags"]
    assert len(tags) == 2
    assert {"Key": "Name", "Value": dhcp1_tag_name} in tags
    assert {"Key": "test-tag", "Value": dhcp_tag_value} in tags

    dhcp_options_sets = client.describe_dhcp_options(
        Filters=[
            {"Name": "tag:Name", "Values": [dhcp2_tag_name]},
            {"Name": "tag:test-tag", "Values": [dhcp_tag_value]},
        ]
    )["DhcpOptions"]

    assert len(dhcp_options_sets) == 1
    config = dhcp_options_sets[0]["DhcpConfigurations"]
    assert len(config) == 2
    assert {"Key": "domain-name", "Values": [{"Value": "example.com"}]} in config
    assert {"Key": "domain-name-servers", "Values": [{"Value": "10.0.20.2"}]} in config
    tags = dhcp_options_sets[0]["Tags"]
    assert len(tags) == 2
    assert {"Key": "Name", "Value": dhcp2_tag_name} in tags
    assert {"Key": "test-tag", "Value": dhcp_tag_value} in tags

    dhcp_options_sets = client.describe_dhcp_options(
        Filters=[{"Name": "tag:test-tag", "Values": [dhcp_tag_value]}]
    )["DhcpOptions"]

    assert len(dhcp_options_sets) == 2


@mock_aws
def test_dhcp_options_get_by_id():
    ec2 = boto3.resource("ec2", region_name="us-west-1")
    client = boto3.client("ec2", region_name="us-west-1")

    dhcp1 = ec2.create_dhcp_options(
        DhcpConfigurations=[
            {"Key": "domain-name", "Values": ["test1.com"]},
            {"Key": "domain-name-servers", "Values": ["10.0.10.2"]},
        ]
    )
    dhcp1.create_tags(Tags=[{"Key": "Name", "Value": "TestDhcpOptions1"}])
    dhcp1.create_tags(Tags=[{"Key": "test-tag", "Value": "test-value"}])

    dhcp2 = ec2.create_dhcp_options(
        DhcpConfigurations=[
            {"Key": "domain-name", "Values": ["test2.com"]},
            {"Key": "domain-name-servers", "Values": ["10.0.20.2"]},
        ]
    )
    dhcp1.create_tags(Tags=[{"Key": "Name", "Value": "TestDhcpOptions2"}])
    dhcp1.create_tags(Tags=[{"Key": "test-tag", "Value": "test-value"}])

    options = client.describe_dhcp_options()["DhcpOptions"]
    d_ids = [d["DhcpOptionsId"] for d in options]
    assert dhcp1.id in d_ids
    assert dhcp2.id in d_ids

    d = client.describe_dhcp_options(
        Filters=[{"Name": "dhcp-options-id", "Values": [dhcp1.id]}]
    )["DhcpOptions"]

    assert len(d) == 1
    assert d[0]["DhcpOptionsId"] == dhcp1.id

    d = client.describe_dhcp_options(
        Filters=[{"Name": "dhcp-options-id", "Values": [dhcp2.id]}]
    )["DhcpOptions"]

    assert len(d) == 1
    assert d[0]["DhcpOptionsId"] == dhcp2.id


@mock_aws
def test_dhcp_options_get_by_value_filter():
    ec2 = boto3.resource("ec2", region_name="us-west-1")

    random_server_1 = ".".join(map(str, (random.randint(0, 99) for _ in range(4))))
    random_server_2 = ".".join(map(str, (random.randint(0, 99) for _ in range(4))))
    random_server_3 = ".".join(map(str, (random.randint(0, 99) for _ in range(4))))

    ec2.create_dhcp_options(
        DhcpConfigurations=[
            {"Key": "domain-name", "Values": ["example.com"]},
            {"Key": "domain-name-servers", "Values": [random_server_1]},
        ]
    )

    ec2.create_dhcp_options(
        DhcpConfigurations=[
            {"Key": "domain-name", "Values": ["example.com"]},
            {"Key": "domain-name-servers", "Values": [random_server_2]},
        ]
    )

    ec2.create_dhcp_options(
        DhcpConfigurations=[
            {"Key": "domain-name", "Values": ["example.com"]},
            {"Key": "domain-name-servers", "Values": [random_server_3]},
        ]
    )

    filters = [{"Name": "value", "Values": [random_server_2]}]
    dhcp_options_sets = list(ec2.dhcp_options_sets.filter(Filters=filters))
    assert len(dhcp_options_sets) == 1


@mock_aws
def test_dhcp_options_get_by_key_filter():
    ec2 = boto3.resource("ec2", region_name="us-west-1")

    random_domain_name = str(uuid.uuid4())[0:6]

    ec2.create_dhcp_options(
        DhcpConfigurations=[{"Key": "domain-name", "Values": [random_domain_name]}]
    )

    ec2.create_dhcp_options(
        DhcpConfigurations=[{"Key": "domain-name", "Values": ["example.com"]}]
    )

    ec2.create_dhcp_options(
        DhcpConfigurations=[{"Key": "domain-name", "Values": [random_domain_name]}]
    )

    filters = [{"Name": "key", "Values": ["domain-name"]}]
    dhcp_options_sets = list(ec2.dhcp_options_sets.filter(Filters=filters))
    assert len(dhcp_options_sets) >= 3, (
        "Should have at least 3 DHCP options just created"
    )

    configs = []
    for d in dhcp_options_sets:
        configs.extend(d.dhcp_configurations)

    servers = []
    for config in configs:
        if config["Key"] == "domain-name":
            servers.extend(config["Values"])
    assert {"Value": random_domain_name} in servers
    assert {"Value": "example.com"} in servers


@mock_aws
def test_dhcp_options_get_by_invalid_filter():
    if settings.TEST_SERVER_MODE:
        raise SkipTest("Will throw a generic 500 in ServerMode")
    ec2 = boto3.resource("ec2", region_name="us-west-1")

    client = boto3.client("ec2", region_name="us-west-1")

    ec2.create_dhcp_options(
        DhcpConfigurations=[
            {"Key": "domain-name", "Values": [SAMPLE_DOMAIN_NAME]},
            {"Key": "domain-name-servers", "Values": SAMPLE_NAME_SERVERS},
        ]
    )

    filters = [{"Name": "invalid-filter", "Values": ["n/a"]}]
    with pytest.raises(NotImplementedError):
        client.describe_dhcp_options(Filters=filters)