Esempio n. 1
0
    def test_upload_build(self):
        self.file_creator.create_file('tmpfile', 'Some contents')
        self.cmd(self.args, self.global_args)
        # Ensure the clients were instantiated correctly.
        client_creation_args = self.mock_create_client.call_args_list
        self.assertEqual(
            client_creation_args,
            [mock.call('gamelift', region_name=self.region,
                       endpoint_url=None, verify=None),
             mock.call('s3', aws_access_key_id=self.access_key,
                       aws_secret_access_key=self.secret_key,
                       aws_session_token=self.session_token,
                       region_name=self.region,
                       verify=None)]
        )

        # Ensure the GameLift client was called correctly.
        self.gamelift_client.create_build.assert_called_once_with(
            Name=self.build_name, Version=self.build_version)

        self.gamelift_client.request_upload_credentials.\
            assert_called_once_with(BuildId=self.build_id)

        # Ensure the underlying S3 transfer call was correct.
        self.upload_file_mock.assert_called_once_with(
            mock.ANY, self.bucket, self.key, callback=mock.ANY)

        tempfile_path = self.upload_file_mock.call_args[0][0]
        # Ensure the temporary zipfile is deleted at the end.
        self.assertFalse(os.path.exists(tempfile_path))
Esempio n. 2
0
    def test_upload_build(self):
        self.file_creator.create_file("tmpfile", "Some contents")
        self.cmd(self.args, self.global_args)
        # Ensure the clients were instantiated correctly.
        client_creation_args = self.mock_create_client.call_args_list
        self.assertEqual(
            client_creation_args,
            [
                mock.call("gamelift", region_name=self.region, endpoint_url=None, verify=None),
                mock.call(
                    "s3",
                    aws_access_key_id=self.access_key,
                    aws_secret_access_key=self.secret_key,
                    aws_session_token=self.session_token,
                    region_name=self.region,
                    verify=None,
                ),
            ],
        )

        # Ensure the GameLift client was called correctly.
        self.gamelift_client.create_build.assert_called_once_with(Name=self.build_name, Version=self.build_version)

        self.gamelift_client.request_upload_credentials.assert_called_once_with(BuildId=self.build_id)

        # Ensure the underlying S3 transfer call was correct.
        self.upload_file_mock.assert_called_once_with(mock.ANY, self.bucket, self.key, callback=mock.ANY)

        tempfile_path = self.upload_file_mock.call_args[0][0]
        # Ensure the temporary zipfile is deleted at the end.
        self.assertFalse(os.path.exists(tempfile_path))
Esempio n. 3
0
 def test_set_client_no_source(self):
     session = mock.Mock()
     cmd_arc = CommandArchitecture(
         session, 'sync', {
             'region': 'us-west-1',
             'endpoint_url': None,
             'verify_ssl': None,
             'source_region': None
         })
     cmd_arc.set_clients()
     self.assertEqual(session.create_client.call_count, 2)
     self.assertEqual(
         session.create_client.call_args_list[0],
         mock.call('s3',
                   region_name='us-west-1',
                   endpoint_url=None,
                   verify=None,
                   config=None))
     # A client created with the same arguments as the first should be used
     # for the source client since no source region was provided.
     self.assertEqual(
         session.create_client.call_args_list[1],
         mock.call('s3',
                   region_name='us-west-1',
                   endpoint_url=None,
                   verify=None,
                   config=None))
Esempio n. 4
0
 def test_register_creates_clients(self):
     self.register._run_main(self.args, self.globals)
     self.session.create_client.assert_has_calls([
         mock.call('codedeploy',
                   region_name=self.region,
                   endpoint_url=self.endpoint_url,
                   verify=self.globals.verify_ssl),
         mock.call('iam', region_name=self.region)
     ])
