From aa88c156e668b509a23ee783d734811b298666d6 Mon Sep 17 00:00:00 2001 From: Alex Hall Date: Mon, 24 Oct 2022 21:12:27 +0200 Subject: [PATCH] (core) Don't swallow TypeErrors in functions like SUM Summary: Math functions like SUM which call `_chain` were catching `TypeError`s raised by the iterable arguments themselves, e.g. `SUM(r.A / r.B for r in $group)` where `r.A / r.B` raises a `TypeError` would silently return wrong results. This diff narrows the `try/catch` to only check whether the argument is iterable as intended, but not catch errors from the process of iterating. Test Plan: Added Python unit test. Reviewers: jarek Reviewed By: jarek Differential Revision: https://phab.getgrist.com/D3679 --- sandbox/grist/functions/math.py | 6 ++++-- sandbox/grist/test_functions.py | 6 ++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/sandbox/grist/functions/math.py b/sandbox/grist/functions/math.py index a475e1c2..a6c150b0 100644 --- a/sandbox/grist/functions/math.py +++ b/sandbox/grist/functions/math.py @@ -21,10 +21,12 @@ import roman def _chain(*values_or_iterables): for v in values_or_iterables: try: - for x in v: - yield x + v = iter(v) except TypeError: yield v + else: + for x in v: + yield x # Iterates through iterable or other arguments, skipping non-numeric ones. diff --git a/sandbox/grist/test_functions.py b/sandbox/grist/test_functions.py index 91d348c4..8498c684 100644 --- a/sandbox/grist/test_functions.py +++ b/sandbox/grist/test_functions.py @@ -80,3 +80,9 @@ class TestUuid(unittest.TestCase): self.check_uuids(1) # because of the `random.seed(0)` in `check_uuids()` finally: uuid.uuid4 = v4 + + +class TestChain(unittest.TestCase): + def test_chain_type_error(self): + with self.assertRaises(TypeError): + functions.SUM(x / "2" for x in [1, 2, 3])