File: test_sessionmanager.py

package info (click to toggle)
awscli 2.31.35-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 156,692 kB
  • sloc: python: 213,816; xml: 14,082; makefile: 189; sh: 178; javascript: 8
file content (430 lines) | stat: -rw-r--r-- 15,102 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
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import errno
import json
import subprocess

import botocore.session
import pytest

from awscli.customizations import sessionmanager
from awscli.testutils import mock, unittest


class TestSessionManager(unittest.TestCase):
    def setUp(self):
        self.session = mock.Mock(botocore.session.Session)
        self.client = mock.Mock()
        self.region = 'us-west-2'
        self.profile = 'testProfile'
        self.endpoint_url = 'testUrl'
        self.client.meta.region_name = self.region
        self.client.meta.endpoint_url = self.endpoint_url
        self.session.create_client.return_value = self.client
        self.session.profile = self.profile
        self.caller = sessionmanager.StartSessionCaller(self.session)

        self.parsed_globals = mock.Mock()
        self.parsed_globals.profile = 'user_profile'

    def test_start_session_when_non_custom_start_session_fails(self):
        self.client.start_session.side_effect = Exception('some exception')
        params = {}
        with self.assertRaisesRegex(Exception, 'some exception'):
            self.caller.invoke('ssm', 'StartSession', params, mock.Mock())

    @mock.patch("awscli.customizations.sessionmanager.check_output")
    @mock.patch('awscli.customizations.sessionmanager.check_call')
    def test_start_session_success_scenario(
        self, mock_check_call, mock_check_output
    ):
        mock_check_output.return_value = "1.2.0.0\n"
        mock_check_call.return_value = 0

        start_session_params = {"Target": "i-123456789"}

        start_session_response = {
            "SessionId": "session-id",
            "TokenValue": "token-value",
            "StreamUrl": "stream-url",
        }

        self.client.start_session.return_value = start_session_response

        rc = self.caller.invoke(
            'ssm', 'StartSession', start_session_params, self.parsed_globals
        )
        self.assertEqual(rc, 0)
        self.client.start_session.assert_called_with(**start_session_params)

        mock_check_output_list = mock_check_output.call_args[0]
        self.assertEqual(
            mock_check_output_list[0], ["session-manager-plugin", "--version"]
        )

        mock_check_call_list = mock_check_call.call_args[0][0]
        mock_check_call_list[1] = json.loads(mock_check_call_list[1])
        self.assertEqual(
            mock_check_call_list,
            [
                'session-manager-plugin',
                start_session_response,
                self.region,
                'StartSession',
                self.parsed_globals.profile,
                json.dumps(start_session_params),
                self.endpoint_url,
            ],
        )

    @mock.patch("awscli.customizations.sessionmanager.check_output")
    @mock.patch('awscli.customizations.sessionmanager.check_call')
    def test_start_session_when_check_call_fails(
        self, mock_check_call, mock_check_output
    ):
        mock_check_output.return_value = "1.2.0.0\n"
        mock_check_call.side_effect = OSError(errno.ENOENT, 'some error')

        start_session_params = {"Target": "i-123456789"}

        start_session_response = {
            "SessionId": "session-id",
            "TokenValue": "token-value",
            "StreamUrl": "stream-url",
        }

        terminate_session_params = {"SessionId": "session-id"}

        self.client.start_session.return_value = start_session_response

        with self.assertRaises(ValueError):
            self.caller.invoke(
                'ssm',
                'StartSession',
                start_session_params,
                self.parsed_globals,
            )

            self.client.start_session.assert_called_with(
                **start_session_params
            )
            self.client.terminate_session.assert_called_with(
                **terminate_session_params
            )

            mock_check_call_list = mock_check_call.call_args[0][0]
            mock_check_call_list[1] = json.loads(mock_check_call_list[1])
            self.assertEqual(
                mock_check_call_list,
                [
                    'session-manager-plugin',
                    start_session_response,
                    self.region,
                    'StartSession',
                    self.parsed_globals.profile,
                    json.dumps(start_session_params),
                    self.endpoint_url,
                ],
            )

    @mock.patch('awscli.customizations.sessionmanager.check_call')
    @mock.patch("awscli.customizations.sessionmanager.check_output")
    def test_start_session_when_no_profile_is_passed(
        self, mock_check_output, mock_check_call
    ):
        mock_check_output.return_value = "1.2.500.0\n"
        self.session.profile = "session_profile"
        self.parsed_globals.profile = None
        mock_check_call.return_value = 0

        start_session_params = {"Target": "i-123456789"}

        start_session_response = {
            "SessionId": "session-id",
            "TokenValue": "token-value",
            "StreamUrl": "stream-url",
        }
        ssm_env_name = "AWS_SSM_START_SESSION_RESPONSE"

        self.client.start_session.return_value = start_session_response

        rc = self.caller.invoke(
            'ssm', 'StartSession', start_session_params, self.parsed_globals
        )
        self.assertEqual(rc, 0)
        self.client.start_session.assert_called_with(**start_session_params)
        mock_check_call_list = mock_check_call.call_args[0][0]
        self.assertEqual(
            mock_check_call_list,
            [
                "session-manager-plugin",
                ssm_env_name,
                self.region,
                "StartSession",
                "",
                json.dumps(start_session_params),
                self.endpoint_url,
            ],
        )

    @mock.patch("awscli.customizations.sessionmanager.check_call")
    @mock.patch("awscli.customizations.sessionmanager.check_output")
    def test_start_session_with_env_variable_success_scenario(
        self, mock_check_output, mock_check_call
    ):
        mock_check_output.return_value = "1.2.500.0\n"
        mock_check_call.return_value = 0

        start_session_params = {"Target": "i-123456789"}

        start_session_response = {
            "SessionId": "session-id",
            "TokenValue": "token-value",
            "StreamUrl": "stream-url",
        }
        ssm_env_name = "AWS_SSM_START_SESSION_RESPONSE"

        self.client.start_session.return_value = start_session_response
        rc = self.caller.invoke(
            "ssm", "StartSession", start_session_params, self.parsed_globals
        )
        self.assertEqual(rc, 0)
        self.client.start_session.assert_called_with(**start_session_params)

        mock_check_output_list = mock_check_output.call_args[0]
        self.assertEqual(
            mock_check_output_list[0], ["session-manager-plugin", "--version"]
        )

        mock_check_call_list = mock_check_call.call_args[0][0]
        self.assertEqual(
            mock_check_call_list,
            [
                "session-manager-plugin",
                ssm_env_name,
                self.region,
                "StartSession",
                self.parsed_globals.profile,
                json.dumps(start_session_params),
                self.endpoint_url,
            ],
        )
        env_variable = mock_check_call.call_args[1]
        self.assertEqual(
            env_variable["env"][ssm_env_name],
            json.dumps(start_session_response),
        )

    @mock.patch("awscli.customizations.sessionmanager.check_call")
    @mock.patch("awscli.customizations.sessionmanager.check_output")
    def test_start_session_when_check_output_fails(
        self, mock_check_output, mock_check_call
    ):
        mock_check_output.side_effect = subprocess.CalledProcessError(
            returncode=1, cmd="session-manager-plugin", output="some error"
        )

        start_session_params = {"Target": "i-123456789"}
        start_session_response = {
            "SessionId": "session-id",
            "TokenValue": "token-value",
            "StreamUrl": "stream-url",
        }

        self.client.start_session.return_value = start_session_response
        with self.assertRaises(subprocess.CalledProcessError):
            self.caller.invoke(
                "ssm",
                "StartSession",
                start_session_params,
                self.parsed_globals,
            )

        self.client.start_session.assert_called_with(**start_session_params)
        self.client.terminate_session.assert_not_called()
        mock_check_output.assert_called_with(
            ["session-manager-plugin", "--version"], text=True
        )
        mock_check_call.assert_not_called()

    @mock.patch("awscli.customizations.sessionmanager.check_call")
    @mock.patch("awscli.customizations.sessionmanager.check_output")
    def test_start_session_when_response_not_json(
        self, mock_check_output, mock_check_call
    ):
        mock_check_output.return_value = "1.2.500.0\n"
        start_session_params = {"Target": "i-123456789"}
        start_session_response = {
            "SessionId": "session-id",
            "TokenValue": "token-value",
            "StreamUrl": "stream-url",
            "para2": {"Not a json format"},
        }
        expected_env_value = {
            "SessionId": "session-id",
            "TokenValue": "token-value",
            "StreamUrl": "stream-url",
        }

        ssm_env_name = "AWS_SSM_START_SESSION_RESPONSE"

        self.client.start_session.return_value = start_session_response
        rc = self.caller.invoke(
            "ssm", "StartSession", start_session_params, self.parsed_globals
        )
        self.assertEqual(rc, 0)
        self.client.start_session.assert_called_with(**start_session_params)

        mock_check_output_list = mock_check_output.call_args[0]
        self.assertEqual(
            mock_check_output_list[0], ["session-manager-plugin", "--version"]
        )

        mock_check_call_list = mock_check_call.call_args[0][0]
        self.assertEqual(
            mock_check_call_list,
            [
                "session-manager-plugin",
                ssm_env_name,
                self.region,
                "StartSession",
                self.parsed_globals.profile,
                json.dumps(start_session_params),
                self.endpoint_url,
            ],
        )
        env_variable = mock_check_call.call_args[1]
        self.assertEqual(
            env_variable["env"][ssm_env_name], json.dumps(expected_env_value)
        )

    @mock.patch("awscli.customizations.sessionmanager.check_call")
    @mock.patch("awscli.customizations.sessionmanager.check_output")
    def test_start_session_when_invalid_plugin_version(
        self, mock_check_output, mock_check_call
    ):
        mock_check_output.return_value = "InvalidVersion"

        start_session_params = {"Target": "i-123456789"}
        start_session_response = {
            "SessionId": "session-id",
            "TokenValue": "token-value",
            "StreamUrl": "stream-url",
        }

        self.client.start_session.return_value = start_session_response
        self.caller.invoke(
            "ssm", "StartSession", start_session_params, self.parsed_globals
        )
        self.client.start_session.assert_called_with(**start_session_params)
        self.client.terminate_session.assert_not_called()
        mock_check_output.assert_called_with(
            ["session-manager-plugin", "--version"], text=True
        )

        mock_check_call_list = mock_check_call.call_args[0][0]
        self.assertEqual(
            mock_check_call_list,
            [
                "session-manager-plugin",
                json.dumps(start_session_response),
                self.region,
                "StartSession",
                self.parsed_globals.profile,
                json.dumps(start_session_params),
                self.endpoint_url,
            ],
        )


