This commit is contained in:
Jakub Roztocil 2012-12-05 04:39:56 +01:00
parent 8190a7c0c6
commit 8175366f27
7 changed files with 40 additions and 44 deletions

View File

@ -13,7 +13,8 @@ from . import __doc__
from . import __version__ from . import __version__
from .sessions import DEFAULT_SESSIONS_DIR from .sessions import DEFAULT_SESSIONS_DIR
from .output import AVAILABLE_STYLES, DEFAULT_STYLE from .output import AVAILABLE_STYLES, DEFAULT_STYLE
from .input import (Parser, AuthCredentialsArgType, KeyValueArgType, from .input import (Parser, AuthCredentialsArgType,
KeyValueArgType, SessionNameArgType,
SEP_PROXY, SEP_CREDENTIALS, SEP_GROUP_ITEMS, SEP_PROXY, SEP_CREDENTIALS, SEP_GROUP_ITEMS,
OUT_REQ_HEAD, OUT_REQ_BODY, OUT_RESP_HEAD, OUT_REQ_HEAD, OUT_REQ_BODY, OUT_RESP_HEAD,
OUT_RESP_BODY, OUTPUT_OPTIONS, OUT_RESP_BODY, OUTPUT_OPTIONS,
@ -27,16 +28,13 @@ def _(text):
parser = Parser( parser = Parser(
description='%s <http://httpie.org>' % __doc__.strip(), description='%s <http://httpie.org>' % __doc__.strip(),
epilog= epilog='For every --option there is a --no-option'
'For every --option there is a --no-option that reverts the option\n' ' that reverts the option to its default value.\n\n'
'to its default value.' 'Suggestions and bug reports are greatly appreciated:\n'
'\n\n' 'https://github.com/jkbr/httpie/issues'
'Suggestions and bug reports are greatly appreciated:\n'
'https://github.com/jkbr/httpie/issues'
) )
############################################################################### ###############################################################################
# Positional arguments. # Positional arguments.
############################################################################### ###############################################################################
@ -45,8 +43,8 @@ positional = parser.add_argument_group(
title='Positional arguments', title='Positional arguments',
description=_(''' description=_('''
These arguments come after any flags and in the These arguments come after any flags and in the
order they are listed here. Only URL is required.''' order they are listed here. Only URL is required.
) ''')
) )
positional.add_argument( positional.add_argument(
'method', metavar='METHOD', 'method', metavar='METHOD',
@ -123,7 +121,7 @@ output_processing = parser.add_argument_group(title='Output processing')
output_processing.add_argument( output_processing.add_argument(
'--output', '-o', type=FileType('w+b'), '--output', '-o', type=FileType('w+b'),
metavar='FILE', metavar='FILE',
help= SUPPRESS if not is_windows else _( help=SUPPRESS if not is_windows else _(
''' '''
Save output to FILE. Save output to FILE.
This option is a replacement for piping output to FILE, This option is a replacement for piping output to FILE,
@ -155,14 +153,13 @@ output_processing.add_argument(
) )
############################################################################### ###############################################################################
# Output options # Output options
############################################################################### ###############################################################################
output_options = parser.add_argument_group(title='Output options') output_options = parser.add_argument_group(title='Output options')
output_options.add_argument('--print', '-p', dest='output_options', output_options.add_argument(
metavar='WHAT', '--print', '-p', dest='output_options', metavar='WHAT',
help=_(''' help=_('''
String specifying what the output should contain: String specifying what the output should contain:
"{request_headers}" stands for the request headers, and "{request_headers}" stands for the request headers, and
@ -173,12 +170,10 @@ output_options.add_argument('--print', '-p', dest='output_options',
headers and body is printed), if standard output is not redirected. headers and body is printed), if standard output is not redirected.
If the output is piped to another program or to a file, If the output is piped to another program or to a file,
then only the body is printed by default. then only the body is printed by default.
'''.format( '''.format(request_headers=OUT_REQ_HEAD,
request_headers=OUT_REQ_HEAD, request_body=OUT_REQ_BODY,
request_body=OUT_REQ_BODY, response_headers=OUT_RESP_HEAD,
response_headers=OUT_RESP_HEAD, response_body=OUT_RESP_BODY,))
response_body=OUT_RESP_BODY,
))
) )
output_options.add_argument( output_options.add_argument(
'--verbose', '-v', dest='output_options', '--verbose', '-v', dest='output_options',
@ -205,7 +200,8 @@ output_options.add_argument(
'''.format(OUT_RESP_BODY)) '''.format(OUT_RESP_BODY))
) )
output_options.add_argument('--stream', '-S', action='store_true', default=False, output_options.add_argument(
'--stream', '-S', action='store_true', default=False,
help=_(''' help=_('''
Always stream the output by line, i.e., behave like `tail -f'. Always stream the output by line, i.e., behave like `tail -f'.
@ -218,8 +214,8 @@ output_options.add_argument('--stream', '-S', action='store_true', default=False
It is useful also without --pretty: It ensures that the output is flushed It is useful also without --pretty: It ensures that the output is flushed
more often and in smaller chunks. more often and in smaller chunks.
''' ''')
)) )
############################################################################### ###############################################################################
@ -229,7 +225,7 @@ sessions = parser.add_argument_group(title='Sessions')\
.add_mutually_exclusive_group(required=False) .add_mutually_exclusive_group(required=False)
sessions.add_argument( sessions.add_argument(
'--session', metavar='SESSION_NAME', '--session', metavar='SESSION_NAME', type=SessionNameArgType(),
help=_(''' help=_('''
Create, or reuse and update a session. Create, or reuse and update a session.
Within a session, custom headers, auth credential, as well as any Within a session, custom headers, auth credential, as well as any
@ -269,7 +265,6 @@ auth.add_argument(
) )
# Network # Network
############################################# #############################################
@ -340,7 +335,8 @@ troubleshooting.add_argument(
action='help', default=SUPPRESS, action='help', default=SUPPRESS,
help='Show this help message and exit' help='Show this help message and exit'
) )
troubleshooting.add_argument('--version', action='version', version=__version__) troubleshooting.add_argument(
'--version', action='version', version=__version__)
troubleshooting.add_argument( troubleshooting.add_argument(
'--traceback', action='store_true', default=False, '--traceback', action='store_true', default=False,
help='Prints exception traceback should one occur.' help='Prints exception traceback should one occur.'

View File

@ -21,8 +21,8 @@ def get_response(args, config_dir):
requests_kwargs = get_requests_kwargs(args) requests_kwargs = get_requests_kwargs(args)
if args.debug: if args.debug:
sys.stderr.write( sys.stderr.write('\n>>> requests.request(%s)\n\n'
'\n>>> requests.request(%s)\n\n' % pformat(requests_kwargs)) % pformat(requests_kwargs))
if not args.session and not args.session_read_only: if not args.session and not args.session_read_only:
response = requests.request(**requests_kwargs) response = requests.request(**requests_kwargs)
@ -34,7 +34,6 @@ def get_response(args, config_dir):
read_only=bool(args.session_read_only), read_only=bool(args.session_read_only),
) )
return response return response

View File

@ -3,7 +3,7 @@ import json
import errno import errno
from . import __version__ from . import __version__
from requests.compat import is_windows from requests.compat import is_windows
DEFAULT_CONFIG_DIR = os.environ.get( DEFAULT_CONFIG_DIR = os.environ.get(

View File

@ -96,8 +96,8 @@ class Parser(ArgumentParser):
self.env = env self.env = env
args, no_options = super(Parser, self).parse_known_args(args, namespace) args, no_options = super(Parser, self).parse_known_args(args,
#args = super(Parser, self).parse_args(args, namespace) namespace)
self._apply_no_options(args, no_options) self._apply_no_options(args, no_options)

View File

@ -155,7 +155,6 @@ class HTTPRequest(HTTPMessage):
if self._orig.params: if self._orig.params:
if url.query: if url.query:
qs += '&' qs += '&'
#noinspection PyUnresolvedReferences
qs += type(self._orig)._encode_params(self._orig.params) qs += type(self._orig)._encode_params(self._orig.params)
# Request-Line # Request-Line
@ -173,6 +172,7 @@ class HTTPRequest(HTTPMessage):
headers = ['%s: %s' % (name, value) headers = ['%s: %s' % (name, value)
for name, value in headers.items()] for name, value in headers.items()]
#noinspection PyTypeChecker
headers.insert(0, request_line) headers.insert(0, request_line)
return '\r\n'.join(headers).strip() return '\r\n'.join(headers).strip()
@ -199,7 +199,6 @@ class HTTPRequest(HTTPMessage):
body = self._orig._enc_data body = self._orig._enc_data
if isinstance(body, dict): if isinstance(body, dict):
#noinspection PyUnresolvedReferences
body = type(self._orig)._encode_params(body) body = type(self._orig)._encode_params(body)
if isinstance(body, str): if isinstance(body, str):

View File

@ -278,7 +278,6 @@ class BufferedPrettyStream(PrettyStream):
def _iter_body(self): def _iter_body(self):
#noinspection PyArgumentList
# Read the whole body before prettifying it, # Read the whole body before prettifying it,
# but bail out immediately if the body is binary. # but bail out immediately if the body is binary.
body = bytearray() body = bytearray()

View File

@ -19,7 +19,6 @@ To make it run faster and offline you can::
HTTPBIN_URL=http://localhost:5000 tox HTTPBIN_URL=http://localhost:5000 tox
""" """
from functools import partial
import subprocess import subprocess
import os import os
import sys import sys
@ -29,7 +28,6 @@ import tempfile
import unittest import unittest
import shutil import shutil
from requests.compat import urlparse
try: try:
from urllib.request import urlopen from urllib.request import urlopen
except ImportError: except ImportError:
@ -38,6 +36,7 @@ try:
from unittest import skipIf, skip from unittest import skipIf, skip
except ImportError: except ImportError:
skip = lambda msg: lambda self: None skip = lambda msg: lambda self: None
def skipIf(cond, reason): def skipIf(cond, reason):
def decorator(test_method): def decorator(test_method):
if cond: if cond:
@ -132,6 +131,7 @@ class TestEnvironment(Environment):
if self.delete_config_dir: if self.delete_config_dir:
self._shutil.rmtree(self.config_dir) self._shutil.rmtree(self.config_dir)
def has_docutils(): def has_docutils():
try: try:
#noinspection PyUnresolvedReferences #noinspection PyUnresolvedReferences
@ -140,6 +140,7 @@ def has_docutils():
except ImportError: except ImportError:
return False return False
def get_readme_errors(): def get_readme_errors():
p = subprocess.Popen([ p = subprocess.Popen([
'rst2pseudoxml.py', 'rst2pseudoxml.py',
@ -154,6 +155,8 @@ def get_readme_errors():
class BytesResponse(bytes): class BytesResponse(bytes):
stderr = json = exit_status = None stderr = json = exit_status = None
class StrResponse(str): class StrResponse(str):
stderr = json = exit_status = None stderr = json = exit_status = None
@ -1007,7 +1010,8 @@ class StreamTest(BaseTestCase):
#self.assertIn(OK_COLOR, r) #self.assertIn(OK_COLOR, r)
def test_encoded_stream(self): def test_encoded_stream(self):
"""Test that --stream works with non-prettified redirected terminal output.""" """Test that --stream works with non-prettified
redirected terminal output."""
with open(BIN_FILE_PATH, 'rb') as f: with open(BIN_FILE_PATH, 'rb') as f:
r = http( r = http(
'--pretty=none', '--pretty=none',
@ -1025,7 +1029,8 @@ class StreamTest(BaseTestCase):
#self.assertIn(OK, r) #self.assertIn(OK, r)
def test_redirected_stream(self): def test_redirected_stream(self):
"""Test that --stream works with non-prettified redirected terminal output.""" """Test that --stream works with non-prettified
redirected terminal output."""
with open(BIN_FILE_PATH, 'rb') as f: with open(BIN_FILE_PATH, 'rb') as f:
r = http( r = http(
'--pretty=none', '--pretty=none',
@ -1049,7 +1054,6 @@ class LineEndingsTest(BaseTestCase):
as the headers/body separator.""" as the headers/body separator."""
def _validate_crlf(self, msg): def _validate_crlf(self, msg):
#noinspection PyUnresolvedReferences
lines = iter(msg.splitlines(True)) lines = iter(msg.splitlines(True))
for header in lines: for header in lines:
if header == CRLF: if header == CRLF:
@ -1084,7 +1088,7 @@ class LineEndingsTest(BaseTestCase):
'GET', 'GET',
httpbin('/get') httpbin('/get')
) )
self.assertEqual(r.exit_status,0) self.assertEqual(r.exit_status, 0)
self._validate_crlf(r) self._validate_crlf(r)
def test_CRLF_ugly_request(self): def test_CRLF_ugly_request(self):
@ -1256,8 +1260,8 @@ class ArgumentParserTestCase(unittest.TestCase):
self.assertEqual(args.items, [ self.assertEqual(args.items, [
input.KeyValue( input.KeyValue(
key='new_item', value='a', sep='=', orig='new_item=a'), key='new_item', value='a', sep='=', orig='new_item=a'),
input.KeyValue(key input.KeyValue(
='old_item', value='b', sep='=', orig='old_item=b'), key='old_item', value='b', sep='=', orig='old_item=b'),
]) ])
@ -1402,5 +1406,4 @@ class SessionTest(BaseTestCase):
if __name__ == '__main__': if __name__ == '__main__':
#noinspection PyCallingNonCallable
unittest.main() unittest.main()