Esempio n. 5
0
 def test_s3_client_created_lazily(self):
     session = mock.Mock()
     command = CloudTrailValidateLogs(session)
     parsed_globals = mock.Mock(region=None,
                                verify_ssl=None,
                                endpoint_url=None)
     command.setup_services(parsed_globals)
     create_client_calls = session.create_client.call_args_list
     self.assertEqual(create_client_calls, [
         mock.call('organizations', verify=None, region_name=None),
         mock.call('cloudtrail', verify=None, region_name=None)
     ])
Esempio n. 6
0
    def test_command_invoked(self, mock_yaml_parse):
        """
        Tests that deploy method is invoked when command is run
        """
        fake_parameter_overrides = []
        fake_tags_dict = {"tagkey1": "tagvalue1"}
        fake_tags = [{"Key": "tagkey1", "Value": "tagvalue1"}]
        fake_parameters = "some return value"
        template_str = "some template"

        with tempfile.NamedTemporaryFile() as handle:
            file_path = handle.name

            open_mock = mock.mock_open()
            # Patch the file open method to return template string
            with mock.patch("awscli.customizations.cloudformation.deploy.open",
                            open_mock(read_data=template_str)) as open_mock:

                fake_template = get_example_template()
                mock_yaml_parse.return_value = fake_template

                self.deploy_command.deploy = mock.MagicMock()
                self.deploy_command.deploy.return_value = 0
                self.deploy_command.parse_key_value_arg = mock.Mock()
                self.deploy_command.parse_key_value_arg.side_effect = [
                    fake_parameter_overrides, fake_tags_dict
                ]
                self.deploy_command.merge_parameters = mock.MagicMock(
                    return_value=fake_parameters)

                self.parsed_args.template_file = file_path
                result = self.deploy_command._run_main(
                    self.parsed_args, parsed_globals=self.parsed_globals)
                self.assertEqual(0, result)

                open_mock.assert_called_once_with(file_path, "r")

                self.deploy_command.deploy.assert_called_once_with(
                    mock.ANY, 'some_stack_name', mock.ANY, fake_parameters,
                    None, not self.parsed_args.no_execute_changeset, None, [],
                    None, fake_tags, True, True)

                self.deploy_command.parse_key_value_arg.assert_has_calls([
                    mock.call(self.parsed_args.parameter_overrides,
                              "parameter-overrides"),
                    mock.call(self.parsed_args.tags, "tags")
                ])

                self.deploy_command.merge_parameters.assert_called_once_with(
                    fake_template, fake_parameter_overrides)

                self.assertEqual(1, mock_yaml_parse.call_count)
Esempio n. 7
0
 def test_run_main_creates_clients(self):
     self.push._validate_args = mock.MagicMock()
     self.push._push = mock.MagicMock()
     self.push._run_main(self.args, self.globals)
     self.session.create_client.assert_has_calls([
         mock.call(
             'codedeploy',
             region_name=self.region,
             endpoint_url=self.endpoint_url,
             verify=self.globals.verify_ssl
         ),
         mock.call('s3', region_name=self.region)
     ])
Esempio n. 8
0
    def test_write_only_strips_until_text_is_found(self):
        self.node.add_child(parser.DataNode('  '))
        tag_child = parser.TagNode('foo')
        tag_child.add_child(parser.DataNode('  '))
        tag_child_2 = parser.TagNode('foo')
        tag_child_2.add_child(parser.DataNode(' foo'))
        tag_child_2.add_child(parser.DataNode(' '))
        tag_child.add_child(tag_child_2)
        self.node.add_child(tag_child)

        self.node.write(self.doc)

        calls = [mock.call('foo'), mock.call(' ')]
        self.doc.handle_data.assert_has_calls(calls)
Esempio n. 9
0
 def test_uninstall(self):
     process = mock.MagicMock()
     process.communicate.return_value = ('', '')
     process.returncode = 0
     self.popen.return_value = process
     self.rhel.uninstall(self.params)
     self.popen.assert_has_calls([
         mock.call(['service', 'codedeploy-agent', 'stop'],
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE),
         mock.call().communicate()
     ])
     self.check_call.assert_has_calls(
         [mock.call(['yum', '-y', 'erase', 'codedeploy-agent'])])
