Skip to content

Commit

Permalink
Refactored --pretty and added tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
jkbrzt committed Mar 4, 2012
1 parent d02ac54 commit 00312ea
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 13 deletions.
24 changes: 15 additions & 9 deletions httpie/httpie.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
SEP_DATA = '='
TYPE_FORM = 'application/x-www-form-urlencoded; charset=utf-8'
TYPE_JSON = 'application/json; charset=utf-8'
PRETTIFY_STDOUT_TTY_ONLY = object()


KeyValue = namedtuple('KeyValue', ['key', 'value', 'sep'])
Expand Down Expand Up @@ -57,8 +58,15 @@ def __call__(self, string):
parser.add_argument('--traceback', action='store_true', default=False,
help='Print a full exception traceback should one'
' be raised by `requests`.')
parser.add_argument('--ugly', '-u', help='Do not prettify the response.',
dest='prettify', action='store_false', default=True)
group_pretty = parser.add_mutually_exclusive_group(required=False)
group_pretty.add_argument('--pretty', '-p', dest='prettify', action='store_true',
default=PRETTIFY_STDOUT_TTY_ONLY,
help='If stdout is a terminal, '
' the response is prettified by default (colorized and'
' indented if it is JSON). This flag ensures'
' prettifying even when stdout is redirected.')
group_pretty.add_argument('--ugly', '-u', help='Do not prettify the response.',
dest='prettify', action='store_false')
group_only = parser.add_mutually_exclusive_group(required=False)
group_only.add_argument('--headers', '-t', dest='print_body',
action='store_false', default=True,
Expand All @@ -70,8 +78,6 @@ def __call__(self, string):
choices=pretty.AVAILABLE_STYLES,
help='Output coloring style, one of %s. Defaults to solarized.'
% ', '.join(sorted(pretty.AVAILABLE_STYLES)))
parser.add_argument('--pretty', '-p', help='Force pretty print.',
dest='force_pretty', action='store_true', default=False)

# ``requests.request`` keyword arguments.
parser.add_argument('--auth', '-a', help='username:password',
Expand All @@ -96,13 +102,13 @@ def __call__(self, string):
' (Use socket.setdefaulttimeout() as fallback).')

# Positional arguments.
parser.add_argument('method',
parser.add_argument('method', metavar='METHOD',
help='HTTP method to be used for the request'
' (GET, POST, PUT, DELETE, PATCH, ...).')
parser.add_argument('url', metavar='URL',
help='Protocol defaults to http:// if the'
' URL does not include it.')
parser.add_argument('items', metavar='item', nargs='*',
parser.add_argument('items', nargs='*',
type=KeyValueType([SEP_COMMON, SEP_DATA]),
help='HTTP header (key:value) or data field (key=value)')

Expand All @@ -114,8 +120,8 @@ def main(args=None,
stdout_isatty=sys.stdout.isatty()):

args = parser.parse_args(args if args is not None else sys.argv[1:])
is_pretty = args.force_pretty or stdout_isatty

do_prettify = (args.prettify is True or
(args.prettify == PRETTIFY_STDOUT_TTY_ONLY and stdout_isatty))
# Parse request headers and data from the command line.
headers = CaseInsensitiveDict()
headers['User-Agent'] = DEFAULT_UA
Expand Down Expand Up @@ -177,7 +183,7 @@ def main(args=None,
response.content.decode(encoding) if response.content else u''
)

if args.prettify and is_pretty:
if do_prettify:
prettify = pretty.PrettyHttp(args.style)
if args.print_headers:
status_line = prettify.headers(status_line).strip()
Expand Down
35 changes: 31 additions & 4 deletions tests.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
from functools import partial
import unittest
from StringIO import StringIO
from httpie import httpie


TERMINAL_COLOR_END = '\x1b[39m'


def http(*args, **kwargs):
stdout = StringIO()
httpie.main(args=args, stdout=stdout,
stdin_isatty=True,
stdout_isatty=False)
http_kwargs = {
'stdin_isatty': True,
'stdout_isatty': False
}
http_kwargs.update(kwargs)
stdout = http_kwargs.setdefault('stdout', StringIO())
httpie.main(args=args, **http_kwargs)
return stdout.getvalue()


Expand All @@ -32,5 +39,25 @@ def test_headers(self):
self.assertIn('"Foo": "bar"', response)


class TestPrettyFlag(unittest.TestCase):
"""Test the --pretty / --ugly flag handling."""

def test_pretty_enabled_by_default(self):
r = http('GET', 'http://httpbin.org/get', stdout_isatty=True)
self.assertIn(TERMINAL_COLOR_END, r)

def test_pretty_enabled_by_default_unless_stdin_redirected(self):
r = http('GET', 'http://httpbin.org/get', stdout_isatty=False)
self.assertNotIn(TERMINAL_COLOR_END, r)

def test_force_pretty(self):
r = http('GET', '--pretty', 'http://httpbin.org/get', stdout_isatty=False)
self.assertIn(TERMINAL_COLOR_END, r)

def test_force_ugly(self):
r = http('GET', '--ugly', 'http://httpbin.org/get', stdout_isatty=True)
self.assertNotIn(TERMINAL_COLOR_END, r)


if __name__ == '__main__':
unittest.main()

0 comments on commit 00312ea

Please sign in to comment.