Skip to content

Commit

Permalink
Merge pull request #51 from jakkdl/split_up_assert
Browse files Browse the repository at this point in the history
  • Loading branch information
Zac-HD authored Oct 27, 2022
2 parents e6fe66b + 8184383 commit 8ceee4b
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/shed/_codemods.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,3 +401,18 @@ def collapse_isinstance_checks(self, _, updated_node):
)
return updated_node.left.with_changes(args=[left_target, merged_type])
return updated_node

# helper function to handle recursive structures created by e.g. `assert a and b and c`
def _flatten_bool(self, expr):
if m.matches(expr, m.BooleanOperation(operator=m.And())):
return self._flatten_bool(expr.left) + self._flatten_bool(expr.right)
return [expr]

# split `assert a and b` into `assert a` and `assert b`
@m.leave(m.Assert(test=m.BooleanOperation(operator=m.And())))
def split_assert_and(self, _, updated_node):
flat_nodes = self._flatten_bool(updated_node.test)
nodes = [updated_node.with_changes(test=flat_nodes[0])]
for node in flat_nodes[1:]:
nodes.append(cst.Assert(node))
return cst.FlattenSentinel(nodes)
62 changes: 62 additions & 0 deletions tests/recorded/split_assert.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
assert a and b # one

assert a and b and c # two

assert (a and b) # three

assert a(1, 2) and b(3, 7) # four

def f():
assert a and b

assert (a and b) and (c and d)

assert a or b and c
assert a and b or c

assert a and (b or c)

assert (a or b) and c

assert a or b

assert a

================================================================================

assert a
assert b # one

assert a
assert b
assert c # two

assert a
assert b # three

assert a(1, 2)
assert b(3, 7) # four


def f():
assert a
assert b


assert a
assert b
assert c
assert d

assert a or b and c
assert a and b or c

assert a
assert b or c

assert a or b
assert c

assert a or b

assert a

0 comments on commit 8ceee4b

Please sign in to comment.