Esempio n. 10
0
 def test_clients_all_from_same_session(self):
     session = mock.Mock()
     subscribe_command = CloudTrailSubscribe(session)
     parsed_globals = mock.Mock(region=None,
                                verify_ssl=None,
                                endpoint_url=None)
     subscribe_command.setup_services(None, parsed_globals)
     create_client_calls = session.create_client.call_args_list
     self.assertEqual(create_client_calls, [
         mock.call('sts', verify=None, region_name=None),
         mock.call('s3', verify=None, region_name=None),
         mock.call('sns', verify=None, region_name=None),
         mock.call('cloudtrail', verify=None, region_name=None),
     ])
Esempio n. 11
0
 def test_iter_log_events_filters_old_events(self):
     self.stubber.add_response(
         'filter_log_events',
         service_response={
             'events': [
                 self.get_event('event-1', 'event-1-message'),
                 self.get_event('event-2', 'event-2-message'),
             ],
         },
         expected_params={
             'logGroupName': self.group_name,
             'interleaved': True,
         }
     )
     # Add a new page that has no nextToken
     # It should update startTime with the max timestamp
     # from the prvious response events
     self.stubber.add_response(
         'filter_log_events',
         service_response={
             'events': [
                 self.get_event('event-1', 'event-1-message'),
                 self.get_event('event-2', 'event-2-message'),
                 self.get_event('event-3', 'event-3-message'),
             ],
         },
         expected_params={
             'logGroupName': self.group_name,
             'interleaved': True,
             'startTime': self.get_event('event-2', 'event-2-message')['timestamp']
         }
     )
     self.mock_sleep.side_effect = [
         None,
         KeyboardInterrupt()
     ]
     with self.stubber:
         log_events_iter = self.logs_generator.iter_log_events(
             self.group_name)
         actual_log_events = [event for event in log_events_iter]
     self.mock_sleep.assert_has_calls([mock.call(5), mock.call(5)])
     self.assertEqual(
         actual_log_events,
         [
             self.get_expected_event('event-1', 'event-1-message'),
             self.get_expected_event('event-2', 'event-2-message'),
             self.get_expected_event('event-3', 'event-3-message'),
         ]
     )
Esempio n. 12
0
 def test_env_configured_pager(self, mock_get_popen_pager):
     mock_get_popen_pager.return_value = {'args': ['mypager', '--option']}
     with self.stream_factory.get_pager_stream('mypager --option'):
         mock_get_popen_pager.assert_called_with('mypager --option')
         self.assertEqual(self.popen.call_args_list, [
             mock.call(args=['mypager', '--option'], stdin=subprocess.PIPE)
         ])
Esempio n. 13
0
 def test_show_specific_id(self):
     self.parsed_args.command_id = 'some-specific-id'
     self.show_cmd._run_main(self.parsed_args, self.parsed_globals)
     self.assertEqual(
         self.db_reader.iter_records.call_args,
         mock.call('some-specific-id')
     )
Esempio n. 14
0
 def test_creates_clients_for_buckets_outside_us_east_1(self):
     session = mock.Mock()
     s3_client = mock.Mock()
     session.create_client.return_value = s3_client
     s3_client.get_bucket_location.return_value = {
         'LocationConstraint': 'us-west-2'
     }
     provider = S3ClientProvider(session, 'us-west-1')
     created_client = provider.get_client('foo')
     self.assertEqual(s3_client, created_client)
     create_client_calls = session.create_client.call_args_list
     self.assertEqual(
         create_client_calls,
         [mock.call('s3', 'us-west-1'),
          mock.call('s3', 'us-west-2')])
     self.assertEqual(1, s3_client.get_bucket_location.call_count)
