From d0f5f1547cedd3d6d9a1147d764ebf8385d1d47e Mon Sep 17 00:00:00 2001 From: Brett Smith Date: Thu, 29 Jun 2017 17:16:45 -0400 Subject: [PATCH] config: Error out when historical arguments are ambiguous. --- oxrlib/config.py | 16 +++++++++++++++- setup.py | 2 +- tests/test_Configuration.py | 9 +++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/oxrlib/config.py b/oxrlib/config.py index 93eac18..00f6eb3 100644 --- a/oxrlib/config.py +++ b/oxrlib/config.py @@ -6,6 +6,7 @@ import os.path import pathlib import babel +import babel.dates import babel.numbers from . import cache, loaders @@ -74,7 +75,7 @@ class Configuration: else: retval -= datetime.timedelta(days=replacements['day']) retval = retval.replace(**replacements) - return retval + return retval, replacements def _build_argparser(self): prog_parser = argparse.ArgumentParser() @@ -191,6 +192,7 @@ class Configuration: return default def _post_hook_historical(self): + self.args.date, date_spec = self.args.date year = self.args.date.year if year < 100: # Don't let the user specify ambiguous dates. @@ -223,6 +225,18 @@ class Configuration: self.args.to_currency = self._convert_or_error(currency_code, next_word) except StopIteration: self.args.to_currency = pref_currency + if ((len(date_spec) == 1) + and self.args.from_currency + and (self.args.amount is None)): + self.error(("ambiguous input: " + "Did you want rates for {args.from_currency} on {date}, " + "or to convert {amt} {args.from_currency} to {args.to_currency}?\n" + "Specify more of the date to disambiguate." + ).format( + args=self.args, + date=babel.dates.format_date(self.args.date), + amt=date_spec['day'], + )) def _build_cache_loader(self): kwargs = dict(self.conffile.items('Cache')) diff --git a/setup.py b/setup.py index c287242..5375d83 100755 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ from setuptools import setup setup( name='oxrlib', description="Library to query the Open Exchange Rates (OXR) API", - version='1.6', + version='1.7', author='Brett Smith', author_email='brettcsmith@brettcsmith.org', license='GNU AGPLv3+', diff --git a/tests/test_Configuration.py b/tests/test_Configuration.py index 4c85edb..7529a9f 100644 --- a/tests/test_Configuration.py +++ b/tests/test_Configuration.py @@ -128,3 +128,12 @@ def test_bad_date_parsing(date_s): pass else: assert not config.args.date, "date parsed from {!r}".format(date_s) + +def test_ambiguous_arglist_failure(): + try: + # It's ambiguous if "2" is "the 2nd" or "2 EUR". + config = config_from(os.devnull, ['historical', '2', 'eur']) + except SystemExit: + pass + else: + assert not config.args, "ambiguous args parsed"