Skip to content

Commit

Permalink
Removed unused handles in file-resource-leak (#648)
Browse files Browse the repository at this point in the history
  • Loading branch information
andrecsilva authored Jun 18, 2024
1 parent aebb18b commit 2882bfc
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 16 deletions.
14 changes: 9 additions & 5 deletions src/core_codemods/file_resource_leak.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,12 +229,16 @@ def _handle_block(
)

# grab the index of the last statement with reference to the resource
last_index = (
self._find_last_index_with_access(
named_targets, original_block, index
)
or index
last_index = self._find_last_index_with_access(
named_targets, original_block, index
)

# No accesses, remove the statement
if last_index is None:
new_stmts[index] = cst.Pass()
new_index_of_original_stmt[index] = -1
continue

# check if the statement in the last_index is now included in some earlier with statement
new_last_index = new_index_of_original_stmt[last_index]

Expand Down
31 changes: 20 additions & 11 deletions tests/codemods/test_file_resource_leak.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,26 @@ def test_simple(self, tmpdir):
"""
self.run_and_assert(tmpdir, input_code, expected)

def test_unused(self, tmpdir):
input_code = """
file = open('test.txt', 'r')
"""
expected = """
"""
self.run_and_assert(tmpdir, input_code, expected)

def test_unused_inside_block(self, tmpdir):
input_code = """
file = open('test.txt', 'r')
file2 = open('test2.txt','r')
file.read()
"""
expected = """
with open('test.txt', 'r') as file:
file.read()
"""
self.run_and_assert(tmpdir, input_code, expected, num_changes=2)

def test_simple_annotated(self, tmpdir):
input_code = """
file: int = open('test.txt', 'r')
Expand Down Expand Up @@ -59,17 +79,6 @@ def foo():
"""
self.run_and_assert(tmpdir, input_code, expected, num_changes=4)

def test_just_open(self, tmpdir):
# strange as this change may be, it still leaks if left untouched
input_code = """
file = open('test.txt', 'r')
"""
expected = """
with open('test.txt', 'r') as file:
pass
"""
self.run_and_assert(tmpdir, input_code, expected)

def test_multiple_assignments(self, tmpdir):
input_code = """
file = file2 = open('test.txt', 'r')
Expand Down

0 comments on commit 2882bfc

Please sign in to comment.