Esempio n. 15
0
 def test_ls_command_with_no_args(self):
     ls_command = ListCommand(self.session)
     parsed_global = FakeArgs(region=None,
                              endpoint_url=None,
                              verify_ssl=None)
     parsed_args = FakeArgs(dir_op=False,
                            paths='s3://',
                            human_readable=False,
                            summarize=False,
                            request_payer=None)
     ls_command._run_main(parsed_args, parsed_global)
     # We should only be a single call.
     call = self.session.create_client.return_value.list_buckets
     self.assertTrue(call.called)
     self.assertEqual(call.call_count, 1)
     self.assertEqual(call.call_args[1], {})
     # Verify get_client
     get_client = self.session.create_client
     args = get_client.call_args
     self.assertEqual(
         args,
         mock.call('s3',
                   region_name=None,
                   endpoint_url=None,
                   verify=None,
                   config=None))
Esempio n. 16
0
 def test_iter_log_events_filters_empty_events_list(self):
     self.stubber.add_response(
         'filter_log_events',
         service_response={
             'events': [],
         },
         expected_params={
             'logGroupName': self.group_name,
             'interleaved': True,
         }
     )
     # Add a new page that has events
     # It should make a call with the same parameters as the
     # previous one
     self.stubber.add_response(
         'filter_log_events',
         service_response={
             'events': [
                 self.get_event('event-1', 'event-1-message'),
                 self.get_event('event-2', 'event-2-message'),
                 self.get_event('event-3', 'event-3-message'),
             ],
         },
         expected_params={
             'logGroupName': self.group_name,
             'interleaved': True,
         }
     )
     self.mock_sleep.side_effect = [
         None,
         KeyboardInterrupt()
     ]
     with self.stubber:
         log_events_iter = self.logs_generator.iter_log_events(
             self.group_name)
         actual_log_events = [event for event in log_events_iter]
     self.mock_sleep.assert_has_calls([mock.call(5), mock.call(5)])
     self.assertEqual(
         actual_log_events,
         [
             self.get_expected_event('event-1', 'event-1-message'),
             self.get_expected_event('event-2', 'event-2-message'),
             self.get_expected_event('event-3', 'event-3-message'),
         ]
     )
Esempio n. 17
0
 def _assert_subprocess_check_output_execution(self, commands):
     expected_calls = [
         mock.call(
             command,
             stderr=subprocess.PIPE,
         ) for command in commands
     ]
     self.subprocess_check_out_mock.assert_has_calls(expected_calls,
                                                     any_order=True)
Esempio n. 18
0
 def test_can_invoke_with_plan_variables(self):
     invoker = core.APIInvoker(self.mock_session)
     invoker.invoke(
         'iam',
         'CreateUser',
         api_params={'UserName': '******'},
         plan_variables={'username': '******'}
     )
     call_method_args = self.get_call_args(self.mock_session)
     self.assertEqual(call_method_args, mock.call(UserName='******'))
Esempio n. 19
0
 def test_endpoint_url_is_used_for_cloudtrail(self):
     endpoint_url = 'https://mycloudtrail.aws.amazon.com/'
     session = mock.Mock()
     command = CloudTrailValidateLogs(session)
     parsed_globals = mock.Mock(region='foo',
                                verify_ssl=None,
                                endpoint_url=endpoint_url)
     command.setup_services(parsed_globals)
     create_client_calls = session.create_client.call_args_list
     self.assertEqual(
         create_client_calls,
         [
             mock.call('organizations', verify=None, region_name='foo'),
             # Here we should inject the endpoint_url only for cloudtrail.
             mock.call('cloudtrail',
                       verify=None,
                       region_name='foo',
                       endpoint_url=endpoint_url)
         ])
