Debian Codegraph @

ansible_collections/amazon/aws/tests/unit/utils/amazon_placebo_fixtures.py

raw
1 from __future__ import absolute_import
2 from __future__ import division
3 from __future__ import print_function
4
5 __metaclass__ = type
6
7 import errno
8 import os
9
10 import mock
11 import pytest
12
13 boto3 = pytest.importorskip("boto3")
14 botocore = pytest.importorskip("botocore")
15 placebo = pytest.importorskip("placebo")
16
17 """
18 Using Placebo to test modules using boto3:
19
20 This is an example test, using the placeboify fixture to test that a module
21 will fail if resources it depends on don't exist.
22
23 > from placebo_fixtures import placeboify, scratch_vpc
24 >
25 > def test_create_with_nonexistent_launch_config(placeboify):
26 > connection = placeboify.client('autoscaling')
27 > module = FakeModule('test-asg-created', None, min_size=0, max_size=0, desired_capacity=0)
28 > with pytest.raises(FailJSON) as excinfo:
29 > asg_module.create_autoscaling_group(connection, module)
30 > .... asserts based on module state/exceptions ....
31 """
32
33
34 @pytest.fixture(name="placeboify")
35 def fixture_placeboify(request, monkeypatch):
36 """This fixture puts a recording/replaying harness around `boto3_conn`
37
38 Placeboify patches the `boto3_conn` function in ec2 module_utils to return
39 a boto3 session that in recording or replaying mode, depending on the
40 PLACEBO_RECORD environment variable. Unset PLACEBO_RECORD (the common case
41 for just running tests) will put placebo in replay mode, set PLACEBO_RECORD
42 to any value to turn off replay & operate on real AWS resources.
43
44 The recorded sessions are stored in the test file's directory, under the
45 namespace `placebo_recordings/{testfile name}/{test function name}` to
46 distinguish them.
47 """
48 session = boto3.Session(
49 region_name="us-west-2", aws_access_key_id="EXAMPLE_KEY", aws_secret_access_key="EXAMPLE_SECRET"
50 )
51
52 recordings_path = os.path.join(
53 request.fspath.dirname,
54 "placebo_recordings",
55 request.fspath.basename.replace(".py", ""),
56 request.function.__name__,
57 # remove the test_ prefix from the function & file name
58 ).replace("test_", "")
59
60 if not os.getenv("PLACEBO_RECORD"):
61 if not os.path.isdir(recordings_path):
62 raise NotImplementedError(f"Missing Placebo recordings in directory: {recordings_path}")
63 else:
64 try:
65 # make sure the directory for placebo test recordings is available
66 os.makedirs(recordings_path)
67 except OSError as e:
68 if e.errno != errno.EEXIST:
69 raise
70
71 pill = placebo.attach(session, data_path=recordings_path)
72 if os.getenv("PLACEBO_RECORD"):
73 pill.record()
74 else:
75 pill.playback()
76
77 def boto3_middleman_connection(module, conn_type, resource, region="us-west-2", **kwargs):
78 if conn_type != "client":
79 # TODO support resource-based connections
80 raise ValueError(f"Mocker only supports client, not {conn_type}")
81 return session.client(resource, region_name=region)
82
83 import ansible_collections.amazon.aws.plugins.module_utils.ec2
84
85 monkeypatch.setattr(
86 ansible_collections.amazon.aws.plugins.module_utils.ec2,
87 "boto3_conn",
88 boto3_middleman_connection,
89 )
90 yield session
91
92 # tear down
93 pill.stop()
94
95
96 @pytest.fixture(scope="module", name="maybe_sleep")
97 def fixture_maybe_sleep():
98 """If placebo is reading saved sessions, make sleep always take 0 seconds.
99
100 AWS modules often perform polling or retries, but when using recorded
101 sessions there's no reason to wait. We can still exercise retry and other
102 code paths without waiting for wall-clock time to pass."""
103 if not os.getenv("PLACEBO_RECORD"):
104 p = mock.patch("time.sleep", return_value=None)
105 p.start()
106 yield
107 p.stop()
108 else:
109 yield