Skip to content

Commit

Permalink
fix(reduce): fail if empty, if one return the element
Browse files Browse the repository at this point in the history
  • Loading branch information
NefixEstrada committed Aug 8, 2023
1 parent 2c73062 commit 43e5ac1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
7 changes: 7 additions & 0 deletions rethinkdb_mock/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from future.utils import iteritems
from future.utils import text_type
from past.utils import old_div
from rethinkdb.errors import ReqlNonExistenceError

from rethinkdb_mock import ast_base
from rethinkdb_mock import joins
Expand Down Expand Up @@ -256,6 +257,12 @@ class Or(BinOp):

class Reduce(ByFuncBase):
def do_run(self, sequence, reduce_fn, arg, scope):
if len(sequence) == 0:
raise ReqlNonExistenceError("Cannot reduce over an empty stream")

if len(sequence) == 1:
return sequence[0]

first, second = sequence[0:2]
result = reduce_fn([first, second])
for elem in sequence[2:]:
Expand Down
27 changes: 27 additions & 0 deletions tests/functional/test_misc.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from rethinkdb import r
from rethinkdb.errors import ReqlNonExistenceError
from rethinkdb.errors import RqlRuntimeError
from tests.common import as_db_and_table
from tests.common import assertEqual
Expand Down Expand Up @@ -399,6 +400,32 @@ def test_reduce_1(self, conn):
)
assertEqual(expected, result)

def test_reduce_one(self, conn):
expected = {"count": 1}
result = (
r.expr([{"count": 1}])
.reduce(
lambda left, right: {
"count": left["count"] + right["count"],
}
)
.run(conn)
)
assertEqual(expected, result)

def test_reduce_errors(self, conn):
err = None
try:
r.expr([]).reduce(
lambda left, right: {
"count": left["count"] + right["count"],
}
).run(conn)
except ReqlNonExistenceError as e:
err = e

assert isinstance(err, ReqlNonExistenceError)


class TestBranch(MockTest):
@staticmethod
Expand Down

0 comments on commit 43e5ac1

Please sign in to comment.