Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import awscli
from argparse import Namespace
from mock import MagicMock, patch, ANY, call
from six import StringIO
from botocore.exceptions import ClientError
from awscli.customizations.codedeploy.push import Push
from awscli.testutils import unittest
from awscli.compat import ZIP_COMPRESSION_MODE
class TestPush(unittest.TestCase):
def setUp(self):
self.application_name = 'MyApp'
self.description = 'MyApp revision'
self.source = '/tmp'
self.appspec = 'appspec.yml'
self.appspec_path = '{0}/{1}'.format(self.source, self.appspec)
self.bucket = 'foo'
self.key = 'bar/baz.zip'
self.s3_location = 's3://' + self.bucket + '/' + self.key
self.eTag = '"1a2b3cd45e"'
self.version_id = '12341234-1234-1234-1234-123412341234'
self.upload_id = 'upload_id'
self.region = 'us-east-1'
self.endpoint_url = 'https://codedeploy.aws.amazon.com'
self.args = Namespace()
# 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 argparse
import datetime
import json
import mock
from botocore.exceptions import ClientError
from awscli.customizations import opsworks
from awscli.testutils import unittest
class TestOpsWorksBase(unittest.TestCase):
def setUp(self):
self.mock_session = mock.Mock()
self.register = opsworks.OpsWorksRegister(self.mock_session)
# stop the clock while testing
self.datetime_patcher = mock.patch.object(
opsworks.datetime, "datetime",
mock.Mock(wraps=datetime.datetime)
)
mocked_datetime = self.datetime_patcher.start()
mocked_datetime.utcnow.return_value = datetime.datetime(
2013, 8, 9, 23, 42)
def tearDown(self):
self.datetime_patcher.stop()
from awscli import clidriver
from awscli.autocomplete import db, generator
from awscli.autocomplete.serverside import model
from awscli.autocomplete.serverside.indexer import APICallIndexer
from awscli.autocomplete.local.indexer import ModelIndexer
from awscli.testutils import unittest
def _ddb_only_command_table(command_table, **kwargs):
for key in list(command_table):
if key != 'dynamodb':
del command_table[key]
class TestCanGenerateServerIndex(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.db_connection = db.DatabaseConnection(":memory:")
index_generator = generator.IndexGenerator(
[ModelIndexer(cls.db_connection),
APICallIndexer(cls.db_connection)],
)
driver = clidriver.create_clidriver()
driver.session.register('building-command-table.main',
_ddb_only_command_table)
index_generator.generate_index(driver)
def test_can_query_model_from_index(self):
lookup = model.DBCompletionLookup(self.db_connection)
# We'll query a few lookups to ensure that we indexed them
# correctly.
compare_key='test.py', size=10,
last_update=time_src, src_type='local',
dest_type='s3', operation_name='upload')
dst_file = FileStat(src='', dest='',
compare_key='test.py', size=10,
last_update=time_dst, src_type='s3',
dest_type='local', operation_name='')
should_sync = self.sync_strategy.determine_should_sync(
src_file, dst_file)
self.assertFalse(should_sync)
if __name__ == "__main__":
unittest.main()
from datetime import datetime
import time
from dateutil import tz
from botocore.session import Session
from botocore.stub import Stubber
from awscli.compat import StringIO
from awscli.customizations.logs.tail import ShortLogEventsFormatter
from awscli.customizations.logs.tail import DetailedLogEventsFormatter
from awscli.customizations.logs.tail import TimestampUtils
from awscli.customizations.logs.tail import NoFollowLogEventsGenerator
from awscli.customizations.logs.tail import FollowLogEventsGenerator
class BaseLogEventsFormatterTest(unittest.TestCase):
def setUp(self):
self.log_event = {
'timestamp': datetime(2018, 1, 1, 0, 29, 43, 79060, tz.tzutc()),
'logStreamName': 'stream_name',
'message': 'my message'
}
self.output = StringIO()
class TestShortLogEventsFormatter(BaseLogEventsFormatterTest):
def test_display(self):
ShortLogEventsFormatter(self.output).display_log_event(self.log_event)
self.assertEqual(
'\x1b[32m2018-01-01T00:29:43\x1b[0m my message\n',
self.output.getvalue()
)
class FakePrompter(object):
def __init__(self, responses):
self.responses = responses
self.recorded_prompts = []
def prompt(self, text, choices=None):
response = self.responses.get(text)
if choices is not None:
entry = text, response, choices
else:
entry = text, response
self.recorded_prompts.append(entry)
return response
class TestPlanner(unittest.TestCase):
def setUp(self):
self.responses = {}
self.prompter = FakePrompter(self.responses)
self.planner = core.Planner(
step_handlers={
'static': core.StaticStep(),
'prompt': core.PromptStep(self.prompter),
'template': core.TemplateStep(),
}
)
def test_can_prompt_for_single_value(self):
loaded = load_wizard("""
plan:
start:
values:
},
"required": ["Name", "Database", "QueryString"],
"type": "structure",
},
"NamedQueryId": {"type": "string"},
"NamedQueryIdList": {
"member": {"shape": "NamedQueryId"},
"type": "list",
},
"QueryString": {"type": "string"},
"Token": {"type": "string"},
},
}
class TestCanGenerateCompletions(unittest.TestCase):
maxDiff = None
def setUp(self):
self.service_model = ServiceModel(BASIC_MODEL)
self.heuristic = ServerCompletionHeuristic()
def test_can_generate_resource_descriptions(self):
resources = self.heuristic.generate_completion_descriptions(
self.service_model)['resources']
self.assertEqual(
resources, {
'Certificate': {
'operation': 'ListCertificates',
'resourceIdentifier': {
'CertificateArn': (
# language governing permissions and limitations under the License.
import os
import shutil
import tempfile
import json
import time
from botocore.session import Session
from botocore.exceptions import ClientError
from awscli.testutils import unittest, aws, random_chars
S3_READ_POLICY_ARN = 'arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess'
class TestAssumeRoleCredentials(unittest.TestCase):
def setUp(self):
super(TestAssumeRoleCredentials, self).setUp()
self.environ = os.environ.copy()
self.parent_session = Session()
self.iam = self.parent_session.create_client('iam')
self.sts = self.parent_session.create_client('sts')
self.tempdir = tempfile.mkdtemp()
self.config_file = os.path.join(self.tempdir, 'config')
# A role trust policy that allows the current account to call assume
# role on itself.
account_id = self.sts.get_caller_identity()['Account']
self.role_policy = {
"Version": "2012-10-17",
"Statement": [
{
import sys
from socket import timeout
from argparse import Namespace
from mock import MagicMock, patch
from awscli.customizations.codedeploy.systems import Ubuntu, Windows, RHEL, System
from awscli.customizations.codedeploy.utils import \
validate_region, validate_instance_name, validate_tags, \
validate_iam_user_arn, validate_instance, validate_s3_location, \
MAX_INSTANCE_NAME_LENGTH, MAX_TAGS_PER_INSTANCE, MAX_TAG_KEY_LENGTH, \
MAX_TAG_VALUE_LENGTH
from awscli.testutils import unittest
class TestUtils(unittest.TestCase):
def setUp(self):
self.iam_user_arn = 'arn:aws:iam::012345678912:user/AWS/CodeDeploy/foo'
self.region = 'us-east-1'
self.arg_name = 's3-location'
self.bucket = 'bucket'
self.key = 'key'
self.system_patcher = patch('platform.system')
self.system = self.system_patcher.start()
self.system.return_value = 'Linux'
self.linux_distribution_patcher = patch('platform.linux_distribution')
self.linux_distribution = self.linux_distribution_patcher.start()
self.linux_distribution.return_value = ('Ubuntu', '', '')
self.urlopen_patcher = patch(
import difflib
import mock
from botocore.compat import OrderedDict
from botocore.model import OperationModel
from awscli.clidriver import (
CLIDriver, ServiceCommand, ServiceOperation, CLICommand)
from awscli.arguments import BaseCLIArgument, CustomArgument
from awscli.help import ProviderHelpCommand
from awscli.completer import Completer
from awscli.testutils import unittest
from awscli.customizations.commands import BasicCommand
class BaseCompleterTest(unittest.TestCase):
def setUp(self):
self.clidriver_creator = MockCLIDriverFactory()
def assert_completion(self, completer, cmdline, expected_results,
point=None):
if point is None:
point = len(cmdline)
actual = set(completer.complete(cmdline, point))
expected = set(expected_results)
if not actual == expected:
# Borrowed from assertDictEqual, though this doesn't
# handle the case when unicode literals are used in one
# dict but not in the other (and we want to consider them
# as being equal).
pretty_d1 = pprint.pformat(actual, width=1).splitlines()