Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removed unused handles in file-resource-leak #648

Merged
merged 1 commit into from
Jun 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading