diff --git a/awscli/formatter.py b/awscli/formatter.py index 61cafb300651..a931d44c8692 100644 --- a/awscli/formatter.py +++ b/awscli/formatter.py @@ -11,7 +11,6 @@ # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. import logging -import sys from botocore.compat import json from botocore.utils import set_value_from_jmespath @@ -91,9 +90,9 @@ def _format_response(self, command_name, response, stream): # the response will be an empty string. We don't want to print # that out to the user but other "falsey" values like an empty # dictionary should be printed. - if response: + if response != {}: json.dump(response, stream, indent=4, default=json_encoder, - ensure_ascii=False) + ensure_ascii=False) stream.write('\n') diff --git a/tests/unit/output/test_json_output.py b/tests/unit/output/test_json_output.py index 564bb12acf5e..ed6ab5788b48 100644 --- a/tests/unit/output/test_json_output.py +++ b/tests/unit/output/test_json_output.py @@ -23,20 +23,29 @@ class TestGetPasswordData(BaseAWSCommandParamsTest): - prefix = 'iam add-user-to-group ' + COMMAND = 'iam add-user-to-group --group-name foo --user-name bar' - def test_empty_response_prints_nothing(self): + def setUp(self): + super(TestGetPasswordData, self).setUp() + self.parsed_response = {} + + def test_empty_dict_response_prints_nothing(self): # This is the default response, but we want to be explicit # that we're returning an empty dict. self.parsed_response = {} - args = ' --group-name foo --user-name bar' - cmdline = self.prefix + args - result = {'GroupName': 'foo', 'UserName': 'bar'} - stdout = self.assert_params_for_cmd(cmdline, result, expected_rc=0)[0] - # We should have printed nothing because the parsed response - # is an empty dict: {}. + stdout = self.run_cmd(self.COMMAND, expected_rc=0)[0] self.assertEqual(stdout, '') + def test_empty_list_prints_list(self): + self.parsed_response = [] + stdout = self.run_cmd(self.COMMAND, expected_rc=0)[0] + self.assertEqual(stdout, '[]\n') + + def test_empty_string_prints_nothing(self): + self.parsed_response = '' + stdout = self.run_cmd(self.COMMAND, expected_rc=0)[0] + self.assertEqual(stdout, '""\n') + class TestListUsers(BaseAWSCommandParamsTest): @@ -76,6 +85,15 @@ def test_jmespath_json_response(self): parsed_output = json.loads(output) self.assertEqual(parsed_output, ['testuser-50', 'testuser-51']) + def test_zero_value_is_printed(self): + # Even though the integer 0 is false-like, we still + # should be printing it to stdout if a jmespath query + # evalutes to 0. + jmespath_query = '`0`' + output = self.run_cmd('iam list-users --query %s' % jmespath_query, + expected_rc=0)[0] + self.assertEqual(output, '0\n') + def test_unknown_output_type_from_env_var(self): # argparse already handles the case with a bad --output # specified on the CLI, we need to verify that a bad