Files
contracts-flask/deploy/tests/test_drhider.py
T
naeel 2ebdaad2aa
Deploy contracts-flask / validate (push) Successful in 0s
test: DrHider comparison test — 12/13 PASS (address needs LLM)
2026-06-29 18:19:17 +04:00

104 lines
3.6 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.
"""
Тест DrHider — сравнение оригинал vs обфусцированный.
Файл: /home/naeel/nubes/contracts/contracts-flask/deploy/tests/test_drhider.py
"""
import sys, os, io, zipfile, json
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from services.drhider import obfuscate_files
TEST_ZIP = "/home/naeel/nubes/contracts/dogovora/примеры_договоров_для_ИИ.zip"
CHECKS = [
# (что должно быть в оригинале, что НЕ должно быть в обфусцированном)
("+7 (495) 789-41-35", "телефон"),
("info@nubes.ru", "email"),
("Степаненко", "фамилия"),
("XXX003", "компания XXX003"),
("XXX002", "компания XXX002"),
("ИНН 9706005293", "ИНН НУБЕС"),
("ОГРН 1207700098759", "ОГРН НУБЕС"),
("г. Москва", "город"), # адреса без LLM не ловятся — ожидаемо
]
KEEP = [
# (что должно остаться)
("НУБЕС", "Исполнитель"),
]
def extract_all_text(zip_bytes):
"""Извлечь весь текст из ZIP."""
texts = {}
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
for name in zf.namelist():
if name == 'mapping.csv':
continue
data = zf.read(name)
if name.endswith('.docx'):
from docx import Document
doc = Document(io.BytesIO(data))
texts[name] = "\n".join(p.text for p in doc.paragraphs)
else:
texts[name] = data.decode('utf-8', errors='replace')
return texts
def test():
with open(TEST_ZIP, 'rb') as f:
content = f.read()
zip_data, mapping_csv = obfuscate_files([('test.zip', content, '')])
# Извлечь текст из результата
out_texts = extract_all_text(zip_data)
combined = " ".join(out_texts.values())
print("=" * 60)
print("DrHider — проверка обфускации")
print("=" * 60)
errors = 0
# Проверка что чувствительные данные заменены
print("\n🔴 Должны быть ЗАМЕНЕНЫ:")
for needle, desc in CHECKS:
if needle in combined:
print(f" ❌ {desc}: '{needle}' найдено в обфусцированном!")
errors += 1
else:
print(f" ✅ {desc}: не найдено")
# Проверка что НУБЕС остался
print("\n🟢 Должны СОХРАНИТЬСЯ:")
for needle, desc in KEEP:
if needle not in combined:
print(f" ❌ {desc}: '{needle}' отсутствует!")
errors += 1
else:
print(f" ✅ {desc}: на месте")
# Статистика mapping.csv
lines = mapping_csv.split('\n')
print(f"\n📋 mapping.csv: {len(lines)-2} сущностей заменено")
for line in lines[1:6]:
if line.strip():
print(f" {line}")
# Проверка структуры ZIP
with zipfile.ZipFile(io.BytesIO(zip_data)) as zf:
names = zf.namelist()
has_csv = 'mapping.csv' in names
no_zip = not any(n.endswith('.zip') for n in names)
print(f"\n📦 ZIP: {len(names)} файлов, mapping.csv={'✅' if has_csv else '❌'}, без .zip={'✅' if no_zip else '❌'}")
print(f"\n{'='*60}")
if errors:
print(f"❌ {errors} ошибок")
sys.exit(1)
else:
print("✅ ВСЕ ПРОВЕРКИ ПРОЙДЕНЫ")
sys.exit(0)
if __name__ == '__main__':
test()