File size: 33,660 Bytes
d086025 | 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 | diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/test_cli.py b/tests/test_cli.py
new file mode 100644
--- /dev/null
+++ b/tests/test_cli.py
@@ -0,0 +1,152 @@
+from __future__ import annotations
+
+import subprocess
+import sys
+from pathlib import Path
+from unittest import mock
+
+import pytest
+
+# import __main__ for coverage
+from ec2_metadata import __main__ # noqa: F401
+from ec2_metadata.cli import main
+
+prog_name = (
+ f"{Path(sys.executable).name} -m pytest"
+ if sys.version_info >= (3, 14) and sys.modules["__main__"].__spec__
+ else Path(sys.argv[0]).name
+)
+
+
+class TestMain:
+ def test_no_subcommand(self, capsys):
+ with pytest.raises(SystemExit) as excinfo:
+ main([])
+
+ assert excinfo.value.code == 2
+ out, err = capsys.readouterr()
+ assert err == (
+ f"usage: {prog_name} [-h] {{get,json}} ...\n"
+ + f"{prog_name}: error: the following arguments are required: command\n"
+ )
+ assert out == ""
+
+ def test_main_help(self):
+ with pytest.raises(SystemExit) as excinfo:
+ main(["--help"])
+
+ assert excinfo.value.code == 0
+
+ def test_main_help_subprocess(self):
+ proc = subprocess.run(
+ [sys.executable, "-m", "ec2_metadata", "--help"],
+ check=True,
+ capture_output=True,
+ )
+
+ if sys.version_info >= (3, 14):
+ assert proc.stdout.startswith(
+ f"usage: {Path(sys.executable).name} -m ec2_metadata ".encode()
+ )
+ else:
+ assert proc.stdout.startswith(b"usage: __main__.py ")
+
+ def test_get_help_command(self, capsys):
+ with pytest.raises(SystemExit) as excinfo:
+ main(["get", "--help"])
+ assert excinfo.value.code == 0
+
+ def test_get_no_name(self, capsys):
+ with pytest.raises(SystemExit) as excinfo:
+ main(["get"])
+
+ assert excinfo.value.code == 2
+
+ def test_get_invalid_name(self, capsys):
+ with pytest.raises(SystemExit) as excinfo:
+ main(["get", "invalid-name!"])
+
+ assert excinfo.value.code == 2
+ out, err = capsys.readouterr()
+ assert out == ""
+ assert err.startswith(
+ f"usage: {prog_name} get [-h] [-n] name\n"
+ + f"{prog_name} get: error: argument name: Invalid metadata name: invalid-name!. Must be one of: account_id, ami_id, "
+ )
+
+ def test_get_valid_name_none(self, capsys):
+ with mock.patch("ec2_metadata.cli.ec2_metadata") as mock_metadata:
+ mock_metadata.user_data = None
+
+ main(["get", "user-data"])
+
+ out, err = capsys.readouterr()
+ assert out == "\n"
+ assert err == ""
+
+ def test_get_valid_name(self, capsys):
+ with mock.patch("ec2_metadata.cli.ec2_metadata") as mock_metadata:
+ mock_metadata.instance_id = "i-1234567890abcdef0"
+
+ main(["get", "instance-id"])
+
+ out, err = capsys.readouterr()
+ assert out == "i-1234567890abcdef0\n"
+ assert err == ""
+
+ def test_get_valid_name_no_newline(self, capsys):
+ with mock.patch("ec2_metadata.cli.ec2_metadata") as mock_metadata:
+ mock_metadata.instance_id = "i-1234567890abcdef0"
+
+ main(["get", "instance-id", "-n"])
+
+ out, err = capsys.readouterr()
+ assert out == "i-1234567890abcdef0"
+ assert err == ""
+
+ def test_json_help_command(self, capsys):
+ with pytest.raises(SystemExit) as excinfo:
+ main(["json", "--help"])
+ assert excinfo.value.code == 0
+
+ def test_json_no_names(self, capsys):
+ with pytest.raises(SystemExit) as excinfo:
+ main(["json"])
+
+ assert excinfo.value.code == 2
+ out, err = capsys.readouterr()
+ assert out == ""
+ assert err.startswith(
+ f"usage: {prog_name} json [-h] names [names ...]\n"
+ + f"{prog_name} json: error: the following arguments are required: names\n"
+ )
+
+ def test_json_invalid_name(self, capsys):
+ with pytest.raises(SystemExit) as excinfo:
+ main(["json", "instance-id", "invalid-name!"])
+
+ assert excinfo.value.code == 2
+ out, err = capsys.readouterr()
+ assert out == ""
+ assert err.startswith(
+ f"usage: {prog_name} json [-h] names [names ...]\n"
+ + f"{prog_name} json: error: argument names: Invalid metadata name: invalid-name!. Must be one of: account_id, ami_id, "
+ )
+
+ def test_json_valid_names(self, capsys):
+ with mock.patch("ec2_metadata.cli.ec2_metadata") as mock_metadata:
+ mock_metadata.instance_id = "i-1234567890abcdef0"
+ mock_metadata.availability_zone = "us-east-1a"
+
+ main(["json", "instance-id", "availability-zone"])
+
+ out, err = capsys.readouterr()
+ # fmt: off
+ assert out == (
+ "{\n"
+ ' "instance-id": "i-1234567890abcdef0",\n'
+ ' "availability-zone": "us-east-1a"\n'
+ "}\n"
+ )
+ # fmt: on
+ assert err == ""
diff --git a/tests/test_ec2_metadata.py b/tests/test_ec2_metadata.py
new file mode 100644
--- /dev/null
+++ b/tests/test_ec2_metadata.py
@@ -0,0 +1,840 @@
+from __future__ import annotations
+
+import datetime as dt
+import json
+from collections.abc import Generator
+from io import BytesIO
+from typing import Any
+from unittest import mock
+
+import pytest
+import urllib3
+from urllib3 import HTTPResponse
+from urllib3.exceptions import HTTPError
+
+from ec2_metadata import (
+ EC2Metadata,
+ InstanceIdentityDocumentDict,
+ NetworkInterface,
+ PublicKey,
+ ec2_metadata,
+)
+
+
+@pytest.fixture(autouse=True)
+def clear_it():
+ ec2_metadata.clear_all()
+
+
+def make_response(*, status: int = 200, body: bytes = b"") -> HTTPResponse:
+ return HTTPResponse(status=status, body=BytesIO(body))
+
+
+@pytest.fixture(autouse=True)
+def mock_pool(monkeypatch: pytest.MonkeyPatch) -> Generator[mock.Mock]:
+ mock_pm = mock.Mock(spec=urllib3.PoolManager)
+ responses: dict[tuple[str, str], HTTPResponse] = {}
+
+ def request_side_effect(method: str, url: str, **kwargs: Any) -> HTTPResponse:
+ return responses[(method, url)]
+
+ mock_pm.request.side_effect = request_side_effect
+ mock_pm._responses = responses
+
+ token_resp = make_response(body=b"example-token")
+ responses[("PUT", "http://169.254.169.254/latest/api/token")] = token_resp
+
+ monkeypatch.setattr(ec2_metadata, "_pool_manager", mock_pm)
+ yield mock_pm
+
+
+example_mac = "00:11:22:33:44:55"
+example_public_key = "ssh-rsa AAAAblahblahblah= exampleuser@examplehost\n"
+
+# EC2Metadata tests
+
+
+def test_custom_session(mock_pool):
+ EC2Metadata(pool_manager=urllib3.PoolManager())
+ mock_pool._responses[("GET", "http://169.254.169.254/latest/meta-data/ami-id")] = (
+ make_response(body=b"ami-12345678")
+ )
+ assert ec2_metadata.ami_id == "ami-12345678"
+
+
+def add_identity_doc_response(
+ mock_pool: mock.Mock,
+ account_id: str = "123456789012",
+ region: str = "eu-west-1",
+) -> InstanceIdentityDocumentDict:
+ identity_doc: InstanceIdentityDocumentDict = {
+ "accountId": account_id,
+ "architecture": "x86_64",
+ "availabilityZone": "eu-west-1a",
+ "billingProducts": None,
+ "imageId": "ami-12345678",
+ "instanceId": "i-12345678",
+ "instanceType": "t2.nano",
+ "kernelId": None,
+ "marketplaceProductCodes": None,
+ "pendingTime": "2022-08-12T10:22:28Z",
+ "privateIp": "172.30.0.0",
+ "ramdiskId": None,
+ "region": region,
+ "version": "2010-08-31",
+ }
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/dynamic/instance-identity/document")
+ ] = HTTPResponse(body=json.dumps(identity_doc).encode())
+ return identity_doc
+
+
+def test_account_id(mock_pool):
+ add_identity_doc_response(mock_pool, account_id="1234")
+ assert ec2_metadata.account_id == "1234"
+
+
+def test_account_id_token_error(mock_pool):
+ mock_pool._responses[("PUT", "http://169.254.169.254/latest/api/token")] = (
+ HTTPResponse(status=500, body=b"")
+ )
+ with pytest.raises(HTTPError):
+ ec2_metadata.account_id # noqa: B018
+
+
+def test_account_id_error(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/dynamic/instance-identity/document")
+ ] = HTTPResponse(status=500, body=b"")
+ with pytest.raises(HTTPError):
+ ec2_metadata.account_id # noqa: B018
+
+
+def test_ami_id(mock_pool):
+ mock_pool._responses[("GET", "http://169.254.169.254/latest/meta-data/ami-id")] = (
+ make_response(body=b"ami-12345678")
+ )
+ assert ec2_metadata.ami_id == "ami-12345678"
+
+
+def test_ami_id_cached(mock_pool):
+ mock_pool._responses[("GET", "http://169.254.169.254/latest/meta-data/ami-id")] = (
+ make_response(body=b"ami-12345678")
+ )
+ ec2_metadata.ami_id # noqa: B018
+ mock_pool._responses[("GET", "http://169.254.169.254/latest/meta-data/ami-id")] = (
+ HTTPResponse(status=500, body=b"")
+ )
+ ec2_metadata.ami_id # noqa: B018 - no error
+
+
+def test_ami_id_cached_cleared(mock_pool):
+ mock_pool._responses[("GET", "http://169.254.169.254/latest/meta-data/ami-id")] = (
+ make_response(body=b"ami-12345678")
+ )
+ ec2_metadata.ami_id # noqa: B018
+
+ ec2_metadata.clear_all()
+ mock_pool._responses[("GET", "http://169.254.169.254/latest/meta-data/ami-id")] = (
+ HTTPResponse(status=500, body=b"")
+ )
+
+ with pytest.raises(HTTPError):
+ ec2_metadata.ami_id # noqa: B018
+
+
+def test_ami_launch_index(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/ami-launch-index")
+ ] = make_response(body=b"0")
+ assert ec2_metadata.ami_launch_index == 0
+
+
+def test_ami_manifest_path(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/ami-manifest-path")
+ ] = make_response(body=b"(unknown)")
+ assert ec2_metadata.ami_manifest_path == "(unknown)"
+
+
+def test_autoscaling_target_lifecycle_state_none(mock_pool):
+ mock_pool._responses[
+ (
+ "GET",
+ "http://169.254.169.254/latest/meta-data/autoscaling/target-lifecycle-state",
+ )
+ ] = HTTPResponse(status=404, body=b"")
+ assert ec2_metadata.autoscaling_target_lifecycle_state is None
+
+
+def test_autoscaling_target_lifecycle_state_in_service(mock_pool):
+ mock_pool._responses[
+ (
+ "GET",
+ "http://169.254.169.254/latest/meta-data/autoscaling/target-lifecycle-state",
+ )
+ ] = make_response(body=b"InService")
+ assert ec2_metadata.autoscaling_target_lifecycle_state == "InService"
+
+
+def test_availability_zone(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/placement/availability-zone")
+ ] = make_response(body=b"eu-west-1a")
+ assert ec2_metadata.availability_zone == "eu-west-1a"
+
+
+def test_availability_zone_id(mock_pool):
+ mock_pool._responses[
+ (
+ "GET",
+ "http://169.254.169.254/latest/meta-data/placement/availability-zone-id",
+ )
+ ] = make_response(body=b"use1-az6")
+ assert ec2_metadata.availability_zone_id == "use1-az6"
+
+
+def test_availability_zone_id_none(mock_pool):
+ mock_pool._responses[
+ (
+ "GET",
+ "http://169.254.169.254/latest/meta-data/placement/availability-zone-id",
+ )
+ ] = HTTPResponse(status=404, body=b"")
+ assert ec2_metadata.availability_zone_id is None
+
+
+def test_domain(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/services/domain")
+ ] = make_response(body=b"amazonaws.com")
+ assert ec2_metadata.domain == "amazonaws.com"
+
+
+def test_iam_info(mock_pool):
+ result = {
+ "InstanceProfileArn": "arn:foobar/myInstanceProfile",
+ "InstanceProfileId": "some-id",
+ "LastUpdated": "2022-08-12T10:22:29Z",
+ }
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/iam/info")
+ ] = make_response(body=json.dumps(result).encode())
+ assert ec2_metadata.iam_info == result
+
+
+def test_iam_info_none(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/iam/info")
+ ] = HTTPResponse(status=404, body=b"")
+ assert ec2_metadata.iam_info is None
+
+
+def test_iam_info_unexpected(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/iam/info")
+ ] = HTTPResponse(status=500, body=b"")
+ with pytest.raises(HTTPError):
+ ec2_metadata.iam_info # noqa: B018
+
+
+def test_iam_security_credentials(mock_pool):
+ profile = "myInstanceProfile"
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/iam/info")
+ ] = HTTPResponse(
+ status=200,
+ body=json.dumps({"InstanceProfileArn": f"arn:foobar/{profile}"}).encode(),
+ )
+ result = {
+ "LastUpdated": "2022-08-12T10:48:52Z",
+ "Type": "AWS-HMAC",
+ "AccessKeyId": "some-access-key-id",
+ "SecretAccessKey": "some-secret-access-key",
+ "Token": "some-token",
+ "Expiration": "2022-08-12T17:03:05Z",
+ }
+ mock_pool._responses[
+ (
+ "GET",
+ f"http://169.254.169.254/latest/meta-data/iam/security-credentials/{profile}",
+ )
+ ] = make_response(body=json.dumps(result).encode())
+ assert ec2_metadata.iam_security_credentials == result
+
+
+def test_iam_security_credentials_none(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/iam/info")
+ ] = HTTPResponse(status=404, body=b"")
+ assert ec2_metadata.iam_security_credentials is None
+
+
+def test_instance_action(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/instance-action")
+ ] = make_response(body=b"none")
+ assert ec2_metadata.instance_action == "none"
+
+
+def test_instance_id(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/instance-id")
+ ] = make_response(body=b"i-12345678")
+ assert ec2_metadata.instance_id == "i-12345678"
+
+
+def test_instance_identity(mock_pool):
+ identity_doc = add_identity_doc_response(mock_pool)
+ assert ec2_metadata.instance_identity_document == identity_doc
+
+
+def test_instance_life_cycle(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/instance-life-cycle")
+ ] = make_response(body=b"on-demand")
+ assert ec2_metadata.instance_life_cycle == "on-demand"
+
+
+def test_instance_profile_arn(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/iam/info")
+ ] = HTTPResponse(
+ status=200,
+ body=b'{"InstanceProfileArn": "arn:foobar/myInstanceProfile"}',
+ )
+ assert ec2_metadata.instance_profile_arn == "arn:foobar/myInstanceProfile"
+
+
+def test_instance_profile_arn_none(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/iam/info")
+ ] = HTTPResponse(status=404, body=b"")
+ assert ec2_metadata.instance_profile_arn is None
+
+
+def test_instance_profile_id(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/iam/info")
+ ] = HTTPResponse(
+ status=200,
+ body=b'{"InstanceProfileId": "some-id"}',
+ )
+ assert ec2_metadata.instance_profile_id == "some-id"
+
+
+def test_instance_profile_id_none(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/iam/info")
+ ] = HTTPResponse(status=404, body=b"")
+ assert ec2_metadata.instance_profile_id is None
+
+
+def test_instance_profile_name(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/iam/info")
+ ] = HTTPResponse(
+ status=200,
+ body=b'{"InstanceProfileArn": "arn:foobar/myInstanceProfile"}',
+ )
+ assert ec2_metadata.instance_profile_name == "myInstanceProfile"
+
+
+def test_instance_type(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/instance-type")
+ ] = make_response(body=b"t2.nano")
+ assert ec2_metadata.instance_type == "t2.nano"
+
+
+def test_kernel_id(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/kernel-id")
+ ] = make_response(body=b"aki-dc9ed9af")
+ assert ec2_metadata.kernel_id == "aki-dc9ed9af"
+
+
+def test_kernel_id_none(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/kernel-id")
+ ] = HTTPResponse(status=404, body=b"")
+ assert ec2_metadata.kernel_id is None
+
+
+def test_mac(mock_pool):
+ mock_pool._responses[("GET", "http://169.254.169.254/latest/meta-data/mac")] = (
+ make_response(body=example_mac.encode())
+ )
+ assert ec2_metadata.mac == example_mac
+
+
+def test_network_interfaces(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/network/interfaces/macs/")
+ ] = make_response(body=f"{example_mac}/".encode())
+ assert ec2_metadata.network_interfaces == {
+ example_mac: NetworkInterface(example_mac, ec2_metadata)
+ }
+
+
+def test_partition(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/services/partition")
+ ] = make_response(body=b"aws")
+ assert ec2_metadata.partition == "aws"
+
+
+def test_private_hostname(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/local-hostname")
+ ] = HTTPResponse(
+ status=200,
+ body=b"ip-172-30-0-0.eu-west-1.compute.internal",
+ )
+ assert ec2_metadata.private_hostname == "ip-172-30-0-0.eu-west-1.compute.internal"
+
+
+def test_private_ipv4(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/local-ipv4")
+ ] = make_response(body=b"172.30.0.0")
+ assert ec2_metadata.private_ipv4 == "172.30.0.0"
+
+
+def test_public_hostname(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/public-hostname")
+ ] = HTTPResponse(
+ status=200,
+ body=b"ec2-1-2-3-4.compute-1.amazonaws.com",
+ )
+ assert ec2_metadata.public_hostname == "ec2-1-2-3-4.compute-1.amazonaws.com"
+
+
+def test_public_hostname_none(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/public-hostname")
+ ] = HTTPResponse(status=404, body=b"")
+ assert ec2_metadata.public_hostname is None
+
+
+def test_public_ipv4(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/public-ipv4")
+ ] = make_response(body=b"1.2.3.4")
+ assert ec2_metadata.public_ipv4 == "1.2.3.4"
+
+
+def test_public_ipv4_none(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/public-ipv4")
+ ] = HTTPResponse(status=404, body=b"")
+ assert ec2_metadata.public_ipv4 is None
+
+
+def test_public_keys(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/public-keys/")
+ ] = make_response(body=b"0=somekey")
+ assert ec2_metadata.public_keys == {"somekey": PublicKey(0, ec2_metadata)}
+
+
+def test_public_keys_none(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/public-keys/")
+ ] = HTTPResponse(status=404, body=b"")
+ assert ec2_metadata.public_keys == {}
+
+
+def test_region(mock_pool):
+ add_identity_doc_response(mock_pool, region="eu-whatever-1")
+ assert ec2_metadata.region == "eu-whatever-1"
+
+
+def test_reservation_id(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/reservation-id")
+ ] = make_response(body=b"r-12345678901234567")
+ assert ec2_metadata.reservation_id == "r-12345678901234567"
+
+
+def test_security_groups_single(mock_pool):
+ # most common case: a single SG
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/security-groups")
+ ] = make_response(body=b"security-group-one")
+ assert ec2_metadata.security_groups == ["security-group-one"]
+
+
+def test_security_groups_two(mock_pool):
+ # another common case: multiple SGs
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/security-groups")
+ ] = HTTPResponse(
+ status=200,
+ body=b"security-group-one\nsecurity-group-2",
+ )
+ assert ec2_metadata.security_groups == ["security-group-one", "security-group-2"]
+
+
+def test_security_groups_emptystring(mock_pool):
+ # Check '' too. Can't create an instance without a SG on EC2 but we should
+ # safely handle it, perhaps it's possible in e.g. OpenStack.
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/security-groups")
+ ] = make_response(body=b"")
+ assert ec2_metadata.security_groups == []
+
+
+def test_spot_instance_action_none(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/spot/instance-action")
+ ] = HTTPResponse(status=404, body=b"")
+ assert ec2_metadata.spot_instance_action is None
+
+
+def test_spot_instance_action(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/spot/instance-action")
+ ] = HTTPResponse(
+ status=200,
+ body=b'{"action": "stop", "time": "2017-09-18T08:22:00Z"}',
+ )
+ sia = ec2_metadata.spot_instance_action
+ assert sia is not None
+ assert sia.action == "stop"
+ assert sia.time == dt.datetime(2017, 9, 18, 8, 22, 0, tzinfo=dt.timezone.utc)
+
+
+def test_tags_not_enabled(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/tags/instance/")
+ ] = HTTPResponse(status=404, body=b"")
+ with pytest.raises(HTTPError):
+ ec2_metadata.tags # noqa: B018
+
+
+def test_tags_empty(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/tags/instance/")
+ ] = make_response(body=b"")
+ assert dict(ec2_metadata.tags) == {}
+
+
+def test_tags_one(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/tags/instance/")
+ ] = make_response(body=b"Name")
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/tags/instance/Name")
+ ] = make_response(body=b"test-instance")
+
+ assert dict(ec2_metadata.tags) == {"Name": "test-instance"}
+
+
+def test_tags_multiple(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/tags/instance/")
+ ] = make_response(body=b"Name\ncustom-tag")
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/tags/instance/Name")
+ ] = make_response(body=b"test-instance")
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/tags/instance/custom-tag")
+ ] = make_response(body=b"custom-value")
+
+ assert dict(ec2_metadata.tags) == {
+ "Name": "test-instance",
+ "custom-tag": "custom-value",
+ }
+
+
+def test_tags_repeat_access(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/tags/instance/")
+ ] = make_response(body=b"Name")
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/tags/instance/Name")
+ ] = make_response(body=b"test-instance")
+
+ ec2_metadata.tags["Name"]
+ ec2_metadata.tags["Name"]
+
+ # 3 requests: api/token, tags/instance, tags/instance/Name
+ assert mock_pool.request.call_count == 3
+
+
+def test_tags_iter(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/tags/instance/")
+ ] = make_response(body=b"Name")
+
+ assert list(iter(ec2_metadata.tags)) == ["Name"]
+
+
+def test_tags_len(mock_pool):
+ mock_pool._responses[
+ ("GET", "http://169.254.169.254/latest/meta-data/tags/instance/")
+ ] = make_response(body=b"Name\ncustom-tag")
+
+ assert len(ec2_metadata.tags) == 2
+
+
+def test_user_data_none(mock_pool):
+ mock_pool._responses[("GET", "http://169.254.169.254/latest/user-data/")] = (
+ HTTPResponse(status=404, body=b"")
+ )
+ assert ec2_metadata.user_data is None
+
+
+def test_user_data_something(mock_pool):
+ mock_pool._responses[("GET", "http://169.254.169.254/latest/user-data/")] = (
+ make_response(body=b"foobar")
+ )
+ assert ec2_metadata.user_data == b"foobar"
+
+
+# NetworkInterface tests
+
+
+def add_interface_response(
+ mock_pool: mock.Mock, url: str, text: str = "", status: int = 200, **kwargs: Any
+) -> None:
+ full_url = f"http://169.254.169.254/latest/meta-data/network/interfaces/macs/{example_mac}{url}"
+ mock_pool._responses[("GET", full_url)] = make_response(
+ status=status, body=text.encode()
+ )
+
+
+def test_network_interface_equal():
+ assert NetworkInterface("a") == NetworkInterface("a")
+
+
+def test_network_interface_not_equal():
+ assert NetworkInterface("a") != NetworkInterface("b")
+
+
+def test_network_interface_not_equal_class():
+ assert NetworkInterface("a") != "a"
+
+
+def test_network_interface_repr():
+ assert "'abc'" in repr(NetworkInterface("abc"))
+
+
+def test_network_interface_device_number(mock_pool):
+ add_interface_response(mock_pool, "/device-number", "0")
+ assert NetworkInterface(example_mac).device_number == 0
+
+
+def test_network_interface_interface_id(mock_pool):
+ add_interface_response(mock_pool, "/interface-id", "eni-12345")
+ assert NetworkInterface(example_mac).interface_id == "eni-12345"
+
+
+def test_network_interface_ipv4_associations(mock_pool):
+ add_interface_response(mock_pool, "/public-ipv4s", "54.0.0.0\n54.0.0.1")
+ add_interface_response(mock_pool, "/ipv4-associations/54.0.0.0", "172.30.0.0")
+ add_interface_response(mock_pool, "/ipv4-associations/54.0.0.1", "172.30.0.1")
+ assert NetworkInterface(example_mac).ipv4_associations == {
+ "54.0.0.0": ["172.30.0.0"],
+ "54.0.0.1": ["172.30.0.1"],
+ }
+
+
+def test_network_interface_ipv6s(mock_pool):
+ add_interface_response(
+ mock_pool,
+ "/ipv6s",
+ "2001:db8:abcd:ef00:cbe5:798:aa26:169b\n2001:db8:abcd:ef00::f",
+ )
+ assert NetworkInterface(example_mac).ipv6s == [
+ "2001:db8:abcd:ef00:cbe5:798:aa26:169b",
+ "2001:db8:abcd:ef00::f",
+ ]
+
+
+def test_network_interface_ipv6s_none(mock_pool):
+ add_interface_response(mock_pool, "/ipv6s", status=404)
+ assert NetworkInterface(example_mac).ipv6s == []
+
+
+def test_network_interface_ipv6_prefix(mock_pool):
+ add_interface_response(
+ mock_pool,
+ "/ipv6-prefix",
+ "2001:db8:abcd:ef00:cbe5:::/80\n2001:db8:abcd:ef00:cbe6:::/80",
+ )
+ assert NetworkInterface(example_mac).ipv6_prefix == [
+ "2001:db8:abcd:ef00:cbe5:::/80",
+ "2001:db8:abcd:ef00:cbe6:::/80",
+ ]
+
+
+def test_network_interface_ipv6_prefix_none(mock_pool):
+ add_interface_response(mock_pool, "/ipv6-prefix", status=404)
+ assert NetworkInterface(example_mac).ipv6_prefix == []
+
+
+def test_network_interface_owner_id(mock_pool):
+ add_interface_response(mock_pool, "/owner-id", "123456789012")
+ assert NetworkInterface(example_mac).owner_id == "123456789012"
+
+
+def test_network_interface_private_hostname(mock_pool):
+ add_interface_response(
+ mock_pool, "/local-hostname", "ip-172-30-0-0.eu-west-1.compute.internal"
+ )
+ assert (
+ NetworkInterface(example_mac).private_hostname
+ == "ip-172-30-0-0.eu-west-1.compute.internal"
+ )
+
+
+def test_network_interface_private_ipv4s(mock_pool):
+ add_interface_response(mock_pool, "/local-ipv4s", "172.30.0.0\n172.30.0.1")
+ assert NetworkInterface(example_mac).private_ipv4s == ["172.30.0.0", "172.30.0.1"]
+
+
+def test_network_interface_public_hostname(mock_pool):
+ add_interface_response(mock_pool, "/public-hostname", "")
+ assert NetworkInterface(example_mac).public_hostname == ""
+
+
+def test_network_interface_public_hostname_none(mock_pool):
+ add_interface_response(mock_pool, "/public-hostname", status=404)
+ assert NetworkInterface(example_mac).public_hostname is None
+
+
+def test_network_interface_public_ipv4s(mock_pool):
+ add_interface_response(mock_pool, "/public-ipv4s", "54.0.0.0\n54.0.0.1")
+ assert NetworkInterface(example_mac).public_ipv4s == ["54.0.0.0", "54.0.0.1"]
+
+
+def test_network_interface_public_ipv4s_empty(mock_pool):
+ add_interface_response(mock_pool, "/public-ipv4s", status=404)
+ assert NetworkInterface(example_mac).public_ipv4s == []
+
+
+def test_network_interface_security_groups(mock_pool):
+ add_interface_response(mock_pool, "/security-groups", "foo\nbar")
+ assert NetworkInterface(example_mac).security_groups == ["foo", "bar"]
+
+
+def test_network_interface_security_group_ids(mock_pool):
+ add_interface_response(mock_pool, "/security-group-ids", "sg-12345678\nsg-12345679")
+ assert NetworkInterface(example_mac).security_group_ids == [
+ "sg-12345678",
+ "sg-12345679",
+ ]
+
+
+def test_network_interface_subnet_id(mock_pool):
+ add_interface_response(mock_pool, "/subnet-id", "subnet-12345678")
+ assert NetworkInterface(example_mac).subnet_id == "subnet-12345678"
+
+
+def test_network_interface_subnet_ipv4_cidr_block(mock_pool):
+ add_interface_response(mock_pool, "/subnet-ipv4-cidr-block", "172.30.0.0/24")
+ assert NetworkInterface(example_mac).subnet_ipv4_cidr_block == "172.30.0.0/24"
+
+
+def test_network_interface_subnet_ipv4_cidr_block_none(mock_pool):
+ add_interface_response(mock_pool, "/subnet-ipv4-cidr-block", status=404)
+ assert NetworkInterface(example_mac).subnet_ipv4_cidr_block is None
+
+
+def test_network_interface_subnet_ipv6_cidr_blocks(mock_pool):
+ add_interface_response(
+ mock_pool, "/subnet-ipv6-cidr-blocks", "2001:db8:abcd:ef00::/64"
+ )
+ assert NetworkInterface(example_mac).subnet_ipv6_cidr_blocks == [
+ "2001:db8:abcd:ef00::/64"
+ ]
+
+
+def test_network_interface_subnet_ipv6_cidr_blocks_none(mock_pool):
+ add_interface_response(mock_pool, "/subnet-ipv6-cidr-blocks", status=404)
+ assert NetworkInterface(example_mac).subnet_ipv6_cidr_blocks == []
+
+
+def test_network_interface_vpc_id(mock_pool):
+ add_interface_response(mock_pool, "/vpc-id", "vpc-12345678")
+ assert NetworkInterface(example_mac).vpc_id == "vpc-12345678"
+
+
+def test_network_interface_vpc_ipv4_cidr_block(mock_pool):
+ add_interface_response(mock_pool, "/vpc-ipv4-cidr-block", "172.30.0.0/16")
+ assert NetworkInterface(example_mac).vpc_ipv4_cidr_block == "172.30.0.0/16"
+
+
+def test_network_interface_vpc_ipv4_cidr_block_none(mock_pool):
+ add_interface_response(mock_pool, "/vpc-ipv4-cidr-block", status=404)
+ assert NetworkInterface(example_mac).vpc_ipv4_cidr_block is None
+
+
+def test_network_interface_vpc_ipv4_cidr_blocks(mock_pool):
+ add_interface_response(mock_pool, "/vpc-ipv4-cidr-blocks", "172.30.0.0/16")
+ assert NetworkInterface(example_mac).vpc_ipv4_cidr_blocks == ["172.30.0.0/16"]
+
+
+def test_network_interface_vpc_ipv4_cidr_blocks_none(mock_pool):
+ add_interface_response(mock_pool, "/vpc-ipv4-cidr-blocks", status=404)
+ assert NetworkInterface(example_mac).vpc_ipv4_cidr_blocks == []
+
+
+def test_network_interface_vpc_ipv6_cidr_blocks(mock_pool):
+ add_interface_response(
+ mock_pool, "/vpc-ipv6-cidr-blocks", "2001:db8:abcd:ef00::/56"
+ )
+ assert NetworkInterface(example_mac).vpc_ipv6_cidr_blocks == [
+ "2001:db8:abcd:ef00::/56"
+ ]
+
+
+def test_network_interface_vpc_ipv6_cidr_blocks_none(mock_pool):
+ add_interface_response(mock_pool, "/vpc-ipv6-cidr-blocks", status=404)
+ assert NetworkInterface(example_mac).vpc_ipv6_cidr_blocks == []
+
+
+# PublicKey tests
+
+
+def add_key_response(
+ mock_pool: mock.Mock,
+ index: int,
+ url: str,
+ text: str = "",
+ status: int = 200,
+ **kwargs: Any,
+) -> None:
+ full_url = f"http://169.254.169.254/latest/meta-data/public-keys/{index}{url}"
+ mock_pool._responses[("GET", full_url)] = make_response(
+ status=status, body=text.encode()
+ )
+
+
+def test_public_key_equal():
+ assert PublicKey(0) == PublicKey(0)
+
+
+def test_public_key_not_equal():
+ assert PublicKey(0) != PublicKey(1)
+
+
+def test_public_key_not_equal_class():
+ assert PublicKey(0) != 0
+
+
+def test_public_key_repr():
+ assert "0" in repr(PublicKey(0))
+
+
+def test_public_key_openssh_key(mock_pool):
+ add_key_response(mock_pool, 0, "/openssh-key", example_public_key)
+ assert PublicKey(0).openssh_key == example_public_key
+
+
+def test_public_key_openssh_key_none(mock_pool):
+ add_key_response(mock_pool, 0, "/openssh-key", status=404)
+ assert PublicKey(0).openssh_key is None
|