def run_cmd(self, cmd, expected_rc=0): logging.debug("Calling cmd: %s", cmd) self.patch_make_request() self.driver.session.register('before-call', self.before_call) self.driver.session.register('before-parameter-build', self.before_parameter_build) if not isinstance(cmd, list): cmdlist = cmd.split() else: cmdlist = cmd captured_stderr = six.StringIO() captured_stdout = six.StringIO() with mock.patch('sys.stderr', captured_stderr): with mock.patch('sys.stdout', captured_stdout): try: rc = self.driver.main(cmdlist) except SystemExit as e: # We need to catch SystemExit so that we # can get a proper rc and still present the # stdout/stderr to the test runner so we can # figure out what went wrong. rc = e.code stderr = captured_stderr.getvalue() stdout = captured_stdout.getvalue() self.assertEqual( rc, expected_rc, "Unexpected rc (expected: %s, actual: %s) for command: %s" % (expected_rc, rc, cmd)) return stdout, stderr, rc
def setUp(self): self.session = FakeSession() self.emitter = mock.Mock() self.emitter.emit.return_value = [] self.stdout = six.StringIO() self.stderr = six.StringIO() self.stdout_patch = mock.patch('sys.stdout', self.stdout) #self.stdout_patch.start() self.stderr_patch = mock.patch('sys.stderr', self.stderr) self.stderr_patch.start()
def test_stream_file_md5_error(self): with mock.patch('sys.stdout', new=six.StringIO()) as mock_stdout: self.response_data['ETag'] = '"0"' with self.assertRaises(MD5Error): fileinfo.save_file(None, self.response_data, None, True) # Make sure nothing is written to stdout. self.assertEqual(mock_stdout.getvalue(), "")
def test_configure_region_from_imds(self): session = FakeSession(all_variables={'region': 'from-imds'}) stream = six.StringIO() self.configure_list = ConfigureListCommand(session, stream) self.configure_list(args=[], parsed_globals=None) rendered = stream.getvalue() self.assertRegexpMatches(rendered, 'region\s+from-imds\s+imds')
def test_multiple_configuration_recorders(self): status = { 'name': 'default', 'recording': True, 'lastStatus': 'SUCCESS' } self.recorder_status.append(status) status = { 'name': 'default', 'recording': True, 'lastStatus': 'FAILURE', 'lastErrorCode': '500', 'lastErrorMessage': 'This is the error' } self.recorder_status.append(status) status = {'name': 'default', 'recording': False} self.recorder_status.append(status) expected_output = ('Configuration Recorders:\n\n' 'name: default\n' 'recorder: ON\n' 'last status: SUCCESS\n\n' 'name: default\n' 'recorder: ON\n' 'last status: FAILURE\n' 'error code: 500\n' 'message: This is the error\n\n' 'name: default\n' 'recorder: OFF\n\n' 'Delivery Channels:\n\n') with mock.patch('sys.stdout', six.StringIO()) as mock_stdout: self.cmd._run_main(self.parsed_args, self.parsed_globals) self.assertEqual(expected_output, mock_stdout.getvalue())
def test_delivery_channel_success_multiple_delivery_info(self): name = 'default' success = {'lastStatus': 'SUCCESS'} stream_delivery_status = success history_delivery_status = success snapshot_delivery_status = success status = self._make_delivery_channel_status( name, stream_delivery_status=stream_delivery_status, history_delivery_status=history_delivery_status, snapshot_delivery_status=snapshot_delivery_status) self.channel_status.append(status) expected_output = ('Configuration Recorders:\n\n' 'Delivery Channels:\n\n' 'name: default\n' 'last stream delivery status: SUCCESS\n' 'last history delivery status: SUCCESS\n' 'last snapshot delivery status: SUCCESS\n\n') with mock.patch('sys.stdout', six.StringIO()) as mock_stdout: self.cmd._run_main(self.parsed_args, self.parsed_globals) self.assertEqual(expected_output, mock_stdout.getvalue())
def assert_expected_output(self, print_task, expected_output, thread, out_file): with mock.patch(out_file, new=six.StringIO()) as mock_out: self.result_queue.put(print_task) self.result_queue.put(ShutdownThreadRequest()) thread.run() self.assertIn(expected_output, mock_out.getvalue())
def test_delivery_channel_mixed_multiple_delivery_info(self): name = 'default' success = {'lastStatus': 'SUCCESS'} failure = { 'lastStatus': 'FAILURE', 'lastErrorCode': '500', 'lastErrorMessage': 'This is the error' } stream_delivery_status = failure history_delivery_status = success snapshot_delivery_status = success status = self._make_delivery_channel_status( name, stream_delivery_status=stream_delivery_status, history_delivery_status=history_delivery_status, snapshot_delivery_status=snapshot_delivery_status) self.channel_status.append(status) expected_output = ('Configuration Recorders:\n\n' 'Delivery Channels:\n\n' 'name: default\n' 'last stream delivery status: FAILURE\n' 'error code: 500\n' 'message: This is the error\n' 'last history delivery status: SUCCESS\n' 'last snapshot delivery status: SUCCESS\n\n') with mock.patch('sys.stdout', six.StringIO()) as mock_stdout: self.cmd._run_main(self.parsed_args, self.parsed_globals) self.assertEqual(expected_output, mock_stdout.getvalue())
def test_error_message_when_directory_is_empty(self): with mock.patch('sys.stderr', six.StringIO()) as mock_stderr: self.cmd(self.args, self.global_args) self.assertEqual( mock_stderr.getvalue(), 'Fail to upload %s. ' 'The build root directory is empty or does not exist.\n' % (self.build_root))
def test_generate_json_skeleton_with_timestamp(self): parsed_args = mock.Mock() parsed_args.generate_cli_skeleton = 'input' input_shape = { 'A': { 'type': 'structure', 'members': { 'B': { 'type': 'timestamp' }, } } } shape = DenormalizedStructureBuilder().with_members( input_shape).build_model() operation_model = mock.Mock(input_shape=shape) argument = GenerateCliSkeletonArgument(self.session, operation_model) with mock.patch('sys.stdout', six.StringIO()) as mock_stdout: rc = argument.generate_json_skeleton(call_parameters=None, parsed_args=parsed_args, parsed_globals=None) self.assertEqual( '{\n' ' "A": {\n' ' "B": "1970-01-01T00:00:00"\n' ' }\n' '}\n', mock_stdout.getvalue()) self.assertEqual(rc, 0)
def test_no_runs_available(self): stream = six.StringIO() formatter = ListRunsFormatter(stream) objects = [] formatter.display_objects_to_user(objects) self.assertEqual( [line.strip() for line in stream.getvalue().splitlines()], [line.strip() for line in EMPTY_RUNS.splitlines()])
def setUp(self): styler = Styler() self.table = MultiTable(initial_section=False, column_separator='|', styler=styler, auto_reformat=False) self.formatter = TableFormatter(Object(color='off')) self.formatter.table = self.table self.stream = six.StringIO()
def test_dotted_get(self): session = FakeSession({}) session.full_config = {'preview': {'emr': 'true'}} stream = six.StringIO() config_get = ConfigureGetCommand(session, stream) config_get(args=['preview.emr'], parsed_globals=None) rendered = stream.getvalue() self.assertEqual(rendered.strip(), 'true')
def test_get_nested_attribute_from_default_does_not_exist(self): session = FakeSession({}) session.full_config = {'profiles': {}} stream = six.StringIO() config_get = ConfigureGetCommand(session, stream) config_get(args=['default.s3.signature_version'], parsed_globals=None) rendered = stream.getvalue() self.assertEqual(rendered.strip(), '')
def test_configure_get_command(self): session = FakeSession({}) session.config['region'] = 'us-west-2' stream = six.StringIO() config_get = ConfigureGetCommand(session, stream) config_get(args=['region'], parsed_globals=None) rendered = stream.getvalue() self.assertEqual(rendered.strip(), 'us-west-2')
def setUp(self): super(TestPreviewMode, self).setUp() self.stderr = six.StringIO() self.stderr_patch = mock.patch('sys.stderr', self.stderr) self.stderr_patch.start() self.full_config = {'profiles': {}} # Implementation detail, but we want to patch out the # session config, as that's the only way to control # preview services. self.driver.session._config = self.full_config
def test_configure_get_command_no_exist(self): no_vars_defined = {} session = FakeSession(no_vars_defined) stream = six.StringIO() config_get = ConfigureGetCommand(session, stream) rc = config_get(args=['region'], parsed_globals=None) rendered = stream.getvalue() # If a config value does not exist, we don't print any output. self.assertEqual(rendered, '') # And we exit with an rc of 1. self.assertEqual(rc, 1)
def split_on_commas(value): if not any(char in value for char in ['"', '\\', "'", ']', '[']): # No quotes or escaping, just use a simple split. return value.split(',') elif not any(char in value for char in ['"', "'", '[', ']']): # Simple escaping, let the csv module handle it. return list(csv.reader(six.StringIO(value), escapechar='\\'))[0] else: # If there's quotes for the values, we have to handle this # ourselves. return _split_with_quotes(value)
def test_no_pager_exists(self): fake_pager = 'foobar' os.environ['MANPAGER'] = fake_pager stdout = six.StringIO() renderer = FakePosixHelpRenderer(output_stream=stdout) renderer.exists_on_path[fake_pager] = False renderer.exists_on_path['groff'] = True renderer.mock_popen.communicate.return_value = (b'foo', '') renderer.render('foo') self.assertEqual(stdout.getvalue(), 'foo\n')
def test_json_prints_unicode_chars(self): self.parsed_response['Users'][1]['UserId'] = u'\u2713' output = self.run_cmd('iam list-users', expected_rc=0)[0] with mock.patch('sys.stdout', six.StringIO()) as f: out = get_stdout_text_writer() out.write(u'\u2713') expected = f.getvalue() # We should not see the '\u<hex>' for of the unicode character. # It should be encoded into the default encoding. self.assertNotIn('\\u2713', output) self.assertIn(expected, output)
def assert_command_does_not_exist(self, service, command): # Basically try to get the help output for the removed # command verify that we get a SystemExit exception # and that we get something in stderr that says that # we made an invalid choice (because the operation is removed). stderr = six.StringIO() with mock.patch('sys.stderr', stderr): with self.assertRaises(SystemExit): self.driver.main([service, command, 'help']) # We should see an error message complaining about # an invalid choice because the operation has been removed. self.assertIn('argument operation: Invalid choice', stderr.getvalue())
def test_configuration_recorder_off(self): status = {'name': 'default', 'recording': False} self.recorder_status.append(status) expected_output = ('Configuration Recorders:\n\n' 'name: default\n' 'recorder: OFF\n\n' 'Delivery Channels:\n\n') with mock.patch('sys.stdout', six.StringIO()) as mock_stdout: self.cmd._run_main(self.parsed_args, self.parsed_globals) self.assertEqual(expected_output, mock_stdout.getvalue())
def test_generate_json_skeleton(self): parsed_args = mock.Mock() parsed_args.generate_cli_skeleton = True with mock.patch('sys.stdout', six.StringIO()) as mock_stdout: rc = self.argument.generate_json_skeleton( service_operation=self.service_operation, call_parameters=None, parsed_args=parsed_args, parsed_globals=None ) # Ensure the contents printed to standard output are correct. self.assertEqual(self.ref_json_output, mock_stdout.getvalue()) # Ensure it is the correct return code of zero. self.assertEqual(rc, 0)
def test_error_message_when_directory_is_not_provided(self): self.args = [ '--name', self.build_name, '--build-version', self.build_version, '--build-root', '' ] with mock.patch('sys.stderr', six.StringIO()) as mock_stderr: self.cmd(self.args, self.global_args) self.assertEqual( mock_stderr.getvalue(), 'Fail to upload %s. ' 'The build root directory is empty or does not exist.\n' % (''))
def test_no_generate_json_skeleton(self): parsed_args = mock.Mock() parsed_args.generate_cli_skeleton = False with mock.patch('sys.stdout', six.StringIO()) as mock_stdout: rc = self.argument.generate_json_skeleton( service_operation=self.service_operation, call_parameters=None, parsed_args=parsed_args, parsed_globals=None ) # Ensure nothing is printed to standard output self.assertEqual('', mock_stdout.getvalue()) # Ensure nothing is returned because it was never called. self.assertEqual(rc, None)
def test_stream_requests(self): # Test that offset has no affect on the order in which requests # are written to stdout. The order of requests for a stream are # first in first out. self.queue.put(IORequest('nonexistant-file', 10, b'foobar', True)) self.queue.put(IORequest('nonexistant-file', 6, b'otherstuff', True)) # The thread should not try to close the file name because it is # writing to stdout. If it does, the thread will fail because # the file does not exist. self.queue.put(ShutdownThreadRequest()) with mock.patch('sys.stdout', new=six.StringIO()) as mock_stdout: self.io_thread.run() self.assertEqual(mock_stdout.getvalue(), 'foobarotherstuff')
def setUp(self): self.session = FakeSession({'config_file': 'myconfigfile'}) self.fake_credentials_filename = os.path.expanduser( '~/fake_credentials_filename') self.session.profile = None self.mock_writer = mock.Mock(spec=ConfigFileWriter) self.importer = CredentialImporter(self.mock_writer) self.stdout = six.StringIO() self.import_command = ConfigureImportCommand( self.session, importer=self.importer, out_stream=self.stdout, )
def test_configure_list_command_nothing_set(self): # Test the case where the user only wants to change a single_value. session = FakeSession( all_variables={'config_file': '/config/location'}) session.full_config = { 'profiles': {'default': {'region': 'AWS_DEFAULT_REGION'}}} stream = six.StringIO() self.configure_list = ConfigureListCommand(session, stream) self.configure_list(args=[], parsed_globals=None) rendered = stream.getvalue() self.assertRegex(rendered, r'profile\s+<not set>') self.assertRegex(rendered, r'access_key\s+<not set>') self.assertRegex(rendered, r'secret_key\s+<not set>') self.assertRegex(rendered, r'region\s+<not set>')
def test_error_message_when_directory_does_not_exist(self): dir_not_exist = os.path.join(self.build_root, 'does_not_exist') self.args = [ '--name', self.build_name, '--build-version', self.build_version, '--build-root', dir_not_exist ] with mock.patch('sys.stderr', six.StringIO()) as mock_stderr: self.cmd(self.args, self.global_args) self.assertEqual( mock_stderr.getvalue(), 'Fail to upload %s. ' 'The build root directory is empty or does not exist.\n' % (dir_not_exist))
def test_generate_json_skeleton_no_input_shape(self): parsed_args = mock.Mock() parsed_args.generate_cli_skeleton = True # Set the input shape to ``None``. self.operation_object.model.input_shape = None with mock.patch('sys.stdout', six.StringIO()) as mock_stdout: rc = self.argument.generate_json_skeleton( service_operation=self.service_operation, call_parameters=None, parsed_args=parsed_args, parsed_globals=None ) # Ensure the contents printed to standard output are correct, # which should be an empty dictionary. self.assertEqual('{}\n', mock_stdout.getvalue()) # Ensure it is the correct return code of zero. self.assertEqual(rc, 0)