Skip to content

Commit

Permalink
add support for argparse's dest
Browse files Browse the repository at this point in the history
  • Loading branch information
ric-evans committed Oct 10, 2023
1 parent 2b59f35 commit ef54bda
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
7 changes: 4 additions & 3 deletions rest_tools/server/arghandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import sys
import time
import traceback
from typing import Any, List, TypeVar, Union
from typing import Any, List, TypeVar, Union, cast

import tornado.web
from tornado.escape import to_unicode
Expand Down Expand Up @@ -76,12 +76,13 @@ def retrieve_json_body_arg(parsed_val: Any) -> Any:
if parsed_val != USE_CACHED_VALUE_PLACEHOLDER:
return parsed_val # this must be the **default** value
# replace placeholder value with actual value
key = cast(str, name or kwargs.get("dest"))
try:
return self.rest_handler.json_body_arguments[name]
return self.rest_handler.json_body_arguments[key]
except KeyError as e:
# just in case, intercept so the user doesn't get a 400
raise RuntimeError(
f"key '{name}' should exist in json body arguments"
f"key '{key}' should exist in json body arguments"
) from e

# TYPE
Expand Down
41 changes: 41 additions & 0 deletions tests/unit_server/arghandler_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -388,3 +388,44 @@ def test_141__extra_argument_with_duplicates(argument_source: str) -> None:
with pytest.raises(tornado.web.HTTPError) as e:
arghand.parse_args()
assert str(e.value) == "HTTP 400: unrecognized arguments: xtra, another"


@pytest.mark.parametrize(
"argument_source",
[QUERY_ARGUMENTS, JSON_BODY_ARGUMENTS],
)
def test_200__argparse_dest(argument_source: str) -> None:
"""Test `argument_source` arguments using argparse's advanced options."""
args: Dict[str, Any] = {
"old_name": "-10",
"bar": "True",
}
if argument_source == JSON_BODY_ARGUMENTS:
args.update(
{
"dicto": {"abc": 123},
"listo": [1, 2, 3],
}
)

# set up ArgumentHandler
arghand = setup_argument_handler(argument_source, args)

for arg, _ in args.items():
print()
print(arg)
if arg == "old_name":
arghand.add_argument("new_name")
else:
arghand.add_argument(arg)
outargs = arghand.parse_args()

# grab each
for arg, val in args.items():
print()
print(arg)
print(val)
if arg == "old_name":
assert val == getattr(outargs, "new_name")
else:
assert val == getattr(outargs, arg.replace("-", "_"))

0 comments on commit ef54bda

Please sign in to comment.