Files
code_scan/test_demo/demo_flaws.py
2026-03-13 16:22:23 +08:00

268 lines
5.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试文件:包含常见代码缺陷,用于验证扫描器
"""
import os
import sys
import json
import pickle
import subprocess
from ast import parse
from typing import List, Dict
# 缺陷1: 未使用的导入
import unused_module # 未使用
import collections as col # 使用了 col 但 flake8 可能检测
# 缺陷2: 未使用的变量
def unused_variable_demo():
"""演示未使用的变量"""
result = calculate() # result 未被使用
print("Function executed")
def calculate():
"""计算并返回结果"""
return 42
# 缺陷3: 未定义的变量
def undefined_variable_demo():
"""演示未定义的变量"""
print(undefined_var) # undefined_var 未定义
# 缺陷4: 变量在定义前使用
def use_before_define():
"""在定义前使用变量"""
print(before_var) # before_var 在下面才定义
before_var = 100
# 缺陷5: 硬编码密码(安全问题)
def connect_database():
"""连接数据库"""
password = "admin123" # 硬编码密码
username = "root"
return f"Connecting with {username}:{password}"
# 缺陷6: 使用 eval安全问题
def unsafe_eval():
"""危险使用 eval"""
user_input = "os.system('ls')"
result = eval(user_input) # 危险!
return result
# 缺陷7: 使用 pickle 反序列化(安全问题)
def unsafe_pickle():
"""不安全的 pickle 反序列化"""
data = b"..." # 模拟恶意数据
obj = pickle.loads(data) # 危险!
# 缺陷8: 行太长(风格问题)
def long_line():
"""这是一行非常非常非常非常非常非常非常非常非常非常非常非常长的代码超过了 120 个字符的限制"""
# 缺陷9: 缺少空格
def missing_spaces():
"""缺少必要空格"""
x=1+2
y=3*4
if x==1:
print(x)
# 缺陷10: 多余空格
def extra_spaces():
"""多余空格"""
x = 1
y = 2
# 缺陷11: 未捕获的异常
def unhandled_exception():
"""捕获异常后未处理"""
try:
result = 10 / 0
except ZeroDivisionError:
pass # 捕获但未处理
# 缺陷12: 过于宽泛的异常
def broad_exception():
"""捕获所有异常"""
try:
data = json.loads('{"key": "value"}')
except Exception:
pass
# 缺陷13: 裸 except 子句
def bare_except():
"""使用裸 except"""
try:
x = int("abc")
except:
pass
# 缺陷14: 重复代码
def duplicate_code():
"""重复代码示例"""
a = 1
b = 2
c = a + b
print(c)
a = 3
b = 4
c = a + b
print(c)
# 缺陷15: 变量名与内置函数冲突
def shadow_builtin():
"""变量名覆盖内置函数"""
list = [1, 2, 3] # 覆盖内置 list
dict = {} # 覆盖内置 dict
str = "hello" # 覆盖内置 str
return list, dict, str
# 缺陷16: 不必要的 pass
def unnecessary_pass():
"""不必要的 pass"""
if True:
pass # 可以直接删除
# 缺陷17: 使用 + 进行字符串拼接(推荐用 join
def string_concat():
"""低效字符串拼接"""
result = ""
for i in range(100):
result = result + str(i)
return result
# 缺陷18: 在循环中修改集合
def modify_during_iteration():
"""在迭代时修改列表"""
items = [1, 2, 3, 4, 5]
for item in items:
if item % 2 == 0:
items.remove(item) # 在迭代时修改
# 缺陷19: 全局变量
global_counter = 0 # 全局变量
def increment():
global global_counter # 依赖全局变量
global_counter += 1
# 缺陷20: 魔法数字
def calculate_price():
"""使用魔法数字"""
price = 100
tax = price * 1.1 # 1.1 是什么?
discount = price * 0.9
return tax, discount
# 缺陷21: 函数参数过多
def bad_function(a, b, c, d, e, f, g, h):
"""参数过多的函数"""
return a + b + c + d + e + f + g + h
# 缺陷22: 空函数体
def empty_function():
"""空函数应该使用 pass 或文档字符串"""
pass
# 缺陷23: 使用 time.sleep 测试
def bad_sleep():
"""生产代码中使用 time.sleep"""
import time
time.sleep(5) # 阻塞
# 缺陷24: 注释掉的代码
def commented_code():
# print("This is commented out")
pass
# 缺陷25: TODO/FIXME 注释
def todo_comment():
# TODO: Implement this
# FIXME: This is broken
pass
# 缺陷26: 导入顺序错误(应先标准库,再第三方,本地)
import sys # 标准库
import flask # 第三方
from . import local # 本地
# 缺陷27: 不必要的列表推导式
def unnecessary_list_comp():
"""不必要的列表推导式"""
result = [x for x in range(10)] # 可简化为 list(range(10))
return result
# 缺陷28: 条件表达式中的赋值
def assignment_in_condition():
"""在条件中赋值(不推荐)"""
if (x := get_value()) > 0: # 海象运算符但可能难以阅读
print(x)
def get_value():
return 5
# 缺陷29: 比较布尔值
def compare_bool():
"""与布尔值比较"""
flag = True
if flag == True: # 应直接用 if flag:
print("yes")
# 缺陷30: 使用 hasattr/getattr 而非异常处理
def use_hasattr():
"""滥用 hasattr"""
class Foo:
pass
obj = Foo()
if hasattr(obj, 'bar'): # 可直接用 try/except
print(obj.bar)
# 主函数入口
def main():
"""主函数"""
connect_database()
unsafe_eval()
unsafe_pickle()
print("Demo executed")
if __name__ == "__main__":
main()