class TestVersionRequirement:
    version_requirement = sessionmanager.VersionRequirement(
        min_version="1.2.497.0"
    )

    @pytest.mark.parametrize(
        "version, expected_result",
        [
            ("2.0.0.0", True),
            ("2.1", True),
            ("2", True),
            ("1.3.1.1", True),
            ("\r\n1. 3.1.1", True),
            ("1.3.1.0", True),
            ("1.3", True),
            ("1.2.498.1", True),
            ("1.2.498", True),
            ("1.2.497.1", True),
            ("1.2.497.0", False),
            ("1.2.497", False),
            ("1.2.1.1", False),
            ("1.2.1", False),
            ("1.2", False),
            ("1.1.1.0", False),
            ("1.1.1", False),
            ("1.0.497.0", False),
            ("1.0. 497.0\r\n", False),
            ("1", False),
            ("0.3.497.0", False),
        ],
    )
    def test_meets_requirement(self, version, expected_result):
        assert expected_result == self.version_requirement.meets_requirement(
            version
        )

    @pytest.mark.parametrize(
        "version, expected_result",
        [
            ("\r\n1.3.1.1", "1.3.1.1"),
            ("\r1.3 .1.1", "1.3.1.1"),
            ("1 .3.1.1", "1.3.1.1"),
            (" 1.3.1.1", "1.3.1.1"),
            ("1.3.1.1 ", "1.3.1.1"),
            (" 1.3.1.1 ", "1.3.1.1"),
            ("\n1.3.1.1 ", "1.3.1.1"),
            ("1.3.1.1\n", "1.3.1.1"),
            ("1.3\r\n.1.1", "1.3.1.1"),
            (" 1\r. 3", "1.3"),
            (" 1. 3. ", "1.3."),
            ("1.1.1\r\n", "1.1.1"),
            ("1\r", "1"),
        ],
    )
    def test_sanitize_plugin_version(self, version, expected_result):
        assert (
            expected_result
            == self.version_requirement._sanitize_plugin_version(version)
        )

    @pytest.mark.parametrize(
        "version, expected_result",
        [
            ("999.99999.99.9", True),
            ("2", True),
            ("1.1.1.1", True),
            ("1.1.1", True),
            ("1.1", True),
            ("1.1.1.1.1", False),
            ("1.1.1.1.0", False),
            ("1.1.1.a", False),
            ("1.a.1.1", False),
            ("1-1.1.1", False),
            ("1.1.", False),
            ("invalid_version", False),
        ],
    )
    def test_is_valid_version(self, version, expected_result):
        assert expected_result == self.version_requirement._is_valid_version(
            version
        )