Esempio n. 20
0
 def test_install(self):
     process = mock.MagicMock()
     process.communicate.return_value = ('', '')
     process.returncode = 0
     self.popen.return_value = process
     self.rhel.install(self.params)
     self.popen.assert_has_calls([
         mock.call(['service', 'codedeploy-agent', 'stop'],
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE),
         mock.call().communicate()
     ])
     self.check_call.assert_has_calls([
         mock.call(['yum', '-y', 'install', 'ruby']),
         mock.call(['chmod', '+x', './{0}'.format(self.installer)]),
         mock.call(['./{0}'.format(self.installer), 'auto'],
                   env=self.environment)
     ])
     self.open.assert_called_with(self.installer, 'wb')
     self.open().write.assert_called_with(self.body)
Esempio n. 21
0
 def test_login(self):
     self.test_subject.login()
     expected_calls = [
         mock.call(
             command,
             stdout=self.subprocess_utils.PIPE,
             stderr=self.subprocess_utils.PIPE,
         ) for command in self.commands
     ]
     self.subprocess_utils.check_call.assert_has_calls(expected_calls,
                                                       any_order=True)
Esempio n. 22
0
 def test_pager_using_shell(self, mock_get_popen_pager):
     mock_get_popen_pager.return_value = {
         'args': 'mypager --option',
         'shell': True
     }
     with self.stream_factory.get_pager_stream():
         mock_get_popen_pager.assert_called_with(None)
         self.assertEqual(self.popen.call_args_list, [
             mock.call(
                 args='mypager --option', stdin=subprocess.PIPE, shell=True)
         ])
Esempio n. 23
0
    def test_uses_exclude(self):
        self.parsed_args.command_id = 'latest'
        self.parsed_args.include = None
        self.parsed_args.exclude = ['CLI_RC']
        self.show_cmd._run_main(self.parsed_args, self.parsed_globals)

        self.assertEqual(
            self.formatter.call_args,
            mock.call(include=None,
                      exclude=['CLI_RC'],
                      output=self.output_stream))
Esempio n. 24
0
 def test_deregister_with_delete_iam_user(self):
     self.args.no_delete_iam_user = False
     self.deregister._run_main(self.args, self.globals)
     self.codedeploy.get_on_premises_instance.assert_called_with(
         instanceName=self.instance_name)
     self.codedeploy.deregister_on_premises_instance.\
         assert_called_with(
             instanceName=self.instance_name
         )
     self.iam.get_paginator.assert_has_calls(
         [mock.call('list_user_policies'),
          mock.call('list_access_keys')])
     self.list_user_policies.paginate.assert_called_with(
         UserName=self.instance_name)
     self.iam.delete_user_policy.assert_called_with(
         UserName=self.instance_name, PolicyName=self.policy_name)
     self.list_access_keys.paginate.assert_called_with(
         UserName=self.instance_name)
     self.iam.delete_access_key.assert_called_with(
         UserName=self.instance_name, AccessKeyId=self.access_key_id)
     self.iam.delete_user.assert_called_with(UserName=self.instance_name)
Esempio n. 25
0
    def test_uses_exclude(self):
        self.parsed_args.command_id = 'latest'
        self.parsed_args.include = None
        self.parsed_args.exclude = ['CLI_RC']
        self.show_cmd._run_main(self.parsed_args, self.parsed_globals)

        self.assertEqual(
            self.formatter.call_args,
            mock.call(
                include=None, exclude=['CLI_RC'],
                output=self.output_stream)
        )
Esempio n. 26
0
 def test_endpoint_url_is_only_used_for_cloudtrail(self):
     endpoint_url = 'https://mycloudtrail.awsamazon.com/'
     session = mock.Mock()
     subscribe_command = CloudTrailSubscribe(session)
     parsed_globals = mock.Mock(region=None,
                                verify_ssl=None,
                                endpoint_url=endpoint_url)
     subscribe_command.setup_services(None, parsed_globals)
     create_client_calls = session.create_client.call_args_list
     self.assertEqual(
         create_client_calls,
         [
             mock.call('sts', verify=None, region_name=None),
             mock.call('s3', verify=None, region_name=None),
             mock.call('sns', verify=None, region_name=None),
             # Here we should inject the endpoint_url only for cloudtrail.
             mock.call('cloudtrail',
                       verify=None,
                       region_name=None,
                       endpoint_url=endpoint_url),
         ])
