mirror of
https://github.com/httpie/cli.git
synced 2025-08-17 15:41:02 +02:00
Compare commits
114 Commits
Author | SHA1 | Date | |
---|---|---|---|
b565b4628e | |||
65081b2f12 | |||
963b2746f5 | |||
098257c0be | |||
30eb0c2f26 | |||
9fbe745987 | |||
01a546eedd | |||
eba6b63c55 | |||
33eb9acd92 | |||
293295cad6 | |||
557911b606 | |||
5300b0b490 | |||
001bda1945 | |||
7c68d87c10 | |||
35a99fe04b | |||
76e15b227c | |||
8881ebf033 | |||
25d1e8e418 | |||
7ce6eb148e | |||
6e1dbadff9 | |||
a6ebc44a48 | |||
5e03aeceb7 | |||
13ee9389aa | |||
bb49a1f979 | |||
4e574e6b8e | |||
529981af7a | |||
6731cb881a | |||
f7d1b739e2 | |||
5bdf4a3bae | |||
2d9414d34c | |||
20823c1702 | |||
5dbd104c3b | |||
13a979ad11 | |||
4cfa143bfe | |||
d24f30d0af | |||
66e168b2af | |||
564670566c | |||
ecbbad816a | |||
0432694661 | |||
dc4da527db | |||
38e8ef14ec | |||
c73dcaf63d | |||
fb85509e91 | |||
a2dca1e3bb | |||
c2dae62af0 | |||
ae7008ee96 | |||
f6824f7ade | |||
7fd46e0b0d | |||
d4067fcb6d | |||
20f01709ea | |||
56afd1adb9 | |||
5e87a2d7e5 | |||
d30e28c2c7 | |||
0d2d24eac7 | |||
e2751e5fa3 | |||
2a25d71aa4 | |||
01ca7f0eb2 | |||
4f8d6c013b | |||
e83e554ffb | |||
345f5a02a2 | |||
f96f0ef9ed | |||
74e4d0b678 | |||
0fc1f61f3d | |||
c50413a9c1 | |||
9f8c452e7e | |||
776328c818 | |||
9312fabc01 | |||
48ce934dfa | |||
3625bb6fa1 | |||
a97f0d52f6 | |||
41b0286f37 | |||
fee54b04d8 | |||
73e0455896 | |||
3b217daddc | |||
e5e5d0ce6d | |||
f43e473de1 | |||
0a002ec554 | |||
576ee83d82 | |||
e42f7b8fc9 | |||
b44e16ed0f | |||
ed08ab133e | |||
5408fb0fb9 | |||
e18b609ef7 | |||
356e043651 | |||
c6d4f6cdf6 | |||
dc1371d4d6 | |||
e2235e56dc | |||
763935b77f | |||
6435532f72 | |||
11a37067e7 | |||
25f0156502 | |||
0f8d04b4df | |||
e385ed6a99 | |||
01fdab55e9 | |||
1127557742 | |||
5898879395 | |||
8c33e5e3d3 | |||
10da7b63a3 | |||
df193a373f | |||
c2f8c36952 | |||
56f498c153 | |||
59e22b16b8 | |||
d32d6f29a9 | |||
274dddfb45 | |||
deb7b747cc | |||
018e1f68de | |||
ac69d4311b | |||
c75c4fa2a6 | |||
a6a79e92e4 | |||
ea76542150 | |||
c6690e0182 | |||
c82c9f0ae4 | |||
84b81c00ea | |||
34c6958dc8 |
1
.coveragerc
Normal file
1
.coveragerc
Normal file
@ -0,0 +1 @@
|
||||
; needs to exist otherwise `$ coveralls` fails
|
18
.gitignore
vendored
18
.gitignore
vendored
@ -1,11 +1,13 @@
|
||||
dist
|
||||
httpie.egg-info
|
||||
build
|
||||
.DS_Store
|
||||
.idea/
|
||||
__pycache__/
|
||||
dist/
|
||||
httpie.egg-info/
|
||||
build/
|
||||
*.egg-info
|
||||
.cache/
|
||||
.tox
|
||||
.coverage
|
||||
*.pyc
|
||||
*.egg
|
||||
.tox
|
||||
README.html
|
||||
.coverage
|
||||
htmlcov
|
||||
.idea
|
||||
.DS_Store
|
||||
|
71
.travis.yml
71
.travis.yml
@ -1,20 +1,79 @@
|
||||
# https://travis-ci.org/jkbrzt/httpie
|
||||
sudo: false
|
||||
|
||||
language: python
|
||||
os:
|
||||
- linux
|
||||
# - osx
|
||||
|
||||
env:
|
||||
global:
|
||||
- NEWEST_PYTHON=3.4
|
||||
language: python
|
||||
- NEWEST_PYTHON=3.5
|
||||
|
||||
python:
|
||||
- 2.6
|
||||
- 2.7
|
||||
- pypy
|
||||
- 3.3
|
||||
- 3.4
|
||||
- 3.5
|
||||
- pypy3
|
||||
|
||||
matrix:
|
||||
|
||||
include:
|
||||
|
||||
# Manually defined OS X builds
|
||||
# https://docs.travis-ci.com/user/multi-os/#Python-example-(unsupported-languages)
|
||||
|
||||
# Stock OSX Python
|
||||
- os: osx
|
||||
language: generic
|
||||
env:
|
||||
- TOXENV=py27
|
||||
|
||||
# Latest Python 2.x from Homebrew
|
||||
- os: osx
|
||||
language: generic
|
||||
env:
|
||||
- TOXENV=py27
|
||||
- BREW_INSTALL=python
|
||||
|
||||
# Latest Python 3.x from Homebrew
|
||||
- os: osx
|
||||
language: generic
|
||||
env:
|
||||
- TOXENV=py35
|
||||
- BREW_INSTALL=python3
|
||||
|
||||
install:
|
||||
- |
|
||||
if [[ $TRAVIS_OS_NAME == 'osx' ]]; then
|
||||
if [[ -n "$BREW_INSTALL" ]]; then
|
||||
brew update
|
||||
brew install "$BREW_INSTALL"
|
||||
fi
|
||||
sudo pip install tox
|
||||
fi
|
||||
|
||||
script:
|
||||
- make
|
||||
- |
|
||||
if [[ $TRAVIS_OS_NAME == 'linux' ]]; then
|
||||
make
|
||||
else
|
||||
PATH="/usr/local/bin:$PATH" tox -e "$TOXENV"
|
||||
fi
|
||||
|
||||
after_success:
|
||||
- if [[ $TRAVIS_PYTHON_VERSION == $NEWEST_PYTHON ]]; then pip install python-coveralls && coveralls; fi
|
||||
- |
|
||||
if [[ $TRAVIS_PYTHON_VERSION == $NEWEST_PYTHON && $TRAVIS_OS_NAME == 'linux' ]]; then
|
||||
pip install python-coveralls && coveralls
|
||||
fi
|
||||
|
||||
notifications:
|
||||
|
||||
webhooks:
|
||||
urls:
|
||||
# https://gitter.im/jkbrzt/httpie
|
||||
- https://webhooks.gitter.im/e/c42fcd359a110d02830b
|
||||
on_success: always # options: [always|never|change] default: always
|
||||
on_failure: always # options: [always|never|change] default: always
|
||||
on_start: always # options: [always|never|change] default: always
|
||||
|
@ -8,6 +8,8 @@ HTTPie authors
|
||||
Patches and ideas
|
||||
-----------------
|
||||
|
||||
`Complete list of contributors on GitHib <https://github.com/jkbrzt/httpie/graphs/contributors>`_
|
||||
|
||||
* `Cláudia T. Delgado <https://github.com/claudiatd>`_ (logo)
|
||||
* `Hank Gay <https://github.com/gthank>`_
|
||||
* `Jake Basile <https://github.com/jakebasile>`_
|
||||
@ -34,3 +36,5 @@ Patches and ideas
|
||||
* `Dennis Brakhane <https://github.com/brakhane>`_
|
||||
* `Matt Layman <https://github.com/mblayman>`_
|
||||
* `Edward Yang <https://github.com/honorabrutroll>`_
|
||||
|
||||
|
||||
|
@ -6,9 +6,40 @@ This document records all notable changes to `HTTPie <http://httpie.org>`_.
|
||||
This project adheres to `Semantic Versioning <http://semver.org/>`_.
|
||||
|
||||
|
||||
`0.9.3`_ (2016-01-01)
|
||||
`1.0.0-dev`_ (Unreleased)
|
||||
-------------------------
|
||||
|
||||
|
||||
`0.9.4`_ (2016-07-01)
|
||||
---------------------
|
||||
|
||||
* Added ``Content-Type`` of files uploaded in ``multipart/form-data`` requests
|
||||
* Added ``--ssl=<PROTOCOL>`` to specify the desired SSL/TLS protocol version
|
||||
to use for HTTPS requests.
|
||||
* Added JSON detection with ``--json, -j`` to work around incorrect
|
||||
``Content-Type``
|
||||
* Added ``--all`` to show intermediate responses such as redirects (with ``--follow``)
|
||||
* Added ``--history-print, -P WHAT`` to specify formatting of intermediate responses
|
||||
* Added ``--max-redirects=N`` (default 30)
|
||||
* Added ``-A`` as short name for ``--auth-type``
|
||||
* Added ``-F`` as short name for ``--follow``
|
||||
* Removed the ``implicit_content_type`` config option
|
||||
(use ``"default_options": ["--form"]`` instead)
|
||||
* Redirected ``stdout`` doesn't trigger an error anymore when ``--output FILE``
|
||||
is set
|
||||
* Changed the default ``--style`` back to ``solarized`` for better support
|
||||
of light and dark terminals
|
||||
* Improved ``--debug`` output
|
||||
* Fixed ``--session`` when used with ``--download``
|
||||
* Fixed ``--download`` to trim too long filenames before saving the file
|
||||
* Fixed the handling of ``Content-Type`` with multiple ``+subtype`` parts
|
||||
* Removed the XML formatter as the implementation suffered from multiple issues
|
||||
|
||||
|
||||
|
||||
`0.9.3`_ (2016-01-01)
|
||||
---------------------
|
||||
|
||||
* Changed the default color ``--style`` from ``solarized`` to ``monokai``
|
||||
* Added basic Bash autocomplete support (need to be installed manually)
|
||||
* Added request details to connection error messages
|
||||
@ -257,4 +288,5 @@ This project adheres to `Semantic Versioning <http://semver.org/>`_.
|
||||
.. _0.9.1: https://github.com/jkbrzt/httpie/compare/0.9.0...0.9.1
|
||||
.. _0.9.2: https://github.com/jkbrzt/httpie/compare/0.9.1...0.9.2
|
||||
.. _0.9.3: https://github.com/jkbrzt/httpie/compare/0.9.2...0.9.3
|
||||
.. _1.0.0-dev: https://github.com/jkbrzt/httpie/compare/0.9.3...master
|
||||
.. _0.9.4: https://github.com/jkbrzt/httpie/compare/0.9.3...0.9.4
|
||||
.. _1.0.0-dev: https://github.com/jkbrzt/httpie/compare/0.9.4...master
|
||||
|
@ -1,12 +1,13 @@
|
||||
######################
|
||||
Contributing to HTTPie
|
||||
######################
|
||||
|
||||
Bug reports and code and documentation patches are greatly appreciated. You can
|
||||
also help by using the development version of HTTPie and reporting any bugs you
|
||||
might encounter.
|
||||
Bug reports and code and documentation patches are welcome. You can
|
||||
help this project also by using the development version of HTTPie
|
||||
and by reporting any bugs you might encounter.
|
||||
|
||||
Bug Reports
|
||||
===========
|
||||
1. Reporting bugs
|
||||
=================
|
||||
|
||||
**It's important that you provide the full command argument list
|
||||
as well as the output of the failing command.**
|
||||
@ -15,12 +16,12 @@ to your bug report, e.g.:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ http --debug [arguments that trigger the error]
|
||||
[complete output]
|
||||
$ http --debug [COMPLETE ARGUMENT LIST THAT TRIGGERS THE ERROR]
|
||||
[COMPLETE OUTPUT]
|
||||
|
||||
|
||||
Contributing Code and Documentation
|
||||
===================================
|
||||
2. Contributing Code and Docs
|
||||
=============================
|
||||
|
||||
Before working on a new feature or a bug, please browse `existing issues`_
|
||||
to see whether it has been previously discussed. If the change in question
|
||||
@ -28,8 +29,11 @@ is a bigger one, it's always good to discuss before your starting working on
|
||||
it.
|
||||
|
||||
|
||||
Development Environment
|
||||
-----------------------
|
||||
Creating Development Environment
|
||||
--------------------------------
|
||||
|
||||
Go to https://github.com/jkbrzt/httpie and fork the project repository.
|
||||
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
@ -52,44 +56,61 @@ Making Changes
|
||||
Please make sure your changes conform to `Style Guide for Python Code`_ (PEP8).
|
||||
|
||||
|
||||
Tests
|
||||
-----
|
||||
Testing
|
||||
-------
|
||||
|
||||
Before opening a pull requests, please make sure the `test suite`_ passes
|
||||
in all of the `supported Python environments`_. You should also **add tests
|
||||
for any new features and bug fixes**.
|
||||
in all of the `supported Python environments`_. You should also add tests
|
||||
for any new features and bug fixes.
|
||||
|
||||
HTTPie uses `pytest`_ and `Tox`_.
|
||||
HTTPie uses `pytest`_ and `Tox`_ for testing.
|
||||
|
||||
|
||||
Running all tests:
|
||||
******************
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
### Running all tests:
|
||||
|
||||
# Current Python
|
||||
# Run all tests on the current Python interpreter
|
||||
make test
|
||||
|
||||
# Current Python with coverage
|
||||
# Run all tests on the current Python with coverage
|
||||
make test-cover
|
||||
|
||||
# All the supported and available Pythons via Tox
|
||||
# Run all tests in all of the supported and available Pythons via Tox
|
||||
make test-tox
|
||||
|
||||
### Running specific tests:
|
||||
# Run all tests for code as well as packaging, etc.
|
||||
make test-all
|
||||
|
||||
# Current Python
|
||||
pytest tests/test_uploads.py
|
||||
|
||||
# All Pythons
|
||||
Running specific tests:
|
||||
***********************
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
# Run specific tests on the current Python
|
||||
py.test tests/test_uploads.py
|
||||
py.test tests/test_uploads.py::TestMultipartFormDataFileUpload
|
||||
py.test tests/test_uploads.py::TestMultipartFormDataFileUpload::test_upload_ok
|
||||
|
||||
# Run specific tests on the on all Pythons via Tox
|
||||
tox -- tests/test_uploads.py --verbose
|
||||
tox -- tests/test_uploads.py::TestMultipartFormDataFileUpload --verbose
|
||||
tox -- tests/test_uploads.py::TestMultipartFormDataFileUpload::test_upload_ok --verbose
|
||||
|
||||
|
||||
Don't forget to add yourself to `AUTHORS.rst`_.
|
||||
-----
|
||||
|
||||
See `Makefile`_ for additional development utilities.
|
||||
Don't forget to add yourself to `AUTHORS`_!
|
||||
|
||||
|
||||
.. _Tox: http://tox.testrun.org
|
||||
.. _supported Python environments: https://github.com/jkbrzt/httpie/blob/master/tox.ini
|
||||
.. _existing issues: https://github.com/jkbrzt/httpie/issues?state=open
|
||||
.. _AUTHORS.rst: https://github.com/jkbrzt/httpie/blob/master/AUTHORS.rst
|
||||
.. _AUTHORS: https://github.com/jkbrzt/httpie/blob/master/AUTHORS.rst
|
||||
.. _Makefile: https://github.com/jkbrzt/httpie/blob/master/Makefile
|
||||
.. _pytest: http://pytest.org/
|
||||
.. _Style Guide for Python Code: http://python.org/dev/peps/pep-0008/
|
||||
.. _test suite: https://github.com/jkbrzt/httpie/tree/master/tests
|
||||
|
2
LICENSE
2
LICENSE
@ -1,4 +1,4 @@
|
||||
Copyright © 2012-2015 Jakub Roztocil <jakub@roztocil.co>
|
||||
Copyright © 2012-2016 Jakub Roztocil <jakub@roztocil.co>
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
45
Makefile
45
Makefile
@ -1,39 +1,42 @@
|
||||
#
|
||||
# See ./CONTRIBUTING.rst
|
||||
#
|
||||
|
||||
VERSION=$(shell grep __version__ httpie/__init__.py)
|
||||
REQUIREMENTS="requirements-dev.txt"
|
||||
TAG="\n\n\033[0;32m\#\#\# "
|
||||
END=" \#\#\# \033[0m\n"
|
||||
|
||||
|
||||
all: test
|
||||
|
||||
uninstall-httpie:
|
||||
@echo $(TAG)Removing existing installation of HTTPie$(END)
|
||||
- pip uninstall --yes httpie >/dev/null
|
||||
! which http
|
||||
@echo
|
||||
|
||||
uninstall-all: uninstall-httpie
|
||||
- pip uninstall --yes -r $(REQUIREMENTS)
|
||||
|
||||
init: uninstall-httpie
|
||||
@echo $(TAG)Installing dev requirements$(END)
|
||||
pip install --upgrade -r $(REQUIREMENTS)
|
||||
|
||||
@echo $(TAG)Installing HTTPie$(END)
|
||||
pip install --upgrade --editable .
|
||||
|
||||
@echo
|
||||
|
||||
|
||||
test: init
|
||||
@echo $(TAG)Running tests in on current Python with coverage $(END)
|
||||
@echo $(TAG)Running tests on the current Python interpreter with coverage $(END)
|
||||
py.test --cov ./httpie --cov ./tests --doctest-modules --verbose ./httpie ./tests
|
||||
@echo
|
||||
|
||||
|
||||
test-tox: init
|
||||
@echo $(TAG)Running tests on all Pythons via Tox$(END)
|
||||
tox
|
||||
@echo
|
||||
|
||||
|
||||
test-dist: test-sdist test-bdist-wheel
|
||||
@echo
|
||||
|
||||
|
||||
test-sdist: clean uninstall-httpie
|
||||
@echo $(TAG)Testing sdist build an installation$(END)
|
||||
python setup.py sdist
|
||||
@ -41,6 +44,7 @@ test-sdist: clean uninstall-httpie
|
||||
which http
|
||||
@echo
|
||||
|
||||
|
||||
test-bdist-wheel: clean uninstall-httpie
|
||||
@echo $(TAG)Testing wheel build an installation$(END)
|
||||
python setup.py bdist_wheel
|
||||
@ -48,9 +52,11 @@ test-bdist-wheel: clean uninstall-httpie
|
||||
which http
|
||||
@echo
|
||||
|
||||
|
||||
# This tests everything, even this Makefile.
|
||||
test-all: uninstall-all clean init test test-tox test-dist
|
||||
|
||||
|
||||
publish: test-all
|
||||
@echo $(TAG)Testing wheel build an installation$(END)
|
||||
@echo "$(VERSION)"
|
||||
@ -60,8 +66,29 @@ publish: test-all
|
||||
python setup.py bdist_wheel upload
|
||||
@echo
|
||||
|
||||
|
||||
clean:
|
||||
@echo $(TAG)Cleaning up$(END)
|
||||
rm -rf .tox *.egg dist build .coverage
|
||||
find . -name '__pycache__' -delete -print -o -name '*.pyc' -delete -print
|
||||
@echo
|
||||
|
||||
|
||||
uninstall-httpie:
|
||||
@echo $(TAG)Uninstalling httpie$(END)
|
||||
- pip uninstall --yes httpie &2>/dev/null
|
||||
|
||||
@echo "Verifying…"
|
||||
cd .. && ! python -m httpie --version &2>/dev/null
|
||||
|
||||
@echo "Done"
|
||||
@echo
|
||||
|
||||
|
||||
uninstall-all: uninstall-httpie
|
||||
|
||||
@echo $(TAG)Uninstalling httpie requirements$(END)
|
||||
- pip uninstall --yes pygments requests
|
||||
|
||||
@echo $(TAG)Uninstalling development requirements$(END)
|
||||
- pip uninstall --yes -r $(REQUIREMENTS)
|
||||
|
215
README.rst
215
README.rst
@ -23,7 +23,7 @@ HTTPie is written in Python, and under the hood it uses the excellent
|
||||
|
||||
-----
|
||||
|
||||
|pypi| |unix_build| |windows_build| |coverage|
|
||||
|pypi| |unix_build| |windows_build| |coverage| |gitter|
|
||||
|
||||
-----
|
||||
|
||||
@ -59,13 +59,21 @@ Installation
|
||||
============
|
||||
|
||||
|
||||
On **Mac OS X**, HTTPie can be installed via `Homebrew <http://brew.sh/>`_:
|
||||
On **Mac OS X**, HTTPie can be installed via `Homebrew <http://brew.sh/>`_
|
||||
(recommended):
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ brew install httpie
|
||||
|
||||
|
||||
A MacPorts *port* is also available:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ port install httpie
|
||||
|
||||
|
||||
Most **Linux** distributions provide a package that can be installed using the
|
||||
system package manager, e.g.:
|
||||
|
||||
@ -106,7 +114,7 @@ The **latest development version** can be installed directly from GitHub:
|
||||
$ brew install httpie --HEAD
|
||||
|
||||
# Universal
|
||||
$ pip install --upgrade https://github.com/jkbrzt/httpie/tarball/master
|
||||
$ pip install --upgrade https://github.com/jkbrzt/httpie/archive/master.tar.gz
|
||||
|
||||
|
||||
|
||||
@ -279,18 +287,20 @@ If the port is omitted, then port 80 is assumed.
|
||||
|
||||
If you find yourself manually constructing URLs with **querystring parameters**
|
||||
on the terminal, you may appreciate the ``param==value`` syntax for appending
|
||||
URL parameters so that you don't have to worry about escaping the ``&``
|
||||
separators. To search for ``HTTPie`` on Google Images you could use this
|
||||
command:
|
||||
URL parameters. With that, you don't have to worry about escaping the ``&``
|
||||
separators for you shell. Also, special characters in parameter values,
|
||||
will also automatically escaped (HTTPie otherwise expects the URL to be
|
||||
already escaped). To search for ``HTTPie logo`` on Google Images you could use
|
||||
this command:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ http GET www.google.com search==HTTPie tbm==isch
|
||||
$ http www.google.com search=='HTTPie logo' tbm==isch
|
||||
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
GET /?search=HTTPie&tbm=isch HTTP/1.1
|
||||
GET /?search=HTTPie+logo&tbm=isch HTTP/1.1
|
||||
|
||||
|
||||
=============
|
||||
@ -333,11 +343,29 @@ their type is distinguished only by the separator used:
|
||||
| | in a ``multipart/form-data`` request. |
|
||||
+-----------------------+-----------------------------------------------------+
|
||||
|
||||
|
||||
You can use ``\`` to escape characters that shouldn't be used as separators
|
||||
(or parts thereof). For instance, ``foo\==bar`` will become a data key/value
|
||||
pair (``foo=`` and ``bar``) instead of a URL parameter.
|
||||
|
||||
You can also quote values, e.g. ``foo="bar baz"``.
|
||||
Often it is necessary to quote the values, e.g. ``foo='bar baz'``.
|
||||
|
||||
If any of the field names or headers starts with a minus
|
||||
(e.g., ``-fieldname``), you need to place all such items after the special
|
||||
token ``--`` to prevent confusion with ``--arguments``:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ http httpbin.org/post -- -name-starting-with-dash=foo --Weird-Header:bar
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
POST /post HTTP/1.1
|
||||
--Weird-Header: bar
|
||||
|
||||
{
|
||||
"-name-starting-with-dash": "value"
|
||||
}
|
||||
|
||||
Note that data fields aren't the only way to specify request data:
|
||||
`Redirected input`_ allows for passing arbitrary data to be sent with the
|
||||
@ -363,7 +391,9 @@ both of which can be overwritten:
|
||||
You can use ``--json, -j`` to explicitly set ``Accept``
|
||||
to ``application/json`` regardless of whether you are sending data
|
||||
(it's a shortcut for setting the header via the usual header notation –
|
||||
``http url Accept:application/json``).
|
||||
``http url Accept:application/json``). Additionally,
|
||||
HTTPie will try to detect JSON responses even when the
|
||||
``Content-Type`` is incorrectly ``text/plain`` or unknown.
|
||||
|
||||
Simple example:
|
||||
|
||||
@ -539,7 +569,7 @@ The currently supported authentication schemes are Basic and Digest
|
||||
supported as well (but credentials passed via ``-a``
|
||||
have higher priority).
|
||||
|
||||
``--auth-type`` Specify the auth mechanism. Possible values are
|
||||
``--auth-type, -A`` Specify the auth mechanism. Possible values are
|
||||
``basic`` and ``digest``. The default value is
|
||||
``basic`` so it can often be omitted.
|
||||
=================== ======================================================
|
||||
@ -559,7 +589,7 @@ Digest auth:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ http --auth-type=digest -a username:password example.org
|
||||
$ http -A digest -a username:password example.org
|
||||
|
||||
|
||||
With password prompt:
|
||||
@ -588,6 +618,7 @@ Auth Plugins
|
||||
------------
|
||||
|
||||
* `httpie-oauth <https://github.com/jkbrzt/httpie-oauth>`_: OAuth
|
||||
* `httpie-hmac-auth <https://github.com/guardian/httpie-hmac-auth>`_: HMAC
|
||||
* `httpie-ntlm <https://github.com/jkbrzt/httpie-ntlm>`_: NTLM (NT LAN Manager)
|
||||
* `httpie-negotiate <https://github.com/ndzou/httpie-negotiate>`_: SPNEGO (GSS Negotiate)
|
||||
* `requests-hawk <https://github.com/mozilla-services/requests-hawk>`_: Hawk
|
||||
@ -596,6 +627,26 @@ Auth Plugins
|
||||
* `httpie-jwt-auth <https://github.com/teracyhq/httpie-jwt-auth>`_: JWTAuth (JSON Web Tokens)
|
||||
|
||||
|
||||
==============
|
||||
HTTP Redirects
|
||||
==============
|
||||
|
||||
By default, HTTP redirects are not followed and only the first
|
||||
response is shown. To instruct HTTPie to follow the ``Location`` header of
|
||||
``30x`` responses and show the final response instead, use the ``--follow, -F`` option.
|
||||
|
||||
If you additionally wish to see the intermediary requests/responses,
|
||||
then use the ``--all`` option as well.
|
||||
|
||||
To change the default limit of maximum 30 redirects, use the
|
||||
``--max-redirects=<limit>`` option.
|
||||
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ http --follow --all --max-redirects=5 httpbin.org/redirect/3
|
||||
|
||||
|
||||
=======
|
||||
Proxies
|
||||
=======
|
||||
@ -679,6 +730,22 @@ path of the key file with ``--cert-key``:
|
||||
$ http --cert=client.crt --cert-key=client.key https://example.org
|
||||
|
||||
|
||||
-----------
|
||||
SSL version
|
||||
-----------
|
||||
|
||||
Use the ``--ssl=<PROTOCOL>`` to specify the desired protocol version to use.
|
||||
This will default to SSL v2.3 which will negotiate the highest protocol that both
|
||||
the server and your installation of OpenSSL support. The available protocols
|
||||
are ``ssl2.3``, ``ssl3``, ``tls1``, ``tls1.1``, ``tls1.2``. (The actually
|
||||
available set of protocols may vary depending on your OpenSSL installation.)
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
# Specify the vulnerable SSL v3 protocol to talk to an outdated server:
|
||||
$ http --ssl=ssl3 https://vulnerable.example.org
|
||||
|
||||
|
||||
----------------------------
|
||||
SNI (Server Name Indication)
|
||||
----------------------------
|
||||
@ -704,8 +771,8 @@ You can use the following command to test SNI support:
|
||||
Output Options
|
||||
==============
|
||||
|
||||
By default, HTTPie outputs the whole response message (headers as well as the
|
||||
body).
|
||||
By default, HTTPie only outputs the final response and the whole response
|
||||
message is printed (headers as well as the body).
|
||||
|
||||
You can control what should be printed via several options:
|
||||
|
||||
@ -713,6 +780,7 @@ You can control what should be printed via several options:
|
||||
``--headers, -h`` Only the response headers are printed.
|
||||
``--body, -b`` Only the response body is printed.
|
||||
``--verbose, -v`` Print the whole HTTP exchange (request and response).
|
||||
This option also enables ``--all`` (see bellow).
|
||||
``--print, -p`` Selects parts of the HTTP exchange.
|
||||
================= =====================================================
|
||||
|
||||
@ -753,10 +821,10 @@ the HTTP exchange:
|
||||
========== ==================
|
||||
Character Stands for
|
||||
========== ==================
|
||||
``H`` Request headers.
|
||||
``B`` Request body.
|
||||
``h`` Response headers.
|
||||
``b`` Response body.
|
||||
``H`` request headers
|
||||
``B`` request body
|
||||
``h`` response headers
|
||||
``b`` response body
|
||||
========== ==================
|
||||
|
||||
Print request and response headers:
|
||||
@ -766,6 +834,34 @@ Print request and response headers:
|
||||
$ http --print=Hh PUT httpbin.org/put hello=world
|
||||
|
||||
|
||||
---------------------------------------
|
||||
Viewing Intermediary Requests/Responses
|
||||
---------------------------------------
|
||||
|
||||
To see *all* the HTTP communication, i.e. the final request/resposne as
|
||||
well as any possible intermediary requests/responses, use the **``--all``**
|
||||
option. The intermediary HTTP communication include followed redirects
|
||||
(with ``--follow``), the first unauthorized request when HTTP digest
|
||||
authentication is used (``--auth=digest``), etc.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
# Include all responses that lead to the final one:
|
||||
$ http --all --follow httpbin.org/redirect/3
|
||||
|
||||
|
||||
The intermediary requests/response are by default formatted according to
|
||||
``--print, -p`` (and its shortcuts described above). If you'd like to change
|
||||
that, use the ``--history-print, -P`` option. It takes the same
|
||||
arguments as ``--print, -p`` but applies to the intermediary requests only.
|
||||
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
# Print the intermediary requests/responses differently than the final one:
|
||||
$ http -A digest -a foo:bar --all -p Hh -P H httpbin.org/digest-auth/auth/foo/bar
|
||||
|
||||
|
||||
-------------------------
|
||||
Conditional Body Download
|
||||
-------------------------
|
||||
@ -904,7 +1000,6 @@ Also, the following formatting is applied:
|
||||
* HTTP headers are sorted by name.
|
||||
* JSON data is indented, sorted by keys, and unicode escapes are converted
|
||||
to the characters they represent.
|
||||
* XML data is indented for better readability.
|
||||
|
||||
One of these options can be used to control output processing:
|
||||
|
||||
@ -1009,20 +1104,17 @@ is being saved to a file.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ http --download https://github.com/jkbrzt/httpie/tarball/master
|
||||
$ http --download https://github.com/jkbrzt/httpie/archive/master.tar.gz
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Connection: keep-alive
|
||||
Content-Disposition: attachment; filename=jkbrzt-httpie-0.4.1-33-gfc4f70a.tar.gz
|
||||
Content-Length: 505530
|
||||
Content-Disposition: attachment; filename=httpie-master.tar.gz
|
||||
Content-Length: 257336
|
||||
Content-Type: application/x-gzip
|
||||
Server: GitHub.com
|
||||
Vary: Accept-Encoding
|
||||
|
||||
Downloading 494.89 kB to "jkbrzt-httpie-0.4.1-33-gfc4f70a.tar.gz"
|
||||
/ 21.01% 104.00 kB 47.55 kB/s 0:00:08 ETA
|
||||
Downloading 251.30 kB to "httpie-master.tar.gz"
|
||||
Done. 251.30 kB in 2.73862s (91.76 kB/s)
|
||||
|
||||
|
||||
If not provided via ``--output, -o``, the output filename will be determined
|
||||
@ -1035,7 +1127,7 @@ headers and progress are still shown in the terminal:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ http -d https://github.com/jkbrzt/httpie/tarball/master | tar zxf -
|
||||
$ http -d https://github.com/jkbrzt/httpie/archive/master.tar.gz | tar zxf -
|
||||
|
||||
|
||||
If ``--output, -o`` is specified, you can resume a partial download using the
|
||||
@ -1166,36 +1258,32 @@ Config
|
||||
HTTPie uses a simple configuration file that contains a JSON object with the
|
||||
following keys:
|
||||
|
||||
========================= =================================================
|
||||
``__meta__`` HTTPie automatically stores some metadata here.
|
||||
Do not change.
|
||||
|
||||
``implicit_content_type`` A ``String`` specifying the implicit content type
|
||||
for request data. The default value for this
|
||||
option is ``json`` and can be changed to
|
||||
``form``.
|
||||
------------
|
||||
``__meta__``
|
||||
------------
|
||||
|
||||
``default_options`` An ``Array`` (by default empty) of options
|
||||
that should be applied to every request.
|
||||
HTTPie automatically stores some of its metadata here. Do not change.
|
||||
|
||||
For instance, you can use this option to change
|
||||
the default style and output options:
|
||||
``"default_options": ["--style=fruity", "--body"]``
|
||||
|
||||
Another useful default option is
|
||||
``"--session=default"`` to make HTTPie always
|
||||
use `sessions`_.
|
||||
-------------------
|
||||
``default_options``
|
||||
-------------------
|
||||
|
||||
Default options from config file can be unset
|
||||
for a particular invocation via
|
||||
``--no-OPTION`` arguments passed on the
|
||||
command line (e.g., ``--no-style``
|
||||
or ``--no-session``).
|
||||
========================= =================================================
|
||||
An ``Array`` (by default empty) of default options that should be applied to
|
||||
every invocation of HTTPie.
|
||||
|
||||
The default location of the configuration file is ``~/.httpie/config.json``
|
||||
(or ``%APPDATA%\httpie\config.json`` on Windows).
|
||||
For instance, you can use this option to change the default style and output
|
||||
options: ``"default_options": ["--style=fruity", "--body"]`` Another useful
|
||||
default option could be ``"--session=default"`` to make HTTPie always
|
||||
use `sessions`_ (one named ``default`` will automatically be used).
|
||||
Or you could change the implicit request content type from JSON to form by
|
||||
adding ``--form`` to the list.
|
||||
|
||||
Default options from config file can be unset for a particular invocation via
|
||||
``--no-OPTION`` arguments passed on the command line (e.g., ``--no-style``
|
||||
or ``--no-session``). The default location of the configuration file is
|
||||
``~/.httpie/config.json`` (or ``%APPDATA%\httpie\config.json`` on Windows).
|
||||
The config directory location can be changed by setting the
|
||||
``HTTPIE_CONFIG_DIR`` environment variable.
|
||||
|
||||
@ -1227,6 +1315,7 @@ Also, the ``--timeout`` option allows to overwrite the default 30s timeout:
|
||||
3) echo 'Unexpected HTTP 3xx Redirection!' ;;
|
||||
4) echo 'HTTP 4xx Client Error!' ;;
|
||||
5) echo 'HTTP 5xx Server Error!' ;;
|
||||
6) echo 'Exceeded --max-redirects=<n> redirects!' ;;
|
||||
*) echo 'Other Error!' ;;
|
||||
esac
|
||||
fi
|
||||
@ -1279,6 +1368,21 @@ HTTPie reaches its final version ``1.0``. All changes are recorded in the
|
||||
|
||||
|
||||
|
||||
=======
|
||||
Support
|
||||
=======
|
||||
|
||||
Please use the following support channels:
|
||||
|
||||
* `GitHub issues <https://github.com/jkbr/httpie/issues>`_
|
||||
for bug reports and feature requests.
|
||||
* `Our Gitter chat room <https://gitter.im/jkbrzt/httpie>`_
|
||||
to ask questions, discuss features, and for general discussion.
|
||||
* `StackOverflow <https://stackoverflow.com>`_
|
||||
to ask questions (please make sure to use the
|
||||
`httpie <http://stackoverflow.com/questions/tagged/httpie>`_ tag).
|
||||
* You can also tweet directly to `@jkbrzt`_.
|
||||
|
||||
=======
|
||||
Authors
|
||||
=======
|
||||
@ -1327,11 +1431,11 @@ Please see `LICENSE <https://github.com/jkbrzt/httpie/blob/master/LICENSE>`_.
|
||||
.. _claudiatd/httpie-artwork: https://github.com/claudiatd/httpie-artwork
|
||||
|
||||
|
||||
.. |pypi| image:: https://img.shields.io/pypi/v/httpie.svg?style=flat-square&label=latest%20version
|
||||
.. |pypi| image:: https://img.shields.io/pypi/v/httpie.svg?style=flat-square&label=latest%20stable%20version
|
||||
:target: https://pypi.python.org/pypi/httpie
|
||||
:alt: Latest version released on PyPi
|
||||
|
||||
.. |coverage| image:: https://img.shields.io/coveralls/jkbrzt/httpie/master.svg?style=flat-square
|
||||
.. |coverage| image:: https://img.shields.io/coveralls/jkbrzt/httpie/master.svg?style=flat-square&label=coverage
|
||||
:target: https://coveralls.io/r/jkbrzt/httpie?branch=master
|
||||
:alt: Test coverage
|
||||
|
||||
@ -1342,3 +1446,8 @@ Please see `LICENSE <https://github.com/jkbrzt/httpie/blob/master/LICENSE>`_.
|
||||
.. |windows_build| image:: https://img.shields.io/appveyor/ci/jkbrzt/httpie.svg?style=flat-square&label=windows%20build
|
||||
:target: https://ci.appveyor.com/project/jkbrzt/httpie
|
||||
:alt: Build status of the master branch on Windows
|
||||
|
||||
.. |gitter| image:: https://badges.gitter.im/jkbrzt/httpie.svg
|
||||
:target: https://gitter.im/jkbrzt/httpie
|
||||
:alt: Chat on Gitter
|
||||
|
||||
|
13
appveyor.yml
13
appveyor.yml
@ -1,17 +1,22 @@
|
||||
# https://ci.appveyor.com/project/jkbrzt/httpie
|
||||
build: false
|
||||
|
||||
environment:
|
||||
matrix:
|
||||
- PYTHON: "C:/Python27"
|
||||
- PYTHON: "C:/Python34"
|
||||
# Python 3.4 has outdated pip
|
||||
# - PYTHON: "C:/Python34"
|
||||
- PYTHON: "C:/Python35"
|
||||
|
||||
init:
|
||||
- "ECHO %PYTHON%"
|
||||
- ps: "ls C:/Python*"
|
||||
|
||||
install:
|
||||
# - ps: (new-object net.webclient).DownloadFile('https://bootstrap.pypa.io/get-pip.py', 'C:/get-pip.py')
|
||||
# - "%PYTHON%/python.exe C:/get-pip.py"
|
||||
- "%PYTHON%/Scripts/pip.exe install -U pip setuptools"
|
||||
# FIXME: updating pip fails with PermissionError
|
||||
# - "%PYTHON%/Scripts/pip.exe install -U pip setuptools"
|
||||
- "%PYTHON%/Scripts/pip.exe install -e ."
|
||||
|
||||
test_script:
|
||||
- "%PYTHON%/Scripts/pip.exe --version"
|
||||
- "%PYTHON%/Scripts/http.exe --debug"
|
||||
|
@ -3,7 +3,7 @@ HTTPie - a CLI, cURL-like tool for humans.
|
||||
|
||||
"""
|
||||
__author__ = 'Jakub Roztocil'
|
||||
__version__ = '0.9.3'
|
||||
__version__ = '0.9.4'
|
||||
__licence__ = 'BSD'
|
||||
|
||||
|
||||
@ -12,8 +12,16 @@ class ExitStatus:
|
||||
OK = 0
|
||||
ERROR = 1
|
||||
ERROR_TIMEOUT = 2
|
||||
ERROR_TOO_MANY_REDIRECTS = 6
|
||||
|
||||
# Used only when requested with --check-status:
|
||||
ERROR_HTTP_3XX = 3
|
||||
ERROR_HTTP_4XX = 4
|
||||
ERROR_HTTP_5XX = 5
|
||||
|
||||
|
||||
EXIT_STATUS_LABELS = dict(
|
||||
(value, key)
|
||||
for key, value in ExitStatus.__dict__.items()
|
||||
if key.isupper()
|
||||
)
|
||||
|
157
httpie/cli.py
157
httpie/cli.py
@ -13,13 +13,14 @@ from httpie.plugins.builtin import BuiltinAuthPlugin
|
||||
from httpie.plugins import plugin_manager
|
||||
from httpie.sessions import DEFAULT_SESSIONS_DIR
|
||||
from httpie.output.formatters.colors import AVAILABLE_STYLES, DEFAULT_STYLE
|
||||
from httpie.input import (Parser, AuthCredentialsArgType, KeyValueArgType,
|
||||
from httpie.input import (HTTPieArgumentParser,
|
||||
AuthCredentialsArgType, KeyValueArgType,
|
||||
SEP_PROXY, SEP_CREDENTIALS, SEP_GROUP_ALL_ITEMS,
|
||||
OUT_REQ_HEAD, OUT_REQ_BODY, OUT_RESP_HEAD,
|
||||
OUT_RESP_BODY, OUTPUT_OPTIONS,
|
||||
OUTPUT_OPTIONS_DEFAULT, PRETTY_MAP,
|
||||
PRETTY_STDOUT_TTY_ONLY, SessionNameValidator,
|
||||
readable_file_arg)
|
||||
readable_file_arg, SSL_VERSION_ARG_MAPPING)
|
||||
|
||||
|
||||
class HTTPieHelpFormatter(RawDescriptionHelpFormatter):
|
||||
@ -40,7 +41,7 @@ class HTTPieHelpFormatter(RawDescriptionHelpFormatter):
|
||||
text = dedent(text).strip() + '\n\n'
|
||||
return text.splitlines()
|
||||
|
||||
parser = Parser(
|
||||
parser = HTTPieArgumentParser(
|
||||
formatter_class=HTTPieHelpFormatter,
|
||||
description='%s <http://httpie.org>' % __doc__.strip(),
|
||||
epilog=dedent("""
|
||||
@ -51,7 +52,7 @@ parser = Parser(
|
||||
|
||||
https://github.com/jkbrzt/httpie/issues
|
||||
|
||||
""")
|
||||
"""),
|
||||
)
|
||||
|
||||
|
||||
@ -249,17 +250,6 @@ output_options.add_argument(
|
||||
default=OUTPUT_OPTIONS_DEFAULT,
|
||||
)
|
||||
)
|
||||
output_options.add_argument(
|
||||
'--verbose', '-v',
|
||||
dest='output_options',
|
||||
action='store_const',
|
||||
const=''.join(OUTPUT_OPTIONS),
|
||||
help="""
|
||||
Print the whole request as well as the response. Shortcut for --print={0}.
|
||||
|
||||
"""
|
||||
.format(''.join(OUTPUT_OPTIONS))
|
||||
)
|
||||
output_options.add_argument(
|
||||
'--headers', '-h',
|
||||
dest='output_options',
|
||||
@ -283,6 +273,42 @@ output_options.add_argument(
|
||||
.format(OUT_RESP_BODY)
|
||||
)
|
||||
|
||||
output_options.add_argument(
|
||||
'--verbose', '-v',
|
||||
dest='verbose',
|
||||
action='store_true',
|
||||
help="""
|
||||
Verbose output. Print the whole request as well as the response. Also print
|
||||
any intermediary requests/responses (such as redirects).
|
||||
It's a shortcut for: --all --print={0}
|
||||
|
||||
"""
|
||||
.format(''.join(OUTPUT_OPTIONS))
|
||||
)
|
||||
output_options.add_argument(
|
||||
'--all',
|
||||
default=False,
|
||||
action='store_true',
|
||||
help="""
|
||||
By default, only the final request/response is shown. Use this flag to show
|
||||
any intermediary requests/responses as well. Intermediary requests include
|
||||
followed redirects (with --follow), the first unauthorized request when
|
||||
Digest auth is used (--auth=digest), etc.
|
||||
|
||||
"""
|
||||
)
|
||||
output_options.add_argument(
|
||||
'--history-print', '-P',
|
||||
dest='output_options_history',
|
||||
metavar='WHAT',
|
||||
help="""
|
||||
The same as --print, -p but applies only to intermediary requests/responses
|
||||
(such as redirects) when their inclusion is enabled with --all. If this
|
||||
options is not specified, then they are formatted the same way as the final
|
||||
response.
|
||||
|
||||
"""
|
||||
)
|
||||
output_options.add_argument(
|
||||
'--stream', '-S',
|
||||
action='store_true',
|
||||
@ -307,8 +333,9 @@ output_options.add_argument(
|
||||
dest='output_file',
|
||||
metavar='FILE',
|
||||
help="""
|
||||
Save output to FILE. If --download is set, then only the response body is
|
||||
saved to the file. Other parts of the HTTP exchange are printed to stderr.
|
||||
Save output to FILE instead of stdout. If --download is also set, then only
|
||||
the response body is saved to FILE. Other parts of the HTTP exchange are
|
||||
printed to stderr.
|
||||
|
||||
"""
|
||||
|
||||
@ -377,7 +404,6 @@ sessions.add_argument(
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
#######################################################################
|
||||
# Authentication
|
||||
#######################################################################
|
||||
@ -397,7 +423,7 @@ auth.add_argument(
|
||||
|
||||
_auth_plugins = plugin_manager.get_auth_plugins()
|
||||
auth.add_argument(
|
||||
'--auth-type',
|
||||
'--auth-type', '-A',
|
||||
choices=[plugin.auth_type for plugin in _auth_plugins],
|
||||
default=_auth_plugins[0].auth_type,
|
||||
help="""
|
||||
@ -444,45 +470,21 @@ network.add_argument(
|
||||
"""
|
||||
)
|
||||
network.add_argument(
|
||||
'--follow',
|
||||
'--follow', '-F',
|
||||
default=False,
|
||||
action='store_true',
|
||||
help="""
|
||||
Set this flag if full redirects are allowed (e.g. re-POST-ing of data at
|
||||
new Location).
|
||||
|
||||
"""
|
||||
)
|
||||
network.add_argument(
|
||||
'--verify',
|
||||
default='yes',
|
||||
help="""
|
||||
Set to "no" to skip checking the host's SSL certificate. You can also pass
|
||||
the path to a CA_BUNDLE file for private certs. You can also set the
|
||||
REQUESTS_CA_BUNDLE environment variable. Defaults to "yes".
|
||||
Follow 30x Location redirects.
|
||||
|
||||
"""
|
||||
)
|
||||
|
||||
network.add_argument(
|
||||
'--cert',
|
||||
default=None,
|
||||
type=readable_file_arg,
|
||||
'--max-redirects',
|
||||
type=int,
|
||||
default=30,
|
||||
help="""
|
||||
You can specify a local cert to use as client side SSL certificate.
|
||||
This file may either contain both private key and certificate or you may
|
||||
specify --cert-key separately.
|
||||
|
||||
"""
|
||||
)
|
||||
|
||||
network.add_argument(
|
||||
'--cert-key',
|
||||
default=None,
|
||||
type=readable_file_arg,
|
||||
help="""
|
||||
The private key to use with SSL. Only needed if --cert is given and the
|
||||
certificate file does not contain the private key.
|
||||
By default, requests have a limit of 30 redirects (works with --follow).
|
||||
|
||||
"""
|
||||
)
|
||||
@ -516,6 +518,57 @@ network.add_argument(
|
||||
)
|
||||
|
||||
|
||||
#######################################################################
|
||||
# SSL
|
||||
#######################################################################
|
||||
|
||||
ssl = parser.add_argument_group(title='SSL')
|
||||
ssl.add_argument(
|
||||
'--verify',
|
||||
default='yes',
|
||||
help="""
|
||||
Set to "no" to skip checking the host's SSL certificate. You can also pass
|
||||
the path to a CA_BUNDLE file for private certs. You can also set the
|
||||
REQUESTS_CA_BUNDLE environment variable. Defaults to "yes".
|
||||
|
||||
"""
|
||||
)
|
||||
ssl.add_argument(
|
||||
'--ssl', # TODO: Maybe something more general, such as --secure-protocol?
|
||||
dest='ssl_version',
|
||||
choices=list(sorted(SSL_VERSION_ARG_MAPPING.keys())),
|
||||
help="""
|
||||
The desired protocol version to use. This will default to
|
||||
SSL v2.3 which will negotiate the highest protocol that both
|
||||
the server and your installation of OpenSSL support. Available protocols
|
||||
may vary depending on OpenSSL installation (only the supported ones
|
||||
are shown here).
|
||||
|
||||
"""
|
||||
)
|
||||
ssl.add_argument(
|
||||
'--cert',
|
||||
default=None,
|
||||
type=readable_file_arg,
|
||||
help="""
|
||||
You can specify a local cert to use as client side SSL certificate.
|
||||
This file may either contain both private key and certificate or you may
|
||||
specify --cert-key separately.
|
||||
|
||||
"""
|
||||
)
|
||||
|
||||
ssl.add_argument(
|
||||
'--cert-key',
|
||||
default=None,
|
||||
type=readable_file_arg,
|
||||
help="""
|
||||
The private key to use with SSL. Only needed if --cert is given and the
|
||||
certificate file does not contain the private key.
|
||||
|
||||
"""
|
||||
)
|
||||
|
||||
#######################################################################
|
||||
# Troubleshooting
|
||||
#######################################################################
|
||||
@ -554,7 +607,7 @@ troubleshooting.add_argument(
|
||||
action='store_true',
|
||||
default=False,
|
||||
help="""
|
||||
Prints exception traceback should one occur.
|
||||
Prints the exception traceback should one occur.
|
||||
|
||||
"""
|
||||
)
|
||||
@ -563,8 +616,8 @@ troubleshooting.add_argument(
|
||||
action='store_true',
|
||||
default=False,
|
||||
help="""
|
||||
Prints exception traceback should one occur, and also other information
|
||||
that is useful for debugging HTTPie itself and for reporting bugs.
|
||||
Prints the exception traceback should one occur, as well as other
|
||||
information useful for debugging HTTPie itself and for reporting bugs.
|
||||
|
||||
"""
|
||||
)
|
||||
|
@ -3,16 +3,18 @@ import sys
|
||||
from pprint import pformat
|
||||
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter
|
||||
from requests.packages import urllib3
|
||||
|
||||
from httpie import sessions
|
||||
from httpie import __version__
|
||||
from httpie.compat import str
|
||||
from httpie.input import SSL_VERSION_ARG_MAPPING
|
||||
from httpie.plugins import plugin_manager
|
||||
|
||||
from httpie.utils import repr_dict_nice
|
||||
|
||||
try:
|
||||
# https://urllib3.readthedocs.org/en/latest/security.html
|
||||
# https://urllib3.readthedocs.io/en/latest/security.html
|
||||
urllib3.disable_warnings()
|
||||
except AttributeError:
|
||||
# In some rare cases, the user may have an old version of the requests
|
||||
@ -27,8 +29,23 @@ JSON = 'application/json'
|
||||
DEFAULT_UA = 'HTTPie/%s' % __version__
|
||||
|
||||
|
||||
def get_requests_session():
|
||||
class HTTPieHTTPAdapter(HTTPAdapter):
|
||||
|
||||
def __init__(self, ssl_version=None, **kwargs):
|
||||
self._ssl_version = ssl_version
|
||||
super(HTTPieHTTPAdapter, self).__init__(**kwargs)
|
||||
|
||||
def init_poolmanager(self, *args, **kwargs):
|
||||
kwargs['ssl_version'] = self._ssl_version
|
||||
super(HTTPieHTTPAdapter, self).init_poolmanager(*args, **kwargs)
|
||||
|
||||
|
||||
def get_requests_session(ssl_version):
|
||||
requests_session = requests.Session()
|
||||
requests_session.mount(
|
||||
'https://',
|
||||
HTTPieHTTPAdapter(ssl_version=ssl_version)
|
||||
)
|
||||
for cls in plugin_manager.get_transport_plugins():
|
||||
transport_plugin = cls()
|
||||
requests_session.mount(prefix=transport_plugin.prefix,
|
||||
@ -39,7 +56,12 @@ def get_requests_session():
|
||||
def get_response(args, config_dir):
|
||||
"""Send the request and return a `request.Response`."""
|
||||
|
||||
requests_session = get_requests_session()
|
||||
ssl_version = None
|
||||
if args.ssl_version:
|
||||
ssl_version = SSL_VERSION_ARG_MAPPING[args.ssl_version]
|
||||
|
||||
requests_session = get_requests_session(ssl_version)
|
||||
requests_session.max_redirects = args.max_redirects
|
||||
|
||||
if not args.session and not args.session_read_only:
|
||||
kwargs = get_requests_kwargs(args)
|
||||
@ -60,7 +82,7 @@ def get_response(args, config_dir):
|
||||
|
||||
def dump_request(kwargs):
|
||||
sys.stderr.write('\n>>> requests.request(**%s)\n\n'
|
||||
% pformat(kwargs))
|
||||
% repr_dict_nice(kwargs))
|
||||
|
||||
|
||||
def encode_headers(headers):
|
||||
|
@ -6,11 +6,11 @@ from httpie import __version__
|
||||
from httpie.compat import is_windows
|
||||
|
||||
|
||||
DEFAULT_CONFIG_DIR = os.environ.get(
|
||||
DEFAULT_CONFIG_DIR = str(os.environ.get(
|
||||
'HTTPIE_CONFIG_DIR',
|
||||
os.path.expanduser('~/.httpie') if not is_windows else
|
||||
os.path.expandvars(r'%APPDATA%\\httpie')
|
||||
)
|
||||
))
|
||||
|
||||
|
||||
class BaseConfigDict(dict):
|
||||
@ -84,7 +84,6 @@ class Config(BaseConfigDict):
|
||||
about = 'HTTPie configuration file'
|
||||
|
||||
DEFAULTS = {
|
||||
'implicit_content_type': 'json',
|
||||
'default_options': []
|
||||
}
|
||||
|
||||
@ -93,5 +92,21 @@ class Config(BaseConfigDict):
|
||||
self.update(self.DEFAULTS)
|
||||
self.directory = directory
|
||||
|
||||
def load(self):
|
||||
super(Config, self).load()
|
||||
self._migrate_implicit_content_type()
|
||||
|
||||
def _get_path(self):
|
||||
return os.path.join(self.directory, self.name + '.json')
|
||||
|
||||
def _migrate_implicit_content_type(self):
|
||||
"""Migrate the removed implicit_content_type config option"""
|
||||
try:
|
||||
implicit_content_type = self.pop('implicit_content_type')
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
if implicit_content_type == 'form':
|
||||
self['default_options'].insert(0, '--form')
|
||||
self.save()
|
||||
self.load()
|
||||
|
@ -3,6 +3,8 @@ import sys
|
||||
from httpie.compat import is_windows
|
||||
from httpie.config import DEFAULT_CONFIG_DIR, Config
|
||||
|
||||
from httpie.utils import repr_dict_nice
|
||||
|
||||
|
||||
class Environment(object):
|
||||
"""
|
||||
@ -82,3 +84,17 @@ class Environment(object):
|
||||
else:
|
||||
self._config.load()
|
||||
return self._config
|
||||
|
||||
def __str__(self):
|
||||
defaults = dict(type(self).__dict__)
|
||||
actual = dict(defaults)
|
||||
actual.update(self.__dict__)
|
||||
actual['config'] = self.config
|
||||
return repr_dict_nice(dict(
|
||||
(key, value)
|
||||
for key, value in actual.items()
|
||||
if not key.startswith('_'))
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return '<{0} {1}>'.format(type(self).__name__, str(self))
|
||||
|
256
httpie/core.py
256
httpie/core.py
@ -12,6 +12,7 @@ Invocation flow:
|
||||
"""
|
||||
import sys
|
||||
import errno
|
||||
import platform
|
||||
|
||||
import requests
|
||||
from requests import __version__ as requests_version
|
||||
@ -20,12 +21,13 @@ from pygments import __version__ as pygments_version
|
||||
from httpie import __version__ as httpie_version, ExitStatus
|
||||
from httpie.compat import str, bytes, is_py3
|
||||
from httpie.client import get_response
|
||||
from httpie.downloads import Download
|
||||
from httpie.downloads import Downloader
|
||||
from httpie.context import Environment
|
||||
from httpie.plugins import plugin_manager
|
||||
from httpie.output.streams import (
|
||||
build_output_stream,
|
||||
write, write_with_colors_win_py3
|
||||
write_stream,
|
||||
write_stream_with_colors_win_py3
|
||||
)
|
||||
|
||||
|
||||
@ -47,11 +49,14 @@ def get_exit_status(http_status, follow=False):
|
||||
def print_debug_info(env):
|
||||
env.stderr.writelines([
|
||||
'HTTPie %s\n' % httpie_version,
|
||||
'HTTPie data: %s\n' % env.config.directory,
|
||||
'Requests %s\n' % requests_version,
|
||||
'Pygments %s\n' % pygments_version,
|
||||
'Python %s %s\n' % (sys.version, sys.platform)
|
||||
'Python %s\n%s\n' % (sys.version, sys.executable),
|
||||
'%s %s' % (platform.system(), platform.release()),
|
||||
])
|
||||
env.stderr.write('\n\n')
|
||||
env.stderr.write(repr(env))
|
||||
env.stderr.write('\n')
|
||||
|
||||
|
||||
def decode_args(args, stdin_encoding):
|
||||
@ -67,8 +72,109 @@ def decode_args(args, stdin_encoding):
|
||||
]
|
||||
|
||||
|
||||
def main(args=sys.argv[1:], env=Environment(), error=None):
|
||||
"""Run the main program and write the output to ``env.stdout``.
|
||||
def program(args, env, log_error):
|
||||
"""
|
||||
The main program without error handling
|
||||
|
||||
:param args: parsed args (argparse.Namespace)
|
||||
:type env: Environment
|
||||
:param log_error: error log function
|
||||
:return: status code
|
||||
|
||||
"""
|
||||
exit_status = ExitStatus.OK
|
||||
downloader = None
|
||||
show_traceback = args.debug or args.traceback
|
||||
|
||||
try:
|
||||
if args.download:
|
||||
args.follow = True # --download implies --follow.
|
||||
downloader = Downloader(
|
||||
output_file=args.output_file,
|
||||
progress_file=env.stderr,
|
||||
resume=args.download_resume
|
||||
)
|
||||
downloader.pre_request(args.headers)
|
||||
|
||||
final_response = get_response(args, config_dir=env.config.directory)
|
||||
if args.all:
|
||||
responses = final_response.history + [final_response]
|
||||
else:
|
||||
responses = [final_response]
|
||||
|
||||
for response in responses:
|
||||
|
||||
if args.check_status or downloader:
|
||||
exit_status = get_exit_status(
|
||||
http_status=response.status_code,
|
||||
follow=args.follow
|
||||
)
|
||||
if not env.stdout_isatty and exit_status != ExitStatus.OK:
|
||||
log_error(
|
||||
'HTTP %s %s', response.raw.status, response.raw.reason,
|
||||
level='warning'
|
||||
)
|
||||
|
||||
write_stream_kwargs = {
|
||||
'stream': build_output_stream(
|
||||
args=args,
|
||||
env=env,
|
||||
request=response.request,
|
||||
response=response,
|
||||
output_options=(
|
||||
args.output_options
|
||||
if response is final_response
|
||||
else args.output_options_history
|
||||
)
|
||||
),
|
||||
# NOTE: `env.stdout` will in fact be `stderr` with `--download`
|
||||
'outfile': env.stdout,
|
||||
'flush': env.stdout_isatty or args.stream
|
||||
}
|
||||
try:
|
||||
if env.is_windows and is_py3 and 'colors' in args.prettify:
|
||||
write_stream_with_colors_win_py3(**write_stream_kwargs)
|
||||
else:
|
||||
write_stream(**write_stream_kwargs)
|
||||
except IOError as e:
|
||||
if not show_traceback and e.errno == errno.EPIPE:
|
||||
# Ignore broken pipes unless --traceback.
|
||||
env.stderr.write('\n')
|
||||
else:
|
||||
raise
|
||||
|
||||
if downloader and exit_status == ExitStatus.OK:
|
||||
# Last response body download.
|
||||
download_stream, download_to = downloader.start(final_response)
|
||||
write_stream(
|
||||
stream=download_stream,
|
||||
outfile=download_to,
|
||||
flush=False,
|
||||
)
|
||||
downloader.finish()
|
||||
if downloader.interrupted:
|
||||
exit_status = ExitStatus.ERROR
|
||||
log_error('Incomplete download: size=%d; downloaded=%d' % (
|
||||
downloader.status.total_size,
|
||||
downloader.status.downloaded
|
||||
))
|
||||
return exit_status
|
||||
|
||||
finally:
|
||||
if downloader and not downloader.finished:
|
||||
downloader.failed()
|
||||
|
||||
if (not isinstance(args, list) and args.output_file and
|
||||
args.output_file_specified):
|
||||
args.output_file.close()
|
||||
|
||||
|
||||
def main(args=sys.argv[1:], env=Environment(), custom_log_error=None):
|
||||
"""
|
||||
The main function.
|
||||
|
||||
Pre-process args, handle some special types of invocations,
|
||||
and run the main program with error handling.
|
||||
|
||||
Return exit status code.
|
||||
|
||||
@ -76,127 +182,79 @@ def main(args=sys.argv[1:], env=Environment(), error=None):
|
||||
args = decode_args(args, env.stdin_encoding)
|
||||
plugin_manager.load_installed_plugins()
|
||||
|
||||
def log_error(msg, *args, **kwargs):
|
||||
msg = msg % args
|
||||
level = kwargs.get('level', 'error')
|
||||
assert level in ['error', 'warning']
|
||||
env.stderr.write('\nhttp: %s: %s\n' % (level, msg))
|
||||
|
||||
from httpie.cli import parser
|
||||
|
||||
if env.config.default_options:
|
||||
args = env.config.default_options + args
|
||||
|
||||
def _error(msg, *args, **kwargs):
|
||||
msg = msg % args
|
||||
level = kwargs.get('level', 'error')
|
||||
env.stderr.write('\nhttp: %s: %s\n' % (level, msg))
|
||||
if custom_log_error:
|
||||
log_error = custom_log_error
|
||||
|
||||
if error is None:
|
||||
error = _error
|
||||
include_debug_info = '--debug' in args
|
||||
include_traceback = include_debug_info or '--traceback' in args
|
||||
|
||||
debug = '--debug' in args
|
||||
traceback = debug or '--traceback' in args
|
||||
exit_status = ExitStatus.OK
|
||||
|
||||
if debug:
|
||||
if include_debug_info:
|
||||
print_debug_info(env)
|
||||
if args == ['--debug']:
|
||||
return exit_status
|
||||
return ExitStatus.OK
|
||||
|
||||
download = None
|
||||
exit_status = ExitStatus.OK
|
||||
|
||||
try:
|
||||
args = parser.parse_args(args=args, env=env)
|
||||
|
||||
if args.download:
|
||||
args.follow = True # --download implies --follow.
|
||||
download = Download(
|
||||
output_file=args.output_file,
|
||||
progress_file=env.stderr,
|
||||
resume=args.download_resume
|
||||
)
|
||||
download.pre_request(args.headers)
|
||||
|
||||
response = get_response(args, config_dir=env.config.directory)
|
||||
|
||||
if args.check_status or download:
|
||||
|
||||
exit_status = get_exit_status(
|
||||
http_status=response.status_code,
|
||||
follow=args.follow
|
||||
)
|
||||
|
||||
if not env.stdout_isatty and exit_status != ExitStatus.OK:
|
||||
error('HTTP %s %s',
|
||||
response.raw.status,
|
||||
response.raw.reason,
|
||||
level='warning')
|
||||
|
||||
write_kwargs = {
|
||||
'stream': build_output_stream(
|
||||
args, env, response.request, response),
|
||||
|
||||
# This will in fact be `stderr` with `--download`
|
||||
'outfile': env.stdout,
|
||||
|
||||
'flush': env.stdout_isatty or args.stream
|
||||
}
|
||||
|
||||
try:
|
||||
|
||||
if env.is_windows and is_py3 and 'colors' in args.prettify:
|
||||
write_with_colors_win_py3(**write_kwargs)
|
||||
else:
|
||||
write(**write_kwargs)
|
||||
|
||||
if download and exit_status == ExitStatus.OK:
|
||||
# Response body download.
|
||||
download_stream, download_to = download.start(response)
|
||||
write(
|
||||
stream=download_stream,
|
||||
outfile=download_to,
|
||||
flush=False,
|
||||
)
|
||||
download.finish()
|
||||
if download.interrupted:
|
||||
exit_status = ExitStatus.ERROR
|
||||
error('Incomplete download: size=%d; downloaded=%d' % (
|
||||
download.status.total_size,
|
||||
download.status.downloaded
|
||||
))
|
||||
|
||||
except IOError as e:
|
||||
if not traceback and e.errno == errno.EPIPE:
|
||||
# Ignore broken pipes unless --traceback.
|
||||
env.stderr.write('\n')
|
||||
else:
|
||||
raise
|
||||
parsed_args = parser.parse_args(args=args, env=env)
|
||||
except KeyboardInterrupt:
|
||||
if traceback:
|
||||
raise
|
||||
env.stderr.write('\n')
|
||||
if include_traceback:
|
||||
raise
|
||||
exit_status = ExitStatus.ERROR
|
||||
except SystemExit as e:
|
||||
if e.code != ExitStatus.OK:
|
||||
if traceback:
|
||||
raise
|
||||
env.stderr.write('\n')
|
||||
if include_traceback:
|
||||
raise
|
||||
exit_status = ExitStatus.ERROR
|
||||
else:
|
||||
try:
|
||||
exit_status = program(
|
||||
args=parsed_args,
|
||||
env=env,
|
||||
log_error=log_error,
|
||||
)
|
||||
except KeyboardInterrupt:
|
||||
env.stderr.write('\n')
|
||||
if include_traceback:
|
||||
raise
|
||||
exit_status = ExitStatus.ERROR
|
||||
except SystemExit as e:
|
||||
if e.code != ExitStatus.OK:
|
||||
env.stderr.write('\n')
|
||||
if include_traceback:
|
||||
raise
|
||||
exit_status = ExitStatus.ERROR
|
||||
except requests.Timeout:
|
||||
exit_status = ExitStatus.ERROR_TIMEOUT
|
||||
error('Request timed out (%ss).', args.timeout)
|
||||
|
||||
log_error('Request timed out (%ss).', parsed_args.timeout)
|
||||
except requests.TooManyRedirects:
|
||||
exit_status = ExitStatus.ERROR_TOO_MANY_REDIRECTS
|
||||
log_error('Too many redirects (--max-redirects=%s).',
|
||||
parsed_args.max_redirects)
|
||||
except Exception as e:
|
||||
# TODO: Better distinction between expected and unexpected errors.
|
||||
# Network errors vs. bugs, etc.
|
||||
if traceback:
|
||||
raise
|
||||
# TODO: Further distinction between expected and unexpected errors.
|
||||
msg = str(e)
|
||||
if hasattr(e, 'request'):
|
||||
request = e.request
|
||||
if hasattr(request, 'url'):
|
||||
msg += ' while doing %s request to URL: %s' % (
|
||||
request.method, request.url)
|
||||
error('%s: %s', type(e).__name__, msg)
|
||||
log_error('%s: %s', type(e).__name__, msg)
|
||||
if include_traceback:
|
||||
raise
|
||||
exit_status = ExitStatus.ERROR
|
||||
|
||||
finally:
|
||||
if download and not download.finished:
|
||||
download.failed()
|
||||
|
||||
return exit_status
|
||||
|
@ -7,6 +7,7 @@ from __future__ import division
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import errno
|
||||
import mimetypes
|
||||
import threading
|
||||
from time import sleep, time
|
||||
@ -135,16 +136,51 @@ def filename_from_url(url, content_type):
|
||||
return fn
|
||||
|
||||
|
||||
def trim_filename(filename, max_len):
|
||||
if len(filename) > max_len:
|
||||
trim_by = len(filename) - max_len
|
||||
name, ext = os.path.splitext(filename)
|
||||
if trim_by >= len(name):
|
||||
filename = filename[:-trim_by]
|
||||
else:
|
||||
filename = name[:-trim_by] + ext
|
||||
return filename
|
||||
|
||||
|
||||
def get_filename_max_length(directory):
|
||||
max_len = 255
|
||||
try:
|
||||
pathconf = os.pathconf
|
||||
except AttributeError:
|
||||
pass # non-posix
|
||||
else:
|
||||
try:
|
||||
max_len = pathconf(directory, 'PC_NAME_MAX')
|
||||
except OSError as e:
|
||||
if e.errno != errno.EINVAL:
|
||||
raise
|
||||
return max_len
|
||||
|
||||
|
||||
def trim_filename_if_needed(filename, directory='.', extra=0):
|
||||
max_len = get_filename_max_length(directory) - extra
|
||||
if len(filename) > max_len:
|
||||
filename = trim_filename(filename, max_len)
|
||||
return filename
|
||||
|
||||
|
||||
def get_unique_filename(filename, exists=os.path.exists):
|
||||
attempt = 0
|
||||
while True:
|
||||
suffix = '-' + str(attempt) if attempt > 0 else ''
|
||||
if not exists(filename + suffix):
|
||||
return filename + suffix
|
||||
try_filename = trim_filename_if_needed(filename, extra=len(suffix))
|
||||
try_filename += suffix
|
||||
if not exists(try_filename):
|
||||
return try_filename
|
||||
attempt += 1
|
||||
|
||||
|
||||
class Download(object):
|
||||
class Downloader(object):
|
||||
|
||||
def __init__(self, output_file=None,
|
||||
resume=False, progress_file=sys.stderr):
|
||||
@ -178,8 +214,8 @@ class Download(object):
|
||||
:type request_headers: dict
|
||||
|
||||
"""
|
||||
# Disable content encoding so that we can resume, etc.
|
||||
request_headers['Accept-Encoding'] = None
|
||||
# Ask the server not to encode the content so that we can resume, etc.
|
||||
request_headers['Accept-Encoding'] = 'identity'
|
||||
if self._resume:
|
||||
bytes_have = os.path.getsize(self._output_file.name)
|
||||
if bytes_have:
|
||||
@ -201,6 +237,8 @@ class Download(object):
|
||||
"""
|
||||
assert not self.status.time_started
|
||||
|
||||
# FIXME: some servers still might sent Content-Encoding: gzip
|
||||
# <https://github.com/jkbrzt/httpie/issues/423>
|
||||
try:
|
||||
total_size = int(response.headers['Content-Length'])
|
||||
except (KeyError, ValueError, TypeError):
|
||||
@ -299,7 +337,6 @@ class Status(object):
|
||||
|
||||
def started(self, resumed_from=0, total_size=None):
|
||||
assert self.time_started is None
|
||||
if total_size is not None:
|
||||
self.total_size = total_size
|
||||
self.downloaded = self.resumed_from = resumed_from
|
||||
self.time_started = time()
|
||||
|
@ -2,6 +2,7 @@
|
||||
|
||||
"""
|
||||
import os
|
||||
import ssl
|
||||
import sys
|
||||
import re
|
||||
import errno
|
||||
@ -103,7 +104,21 @@ OUTPUT_OPTIONS_DEFAULT = OUT_RESP_HEAD + OUT_RESP_BODY
|
||||
OUTPUT_OPTIONS_DEFAULT_STDOUT_REDIRECTED = OUT_RESP_BODY
|
||||
|
||||
|
||||
class Parser(ArgumentParser):
|
||||
SSL_VERSION_ARG_MAPPING = {
|
||||
'ssl2.3': 'PROTOCOL_SSLv23',
|
||||
'ssl3': 'PROTOCOL_SSLv3',
|
||||
'tls1': 'PROTOCOL_TLSv1',
|
||||
'tls1.1': 'PROTOCOL_TLSv1_1',
|
||||
'tls1.2': 'PROTOCOL_TLSv1_2',
|
||||
}
|
||||
SSL_VERSION_ARG_MAPPING = dict(
|
||||
(cli_arg, getattr(ssl, ssl_constant))
|
||||
for cli_arg, ssl_constant in SSL_VERSION_ARG_MAPPING.items()
|
||||
if hasattr(ssl, ssl_constant)
|
||||
)
|
||||
|
||||
|
||||
class HTTPieArgumentParser(ArgumentParser):
|
||||
"""Adds additional logic to `argparse.ArgumentParser`.
|
||||
|
||||
Handles all input (CLI args, file args, stdin), applies defaults,
|
||||
@ -113,13 +128,13 @@ class Parser(ArgumentParser):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
kwargs['add_help'] = False
|
||||
super(Parser, self).__init__(*args, **kwargs)
|
||||
super(HTTPieArgumentParser, self).__init__(*args, **kwargs)
|
||||
|
||||
# noinspection PyMethodOverriding
|
||||
def parse_args(self, env, args=None, namespace=None):
|
||||
|
||||
self.env = env
|
||||
self.args, no_options = super(Parser, self)\
|
||||
self.args, no_options = super(HTTPieArgumentParser, self)\
|
||||
.parse_known_args(args, namespace)
|
||||
|
||||
if self.args.debug:
|
||||
@ -127,7 +142,6 @@ class Parser(ArgumentParser):
|
||||
|
||||
# Arguments processing and environment setup.
|
||||
self._apply_no_options(no_options)
|
||||
self._apply_config()
|
||||
self._validate_download_options()
|
||||
self._setup_standard_streams()
|
||||
self._process_output_options()
|
||||
@ -164,19 +178,17 @@ class Parser(ArgumentParser):
|
||||
}.get(file, file)
|
||||
if not hasattr(file, 'buffer') and isinstance(message, str):
|
||||
message = message.encode(self.env.stdout_encoding)
|
||||
super(Parser, self)._print_message(message, file)
|
||||
super(HTTPieArgumentParser, self)._print_message(message, file)
|
||||
|
||||
def _setup_standard_streams(self):
|
||||
"""
|
||||
Modify `env.stdout` and `env.stdout_isatty` based on args, if needed.
|
||||
|
||||
"""
|
||||
if not self.env.stdout_isatty and self.args.output_file:
|
||||
self.error('Cannot use --output, -o with redirected output.')
|
||||
|
||||
self.args.output_file_specified = bool(self.args.output_file)
|
||||
if self.args.download:
|
||||
# FIXME: Come up with a cleaner solution.
|
||||
if not self.env.stdout_isatty:
|
||||
if not self.args.output_file and not self.env.stdout_isatty:
|
||||
# Use stdout as the download output file.
|
||||
self.args.output_file = self.env.stdout
|
||||
# With `--download`, we write everything that would normally go to
|
||||
@ -201,11 +213,6 @@ class Parser(ArgumentParser):
|
||||
self.env.stdout = self.args.output_file
|
||||
self.env.stdout_isatty = False
|
||||
|
||||
def _apply_config(self):
|
||||
if (not self.args.json
|
||||
and self.env.config.implicit_content_type == 'form'):
|
||||
self.args.form = True
|
||||
|
||||
def _process_auth(self):
|
||||
"""
|
||||
If only a username provided via --auth, then ask for a password.
|
||||
@ -336,17 +343,14 @@ class Parser(ArgumentParser):
|
||||
'Invalid file fields (perhaps you meant --form?): %s'
|
||||
% ','.join(file_fields))
|
||||
|
||||
fn, fd = self.args.files['']
|
||||
fn, fd, ct = self.args.files['']
|
||||
self.args.files = {}
|
||||
|
||||
self._body_from_file(fd)
|
||||
|
||||
if 'Content-Type' not in self.args.headers:
|
||||
mime, encoding = mimetypes.guess_type(fn, strict=False)
|
||||
if mime:
|
||||
content_type = mime
|
||||
if encoding:
|
||||
content_type = '%s; charset=%s' % (mime, encoding)
|
||||
content_type = get_content_type(fn)
|
||||
if content_type:
|
||||
self.args.headers['Content-Type'] = content_type
|
||||
|
||||
def _process_output_options(self):
|
||||
@ -355,18 +359,32 @@ class Parser(ArgumentParser):
|
||||
The default output options are stdout-type-sensitive.
|
||||
|
||||
"""
|
||||
if not self.args.output_options:
|
||||
def check_options(value, option):
|
||||
unknown = set(value) - OUTPUT_OPTIONS
|
||||
if unknown:
|
||||
self.error('Unknown output options: {0}={1}'.format(
|
||||
option,
|
||||
','.join(unknown)
|
||||
))
|
||||
|
||||
if self.args.verbose:
|
||||
self.args.all = True
|
||||
|
||||
if self.args.output_options is None:
|
||||
if self.args.verbose:
|
||||
self.args.output_options = ''.join(OUTPUT_OPTIONS)
|
||||
else:
|
||||
self.args.output_options = (
|
||||
OUTPUT_OPTIONS_DEFAULT
|
||||
if self.env.stdout_isatty
|
||||
else OUTPUT_OPTIONS_DEFAULT_STDOUT_REDIRECTED
|
||||
)
|
||||
|
||||
unknown_output_options = set(self.args.output_options) - OUTPUT_OPTIONS
|
||||
if unknown_output_options:
|
||||
self.error(
|
||||
'Unknown output options: %s' % ','.join(unknown_output_options)
|
||||
)
|
||||
if self.args.output_options_history is None:
|
||||
self.args.output_options_history = self.args.output_options
|
||||
|
||||
check_options(self.args.output_options, '--print')
|
||||
check_options(self.args.output_options_history, '--history-print')
|
||||
|
||||
if self.args.download and OUT_RESP_BODY in self.args.output_options:
|
||||
# Response body is always downloaded with --download and it goes
|
||||
@ -609,6 +627,21 @@ RequestItems = namedtuple('RequestItems',
|
||||
['headers', 'data', 'files', 'params'])
|
||||
|
||||
|
||||
def get_content_type(filename):
|
||||
"""
|
||||
Return the content type for ``filename`` in format appropriate
|
||||
for Content-Type headers, or ``None`` if the file type is unknown
|
||||
to ``mimetypes``.
|
||||
|
||||
"""
|
||||
mime, encoding = mimetypes.guess_type(filename, strict=False)
|
||||
if mime:
|
||||
content_type = mime
|
||||
if encoding:
|
||||
content_type = '%s; charset=%s' % (mime, encoding)
|
||||
return content_type
|
||||
|
||||
|
||||
def parse_items(items,
|
||||
headers_class=CaseInsensitiveDict,
|
||||
data_class=OrderedDict,
|
||||
@ -634,7 +667,8 @@ def parse_items(items,
|
||||
try:
|
||||
with open(os.path.expanduser(value), 'rb') as f:
|
||||
value = (os.path.basename(value),
|
||||
BytesIO(f.read()))
|
||||
BytesIO(f.read()),
|
||||
get_content_type(value))
|
||||
except IOError as e:
|
||||
raise ParseError('"%s": %s' % (item.orig, e))
|
||||
target = files
|
||||
|
@ -1,3 +1,6 @@
|
||||
from __future__ import absolute_import
|
||||
import json
|
||||
|
||||
import pygments.lexer
|
||||
import pygments.token
|
||||
import pygments.styles
|
||||
@ -5,16 +8,22 @@ import pygments.lexers
|
||||
import pygments.style
|
||||
from pygments.formatters.terminal import TerminalFormatter
|
||||
from pygments.formatters.terminal256 import Terminal256Formatter
|
||||
from pygments.lexers.special import TextLexer
|
||||
from pygments.util import ClassNotFound
|
||||
|
||||
from httpie.compat import is_windows
|
||||
from httpie.plugins import FormatterPlugin
|
||||
|
||||
|
||||
# Colors on Windows via colorama don't look that
|
||||
# great and fruity seems to give the best result there.
|
||||
AVAILABLE_STYLES = set(pygments.styles.STYLE_MAP.keys())
|
||||
AVAILABLE_STYLES.add('solarized')
|
||||
DEFAULT_STYLE = 'monokai'
|
||||
|
||||
if is_windows:
|
||||
# Colors on Windows via colorama don't look that
|
||||
# great and fruity seems to give the best result there
|
||||
DEFAULT_STYLE = 'fruity'
|
||||
else:
|
||||
DEFAULT_STYLE = 'solarized'
|
||||
|
||||
|
||||
class ColorFormatter(FormatterPlugin):
|
||||
@ -27,14 +36,15 @@ class ColorFormatter(FormatterPlugin):
|
||||
"""
|
||||
group_name = 'colors'
|
||||
|
||||
def __init__(self, env, color_scheme=DEFAULT_STYLE, **kwargs):
|
||||
def __init__(self, env, explicit_json=False,
|
||||
color_scheme=DEFAULT_STYLE, **kwargs):
|
||||
super(ColorFormatter, self).__init__(**kwargs)
|
||||
if not env.colors:
|
||||
self.enabled = False
|
||||
return
|
||||
|
||||
# Cache to speed things up when we process streamed body by line.
|
||||
self.lexer_cache = {}
|
||||
# --json, -j
|
||||
self.explicit_json = explicit_json
|
||||
|
||||
try:
|
||||
style_class = pygments.styles.get_style_by_name(color_scheme)
|
||||
@ -51,34 +61,40 @@ class ColorFormatter(FormatterPlugin):
|
||||
return pygments.highlight(headers, HTTPLexer(), self.formatter).strip()
|
||||
|
||||
def format_body(self, body, mime):
|
||||
lexer = self.get_lexer(mime)
|
||||
lexer = self.get_lexer(mime, body)
|
||||
if lexer:
|
||||
body = pygments.highlight(body, lexer, self.formatter)
|
||||
return body.strip()
|
||||
|
||||
def get_lexer(self, mime):
|
||||
if mime in self.lexer_cache:
|
||||
return self.lexer_cache[mime]
|
||||
self.lexer_cache[mime] = get_lexer(mime)
|
||||
return self.lexer_cache[mime]
|
||||
def get_lexer(self, mime, body):
|
||||
return get_lexer(
|
||||
mime=mime,
|
||||
explicit_json=self.explicit_json,
|
||||
body=body,
|
||||
)
|
||||
|
||||
|
||||
def get_lexer(mime):
|
||||
def get_lexer(mime, explicit_json=False, body=''):
|
||||
|
||||
# Build candidate mime type and lexer names.
|
||||
mime_types, lexer_names = [mime], []
|
||||
type_, subtype = mime.split('/')
|
||||
type_, subtype = mime.split('/', 1)
|
||||
if '+' not in subtype:
|
||||
lexer_names.append(subtype)
|
||||
else:
|
||||
subtype_name, subtype_suffix = subtype.split('+')
|
||||
subtype_name, subtype_suffix = subtype.split('+', 1)
|
||||
lexer_names.extend([subtype_name, subtype_suffix])
|
||||
mime_types.extend([
|
||||
'%s/%s' % (type_, subtype_name),
|
||||
'%s/%s' % (type_, subtype_suffix)
|
||||
])
|
||||
# as a last resort, if no lexer feels responsible, and
|
||||
|
||||
# As a last resort, if no lexer feels responsible, and
|
||||
# the subtype contains 'json', take the JSON lexer
|
||||
if 'json' in subtype:
|
||||
lexer_names.append('json')
|
||||
|
||||
# Try to resolve the right lexer.
|
||||
lexer = None
|
||||
for mime_type in mime_types:
|
||||
try:
|
||||
@ -92,6 +108,16 @@ def get_lexer(mime):
|
||||
lexer = pygments.lexers.get_lexer_by_name(name)
|
||||
except ClassNotFound:
|
||||
pass
|
||||
|
||||
if explicit_json and body and (not lexer or isinstance(lexer, TextLexer)):
|
||||
# JSON response with an incorrect Content-Type?
|
||||
try:
|
||||
json.loads(body) # FIXME: the body also gets parsed in json.py
|
||||
except ValueError:
|
||||
pass # Nope
|
||||
else:
|
||||
lexer = pygments.lexers.get_lexer_by_name('json')
|
||||
|
||||
return lexer
|
||||
|
||||
|
||||
@ -143,8 +169,6 @@ class HTTPLexer(pygments.lexer.RegexLexer):
|
||||
}
|
||||
|
||||
|
||||
# TODO: As Solarized is not the default theme any longer, it should be removed
|
||||
# or bundled directly with Pygments so that we don't need to support it.
|
||||
class Solarized256Style(pygments.style.Style):
|
||||
"""
|
||||
solarized256
|
||||
|
@ -10,17 +10,24 @@ DEFAULT_INDENT = 4
|
||||
class JSONFormatter(FormatterPlugin):
|
||||
|
||||
def format_body(self, body, mime):
|
||||
if 'json' in mime:
|
||||
maybe_json = [
|
||||
'json',
|
||||
'javascript',
|
||||
'text',
|
||||
]
|
||||
if (self.kwargs['explicit_json'] or
|
||||
any(token in mime for token in maybe_json)):
|
||||
try:
|
||||
obj = json.loads(body)
|
||||
except ValueError:
|
||||
# Invalid JSON, ignore.
|
||||
pass
|
||||
pass # Invalid JSON, ignore.
|
||||
else:
|
||||
# Indent, sort keys by name, and avoid
|
||||
# unicode escapes to improve readability.
|
||||
body = json.dumps(obj,
|
||||
body = json.dumps(
|
||||
obj=obj,
|
||||
sort_keys=True,
|
||||
ensure_ascii=False,
|
||||
indent=DEFAULT_INDENT)
|
||||
indent=DEFAULT_INDENT
|
||||
)
|
||||
return body
|
||||
|
@ -1,61 +0,0 @@
|
||||
from __future__ import absolute_import
|
||||
import re
|
||||
from xml.etree import ElementTree
|
||||
|
||||
from httpie.plugins import FormatterPlugin
|
||||
|
||||
|
||||
DECLARATION_RE = re.compile('<\?xml[^\n]+?\?>', flags=re.I)
|
||||
DOCTYPE_RE = re.compile('<!DOCTYPE[^\n]+?>', flags=re.I)
|
||||
|
||||
|
||||
DEFAULT_INDENT = 4
|
||||
|
||||
|
||||
def indent(elem, indent_text=' ' * DEFAULT_INDENT):
|
||||
"""
|
||||
In-place prettyprint formatter
|
||||
C.f. http://effbot.org/zone/element-lib.htm#prettyprint
|
||||
|
||||
"""
|
||||
def _indent(elem, level=0):
|
||||
i = "\n" + level * indent_text
|
||||
if len(elem):
|
||||
if not elem.text or not elem.text.strip():
|
||||
elem.text = i + indent_text
|
||||
if not elem.tail or not elem.tail.strip():
|
||||
elem.tail = i
|
||||
for elem in elem:
|
||||
_indent(elem, level + 1)
|
||||
if not elem.tail or not elem.tail.strip():
|
||||
elem.tail = i
|
||||
else:
|
||||
if level and (not elem.tail or not elem.tail.strip()):
|
||||
elem.tail = i
|
||||
|
||||
return _indent(elem)
|
||||
|
||||
|
||||
class XMLFormatter(FormatterPlugin):
|
||||
# TODO: tests
|
||||
|
||||
def format_body(self, body, mime):
|
||||
if 'xml' in mime:
|
||||
# FIXME: orig NS names get forgotten during the conversion, etc.
|
||||
try:
|
||||
root = ElementTree.fromstring(body.encode('utf8'))
|
||||
except ElementTree.ParseError:
|
||||
# Ignore invalid XML errors (skips attempting to pretty print)
|
||||
pass
|
||||
else:
|
||||
indent(root)
|
||||
# Use the original declaration
|
||||
declaration = DECLARATION_RE.match(body)
|
||||
doctype = DOCTYPE_RE.match(body)
|
||||
body = ElementTree.tostring(root, encoding='utf-8')\
|
||||
.decode('utf8')
|
||||
if doctype:
|
||||
body = '%s\n%s' % (doctype.group(0), body)
|
||||
if declaration:
|
||||
body = '%s\n%s' % (declaration.group(0), body)
|
||||
return body
|
@ -24,7 +24,7 @@ class BinarySuppressedError(Exception):
|
||||
message = BINARY_SUPPRESSED_NOTICE
|
||||
|
||||
|
||||
def write(stream, outfile, flush):
|
||||
def write_stream(stream, outfile, flush):
|
||||
"""Write the output stream."""
|
||||
try:
|
||||
# Writing bytes so we use the buffer interface (Python 3).
|
||||
@ -38,7 +38,7 @@ def write(stream, outfile, flush):
|
||||
outfile.flush()
|
||||
|
||||
|
||||
def write_with_colors_win_py3(stream, outfile, flush):
|
||||
def write_stream_with_colors_win_py3(stream, outfile, flush):
|
||||
"""Like `write`, but colorized chunks are written as text
|
||||
directly to `outfile` to ensure it gets processed by colorama.
|
||||
Applies only to Windows with Python 3 and colorized terminal output.
|
||||
@ -55,15 +55,15 @@ def write_with_colors_win_py3(stream, outfile, flush):
|
||||
outfile.flush()
|
||||
|
||||
|
||||
def build_output_stream(args, env, request, response):
|
||||
def build_output_stream(args, env, request, response, output_options):
|
||||
"""Build and return a chain of iterators over the `request`-`response`
|
||||
exchange each of which yields `bytes` chunks.
|
||||
|
||||
"""
|
||||
req_h = OUT_REQ_HEAD in args.output_options
|
||||
req_b = OUT_REQ_BODY in args.output_options
|
||||
resp_h = OUT_RESP_HEAD in args.output_options
|
||||
resp_b = OUT_RESP_BODY in args.output_options
|
||||
req_h = OUT_REQ_HEAD in output_options
|
||||
req_b = OUT_REQ_BODY in output_options
|
||||
resp_h = OUT_RESP_HEAD in output_options
|
||||
resp_b = OUT_RESP_BODY in output_options
|
||||
req = req_h or req_b
|
||||
resp = resp_h or resp_b
|
||||
|
||||
@ -112,8 +112,12 @@ def get_stream_type(env, args):
|
||||
PrettyStream if args.stream else BufferedPrettyStream,
|
||||
env=env,
|
||||
conversion=Conversion(),
|
||||
formatting=Formatting(env=env, groups=args.prettify,
|
||||
color_scheme=args.style),
|
||||
formatting=Formatting(
|
||||
env=env,
|
||||
groups=args.prettify,
|
||||
color_scheme=args.style,
|
||||
explicit_json=args.json,
|
||||
),
|
||||
)
|
||||
else:
|
||||
Stream = partial(EncodedStream, env=env)
|
||||
|
@ -11,7 +11,6 @@ from httpie.plugins.manager import PluginManager
|
||||
from httpie.plugins.builtin import BasicAuthPlugin, DigestAuthPlugin
|
||||
from httpie.output.formatters.headers import HeadersFormatter
|
||||
from httpie.output.formatters.json import JSONFormatter
|
||||
from httpie.output.formatters.xml import XMLFormatter
|
||||
from httpie.output.formatters.colors import ColorFormatter
|
||||
|
||||
|
||||
@ -20,5 +19,4 @@ plugin_manager.register(BasicAuthPlugin,
|
||||
DigestAuthPlugin)
|
||||
plugin_manager.register(HeadersFormatter,
|
||||
JSONFormatter,
|
||||
XMLFormatter,
|
||||
ColorFormatter)
|
||||
|
@ -22,7 +22,7 @@ SESSION_IGNORED_HEADER_PREFIXES = ['Content-', 'If-']
|
||||
|
||||
def get_response(requests_session, session_name,
|
||||
config_dir, args, read_only=False):
|
||||
"""Like `client.get_response`, but applies permanent
|
||||
"""Like `client.get_responses`, but applies permanent
|
||||
aspects of the session to the request.
|
||||
|
||||
"""
|
||||
@ -30,8 +30,8 @@ def get_response(requests_session, session_name,
|
||||
if os.path.sep in session_name:
|
||||
path = os.path.expanduser(session_name)
|
||||
else:
|
||||
hostname = (args.headers.get('Host', None)
|
||||
or urlsplit(args.url).netloc.split('@')[-1])
|
||||
hostname = (args.headers.get('Host', None) or
|
||||
urlsplit(args.url).netloc.split('@')[-1])
|
||||
if not hostname:
|
||||
# HACK/FIXME: httpie-unixsocket's URLs have no hostname.
|
||||
hostname = 'localhost'
|
||||
@ -101,6 +101,10 @@ class Session(BaseConfigDict):
|
||||
|
||||
"""
|
||||
for name, value in request_headers.items():
|
||||
|
||||
if value is None:
|
||||
continue # Ignore explicitely unset headers
|
||||
|
||||
value = value.decode('utf8')
|
||||
if name == 'User-Agent' and value.startswith('HTTPie/'):
|
||||
continue
|
||||
|
@ -10,6 +10,22 @@ def load_json_preserve_order(s):
|
||||
return json.loads(s, object_pairs_hook=OrderedDict)
|
||||
|
||||
|
||||
def repr_dict_nice(d):
|
||||
def prepare_dict(d):
|
||||
for k, v in d.items():
|
||||
if isinstance(v, dict):
|
||||
v = dict(prepare_dict(v))
|
||||
elif isinstance(v, bytes):
|
||||
v = v.decode('utf8')
|
||||
elif not isinstance(v, (int, str)):
|
||||
v = repr(v)
|
||||
yield k, v
|
||||
return json.dumps(
|
||||
dict(prepare_dict(d)),
|
||||
indent=4, sort_keys=True,
|
||||
)
|
||||
|
||||
|
||||
def humanize_bytes(n, precision=2):
|
||||
# Author: Doug Latornell
|
||||
# Licence: MIT
|
||||
|
@ -1,3 +1,2 @@
|
||||
[pytest]
|
||||
addopts = --tb=native
|
||||
norecursedirs = tests/fixtures
|
||||
|
2
setup.py
2
setup.py
@ -56,7 +56,7 @@ if 'bdist_wheel' not in sys.argv:
|
||||
|
||||
# bdist_wheel
|
||||
extras_require = {
|
||||
# http://wheel.readthedocs.org/en/latest/#defining-conditional-dependencies
|
||||
# http://wheel.readthedocs.io/en/latest/#defining-conditional-dependencies
|
||||
':python_version == "2.6"'
|
||||
' or python_version == "3.0"'
|
||||
' or python_version == "3.1" ': ['argparse>=1.2.1'],
|
||||
|
14
tests/conftest.py
Normal file
14
tests/conftest.py
Normal file
@ -0,0 +1,14 @@
|
||||
import pytest
|
||||
from pytest_httpbin.plugin import httpbin_ca_bundle
|
||||
|
||||
|
||||
# Make httpbin's CA trusted by default
|
||||
pytest.fixture(autouse=True)(httpbin_ca_bundle)
|
||||
|
||||
|
||||
@pytest.fixture(scope='function')
|
||||
def httpbin_secure_untrusted(monkeypatch, httpbin_secure):
|
||||
"""Like the `httpbin_secure` fixture, but without the
|
||||
make-CA-trusted-by-default"""
|
||||
monkeypatch.delenv('REQUESTS_CA_BUNDLE')
|
||||
return httpbin_secure
|
@ -12,7 +12,7 @@ def patharg(path):
|
||||
return path.replace('\\', '\\\\\\')
|
||||
|
||||
|
||||
FIXTURES_ROOT = path.join(path.abspath(path.dirname(__file__)), 'fixtures')
|
||||
FIXTURES_ROOT = path.join(path.abspath(path.dirname(__file__)))
|
||||
FILE_PATH = path.join(FIXTURES_ROOT, 'test.txt')
|
||||
JSON_FILE_PATH = path.join(FIXTURES_ROOT, 'test.json')
|
||||
BIN_FILE_PATH = path.join(FIXTURES_ROOT, 'test.bin')
|
@ -1,5 +1,5 @@
|
||||
"""HTTP authentication-related tests."""
|
||||
import requests
|
||||
import mock
|
||||
import pytest
|
||||
|
||||
from utils import http, add_auth, HTTP_OK, TestEnvironment
|
||||
@ -7,50 +7,53 @@ import httpie.input
|
||||
import httpie.cli
|
||||
|
||||
|
||||
class TestAuth:
|
||||
def test_basic_auth(self, httpbin):
|
||||
def test_basic_auth(httpbin_both):
|
||||
r = http('--auth=user:password',
|
||||
'GET', httpbin.url + '/basic-auth/user/password')
|
||||
'GET', httpbin_both + '/basic-auth/user/password')
|
||||
assert HTTP_OK in r
|
||||
assert r.json == {'authenticated': True, 'user': 'user'}
|
||||
|
||||
@pytest.mark.skipif(
|
||||
requests.__version__ == '0.13.6',
|
||||
reason='Redirects with prefetch=False are broken in Requests 0.13.6')
|
||||
def test_digest_auth(self, httpbin):
|
||||
r = http('--auth-type=digest', '--auth=user:password',
|
||||
'GET', httpbin.url + '/digest-auth/auth/user/password')
|
||||
|
||||
@pytest.mark.parametrize('argument_name', ['--auth-type', '-A'])
|
||||
def test_digest_auth(httpbin_both, argument_name):
|
||||
r = http(argument_name + '=digest', '--auth=user:password',
|
||||
'GET', httpbin_both.url + '/digest-auth/auth/user/password')
|
||||
assert HTTP_OK in r
|
||||
assert r.json == {'authenticated': True, 'user': 'user'}
|
||||
|
||||
def test_password_prompt(self, httpbin):
|
||||
httpie.input.AuthCredentials._getpass = lambda self, prompt: 'password'
|
||||
|
||||
@mock.patch('httpie.input.AuthCredentials._getpass',
|
||||
new=lambda self, prompt: 'password')
|
||||
def test_password_prompt(httpbin):
|
||||
r = http('--auth', 'user',
|
||||
'GET', httpbin.url + '/basic-auth/user/password')
|
||||
assert HTTP_OK in r
|
||||
assert r.json == {'authenticated': True, 'user': 'user'}
|
||||
|
||||
def test_credentials_in_url(self, httpbin):
|
||||
url = add_auth(httpbin.url + '/basic-auth/user/password',
|
||||
|
||||
def test_credentials_in_url(httpbin_both):
|
||||
url = add_auth(httpbin_both.url + '/basic-auth/user/password',
|
||||
auth='user:password')
|
||||
r = http('GET', url)
|
||||
assert HTTP_OK in r
|
||||
assert r.json == {'authenticated': True, 'user': 'user'}
|
||||
|
||||
def test_credentials_in_url_auth_flag_has_priority(self, httpbin):
|
||||
|
||||
def test_credentials_in_url_auth_flag_has_priority(httpbin_both):
|
||||
"""When credentials are passed in URL and via -a at the same time,
|
||||
then the ones from -a are used."""
|
||||
url = add_auth(httpbin.url + '/basic-auth/user/password',
|
||||
url = add_auth(httpbin_both.url + '/basic-auth/user/password',
|
||||
auth='user:wrong')
|
||||
r = http('--auth=user:password', 'GET', url)
|
||||
assert HTTP_OK in r
|
||||
assert r.json == {'authenticated': True, 'user': 'user'}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('url', [
|
||||
'username@example.org',
|
||||
'username:@example.org',
|
||||
])
|
||||
def test_only_username_in_url(self, url):
|
||||
def test_only_username_in_url(url):
|
||||
"""
|
||||
https://github.com/jkbrzt/httpie/issues/242
|
||||
|
||||
|
@ -6,6 +6,7 @@ from fixtures import BIN_FILE_PATH, BIN_FILE_CONTENT, BIN_FILE_PATH_ARG
|
||||
|
||||
|
||||
class TestBinaryRequestData:
|
||||
|
||||
def test_binary_stdin(self, httpbin):
|
||||
with open(BIN_FILE_PATH, 'rb') as stdin:
|
||||
env = TestEnvironment(
|
||||
|
@ -154,7 +154,7 @@ class TestQuerystring:
|
||||
assert '"url": "%s"' % url in r
|
||||
|
||||
|
||||
class TestURLshorthand:
|
||||
class TestLocalhostShorthand:
|
||||
def test_expand_localhost_shorthand(self):
|
||||
args = parser.parse_args(args=[':'], env=TestEnvironment())
|
||||
assert args.url == 'http://localhost'
|
||||
@ -201,7 +201,7 @@ class TestURLshorthand:
|
||||
class TestArgumentParser:
|
||||
|
||||
def setup_method(self, method):
|
||||
self.parser = input.Parser()
|
||||
self.parser = input.HTTPieArgumentParser()
|
||||
|
||||
def test_guess_when_method_set_and_valid(self):
|
||||
self.parser.args = argparse.Namespace()
|
||||
|
33
tests/test_config.py
Normal file
33
tests/test_config.py
Normal file
@ -0,0 +1,33 @@
|
||||
from utils import TestEnvironment, http
|
||||
|
||||
|
||||
def test_default_options(httpbin):
|
||||
env = TestEnvironment()
|
||||
env.config['default_options'] = ['--form']
|
||||
env.config.save()
|
||||
r = http(httpbin.url + '/post', 'foo=bar', env=env)
|
||||
assert r.json['form'] == {"foo": "bar"}
|
||||
|
||||
|
||||
def test_default_options_overwrite(httpbin):
|
||||
env = TestEnvironment()
|
||||
env.config['default_options'] = ['--form']
|
||||
env.config.save()
|
||||
r = http('--json', httpbin.url + '/post', 'foo=bar', env=env)
|
||||
assert r.json['json'] == {"foo": "bar"}
|
||||
|
||||
|
||||
def test_migrate_implicit_content_type():
|
||||
config = TestEnvironment().config
|
||||
|
||||
config['implicit_content_type'] = 'json'
|
||||
config.save()
|
||||
config.load()
|
||||
assert 'implicit_content_type' not in config
|
||||
assert not config['default_options']
|
||||
|
||||
config['implicit_content_type'] = 'form'
|
||||
config.save()
|
||||
config.load()
|
||||
assert 'implicit_content_type' not in config
|
||||
assert config['default_options'] == ['--form']
|
@ -2,7 +2,7 @@
|
||||
Tests for the provided defaults regarding HTTP method, and --json vs. --form.
|
||||
|
||||
"""
|
||||
from utils import TestEnvironment, http, HTTP_OK, no_content_type
|
||||
from utils import TestEnvironment, http, HTTP_OK
|
||||
from fixtures import FILE_PATH
|
||||
|
||||
|
||||
@ -46,7 +46,7 @@ class TestAutoContentTypeAndAcceptHeaders:
|
||||
r = http('GET', httpbin.url + '/headers')
|
||||
assert HTTP_OK in r
|
||||
assert r.json['headers']['Accept'] == '*/*'
|
||||
assert no_content_type(r.json['headers'])
|
||||
assert 'Content-Type' not in r.json['headers']
|
||||
|
||||
def test_POST_no_data_no_auto_headers(self, httpbin):
|
||||
# JSON headers shouldn't be automatically set for POST with no data.
|
||||
|
@ -36,4 +36,4 @@ def test_rst_file_syntax(filename):
|
||||
stdout=subprocess.PIPE
|
||||
)
|
||||
err = p.communicate()[1]
|
||||
assert p.returncode == 0, err
|
||||
assert p.returncode == 0, err.decode('utf8')
|
||||
|
@ -2,12 +2,13 @@ import os
|
||||
import time
|
||||
|
||||
import pytest
|
||||
import mock
|
||||
from requests.structures import CaseInsensitiveDict
|
||||
|
||||
from httpie.compat import urlopen
|
||||
from httpie.downloads import (
|
||||
parse_content_range, filename_from_content_disposition, filename_from_url,
|
||||
get_unique_filename, ContentRangeError, Download,
|
||||
get_unique_filename, ContentRangeError, Downloader,
|
||||
)
|
||||
from utils import http, TestEnvironment
|
||||
|
||||
@ -74,7 +75,31 @@ class TestDownloadUtils:
|
||||
content_type='x-foo/bar'
|
||||
)
|
||||
|
||||
def test_unique_filename(self):
|
||||
@pytest.mark.parametrize(
|
||||
'orig_name, unique_on_attempt, expected',
|
||||
[
|
||||
# Simple
|
||||
('foo.bar', 0, 'foo.bar'),
|
||||
('foo.bar', 1, 'foo.bar-1'),
|
||||
('foo.bar', 10, 'foo.bar-10'),
|
||||
# Trim
|
||||
('A' * 20, 0, 'A' * 10),
|
||||
('A' * 20, 1, 'A' * 8 + '-1'),
|
||||
('A' * 20, 10, 'A' * 7 + '-10'),
|
||||
# Trim before ext
|
||||
('A' * 20 + '.txt', 0, 'A' * 6 + '.txt'),
|
||||
('A' * 20 + '.txt', 1, 'A' * 4 + '.txt-1'),
|
||||
# Trim at the end
|
||||
('foo.' + 'A' * 20, 0, 'foo.' + 'A' * 6),
|
||||
('foo.' + 'A' * 20, 1, 'foo.' + 'A' * 4 + '-1'),
|
||||
('foo.' + 'A' * 20, 10, 'foo.' + 'A' * 3 + '-10'),
|
||||
]
|
||||
)
|
||||
@mock.patch('httpie.downloads.get_filename_max_length')
|
||||
def test_unique_filename(self, get_filename_max_length,
|
||||
orig_name, unique_on_attempt,
|
||||
expected):
|
||||
|
||||
def attempts(unique_on_attempt=0):
|
||||
# noinspection PyUnresolvedReferences,PyUnusedLocal
|
||||
def exists(filename):
|
||||
@ -86,54 +111,55 @@ class TestDownloadUtils:
|
||||
exists.attempt = 0
|
||||
return exists
|
||||
|
||||
assert 'foo.bar' == get_unique_filename('foo.bar', attempts(0))
|
||||
assert 'foo.bar-1' == get_unique_filename('foo.bar', attempts(1))
|
||||
assert 'foo.bar-10' == get_unique_filename('foo.bar', attempts(10))
|
||||
get_filename_max_length.return_value = 10
|
||||
|
||||
actual = get_unique_filename(orig_name, attempts(unique_on_attempt))
|
||||
assert expected == actual
|
||||
|
||||
|
||||
class TestDownloads:
|
||||
# TODO: more tests
|
||||
|
||||
def test_actual_download(self, httpbin):
|
||||
url = httpbin.url + '/robots.txt'
|
||||
body = urlopen(url).read().decode()
|
||||
def test_actual_download(self, httpbin_both, httpbin):
|
||||
robots_txt = '/robots.txt'
|
||||
body = urlopen(httpbin + robots_txt).read().decode()
|
||||
env = TestEnvironment(stdin_isatty=True, stdout_isatty=False)
|
||||
r = http('--download', url, env=env)
|
||||
r = http('--download', httpbin_both.url + robots_txt, env=env)
|
||||
assert 'Downloading' in r.stderr
|
||||
assert '[K' in r.stderr
|
||||
assert 'Done' in r.stderr
|
||||
assert body == r
|
||||
|
||||
def test_download_with_Content_Length(self, httpbin):
|
||||
def test_download_with_Content_Length(self, httpbin_both):
|
||||
devnull = open(os.devnull, 'w')
|
||||
download = Download(output_file=devnull, progress_file=devnull)
|
||||
download.start(Response(
|
||||
url=httpbin.url + '/',
|
||||
downloader = Downloader(output_file=devnull, progress_file=devnull)
|
||||
downloader.start(Response(
|
||||
url=httpbin_both.url + '/',
|
||||
headers={'Content-Length': 10}
|
||||
))
|
||||
time.sleep(1.1)
|
||||
download.chunk_downloaded(b'12345')
|
||||
downloader.chunk_downloaded(b'12345')
|
||||
time.sleep(1.1)
|
||||
download.chunk_downloaded(b'12345')
|
||||
download.finish()
|
||||
assert not download.interrupted
|
||||
downloader.chunk_downloaded(b'12345')
|
||||
downloader.finish()
|
||||
assert not downloader.interrupted
|
||||
|
||||
def test_download_no_Content_Length(self, httpbin):
|
||||
def test_download_no_Content_Length(self, httpbin_both):
|
||||
devnull = open(os.devnull, 'w')
|
||||
download = Download(output_file=devnull, progress_file=devnull)
|
||||
download.start(Response(url=httpbin.url + '/'))
|
||||
downloader = Downloader(output_file=devnull, progress_file=devnull)
|
||||
downloader.start(Response(url=httpbin_both.url + '/'))
|
||||
time.sleep(1.1)
|
||||
download.chunk_downloaded(b'12345')
|
||||
download.finish()
|
||||
assert not download.interrupted
|
||||
downloader.chunk_downloaded(b'12345')
|
||||
downloader.finish()
|
||||
assert not downloader.interrupted
|
||||
|
||||
def test_download_interrupted(self, httpbin):
|
||||
def test_download_interrupted(self, httpbin_both):
|
||||
devnull = open(os.devnull, 'w')
|
||||
download = Download(output_file=devnull, progress_file=devnull)
|
||||
download.start(Response(
|
||||
url=httpbin.url + '/',
|
||||
downloader = Downloader(output_file=devnull, progress_file=devnull)
|
||||
downloader.start(Response(
|
||||
url=httpbin_both.url + '/',
|
||||
headers={'Content-Length': 5}
|
||||
))
|
||||
download.chunk_downloaded(b'1234')
|
||||
download.finish()
|
||||
assert download.interrupted
|
||||
downloader.chunk_downloaded(b'1234')
|
||||
downloader.finish()
|
||||
assert downloader.interrupted
|
||||
|
@ -3,6 +3,7 @@ from pytest import raises
|
||||
from requests import Request, Timeout
|
||||
from requests.exceptions import ConnectionError
|
||||
|
||||
from httpie import ExitStatus
|
||||
from httpie.core import main
|
||||
|
||||
error_msg = None
|
||||
@ -17,8 +18,8 @@ def test_error(get_response):
|
||||
exc = ConnectionError('Connection aborted')
|
||||
exc.request = Request(method='GET', url='http://www.google.com')
|
||||
get_response.side_effect = exc
|
||||
ret = main(['--ignore-stdin', 'www.google.com'], error=error)
|
||||
assert ret == 1
|
||||
ret = main(['--ignore-stdin', 'www.google.com'], custom_log_error=error)
|
||||
assert ret == ExitStatus.ERROR
|
||||
assert error_msg == (
|
||||
'ConnectionError: '
|
||||
'Connection aborted while doing GET request to URL: '
|
||||
@ -31,7 +32,7 @@ def test_error_traceback(get_response):
|
||||
exc.request = Request(method='GET', url='http://www.google.com')
|
||||
get_response.side_effect = exc
|
||||
with raises(ConnectionError):
|
||||
ret = main(['--ignore-stdin', '--traceback', 'www.google.com'])
|
||||
main(['--ignore-stdin', '--traceback', 'www.google.com'])
|
||||
|
||||
|
||||
@mock.patch('httpie.core.get_response')
|
||||
@ -43,6 +44,6 @@ def test_timeout(get_response):
|
||||
exc = Timeout('Request timed out')
|
||||
exc.request = Request(method='GET', url='http://www.google.com')
|
||||
get_response.side_effect = exc
|
||||
ret = main(['--ignore-stdin', 'www.google.com'], error=error)
|
||||
assert ret == 2
|
||||
ret = main(['--ignore-stdin', 'www.google.com'], custom_log_error=error)
|
||||
assert ret == ExitStatus.ERROR_TIMEOUT
|
||||
assert error_msg == 'Request timed out (30s).'
|
||||
|
@ -1,34 +1,29 @@
|
||||
import requests
|
||||
import pytest
|
||||
|
||||
from httpie import ExitStatus
|
||||
from utils import TestEnvironment, http, HTTP_OK
|
||||
|
||||
|
||||
class TestExitStatus:
|
||||
def test_ok_response_exits_0(self, httpbin):
|
||||
def test_ok_response_exits_0(httpbin):
|
||||
r = http('GET', httpbin.url + '/status/200')
|
||||
assert HTTP_OK in r
|
||||
assert r.exit_status == ExitStatus.OK
|
||||
|
||||
def test_error_response_exits_0_without_check_status(self, httpbin):
|
||||
|
||||
def test_error_response_exits_0_without_check_status(httpbin):
|
||||
r = http('GET', httpbin.url + '/status/500')
|
||||
assert '500 INTERNAL SERVER ERRO' in r
|
||||
assert r.exit_status == ExitStatus.OK
|
||||
assert not r.stderr
|
||||
|
||||
@pytest.mark.skipif(
|
||||
tuple(map(int, requests.__version__.split('.'))) < (2, 3, 0),
|
||||
reason='timeout broken in requests prior v2.3.0 (#185)'
|
||||
)
|
||||
def test_timeout_exit_status(self, httpbin):
|
||||
|
||||
r = http('--timeout=0.5', 'GET', httpbin.url + '/delay/1',
|
||||
def test_timeout_exit_status(httpbin):
|
||||
|
||||
r = http('--timeout=0.01', 'GET', httpbin.url + '/delay/0.02',
|
||||
error_exit_ok=True)
|
||||
assert r.exit_status == ExitStatus.ERROR_TIMEOUT
|
||||
|
||||
|
||||
def test_3xx_check_status_exits_3_and_stderr_when_stdout_redirected(
|
||||
self, httpbin):
|
||||
httpbin):
|
||||
env = TestEnvironment(stdout_isatty=False)
|
||||
r = http('--check-status', '--headers',
|
||||
'GET', httpbin.url + '/status/301',
|
||||
@ -37,10 +32,8 @@ class TestExitStatus:
|
||||
assert r.exit_status == ExitStatus.ERROR_HTTP_3XX
|
||||
assert '301 moved permanently' in r.stderr.lower()
|
||||
|
||||
@pytest.mark.skipif(
|
||||
requests.__version__ == '0.13.6',
|
||||
reason='Redirects with prefetch=False are broken in Requests 0.13.6')
|
||||
def test_3xx_check_status_redirects_allowed_exits_0(self, httpbin):
|
||||
|
||||
def test_3xx_check_status_redirects_allowed_exits_0(httpbin):
|
||||
r = http('--check-status', '--follow',
|
||||
'GET', httpbin.url + '/status/301',
|
||||
error_exit_ok=True)
|
||||
@ -48,7 +41,8 @@ class TestExitStatus:
|
||||
assert HTTP_OK in r
|
||||
assert r.exit_status == ExitStatus.OK
|
||||
|
||||
def test_4xx_check_status_exits_4(self, httpbin):
|
||||
|
||||
def test_4xx_check_status_exits_4(httpbin):
|
||||
r = http('--check-status', 'GET', httpbin.url + '/status/401',
|
||||
error_exit_ok=True)
|
||||
assert '401 UNAUTHORIZED' in r
|
||||
@ -56,7 +50,8 @@ class TestExitStatus:
|
||||
# Also stderr should be empty since stdout isn't redirected.
|
||||
assert not r.stderr
|
||||
|
||||
def test_5xx_check_status_exits_5(self, httpbin):
|
||||
|
||||
def test_5xx_check_status_exits_5(httpbin):
|
||||
r = http('--check-status', 'GET', httpbin.url + '/status/500',
|
||||
error_exit_ok=True)
|
||||
assert '500 INTERNAL SERVER ERROR' in r
|
||||
|
@ -7,72 +7,80 @@ import httpie
|
||||
from httpie.compat import is_py26
|
||||
|
||||
|
||||
class TestHTTPie:
|
||||
|
||||
def test_debug(self):
|
||||
def test_debug():
|
||||
r = http('--debug')
|
||||
assert r.exit_status == httpie.ExitStatus.OK
|
||||
assert 'HTTPie %s' % httpie.__version__ in r.stderr
|
||||
assert 'HTTPie data:' in r.stderr
|
||||
|
||||
def test_help(self):
|
||||
|
||||
def test_help():
|
||||
r = http('--help', error_exit_ok=True)
|
||||
assert r.exit_status == httpie.ExitStatus.OK
|
||||
assert 'https://github.com/jkbrzt/httpie/issues' in r
|
||||
|
||||
def test_version(self):
|
||||
|
||||
def test_version():
|
||||
r = http('--version', error_exit_ok=True)
|
||||
assert r.exit_status == httpie.ExitStatus.OK
|
||||
# FIXME: py3 has version in stdout, py2 in stderr
|
||||
assert httpie.__version__ == r.stderr.strip() + r.strip()
|
||||
|
||||
def test_GET(self, httpbin):
|
||||
r = http('GET', httpbin.url + '/get')
|
||||
|
||||
def test_GET(httpbin_both):
|
||||
r = http('GET', httpbin_both + '/get')
|
||||
assert HTTP_OK in r
|
||||
|
||||
def test_DELETE(self, httpbin):
|
||||
r = http('DELETE', httpbin.url + '/delete')
|
||||
|
||||
def test_DELETE(httpbin_both):
|
||||
r = http('DELETE', httpbin_both + '/delete')
|
||||
assert HTTP_OK in r
|
||||
|
||||
def test_PUT(self, httpbin):
|
||||
r = http('PUT', httpbin.url + '/put', 'foo=bar')
|
||||
|
||||
def test_PUT(httpbin_both):
|
||||
r = http('PUT', httpbin_both + '/put', 'foo=bar')
|
||||
assert HTTP_OK in r
|
||||
assert r.json['json']['foo'] == 'bar'
|
||||
|
||||
def test_POST_JSON_data(self, httpbin):
|
||||
r = http('POST', httpbin.url + '/post', 'foo=bar')
|
||||
|
||||
def test_POST_JSON_data(httpbin_both):
|
||||
r = http('POST', httpbin_both + '/post', 'foo=bar')
|
||||
assert HTTP_OK in r
|
||||
assert r.json['json']['foo'] == 'bar'
|
||||
|
||||
def test_POST_form(self, httpbin):
|
||||
r = http('--form', 'POST', httpbin.url + '/post', 'foo=bar')
|
||||
|
||||
def test_POST_form(httpbin_both):
|
||||
r = http('--form', 'POST', httpbin_both + '/post', 'foo=bar')
|
||||
assert HTTP_OK in r
|
||||
assert '"foo": "bar"' in r
|
||||
|
||||
def test_POST_form_multiple_values(self, httpbin):
|
||||
r = http('--form', 'POST', httpbin.url + '/post', 'foo=bar', 'foo=baz')
|
||||
|
||||
def test_POST_form_multiple_values(httpbin_both):
|
||||
r = http('--form', 'POST', httpbin_both + '/post', 'foo=bar', 'foo=baz')
|
||||
assert HTTP_OK in r
|
||||
assert r.json['form'] == {'foo': ['bar', 'baz']}
|
||||
|
||||
def test_POST_stdin(self, httpbin):
|
||||
|
||||
def test_POST_stdin(httpbin_both):
|
||||
with open(FILE_PATH) as f:
|
||||
env = TestEnvironment(stdin=f, stdin_isatty=False)
|
||||
r = http('--form', 'POST', httpbin.url + '/post', env=env)
|
||||
r = http('--form', 'POST', httpbin_both + '/post', env=env)
|
||||
assert HTTP_OK in r
|
||||
assert FILE_CONTENT in r
|
||||
|
||||
def test_headers(self, httpbin):
|
||||
r = http('GET', httpbin.url + '/headers', 'Foo:bar')
|
||||
|
||||
def test_headers(httpbin_both):
|
||||
r = http('GET', httpbin_both + '/headers', 'Foo:bar')
|
||||
assert HTTP_OK in r
|
||||
assert '"User-Agent": "HTTPie' in r, r
|
||||
assert '"Foo": "bar"' in r
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
is_py26,
|
||||
reason='the `object_pairs_hook` arg for `json.loads()` is Py>2.6 only'
|
||||
)
|
||||
def test_json_input_preserve_order(self, httpbin):
|
||||
r = http('PATCH', httpbin.url + '/patch',
|
||||
def test_json_input_preserve_order(httpbin_both):
|
||||
r = http('PATCH', httpbin_both + '/patch',
|
||||
'order:={"map":{"1":"first","2":"second"}}')
|
||||
assert HTTP_OK in r
|
||||
assert r.json['data'] == \
|
||||
|
@ -1,10 +1,30 @@
|
||||
import os
|
||||
from tempfile import gettempdir
|
||||
|
||||
import pytest
|
||||
|
||||
from utils import TestEnvironment, http, HTTP_OK, COLOR, CRLF
|
||||
from httpie import ExitStatus
|
||||
from httpie.compat import urlopen
|
||||
from httpie.output.formatters.colors import get_lexer
|
||||
|
||||
|
||||
@pytest.mark.parametrize('stdout_isatty', [True, False])
|
||||
def test_output_option(httpbin, stdout_isatty):
|
||||
output_filename = os.path.join(gettempdir(), test_output_option.__name__)
|
||||
url = httpbin + '/robots.txt'
|
||||
|
||||
r = http('--output', output_filename, url,
|
||||
env=TestEnvironment(stdout_isatty=stdout_isatty))
|
||||
assert r == ''
|
||||
|
||||
expected_body = urlopen(url).read().decode()
|
||||
with open(output_filename, 'r') as f:
|
||||
actual_body = f.read()
|
||||
|
||||
assert actual_body == expected_body
|
||||
|
||||
|
||||
class TestVerboseFlag:
|
||||
def test_verbose(self, httpbin):
|
||||
r = http('--verbose',
|
||||
@ -25,25 +45,38 @@ class TestVerboseFlag:
|
||||
assert HTTP_OK in r
|
||||
assert '"baz": "bar"' in r
|
||||
|
||||
def test_verbose_implies_all(self, httpbin):
|
||||
r = http('--verbose', '--follow', httpbin + '/redirect/1')
|
||||
assert 'GET /redirect/1 HTTP/1.1' in r
|
||||
assert 'HTTP/1.1 302 FOUND' in r
|
||||
assert 'GET /get HTTP/1.1' in r
|
||||
assert HTTP_OK in r
|
||||
|
||||
|
||||
class TestColors:
|
||||
|
||||
@pytest.mark.parametrize('mime', [
|
||||
'application/json',
|
||||
'application/json+foo',
|
||||
'application/foo+json',
|
||||
'application/json-foo',
|
||||
'application/x-json',
|
||||
'foo/json',
|
||||
'foo/json+bar',
|
||||
'foo/bar+json',
|
||||
'foo/json-foo',
|
||||
'foo/x-json',
|
||||
])
|
||||
def test_get_lexer(self, mime):
|
||||
lexer = get_lexer(mime)
|
||||
@pytest.mark.parametrize(
|
||||
argnames=['mime', 'explicit_json', 'body', 'expected_lexer_name'],
|
||||
argvalues=[
|
||||
('application/json', False, None, 'JSON'),
|
||||
('application/json+foo', False, None, 'JSON'),
|
||||
('application/foo+json', False, None, 'JSON'),
|
||||
('application/json-foo', False, None, 'JSON'),
|
||||
('application/x-json', False, None, 'JSON'),
|
||||
('foo/json', False, None, 'JSON'),
|
||||
('foo/json+bar', False, None, 'JSON'),
|
||||
('foo/bar+json', False, None, 'JSON'),
|
||||
('foo/json-foo', False, None, 'JSON'),
|
||||
('foo/x-json', False, None, 'JSON'),
|
||||
('application/vnd.comverge.grid+hal+json', False, None, 'JSON'),
|
||||
('text/plain', True, '{}', 'JSON'),
|
||||
('text/plain', True, 'foo', 'Text only'),
|
||||
]
|
||||
)
|
||||
def test_get_lexer(self, mime, explicit_json, body, expected_lexer_name):
|
||||
lexer = get_lexer(mime, body=body, explicit_json=explicit_json)
|
||||
assert lexer is not None
|
||||
assert lexer.name == 'JSON'
|
||||
assert lexer.name == expected_lexer_name
|
||||
|
||||
def test_get_lexer_not_found(self):
|
||||
assert get_lexer('xxx/yyy') is None
|
||||
|
47
tests/test_redirects.py
Normal file
47
tests/test_redirects.py
Normal file
@ -0,0 +1,47 @@
|
||||
"""High-level tests."""
|
||||
import pytest
|
||||
|
||||
from httpie import ExitStatus
|
||||
from utils import http, HTTP_OK
|
||||
|
||||
|
||||
def test_follow_all_redirects_shown(httpbin):
|
||||
r = http('--follow', '--all', httpbin.url + '/redirect/2')
|
||||
assert r.count('HTTP/1.1') == 3
|
||||
assert r.count('HTTP/1.1 302 FOUND', 2)
|
||||
assert HTTP_OK in r
|
||||
|
||||
|
||||
@pytest.mark.parametrize('follow_flag', ['--follow', '-F'])
|
||||
def test_follow_without_all_redirects_hidden(httpbin, follow_flag):
|
||||
r = http(follow_flag, httpbin.url + '/redirect/2')
|
||||
assert r.count('HTTP/1.1') == 1
|
||||
assert HTTP_OK in r
|
||||
|
||||
|
||||
def test_follow_all_output_options_used_for_redirects(httpbin):
|
||||
r = http('--check-status',
|
||||
'--follow',
|
||||
'--all',
|
||||
'--print=H',
|
||||
httpbin.url + '/redirect/2')
|
||||
assert r.count('GET /') == 3
|
||||
assert HTTP_OK not in r
|
||||
|
||||
|
||||
def test_follow_redirect_output_options(httpbin):
|
||||
r = http('--check-status',
|
||||
'--follow',
|
||||
'--all',
|
||||
'--print=h',
|
||||
'--history-print=H',
|
||||
httpbin.url + '/redirect/2')
|
||||
assert r.count('GET /') == 2
|
||||
assert 'HTTP/1.1 302 FOUND' not in r
|
||||
assert HTTP_OK in r
|
||||
|
||||
|
||||
def test_max_redirects(httpbin):
|
||||
r = http('--max-redirects=1', '--follow', httpbin.url + '/redirect/3',
|
||||
error_exit_ok=True)
|
||||
assert r.exit_status == ExitStatus.ERROR_TOO_MANY_REDIRECTS
|
@ -2,12 +2,12 @@
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from tempfile import gettempdir
|
||||
|
||||
import pytest
|
||||
|
||||
from httpie.plugins.builtin import HTTPBasicAuth
|
||||
from utils import TestEnvironment, mk_config_dir, http, HTTP_OK, \
|
||||
no_content_type
|
||||
from utils import TestEnvironment, mk_config_dir, http, HTTP_OK
|
||||
from fixtures import UNICODE
|
||||
|
||||
|
||||
@ -125,7 +125,7 @@ class TestSession(SessionTestBase):
|
||||
r2 = http('--session=test', 'GET', httpbin.url + '/get',
|
||||
env=self.env())
|
||||
assert HTTP_OK in r2
|
||||
assert no_content_type(r2.json['headers'])
|
||||
assert 'Content-Type' not in r2.json['headers']
|
||||
assert 'If-Unmodified-Since' not in r2.json['headers']
|
||||
|
||||
def test_session_by_path(self, httpbin):
|
||||
@ -157,8 +157,8 @@ class TestSession(SessionTestBase):
|
||||
assert HTTP_OK in r2
|
||||
|
||||
# FIXME: Authorization *sometimes* is not present on Python3
|
||||
assert (r2.json['headers']['Authorization']
|
||||
== HTTPBasicAuth.make_header(u'test', UNICODE))
|
||||
assert (r2.json['headers']['Authorization'] ==
|
||||
HTTPBasicAuth.make_header(u'test', UNICODE))
|
||||
# httpbin doesn't interpret utf8 headers
|
||||
assert UNICODE in r2
|
||||
|
||||
@ -174,3 +174,14 @@ class TestSession(SessionTestBase):
|
||||
r2 = http('--session=test', httpbin.url + '/headers', env=self.env())
|
||||
assert HTTP_OK in r2
|
||||
assert r2.json['headers']['User-Agent'] == 'custom'
|
||||
|
||||
def test_download_in_session(self, httpbin):
|
||||
# https://github.com/jkbrzt/httpie/issues/412
|
||||
self.start_session(httpbin)
|
||||
cwd = os.getcwd()
|
||||
os.chdir(gettempdir())
|
||||
try:
|
||||
http('--session=test', '--download',
|
||||
httpbin.url + '/get', env=self.env())
|
||||
finally:
|
||||
os.chdir(cwd)
|
||||
|
@ -5,6 +5,7 @@ import pytest_httpbin.certs
|
||||
from requests.exceptions import SSLError
|
||||
|
||||
from httpie import ExitStatus
|
||||
from httpie.input import SSL_VERSION_ARG_MAPPING
|
||||
from utils import http, HTTP_OK, TESTS_ROOT
|
||||
|
||||
|
||||
@ -12,17 +13,44 @@ CLIENT_CERT = os.path.join(TESTS_ROOT, 'client_certs', 'client.crt')
|
||||
CLIENT_KEY = os.path.join(TESTS_ROOT, 'client_certs', 'client.key')
|
||||
CLIENT_PEM = os.path.join(TESTS_ROOT, 'client_certs', 'client.pem')
|
||||
|
||||
# FIXME:
|
||||
# We test against a local httpbin instance which uses a self-signed cert.
|
||||
# Requests without --verify=<CA_BUNDLE> will fail with a verification error.
|
||||
# See: https://github.com/kevin1024/pytest-httpbin#https-support
|
||||
CA_BUNDLE = pytest_httpbin.certs.where()
|
||||
|
||||
|
||||
class TestClientSSLCertHandling(object):
|
||||
@pytest.mark.parametrize('ssl_version', SSL_VERSION_ARG_MAPPING.keys())
|
||||
def test_ssl_version(httpbin_secure, ssl_version):
|
||||
try:
|
||||
r = http(
|
||||
'--ssl', ssl_version,
|
||||
httpbin_secure + '/get'
|
||||
)
|
||||
assert HTTP_OK in r
|
||||
except SSLError as e:
|
||||
if ssl_version == 'ssl3':
|
||||
# pytest-httpbin doesn't support ssl3
|
||||
assert 'SSLV3_ALERT_HANDSHAKE_FAILURE' in str(e)
|
||||
else:
|
||||
raise
|
||||
|
||||
|
||||
class TestClientCert:
|
||||
|
||||
def test_cert_and_key(self, httpbin_secure):
|
||||
r = http(httpbin_secure + '/get',
|
||||
'--cert', CLIENT_CERT,
|
||||
'--cert-key', CLIENT_KEY)
|
||||
assert HTTP_OK in r
|
||||
|
||||
def test_cert_pem(self, httpbin_secure):
|
||||
r = http(httpbin_secure + '/get',
|
||||
'--cert', CLIENT_PEM)
|
||||
assert HTTP_OK in r
|
||||
|
||||
def test_cert_file_not_found(self, httpbin_secure):
|
||||
r = http(httpbin_secure + '/get',
|
||||
'--verify', CA_BUNDLE,
|
||||
'--cert', '/__not_found__',
|
||||
error_exit_ok=True)
|
||||
assert r.exit_status == ExitStatus.ERROR
|
||||
@ -31,45 +59,31 @@ class TestClientSSLCertHandling(object):
|
||||
def test_cert_file_invalid(self, httpbin_secure):
|
||||
with pytest.raises(SSLError):
|
||||
http(httpbin_secure + '/get',
|
||||
'--verify', CA_BUNDLE,
|
||||
'--cert', __file__)
|
||||
|
||||
def test_cert_ok_but_missing_key(self, httpbin_secure):
|
||||
with pytest.raises(SSLError):
|
||||
http(httpbin_secure + '/get',
|
||||
'--verify', CA_BUNDLE,
|
||||
'--cert', CLIENT_CERT)
|
||||
|
||||
def test_cert_and_key(self, httpbin_secure):
|
||||
r = http(httpbin_secure + '/get',
|
||||
'--verify', CA_BUNDLE,
|
||||
'--cert', CLIENT_CERT,
|
||||
'--cert-key', CLIENT_KEY)
|
||||
assert HTTP_OK in r
|
||||
|
||||
def test_cert_pem(self, httpbin_secure):
|
||||
r = http(httpbin_secure + '/get',
|
||||
'--verify', CA_BUNDLE,
|
||||
'--cert', CLIENT_PEM)
|
||||
assert HTTP_OK in r
|
||||
|
||||
|
||||
class TestServerSSLCertHandling(object):
|
||||
|
||||
def test_self_signed_server_cert_by_default_raises_ssl_error(
|
||||
self, httpbin_secure):
|
||||
with pytest.raises(SSLError):
|
||||
http(httpbin_secure.url + '/get')
|
||||
class TestServerCert:
|
||||
|
||||
def test_verify_no_OK(self, httpbin_secure):
|
||||
r = http(httpbin_secure.url + '/get', '--verify=no')
|
||||
assert HTTP_OK in r
|
||||
|
||||
def test_verify_custom_ca_bundle_path(
|
||||
self, httpbin_secure):
|
||||
r = http(httpbin_secure.url + '/get', '--verify', CA_BUNDLE)
|
||||
self, httpbin_secure_untrusted):
|
||||
r = http(httpbin_secure_untrusted + '/get', '--verify', CA_BUNDLE)
|
||||
assert HTTP_OK in r
|
||||
|
||||
def test_self_signed_server_cert_by_default_raises_ssl_error(
|
||||
self,
|
||||
httpbin_secure_untrusted):
|
||||
with pytest.raises(SSLError):
|
||||
http(httpbin_secure_untrusted.url + '/get')
|
||||
|
||||
def test_verify_custom_ca_bundle_invalid_path(self, httpbin_secure):
|
||||
with pytest.raises(SSLError):
|
||||
http(httpbin_secure.url + '/get', '--verify', '/__not_found__')
|
||||
|
@ -6,12 +6,12 @@ from utils import http, TestEnvironment
|
||||
from fixtures import BIN_FILE_CONTENT, BIN_FILE_PATH
|
||||
|
||||
|
||||
class TestStream:
|
||||
# GET because httpbin 500s with binary POST body.
|
||||
|
||||
|
||||
@pytest.mark.skipif(is_windows,
|
||||
reason='Pretty redirect not supported under Windows')
|
||||
def test_pretty_redirected_stream(self, httpbin):
|
||||
def test_pretty_redirected_stream(httpbin):
|
||||
"""Test that --stream works with prettified redirected output."""
|
||||
with open(BIN_FILE_PATH, 'rb') as f:
|
||||
env = TestEnvironment(colors=256, stdin=f,
|
||||
@ -21,7 +21,8 @@ class TestStream:
|
||||
httpbin.url + '/get', env=env)
|
||||
assert BINARY_SUPPRESSED_NOTICE.decode() in r
|
||||
|
||||
def test_encoded_stream(self, httpbin):
|
||||
|
||||
def test_encoded_stream(httpbin):
|
||||
"""Test that --stream works with non-prettified
|
||||
redirected terminal output."""
|
||||
with open(BIN_FILE_PATH, 'rb') as f:
|
||||
@ -30,7 +31,8 @@ class TestStream:
|
||||
httpbin.url + '/get', env=env)
|
||||
assert BINARY_SUPPRESSED_NOTICE.decode() in r
|
||||
|
||||
def test_redirected_stream(self, httpbin):
|
||||
|
||||
def test_redirected_stream(httpbin):
|
||||
"""Test that --stream works with non-prettified
|
||||
redirected terminal output."""
|
||||
with open(BIN_FILE_PATH, 'rb') as f:
|
||||
|
@ -7,64 +7,72 @@ from utils import http, HTTP_OK
|
||||
from fixtures import UNICODE
|
||||
|
||||
|
||||
class TestUnicode:
|
||||
|
||||
def test_unicode_headers(self, httpbin):
|
||||
def test_unicode_headers(httpbin):
|
||||
# httpbin doesn't interpret utf8 headers
|
||||
r = http(httpbin.url + '/headers', u'Test:%s' % UNICODE)
|
||||
assert HTTP_OK in r
|
||||
|
||||
def test_unicode_headers_verbose(self, httpbin):
|
||||
|
||||
def test_unicode_headers_verbose(httpbin):
|
||||
# httpbin doesn't interpret utf8 headers
|
||||
r = http('--verbose', httpbin.url + '/headers', u'Test:%s' % UNICODE)
|
||||
assert HTTP_OK in r
|
||||
assert UNICODE in r
|
||||
|
||||
def test_unicode_form_item(self, httpbin):
|
||||
|
||||
def test_unicode_form_item(httpbin):
|
||||
r = http('--form', 'POST', httpbin.url + '/post', u'test=%s' % UNICODE)
|
||||
assert HTTP_OK in r
|
||||
assert r.json['form'] == {'test': UNICODE}
|
||||
|
||||
def test_unicode_form_item_verbose(self, httpbin):
|
||||
|
||||
def test_unicode_form_item_verbose(httpbin):
|
||||
r = http('--verbose', '--form',
|
||||
'POST', httpbin.url + '/post', u'test=%s' % UNICODE)
|
||||
assert HTTP_OK in r
|
||||
assert UNICODE in r
|
||||
|
||||
def test_unicode_json_item(self, httpbin):
|
||||
|
||||
def test_unicode_json_item(httpbin):
|
||||
r = http('--json', 'POST', httpbin.url + '/post', u'test=%s' % UNICODE)
|
||||
assert HTTP_OK in r
|
||||
assert r.json['json'] == {'test': UNICODE}
|
||||
|
||||
def test_unicode_json_item_verbose(self, httpbin):
|
||||
|
||||
def test_unicode_json_item_verbose(httpbin):
|
||||
r = http('--verbose', '--json',
|
||||
'POST', httpbin.url + '/post', u'test=%s' % UNICODE)
|
||||
assert HTTP_OK in r
|
||||
assert UNICODE in r
|
||||
|
||||
def test_unicode_raw_json_item(self, httpbin):
|
||||
|
||||
def test_unicode_raw_json_item(httpbin):
|
||||
r = http('--json', 'POST', httpbin.url + '/post',
|
||||
u'test:={ "%s" : [ "%s" ] }' % (UNICODE, UNICODE))
|
||||
assert HTTP_OK in r
|
||||
assert r.json['json'] == {'test': {UNICODE: [UNICODE]}}
|
||||
|
||||
def test_unicode_raw_json_item_verbose(self, httpbin):
|
||||
|
||||
def test_unicode_raw_json_item_verbose(httpbin):
|
||||
r = http('--json', 'POST', httpbin.url + '/post',
|
||||
u'test:={ "%s" : [ "%s" ] }' % (UNICODE, UNICODE))
|
||||
assert HTTP_OK in r
|
||||
assert r.json['json'] == {'test': {UNICODE: [UNICODE]}}
|
||||
|
||||
def test_unicode_url_query_arg_item(self, httpbin):
|
||||
|
||||
def test_unicode_url_query_arg_item(httpbin):
|
||||
r = http(httpbin.url + '/get', u'test==%s' % UNICODE)
|
||||
assert HTTP_OK in r
|
||||
assert r.json['args'] == {'test': UNICODE}, r
|
||||
|
||||
def test_unicode_url_query_arg_item_verbose(self, httpbin):
|
||||
|
||||
def test_unicode_url_query_arg_item_verbose(httpbin):
|
||||
r = http('--verbose', httpbin.url + '/get', u'test==%s' % UNICODE)
|
||||
assert HTTP_OK in r
|
||||
assert UNICODE in r
|
||||
|
||||
def test_unicode_url(self, httpbin):
|
||||
|
||||
def test_unicode_url(httpbin):
|
||||
r = http(httpbin.url + u'/get?test=' + UNICODE)
|
||||
assert HTTP_OK in r
|
||||
assert r.json['args'] == {'test': UNICODE}
|
||||
@ -73,13 +81,15 @@ class TestUnicode:
|
||||
# r = http(httpbin.url + '--verbose', u'/get?test=' + UNICODE)
|
||||
# assert HTTP_OK in r
|
||||
|
||||
def test_unicode_basic_auth(self, httpbin):
|
||||
|
||||
def test_unicode_basic_auth(httpbin):
|
||||
# it doesn't really authenticate us because httpbin
|
||||
# doesn't interpret the utf8-encoded auth
|
||||
http('--verbose', '--auth', u'test:%s' % UNICODE,
|
||||
httpbin.url + u'/basic-auth/test/' + UNICODE)
|
||||
|
||||
def test_unicode_digest_auth(self, httpbin):
|
||||
|
||||
def test_unicode_digest_auth(httpbin):
|
||||
# it doesn't really authenticate us because httpbin
|
||||
# doesn't interpret the utf8-encoded auth
|
||||
http('--auth-type=digest',
|
||||
|
@ -23,6 +23,7 @@ class TestMultipartFormDataFileUpload:
|
||||
' filename="%s"' % os.path.basename(FILE_PATH) in r
|
||||
assert FILE_CONTENT in r
|
||||
assert '"foo": "bar"' in r
|
||||
assert 'Content-Type: text/plain' in r
|
||||
|
||||
def test_upload_multiple_fields_with_the_same_name(self, httpbin):
|
||||
r = http('--form', '--verbose', 'POST', httpbin.url + '/post',
|
||||
@ -34,6 +35,7 @@ class TestMultipartFormDataFileUpload:
|
||||
# Should be 4, but is 3 because httpbin
|
||||
# doesn't seem to support filed field lists
|
||||
assert r.count(FILE_CONTENT) in [3, 4]
|
||||
assert r.count('Content-Type: text/plain') == 2
|
||||
|
||||
|
||||
class TestRequestBodyFromFilePath:
|
||||
|
@ -22,7 +22,9 @@ class TestFakeWindows:
|
||||
def test_output_file_pretty_not_allowed_on_windows(self, httpbin):
|
||||
env = TestEnvironment(is_windows=True)
|
||||
output_file = os.path.join(
|
||||
tempfile.gettempdir(), '__httpie_test_output__')
|
||||
tempfile.gettempdir(),
|
||||
self.test_output_file_pretty_not_allowed_on_windows.__name__
|
||||
)
|
||||
r = http('--output', output_file,
|
||||
'--pretty=all', 'GET', httpbin.url + '/get',
|
||||
env=env, error_exit_ok=True)
|
||||
|
285
tests/utils.py
285
tests/utils.py
@ -1,23 +1,18 @@
|
||||
# coding=utf-8
|
||||
"""Utilities used by HTTPie tests.
|
||||
|
||||
"""
|
||||
"""Utilities for HTTPie test suite."""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import json
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
import httpie
|
||||
from httpie import ExitStatus, EXIT_STATUS_LABELS
|
||||
from httpie.context import Environment
|
||||
from httpie.core import main
|
||||
from httpie.compat import bytes, str
|
||||
|
||||
|
||||
TESTS_ROOT = os.path.abspath(os.path.dirname(__file__))
|
||||
|
||||
|
||||
CRLF = '\r\n'
|
||||
COLOR = '\x1b['
|
||||
HTTP_OK = '200 OK'
|
||||
@ -28,14 +23,9 @@ HTTP_OK_COLOR = (
|
||||
)
|
||||
|
||||
|
||||
def no_content_type(headers):
|
||||
return (
|
||||
'Content-Type' not in headers
|
||||
# We need to do also this because of this issue:
|
||||
# <https://github.com/kevin1024/pytest-httpbin/issues/5>
|
||||
# TODO: remove this function once the issue is if fixed
|
||||
or headers['Content-Type'] == 'text/plain'
|
||||
)
|
||||
def mk_config_dir():
|
||||
dirname = tempfile.mkdtemp(prefix='httpie_config_')
|
||||
return dirname
|
||||
|
||||
|
||||
def add_auth(url, auth):
|
||||
@ -44,136 +34,44 @@ def add_auth(url, auth):
|
||||
|
||||
|
||||
class TestEnvironment(Environment):
|
||||
"""
|
||||
Environment subclass with reasonable defaults suitable for testing.
|
||||
|
||||
"""
|
||||
"""Environment subclass with reasonable defaults for testing."""
|
||||
colors = 0
|
||||
stdin_isatty = True,
|
||||
stdout_isatty = True
|
||||
is_windows = False
|
||||
|
||||
_shutil = shutil # needed by __del__ (would get gc'd)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
|
||||
if 'stdout' not in kwargs:
|
||||
kwargs['stdout'] = tempfile.TemporaryFile('w+b')
|
||||
|
||||
kwargs['stdout'] = tempfile.TemporaryFile(
|
||||
mode='w+b',
|
||||
prefix='httpie_stdout'
|
||||
)
|
||||
if 'stderr' not in kwargs:
|
||||
kwargs['stderr'] = tempfile.TemporaryFile('w+t')
|
||||
|
||||
self.delete_config_dir = False
|
||||
if 'config_dir' not in kwargs:
|
||||
kwargs['config_dir'] = mk_config_dir()
|
||||
self.delete_config_dir = True
|
||||
|
||||
kwargs['stderr'] = tempfile.TemporaryFile(
|
||||
mode='w+t',
|
||||
prefix='httpie_stderr'
|
||||
)
|
||||
super(TestEnvironment, self).__init__(**kwargs)
|
||||
self._delete_config_dir = False
|
||||
|
||||
@property
|
||||
def config(self):
|
||||
if not self.config_dir.startswith(tempfile.gettempdir()):
|
||||
self.config_dir = mk_config_dir()
|
||||
self._delete_config_dir = True
|
||||
return super(TestEnvironment, self).config
|
||||
|
||||
def cleanup(self):
|
||||
if self._delete_config_dir:
|
||||
assert self.config_dir.startswith(tempfile.gettempdir())
|
||||
from shutil import rmtree
|
||||
rmtree(self.config_dir)
|
||||
|
||||
def __del__(self):
|
||||
if self.delete_config_dir:
|
||||
self._shutil.rmtree(self.config_dir)
|
||||
|
||||
|
||||
def http(*args, **kwargs):
|
||||
"""
|
||||
Run HTTPie and capture stderr/out and exit status.
|
||||
|
||||
Invoke `httpie.core.main()` with `args` and `kwargs`,
|
||||
and return a `CLIResponse` subclass instance.
|
||||
|
||||
The return value is either a `StrCLIResponse`, or `BytesCLIResponse`
|
||||
if unable to decode the output.
|
||||
|
||||
The response has the following attributes:
|
||||
|
||||
`stdout` is represented by the instance itself (print r)
|
||||
`stderr`: text written to stderr
|
||||
`exit_status`: the exit status
|
||||
`json`: decoded JSON (if possible) or `None`
|
||||
|
||||
Exceptions are propagated.
|
||||
|
||||
If you pass ``error_exit_ok=True``, then error exit statuses
|
||||
won't result into an exception.
|
||||
|
||||
Example:
|
||||
|
||||
$ http --auth=user:password GET httpbin.org/basic-auth/user/password
|
||||
|
||||
>>> r = http('-a', 'user:pw', 'httpbin.org/basic-auth/user/pw')
|
||||
>>> type(r) == StrCLIResponse
|
||||
True
|
||||
>>> r.exit_status
|
||||
0
|
||||
>>> r.stderr
|
||||
''
|
||||
>>> 'HTTP/1.1 200 OK' in r
|
||||
True
|
||||
>>> r.json == {'authenticated': True, 'user': 'user'}
|
||||
True
|
||||
|
||||
|
||||
"""
|
||||
error_exit_ok = kwargs.pop('error_exit_ok', False)
|
||||
env = kwargs.get('env')
|
||||
if not env:
|
||||
env = kwargs['env'] = TestEnvironment()
|
||||
|
||||
stdout = env.stdout
|
||||
stderr = env.stderr
|
||||
|
||||
args = list(args)
|
||||
if '--debug' not in args and '--traceback' not in args:
|
||||
args = ['--traceback'] + args
|
||||
|
||||
def dump_stderr():
|
||||
stderr.seek(0)
|
||||
sys.stderr.write(stderr.read())
|
||||
|
||||
try:
|
||||
try:
|
||||
exit_status = main(args=args, **kwargs)
|
||||
if '--download' in args:
|
||||
# Let the progress reporter thread finish.
|
||||
time.sleep(.5)
|
||||
except SystemExit:
|
||||
if error_exit_ok:
|
||||
exit_status = httpie.ExitStatus.ERROR
|
||||
else:
|
||||
dump_stderr()
|
||||
raise
|
||||
self.cleanup()
|
||||
except Exception:
|
||||
stderr.seek(0)
|
||||
sys.stderr.write(stderr.read())
|
||||
raise
|
||||
else:
|
||||
if exit_status != httpie.ExitStatus.OK and not error_exit_ok:
|
||||
dump_stderr()
|
||||
raise Exception('Unexpected exit status: %s', exit_status)
|
||||
|
||||
stdout.seek(0)
|
||||
stderr.seek(0)
|
||||
output = stdout.read()
|
||||
try:
|
||||
output = output.decode('utf8')
|
||||
except UnicodeDecodeError:
|
||||
# noinspection PyArgumentList
|
||||
r = BytesCLIResponse(output)
|
||||
else:
|
||||
# noinspection PyArgumentList
|
||||
r = StrCLIResponse(output)
|
||||
r.stderr = stderr.read()
|
||||
r.exit_status = exit_status
|
||||
|
||||
if r.exit_status != httpie.ExitStatus.OK:
|
||||
sys.stderr.write(r.stderr)
|
||||
|
||||
return r
|
||||
|
||||
finally:
|
||||
stdout.close()
|
||||
stderr.close()
|
||||
pass
|
||||
|
||||
|
||||
class BaseCLIResponse(object):
|
||||
@ -221,8 +119,8 @@ class StrCLIResponse(str, BaseCLIResponse):
|
||||
elif self.strip().startswith('{'):
|
||||
# Looks like JSON body.
|
||||
self._json = json.loads(self)
|
||||
elif (self.count('Content-Type:') == 1
|
||||
and 'application/json' in self):
|
||||
elif (self.count('Content-Type:') == 1 and
|
||||
'application/json' in self):
|
||||
# Looks like a whole JSON HTTP message,
|
||||
# try to extract its body.
|
||||
try:
|
||||
@ -237,5 +135,120 @@ class StrCLIResponse(str, BaseCLIResponse):
|
||||
return self._json
|
||||
|
||||
|
||||
def mk_config_dir():
|
||||
return tempfile.mkdtemp(prefix='httpie_test_config_dir_')
|
||||
class ExitStatusError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def http(*args, **kwargs):
|
||||
# noinspection PyUnresolvedReferences
|
||||
"""
|
||||
Run HTTPie and capture stderr/out and exit status.
|
||||
|
||||
Invoke `httpie.core.main()` with `args` and `kwargs`,
|
||||
and return a `CLIResponse` subclass instance.
|
||||
|
||||
The return value is either a `StrCLIResponse`, or `BytesCLIResponse`
|
||||
if unable to decode the output.
|
||||
|
||||
The response has the following attributes:
|
||||
|
||||
`stdout` is represented by the instance itself (print r)
|
||||
`stderr`: text written to stderr
|
||||
`exit_status`: the exit status
|
||||
`json`: decoded JSON (if possible) or `None`
|
||||
|
||||
Exceptions are propagated.
|
||||
|
||||
If you pass ``error_exit_ok=True``, then error exit statuses
|
||||
won't result into an exception.
|
||||
|
||||
Example:
|
||||
|
||||
$ http --auth=user:password GET httpbin.org/basic-auth/user/password
|
||||
|
||||
>>> httpbin = getfixture('httpbin')
|
||||
>>> r = http('-a', 'user:pw', httpbin.url + '/basic-auth/user/pw')
|
||||
>>> type(r) == StrCLIResponse
|
||||
True
|
||||
>>> r.exit_status
|
||||
0
|
||||
>>> r.stderr
|
||||
''
|
||||
>>> 'HTTP/1.1 200 OK' in r
|
||||
True
|
||||
>>> r.json == {'authenticated': True, 'user': 'user'}
|
||||
True
|
||||
|
||||
"""
|
||||
error_exit_ok = kwargs.pop('error_exit_ok', False)
|
||||
env = kwargs.get('env')
|
||||
if not env:
|
||||
env = kwargs['env'] = TestEnvironment()
|
||||
|
||||
stdout = env.stdout
|
||||
stderr = env.stderr
|
||||
|
||||
args = list(args)
|
||||
args_with_config_defaults = args + env.config.default_options
|
||||
add_to_args = []
|
||||
if '--debug' not in args_with_config_defaults:
|
||||
if '--traceback' not in args_with_config_defaults:
|
||||
add_to_args.append('--traceback')
|
||||
if not any('--timeout' in arg for arg in args_with_config_defaults):
|
||||
add_to_args.append('--timeout=3')
|
||||
args = add_to_args + args
|
||||
|
||||
def dump_stderr():
|
||||
stderr.seek(0)
|
||||
sys.stderr.write(stderr.read())
|
||||
|
||||
try:
|
||||
try:
|
||||
exit_status = main(args=args, **kwargs)
|
||||
if '--download' in args:
|
||||
# Let the progress reporter thread finish.
|
||||
time.sleep(.5)
|
||||
except SystemExit:
|
||||
if error_exit_ok:
|
||||
exit_status = ExitStatus.ERROR
|
||||
else:
|
||||
dump_stderr()
|
||||
raise
|
||||
except Exception:
|
||||
stderr.seek(0)
|
||||
sys.stderr.write(stderr.read())
|
||||
raise
|
||||
else:
|
||||
if not error_exit_ok and exit_status != ExitStatus.OK:
|
||||
dump_stderr()
|
||||
raise ExitStatusError(
|
||||
'httpie.core.main() unexpectedly returned'
|
||||
' a non-zero exit status: {0} ({1})'.format(
|
||||
exit_status,
|
||||
EXIT_STATUS_LABELS[exit_status]
|
||||
)
|
||||
)
|
||||
|
||||
stdout.seek(0)
|
||||
stderr.seek(0)
|
||||
output = stdout.read()
|
||||
try:
|
||||
output = output.decode('utf8')
|
||||
except UnicodeDecodeError:
|
||||
# noinspection PyArgumentList
|
||||
r = BytesCLIResponse(output)
|
||||
else:
|
||||
# noinspection PyArgumentList
|
||||
r = StrCLIResponse(output)
|
||||
r.stderr = stderr.read()
|
||||
r.exit_status = exit_status
|
||||
|
||||
if r.exit_status != ExitStatus.OK:
|
||||
sys.stderr.write(r.stderr)
|
||||
|
||||
return r
|
||||
|
||||
finally:
|
||||
stdout.close()
|
||||
stderr.close()
|
||||
env.cleanup()
|
||||
|
16
tox.ini
16
tox.ini
@ -1,18 +1,22 @@
|
||||
# Tox (http://tox.testrun.org/) is a tool for running tests
|
||||
# in multiple virtualenvs.
|
||||
# Run:
|
||||
# $ pip install -r requirements-dev.txt
|
||||
# $ tox
|
||||
# in multiple virtualenvs. See ./CONTRIBUTING.rst
|
||||
|
||||
|
||||
[tox]
|
||||
envlist = py26, py27, py34, pypy
|
||||
envlist = py26, py27, py35, pypy
|
||||
|
||||
|
||||
[testenv]
|
||||
deps =
|
||||
mock
|
||||
pytest
|
||||
pytest-httpbin>=0.0.6
|
||||
|
||||
|
||||
commands =
|
||||
py.test --verbose --doctest-modules --basetemp={envtmpdir} {posargs:./tests ./httpie}
|
||||
# NOTE: the order of the directories in posargs seems to matter.
|
||||
# When changed, then many ImportMismatchError exceptions occurrs.
|
||||
py.test \
|
||||
--verbose \
|
||||
--doctest-modules \
|
||||
{posargs:./httpie ./tests}
|
||||
|
Reference in New Issue
Block a user