Skip to content
Closed
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
79 changes: 79 additions & 0 deletions codereview-test
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""
A simple calculator script with various errors for testing code review tools.
"""

import os
import sys
import json # unused import

def calculate_average(numbers):
# Missing input validation
total = 0
for num in numbers:
total += num
# Division by zero potential
return total / len(numbers)
Comment on lines +10 to +16

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness: The calculate_average function lacks input validation, which could lead to runtime errors if numbers is empty or contains non-numeric values.

📝 Committable Code Suggestion

‼️ Ensure you review the code suggestion before committing it to the branch. Make sure it replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
def calculate_average(numbers):
# Missing input validation
total = 0
for num in numbers:
total += num
# Division by zero potential
return total / len(numbers)
def calculate_average(numbers):
# Missing input validation
if not numbers:
return 0
total = 0
for num in numbers:
total += num
# Division by zero potential
return total / len(numbers)

Comment on lines +10 to +16
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add input validation to prevent division by zero.

The function will raise a ZeroDivisionError if an empty list is passed. Additionally, the function lacks type hints and validation for non-numeric values.

Apply this diff to fix the issues:

-def calculate_average(numbers):
-    # Missing input validation
-    total = 0
-    for num in numbers:
-        total += num
-    # Division by zero potential
-    return total / len(numbers)
+def calculate_average(numbers: list[float]) -> float:
+    """Calculate the average of a list of numbers.
+    
+    Args:
+        numbers: List of numeric values
+        
+    Returns:
+        The average of the numbers
+        
+    Raises:
+        ValueError: If the list is empty
+    """
+    if not numbers:
+        raise ValueError("Cannot calculate average of empty list")
+    return sum(numbers) / len(numbers)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def calculate_average(numbers):
# Missing input validation
total = 0
for num in numbers:
total += num
# Division by zero potential
return total / len(numbers)
def calculate_average(numbers: list[float]) -> float:
"""Calculate the average of a list of numbers.
Args:
numbers: List of numeric values
Returns:
The average of the numbers
Raises:
ValueError: If the list is empty
"""
if not numbers:
raise ValueError("Cannot calculate average of empty list")
return sum(numbers) / len(numbers)
🤖 Prompt for AI Agents
In codereview-test around lines 10 to 16, the calculate_average function lacks
input validation, which can cause a ZeroDivisionError if an empty list is
passed, and it does not check for non-numeric values or include type hints. Fix
this by adding a check to return 0 or raise a clear exception if the input list
is empty, validate that all elements are numeric before processing, and add
appropriate type hints to the function signature.


def process_data(data):
# Undefined variable error
result = []
for item in data:
if item > threshold: # threshold is not defined
result.append(item * 2)
return result
Comment on lines +18 to +24

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness: The process_data function uses an undefined variable threshold, which will cause a NameError at runtime.

📝 Committable Code Suggestion

‼️ Ensure you review the code suggestion before committing it to the branch. Make sure it replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
def process_data(data):
# Undefined variable error
result = []
for item in data:
if item > threshold: # threshold is not defined
result.append(item * 2)
return result
def process_data(data, threshold=0):
# Undefined variable error
result = []
for item in data:
if item > threshold: # threshold is not defined
result.append(item * 2)
return result

Comment on lines +18 to +24
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix undefined variable error.

The variable threshold is not defined, which will cause a NameError at runtime.

Apply this diff to fix the issue by adding threshold as a parameter:

-def process_data(data):
-    # Undefined variable error
-    result = []
-    for item in data:
-        if item > threshold:  # threshold is not defined
-            result.append(item * 2)
-    return result
+def process_data(data: list[float], threshold: float) -> list[float]:
+    """Process data by filtering and transforming values above threshold.
+    
+    Args:
+        data: List of numeric values
+        threshold: Minimum value to include
+        
+    Returns:
+        List of values above threshold, multiplied by 2
+    """
+    return [item * 2 for item in data if item > threshold]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def process_data(data):
# Undefined variable error
result = []
for item in data:
if item > threshold: # threshold is not defined
result.append(item * 2)
return result
def process_data(data: list[float], threshold: float) -> list[float]:
"""Process data by filtering and transforming values above threshold.
Args:
data: List of numeric values
threshold: Minimum value to include
Returns:
List of values above threshold, multiplied by 2
"""
return [item * 2 for item in data if item > threshold]
🤖 Prompt for AI Agents
In codereview-test around lines 18 to 24, the variable 'threshold' is used but
not defined, causing a NameError. Fix this by adding 'threshold' as a parameter
to the 'process_data' function definition and update all calls to this function
accordingly to pass the threshold value.


class Calculator:
def __init__(self):
self.history = []

def add(self, a, b):
# Missing type hints and validation
result = a + b
self.history.append(result)
return result
Comment on lines +30 to +34
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add type hints and validation to the add method.

The method lacks type hints which reduces code clarity and maintainability.

Apply this diff to improve the method:

-    def add(self, a, b):
-        # Missing type hints and validation
-        result = a + b
-        self.history.append(result)
-        return result
+    def add(self, a: float, b: float) -> float:
+        """Add two numbers and store result in history.
+        
+        Args:
+            a: First number
+            b: Second number
+            
+        Returns:
+            Sum of a and b
+        """
+        result = a + b
+        self.history.append(result)
+        return result
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def add(self, a, b):
# Missing type hints and validation
result = a + b
self.history.append(result)
return result
def add(self, a: float, b: float) -> float:
"""Add two numbers and store result in history.
Args:
a: First number
b: Second number
Returns:
Sum of a and b
"""
result = a + b
self.history.append(result)
return result
🤖 Prompt for AI Agents
In codereview-test around lines 30 to 34, the add method lacks type hints and
input validation. Add type hints specifying that both parameters a and b are
numbers (e.g., int or float) and the return type is also a number. Include
validation to check that a and b are of the expected numeric types before
performing the addition, raising a TypeError if not. This will improve code
clarity and robustness.


def divide(self, a, b):
# No zero division check
return a / b
Comment on lines +36 to +38

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness: The divide method doesn't check for division by zero, which will raise a ZeroDivisionError if b is zero.

📝 Committable Code Suggestion

‼️ Ensure you review the code suggestion before committing it to the branch. Make sure it replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
def divide(self, a, b):
# No zero division check
return a / b
def divide(self, a, b):
# No zero division check
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b

Comment on lines +36 to +38
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add zero division check.

The divide method will raise a ZeroDivisionError if b is zero.

Apply this diff to add proper error handling:

-    def divide(self, a, b):
-        # No zero division check
-        return a / b
+    def divide(self, a: float, b: float) -> float:
+        """Divide two numbers.
+        
+        Args:
+            a: Dividend
+            b: Divisor
+            
+        Returns:
+            Result of a divided by b
+            
+        Raises:
+            ValueError: If divisor is zero
+        """
+        if b == 0:
+            raise ValueError("Cannot divide by zero")
+        return a / b
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def divide(self, a, b):
# No zero division check
return a / b
def divide(self, a: float, b: float) -> float:
"""Divide two numbers.
Args:
a: Dividend
b: Divisor
Returns:
Result of a divided by b
Raises:
ValueError: If divisor is zero
"""
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
🤖 Prompt for AI Agents
In codereview-test around lines 36 to 38, the divide method lacks a check for
division by zero, which causes a ZeroDivisionError when b is zero. Add a
conditional check before the division to verify if b is zero, and handle this
case appropriately by raising a custom error or returning a specific value to
prevent the exception.


def get_history(self):
# Returning mutable reference
return self.history
Comment on lines +40 to +42

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness: The get_history method returns a direct reference to the internal history list, allowing external code to modify the internal state unexpectedly.

📝 Committable Code Suggestion

‼️ Ensure you review the code suggestion before committing it to the branch. Make sure it replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
def get_history(self):
# Returning mutable reference
return self.history
def get_history(self):
# Returning mutable reference
return self.history.copy()

Comment on lines +40 to +42
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Return a copy of history to prevent external modifications.

Returning the mutable list directly allows external code to modify the internal state of the Calculator.

Apply this diff to fix the encapsulation issue:

-    def get_history(self):
-        # Returning mutable reference
-        return self.history
+    def get_history(self) -> list[float]:
+        """Get a copy of the calculation history.
+        
+        Returns:
+            Copy of the history list
+        """
+        return self.history.copy()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def get_history(self):
# Returning mutable reference
return self.history
def get_history(self) -> list[float]:
"""Get a copy of the calculation history.
Returns:
Copy of the history list
"""
return self.history.copy()
🤖 Prompt for AI Agents
In codereview-test around lines 40 to 42, the get_history method returns the
internal mutable list directly, which allows external code to modify the
Calculator's internal state. To fix this, modify get_history to return a copy of
the history list instead of the original, preserving encapsulation and
preventing unintended external modifications.


def main():
# Syntax error - missing closing bracket
numbers = [1, 2, 3, 4, 5
Comment on lines +45 to +46
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix syntax error - missing closing bracket.

The list definition is missing a closing bracket, which will cause a SyntaxError.

Apply this diff:

-    # Syntax error - missing closing bracket
-    numbers = [1, 2, 3, 4, 5
+    numbers = [1, 2, 3, 4, 5]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Syntax error - missing closing bracket
numbers = [1, 2, 3, 4, 5
numbers = [1, 2, 3, 4, 5]
🤖 Prompt for AI Agents
In codereview-test around lines 45 to 46, the list assigned to the variable
'numbers' is missing a closing bracket, causing a syntax error. Add the missing
closing bracket ']' at the end of the list definition to fix the syntax error.

Comment on lines +45 to +46

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness: Syntax error in main() function - missing closing bracket for the numbers list, which will prevent the code from running.

📝 Committable Code Suggestion

‼️ Ensure you review the code suggestion before committing it to the branch. Make sure it replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
# Syntax error - missing closing bracket
numbers = [1, 2, 3, 4, 5
# Syntax error - missing closing bracket
numbers = [1, 2, 3, 4, 5]


# Logic error - wrong function name
avg = calculate_mean(numbers) # function is called calculate_average

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness: The function calculate_mean is called but doesn't exist - the actual function is named calculate_average, causing a NameError.

📝 Committable Code Suggestion

‼️ Ensure you review the code suggestion before committing it to the branch. Make sure it replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
avg = calculate_mean(numbers) # function is called calculate_average
avg = calculate_average(numbers) # function is called calculate_average

print(f"Average: {avg}")
Comment on lines +48 to +50
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix function name error.

The function calculate_mean does not exist. The correct function name is calculate_average.

Apply this diff:

-    # Logic error - wrong function name
-    avg = calculate_mean(numbers)  # function is called calculate_average
-    print(f"Average: {avg}")
+    avg = calculate_average(numbers)
+    print(f"Average: {avg}")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Logic error - wrong function name
avg = calculate_mean(numbers) # function is called calculate_average
print(f"Average: {avg}")
avg = calculate_average(numbers)
print(f"Average: {avg}")
🤖 Prompt for AI Agents
In codereview-test around lines 48 to 50, the function call uses the incorrect
name `calculate_mean`. Replace `calculate_mean` with the correct function name
`calculate_average` to fix the logic error and ensure the code calls the
existing function.


# Unused variable
unused_var = "this is never used"

# Inefficient loop
large_list = list(range(10000))
squared = []
for i in range(len(large_list)): # should use enumerate or direct iteration
squared.append(large_list[i] ** 2)

# String concatenation in loop (inefficient)
message = ""
for i in range(100):
message += f"Item {i} "

# Security issue - using eval
user_input = "2 + 2"
result = eval(user_input)
Comment on lines +66 to +68
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove eval() - serious security vulnerability.

Using eval() is a critical security risk as it can execute arbitrary code. Even with hardcoded input, this sets a dangerous precedent.

Apply this diff:

-    # Security issue - using eval
-    user_input = "2 + 2"
-    result = eval(user_input)
+    # Safe alternative to eval for simple arithmetic
+    result = 2 + 2

If you need to evaluate mathematical expressions from user input, consider using a safe expression parser library like ast.literal_eval() for literals only, or a dedicated math expression parser.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Security issue - using eval
user_input = "2 + 2"
result = eval(user_input)
# Safe alternative to eval for simple arithmetic
result = 2 + 2
🤖 Prompt for AI Agents
In codereview-test around lines 66 to 68, the use of eval() to evaluate user
input poses a serious security risk. Remove the eval() call entirely and replace
it with a safe alternative such as using ast.literal_eval() if only literals are
expected, or integrate a dedicated math expression parser library to safely
evaluate mathematical expressions without executing arbitrary code.

Comment on lines +66 to +68

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Security: Using eval() on user input is a serious security vulnerability that could allow arbitrary code execution. Even with hardcoded input, this pattern is dangerous.

📝 Committable Code Suggestion

‼️ Ensure you review the code suggestion before committing it to the branch. Make sure it replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
# Security issue - using eval
user_input = "2 + 2"
result = eval(user_input)
# Security issue - using eval
user_input = "2 + 2"
# Use a safer alternative like ast.literal_eval or a proper expression parser
import ast
try:
result = ast.literal_eval(user_input)
except:
# Handle expressions that aren't literals
result = None


# Missing exception handling
with open("nonexistent_file.txt", "r") as f:
content = f.read()
Comment on lines +70 to +72
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add exception handling for file operations.

File operations should always include proper exception handling to handle cases where the file doesn't exist or can't be read.

Apply this diff:

-    # Missing exception handling
-    with open("nonexistent_file.txt", "r") as f:
-        content = f.read()
+    try:
+        with open("nonexistent_file.txt", "r") as f:
+            content = f.read()
+    except FileNotFoundError:
+        print("Error: File 'nonexistent_file.txt' not found")
+        content = ""
+    except IOError as e:
+        print(f"Error reading file: {e}")
+        content = ""
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Missing exception handling
with open("nonexistent_file.txt", "r") as f:
content = f.read()
try:
with open("nonexistent_file.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("Error: File 'nonexistent_file.txt' not found")
content = ""
except IOError as e:
print(f"Error reading file: {e}")
content = ""
🤖 Prompt for AI Agents
In codereview-test around lines 70 to 72, the file open operation lacks
exception handling, which can cause the program to crash if the file does not
exist or cannot be read. Wrap the file open and read code in a try-except block
that catches exceptions like FileNotFoundError and IOError, and handle these
exceptions appropriately, such as logging an error message or providing a
fallback.

Comment on lines +70 to +72

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness: File operation lacks exception handling, which will cause the program to crash when trying to open a non-existent file.

📝 Committable Code Suggestion

‼️ Ensure you review the code suggestion before committing it to the branch. Make sure it replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
# Missing exception handling
with open("nonexistent_file.txt", "r") as f:
content = f.read()
# Missing exception handling
try:
with open("nonexistent_file.txt", "r") as f:
content = f.read()
except FileNotFoundError:
content = ""


calc = Calculator()
# Potential error - passing string to add method
calc.add("5", 3)
Comment on lines +74 to +76
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix type error in Calculator usage.

Passing a string "5" to the add method will cause issues if the method expects numeric types. This will result in string concatenation instead of numeric addition.

Apply this diff:

-    calc = Calculator()
-    # Potential error - passing string to add method
-    calc.add("5", 3)
+    calc = Calculator()
+    calc.add(5, 3)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
calc = Calculator()
# Potential error - passing string to add method
calc.add("5", 3)
calc = Calculator()
calc.add(5, 3)
🤖 Prompt for AI Agents
In codereview-test around lines 74 to 76, the add method of Calculator is called
with a string "5" and a number 3, which causes a type error and unintended
string concatenation. To fix this, convert the string "5" to a numeric type
before passing it to the add method, ensuring both arguments are numbers for
proper addition.

Comment on lines +74 to +76

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness: The add method accepts any types for parameters a and b, but adding a string and integer will cause type errors or unexpected behavior.

📝 Committable Code Suggestion

‼️ Ensure you review the code suggestion before committing it to the branch. Make sure it replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
calc = Calculator()
# Potential error - passing string to add method
calc.add("5", 3)
calc = Calculator()
# Potential error - passing string to add method
calc.add(5, 3)


if __name__ == "__main__":
main()