diff --git a/hyper/cli.py b/hyper/cli.py index 1d5384cd..c373cc57 100644 --- a/hyper/cli.py +++ b/hyper/cli.py @@ -28,8 +28,10 @@ SEP_HEADERS = ':' SEP_QUERY = '==' SEP_DATA = '=' +SEP_JSON = '@=' SEP_GROUP_ITEMS = [ + SEP_JSON, SEP_HEADERS, SEP_QUERY, SEP_DATA, @@ -93,9 +95,13 @@ def make_positional_argument(parser): search==hyper - '=' Data fields to be serialized into a JSON object: + '=' String data fields to be serialized into a JSON object: name=Hyper language=Python description='CLI HTTP client' + + '@=' JSON data fields + + name@='{"name": "John", "surname": "Doe"}' list@='[1, 2, 3]' """)) @@ -167,7 +173,13 @@ def set_url_info(args): def set_request_data(args): body, headers, params = {}, {}, {} for i in args.items: - if i.sep == SEP_HEADERS: + if i.sep == SEP_JSON: + try: + value = json.loads(i.value) + body[i.key] = value + except ValueError: + log.warning('Unable to decode JSON, ignoring it (%s)', i.value) + elif i.sep == SEP_HEADERS: if i.key: headers[i.key] = i.value else: diff --git a/test/test_cli.py b/test/test_cli.py index d545c6d3..0d42b10f 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -111,6 +111,8 @@ def test_cli_with_system_exit(argv): {'method': 'GET', 'url.path': '/?param=test'}), (['POST', 'example.com', 'data=test'], {'method': 'POST', 'body': '{"data": "test"}'}), + (['POST', 'example.com', 'data@={"json":[1,2,3]}'], + {'method': 'POST', 'body': '{"data": {"json": [1, 2, 3]}}'}), (['GET', 'example.com', ':authority:example.org'], {'method': 'GET', 'headers': { ':authority': 'example.org'}}), @@ -118,14 +120,18 @@ def test_cli_with_system_exit(argv): {'method': 'GET', 'headers': { ':authority': 'example.org', 'x-test': 'header'}}), + (['POST', 'example.com', 'data@={"invalidjson":1,2,3}'], + {'body': None}), ], ids=[ 'specified "--debug" option', 'specify host with lower get method', 'specified host and additional header', 'specified host and get parameter', 'specified host and post data', + 'specified host and post JSON data', 'specified host and override default header', 'specified host and override default header and additional header', + 'specified host and post invalid JSON data', ]) def test_parse_argument(argv, expected): args = parse_argument(argv)