/
test_context.py
285 lines (237 loc) · 11.3 KB
/
test_context.py
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
"""Tests for context module."""
# pylint: disable=protected-access,no-self-use
import logging
import os
import boto3
import pytest
from botocore.stub import Stubber
from mock import patch
from runway.context import Context
from runway.util import environ
from .factories import MockBoto3Session
LOGGER = logging.getLogger('runway')
TEST_CREDENTIALS = {
'AWS_ACCESS_KEY_ID': 'foo',
'AWS_SECRET_ACCESS_KEY': 'bar',
'AWS_SESSION_TOKEN': 'foobar'
}
class TestContext(object):
"""Test Context class."""
def test_account_id(self, monkeypatch):
"""Test account_id."""
account_id = '123456789012'
client = boto3.client('sts')
stubber = Stubber(client)
mock_session = MockBoto3Session(clients={'sts.us-east-1': client},
region_name='us-east-1')
monkeypatch.setattr(Context, 'get_session', lambda self_: mock_session)
context = Context(env_name='test',
env_region='us-east-1',
env_root='./',
env_vars={})
stubber.add_response(method='get_caller_identity',
service_response={'UserId': 'test-user',
'Account': account_id,
'Arn': 'arn:aws:iam::{}:'
'user/test-user'
.format(account_id)})
with stubber as stub:
assert context.account_id == account_id
stub.assert_no_pending_responses()
def test_boto3_credentials(self):
"""Test boto3_credentials."""
context = Context(env_name='test',
env_region='us-east-1',
env_root='./',
env_vars=TEST_CREDENTIALS.copy())
assert context.boto3_credentials == {key.lower(): value
for key, value in
TEST_CREDENTIALS.items()}
def test_current_aws_creds(self):
"""Test current_aws_creds."""
context = Context(env_name='test',
env_region='us-east-1',
env_root='./',
env_vars=TEST_CREDENTIALS.copy())
assert context.current_aws_creds == TEST_CREDENTIALS
@pytest.mark.parametrize('colorize, isatty, expected', [
(None, True, False),
(None, False, True),
(True, False, False),
(False, True, True),
('true', False, False),
('false', True, True),
(ValueError, True, False),
(ValueError, False, True)
])
@patch('runway.context.sys.stdout')
def test_no_color(self, mock_stdout, colorize, isatty, expected):
"""Test no_color."""
mock_stdout.isatty.return_value = isatty
env_vars = {}
if colorize is not None:
env_vars['RUNWAY_COLORIZE'] = colorize
ctx = Context('test', 'us-east-1', './tests', env_vars=env_vars)
assert ctx.no_color == expected
def test_is_interactive(self):
"""Test is_interactive."""
context = Context(env_name='test',
env_region='us-east-1',
env_root='./',
env_vars={'NON_EMPTY': '1'})
assert context.is_interactive
context.env_vars['CI'] = '1'
assert not context.is_interactive
def test_is_noninteractive(self):
"""Test is_noninteractive."""
context = Context(env_name='test',
env_region='us-east-1',
env_root='./',
env_vars={'NON_EMPTY': '1'})
assert not context.is_noninteractive
context.env_vars['CI'] = '1'
assert context.is_noninteractive
def test_is_python3(self):
"""Test is_python3."""
from runway.context import sys
context = Context(env_name='test',
env_region='us-east-1',
env_root='./')
with patch.object(sys, 'version_info') as version_info:
version_info.major = 2
assert not context.is_python3
with patch.object(sys, 'version_info') as version_info:
version_info.major = 3
assert context.is_python3
def test_max_concurrent_cfngin_stacks(self):
"""Test max_concurrent_cfngin_stacks."""
context = Context(env_name='test',
env_region='us-east-1',
env_root='./')
assert context.max_concurrent_cfngin_stacks == 0
context.env_vars['RUNWAY_MAX_CONCURRENT_CFNGIN_STACKS'] = '1'
assert context.max_concurrent_cfngin_stacks == 1
def test_max_concurrent_modules(self):
"""Test max_concurrent_modules."""
context = Context(env_name='test',
env_region='us-east-1',
env_root='./',
env_vars={'RUNWAY_MAX_CONCURRENT_MODULES': '1'})
assert context.max_concurrent_modules == 1
del context.env_vars['RUNWAY_MAX_CONCURRENT_MODULES']
with patch('runway.context.multiprocessing.cpu_count') as cpu_count:
cpu_count.return_value = 8
assert context.max_concurrent_modules == 8
def test_max_concurrent_regions(self):
"""Test max_concurrent_regions."""
context = Context(env_name='test',
env_region='us-east-1',
env_root='./',
env_vars={'RUNWAY_MAX_CONCURRENT_REGIONS': '1'})
assert context.max_concurrent_regions == 1
del context.env_vars['RUNWAY_MAX_CONCURRENT_REGIONS']
with patch('runway.context.multiprocessing.cpu_count') as cpu_count:
cpu_count.return_value = 8
assert context.max_concurrent_regions == 8
def test_use_concurrent(self):
"""Test use_concurrent."""
from runway.context import sys
context = Context(env_name='test',
env_region='us-east-1',
env_root='./',
env_vars={'NON_EMPTY': '1'})
context_ci = Context(env_name='test',
env_region='us-east-1',
env_root='./',
env_vars={'CI': '1'})
with patch.object(sys, 'version_info') as version_info:
version_info.major = 2
assert not context.use_concurrent
assert not context_ci.use_concurrent
with patch.object(sys, 'version_info') as version_info:
version_info.major = 3
assert not context.use_concurrent
assert context_ci.use_concurrent
def test_init_name_from_arg(self):
"""_env_name_from_env should be false when DEPLOY_ENVIRONMENT not set."""
context = Context(env_name='test', env_region='us-east-1',
env_root='./')
assert context.env_name == 'test'
assert context.env_vars['DEPLOY_ENVIRONMENT'] == context.env_name, \
'env_vars.DEPLOY_ENVIRONMENT should be set from env_name'
assert not context._env_name_from_env, \
'should be false when env_name was not derived from env_var'
def test_init_from_envvar(self):
"""_env_name_from_env should be true when DEPLOY_ENVIRONMENT is set."""
context = Context(env_name='test', env_region='us-east-1',
env_root='./', env_vars={'DEPLOY_ENVIRONMENT': 'test'})
assert context.env_name == 'test'
assert context.env_vars['DEPLOY_ENVIRONMENT'] == context.env_name, \
'env_vars.DEPLOY_ENVIRONMENT should be set from env_name'
assert context._env_name_from_env, \
'should be true when env_name was not derived from env_var'
def test_echo_detected_environment_not_env(self, caplog):
"""Environment helper note when DEPLOY_ENVIRONMENT is not set."""
context = Context(env_name='test', env_region='us-east-1',
env_root='./')
expected = ['',
'Environment "test" was determined from the '
'current git branch or parent directory.',
'If this is not the environment name, update '
'the branch/folder name or set an override value via the '
'DEPLOY_ENVIRONMENT environment variable',
'']
with caplog.at_level(logging.INFO):
context.echo_detected_environment()
assert [rec.message for rec in caplog.records] == expected
def test_echo_detected_environment_from_env(self, caplog):
"""Environment helper note when DEPLOY_ENVIRONMENT is set."""
context = Context(env_name='test', env_region='us-east-1',
env_root='./', env_vars={'DEPLOY_ENVIRONMENT': 'test'})
expected = ['',
'Environment "test" was determined from the '
'DEPLOY_ENVIRONMENT environment variable.',
'If this is not correct, update the value (or '
'unset it to fall back to the name of the current git '
'branch or parent directory).',
'']
with caplog.at_level(logging.INFO):
context.echo_detected_environment()
assert [rec.message for rec in caplog.records] == expected
def test_save_existing_iam_env_vars(self):
"""Test save_existing_iam_env_vars."""
context = Context(env_name='dev', env_region='us-east-1',
env_root='./', env_vars=TEST_CREDENTIALS.copy())
context.save_existing_iam_env_vars()
assert context.env_vars['OLD_AWS_ACCESS_KEY_ID'] == 'foo'
assert context.env_vars['OLD_AWS_SECRET_ACCESS_KEY'] == 'bar'
assert context.env_vars['OLD_AWS_SESSION_TOKEN'] == 'foobar'
def test_init(self, tmp_path):
"""Test init process."""
env_name = 'test'
env_region = 'us-east-1'
env_root = str(tmp_path)
config_file = tmp_path / 'config'
config_file.write_text(u'[profile test]\n'
'aws_access_key_id = bar\n'
'aws_secret_access_key = foo')
with environ(dict(AWS_PROFILE='test', **TEST_CREDENTIALS)):
env_vars = os.environ.copy()
env_vars['DEPLOY_ENVIRONMENT'] = env_name
ctx = Context(env_name, env_region, env_root)
assert not ctx.command
assert not ctx.debug
assert ctx.env_name == env_name
assert ctx.env_region == env_region
assert ctx.env_root == env_root
assert sorted(ctx.env_vars) == sorted(env_vars)
with environ({'AWS_PROFILE': 'test', 'AWS_CONFIG_FILE': str(config_file)}):
os.environ.pop('AWS_ACCESS_KEY_ID', None)
os.environ.pop('AWS_SECRET_ACCESS_KEY', None)
os.environ.pop('AWS_SESSION_TOKEN', None)
env_vars = os.environ.copy()
env_vars['DEPLOY_ENVIRONMENT'] = env_name
ctx = Context(env_name, env_region, env_root)
assert ctx.env_vars != os.environ
assert ctx.env_vars['AWS_ACCESS_KEY_ID'] == 'bar'
assert ctx.env_vars['AWS_SECRET_ACCESS_KEY'] == 'foo'