Esempio n. 27
0
 def test_env_configured_pager(self, mock_get_popen_pager):
     mock_get_popen_pager.return_value = {
         'args': ['mypager', '--option']
     }
     with self.stream_factory.get_pager_stream('mypager --option'):
         mock_get_popen_pager.assert_called_with('mypager --option')
         self.assertEqual(
             self.popen.call_args_list,
             [mock.call(
                 args=['mypager', '--option'],
                 stdin=subprocess.PIPE)]
         )
Esempio n. 28
0
 def test_install(self):
     process = mock.MagicMock()
     process.communicate.side_effect = [('', ''), ('Running', '')]
     process.returncode = 0
     self.popen.return_value = process
     self.windows.install(self.params)
     self.popen.assert_has_calls([
         mock.call([
             'powershell.exe', '-Command', 'Stop-Service', '-Name',
             'codedeployagent'
         ],
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE),
         mock.call().communicate(),
         mock.call([
             'powershell.exe', '-Command', 'Get-Service', '-Name',
             'codedeployagent'
         ],
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE),
         mock.call().communicate()
     ])
     self.check_call.assert_has_calls([
         mock.call([
             r'.\{0}'.format(self.installer), '/quiet', '/l',
             r'.\codedeploy-agent-install-log.txt'
         ],
                   shell=True),
         mock.call([
             'powershell.exe', '-Command', 'Restart-Service', '-Name',
             'codedeployagent'
         ])
     ])
     self.open.assert_called_with(self.installer, 'wb')
     self.open().write.assert_called_with(self.body)
Esempio n. 29
0
    def test_detailed_formatter_no_color_for_windows(self):
        self.formatter = mock.Mock(DetailedFormatter)
        self.add_formatter('detailed', self.formatter)
        self.parsed_args.format = 'detailed'
        self.parsed_args.command_id = 'latest'

        self.show_cmd._run_main(self.parsed_args, self.parsed_globals)
        self.assertEqual(
            self.formatter.call_args,
            mock.call(include=None,
                      exclude=None,
                      output=self.output_stream,
                      colorize=False))
Esempio n. 30
0
 def test_pager_using_shell(self, mock_get_popen_pager):
     mock_get_popen_pager.return_value = {
         'args': 'mypager --option', 'shell': True
     }
     with self.stream_factory.get_pager_stream():
         mock_get_popen_pager.assert_called_with(None)
         self.assertEqual(
             self.popen.call_args_list,
             [mock.call(
                 args='mypager --option',
                 stdin=subprocess.PIPE,
                 shell=True)]
         )
Esempio n. 31
0
 def test_uninstall(self):
     process = mock.MagicMock()
     process.communicate.side_effect = [('', ''), ('', '')]
     process.returncode = 0
     self.popen.return_value = process
     self.windows.uninstall(self.params)
     self.popen.assert_has_calls([
         mock.call([
             'powershell.exe', '-Command', 'Stop-Service', '-Name',
             'codedeployagent'
         ],
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE),
         mock.call().communicate(),
         mock.call([
             'wmic', 'product', 'where', 'name="CodeDeploy Host Agent"',
             'call', 'uninstall', '/nointeractive'
         ],
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE),
         mock.call().communicate()
     ])
Esempio n. 32
0
    def test_detailed_formatter_not_a_tty(self, mock_is_a_tty):
        mock_is_a_tty.return_value = False
        self.formatter = mock.Mock(DetailedFormatter)
        self.add_formatter('detailed', self.formatter)
        self.parsed_args.format = 'detailed'
        self.parsed_args.command_id = 'latest'

        self.show_cmd._run_main(self.parsed_args, self.parsed_globals)
        self.assertEqual(
            self.formatter.call_args,
            mock.call(include=None,
                      exclude=None,
                      output=self.output_stream,
                      colorize=False))
