15r10nk/pysource-codegen
GitHub: 15r10nk/pysource-codegen
一款基于种子生成可编译随机 Python 代码的工具,专门用于测试 linter、formatter 及其他 Python 代码处理工具的健壮性。
Stars: 58 | Forks: 3
[](https://pypi.org/project/pysource-codegen/)


[](https://github.com/sponsors/15r10nk)
# 简介
`pysource_codegen` 能够生成可编译的随机 Python 代码。
编译后的代码不应被执行。
这仍然是一个非常早期的版本,但它可以胜任其工作。
它通常对于测试格式化工具、linters 或任何处理 Python 代码的工具非常有用。
## 安装:
```
pip install pysource-codegen
```
## 用法:
该工具可通过 CLI 使用:
```
pysource-codegen --seed 42
```
或作为库使用:
```
from pysource_codegen import generate
seed = 42
print(generate(seed))
```
您可能也会发现 [pysource-minimize](https://github.com/15r10nk/pysource-minimize) 很有用,
它可以将触发您的 bug 的生成代码缩减为最小的代码片段,
从而用于修复该问题。
```
from pysource_codegen import generate
from pysource_minimize import minimize
def contains_bug(code):
"""
returns True if the code triggers a bug and False otherwise
"""
try:
test_something_with(code) # might throw
if "bug" in code: # maybe other checks
return True
except:
return True
return False
def find_issue():
for seed in range(0, 10000):
code = generate(seed)
if contains_bug(code):
new_code = minimize(code, contains_bug)
print("the following code triggers a bug")
print(new_code)
return
find_issue()
```
## 在其他项目中发现的 Bug:
### black
* https://github.com/psf/black/issues/3676
* https://github.com/psf/black/issues/3678
* https://github.com/psf/black/issues/3677
### cpython
#### 3.12
* https://github.com/python/cpython/issues/109219
* https://github.com/python/cpython/issues/109823
* https://github.com/python/cpython/issues/109719
* https://github.com/python/cpython/issues/109627
* https://github.com/python/cpython/issues/109219
* https://github.com/python/cpython/issues/109118
* https://github.com/python/cpython/issues/109114
* https://github.com/python/cpython/issues/109889
#### 3.13
* https://github.com/python/cpython/issues/120367
* https://github.com/python/cpython/issues/120225
* https://github.com/python/cpython/issues/124746
* https://github.com/python/cpython/issues/124871
#### 3.14
* https://github.com/python/cpython/issues/138558
* https://github.com/python/cpython/issues/138479
* https://github.com/python/cpython/issues/138349
* https://github.com/python/cpython/issues/132479
## 待办事项:
* [ ] 重构现有代码
* 为 `probability()` 添加更好的上下文信息
* 移除 `fix()` 函数并将代码移至 `probability()` 中
* [ ] 使用现有 Python 代码中 ast-nodes 的概率(使用马尔可夫链)
* [x] 支持旧版 Python
* [ ] 允许自定义概率以生成代码来测试特定的语言特性
* [ ] 支持 [hypothesis](https://hypothesis.readthedocs.io/en/latest/)
标签:Python, 云安全监控, 代码生成, 文档结构分析, 无后门, 测试工具, 渗透测试工具, 自动化payload嵌入, 逆向工具, 静态分析