Esempio n. 33
0
    def test_detailed_formatter_no_color_for_windows(self):
        self.formatter = mock.Mock(DetailedFormatter)
        self.add_formatter('detailed', self.formatter)
        self.parsed_args.format = 'detailed'
        self.parsed_args.command_id = 'latest'

        self.show_cmd._run_main(self.parsed_args, self.parsed_globals)
        self.assertEqual(
            self.formatter.call_args,
            mock.call(
                include=None, exclude=None,
                output=self.output_stream, colorize=False
            )
        )
Esempio n. 34
0
    def test_uses_format(self):
        formatter = mock.Mock(Formatter)
        self.add_formatter('myformatter', formatter)

        return_record = {'id': 'myid', 'event_type': 'CLI_RC', 'payload': 0}
        self.db_reader.iter_latest_records.return_value = [return_record]

        self.parsed_args.format = 'myformatter'
        self.parsed_args.command_id = 'latest'
        self.show_cmd._run_main(self.parsed_args, self.parsed_globals)

        self.assertTrue(formatter.called)
        self.assertEqual(formatter.return_value.display.call_args_list,
                         [mock.call(return_record)])
Esempio n. 35
0
    def test_detailed_formatter_is_a_tty(self, mock_is_a_tty):
        mock_is_a_tty.return_value = True
        self.formatter = mock.Mock(DetailedFormatter)
        self.add_formatter('detailed', self.formatter)
        self.parsed_args.format = 'detailed'
        self.parsed_args.command_id = 'latest'

        self.show_cmd._run_main(self.parsed_args, self.parsed_globals)
        call = self.output_stream_factory.get_pager_stream.call_args
        self.assertEqual(
            self.formatter.call_args,
            mock.call(
                include=None, exclude=None,
                output=self.output_stream, colorize=True
            )
        )
Esempio n. 36
0
    def test_uses_format(self):
        formatter = mock.Mock(Formatter)
        self.add_formatter('myformatter', formatter)

        return_record = {'id': 'myid', 'event_type': 'CLI_RC', 'payload': 0}
        self.db_reader.iter_latest_records.return_value = [return_record]

        self.parsed_args.format = 'myformatter'
        self.parsed_args.command_id = 'latest'
        self.show_cmd._run_main(self.parsed_args, self.parsed_globals)

        self.assertTrue(formatter.called)
        self.assertEqual(
            formatter.return_value.display.call_args_list,
            [mock.call(return_record)]
        )
Esempio n. 37
0
    def test_can_handle_ctrl_c(self):
        class CtrlCRenderer(FakePosixHelpRenderer):
            def _popen(self, *args, **kwargs):
                if self._is_pager_call(args):
                    os.kill(os.getpid(), signal.SIGINT)
                return self.mock_popen

            def _is_pager_call(self, args):
                return 'less' in args[0]

        renderer = CtrlCRenderer()
        renderer.mock_popen.communicate.return_value = ('send to pager', '')
        renderer.exists_on_path['groff'] = True
        renderer.exists_on_path['less'] = True
        renderer.render('foo')
        last_call = renderer.mock_popen.communicate.call_args_list[-1]
        self.assertEqual(last_call, mock.call(input='send to pager'))
Esempio n. 38
0
    def test_disable_color(self, mock_is_a_tty):
        self.formatter = mock.Mock(DetailedFormatter)
        self.add_formatter('detailed', self.formatter)
        self.parsed_args.format = 'detailed'
        self.parsed_args.command_id = 'latest'

        self.parsed_globals.color = 'off'
        # Even with settings that would typically enable color, it
        # should be turned off because it was explicitly turned off
        mock_is_a_tty.return_value = True

        self.show_cmd._run_main(self.parsed_args, self.parsed_globals)
        self.assertEqual(
            self.formatter.call_args,
            mock.call(
                include=None, exclude=None,
                output=self.output_stream, colorize=False
            )
        )