import os
import subprocess
from pathlib import Path
import shutil
import tempfile
import pytest
from domin8.tools.pre_approval_checks import normalize_files_with_formatters
def _fake_black_run(cmd, cwd=None, capture_output=None, text=None, check=None):
# Simulate black formatting by appending a newline comment to each file passed
class R:
returncode = 0
stdout = 'formatted'
stderr = ''
# cmd will be e.g. ['black', 'path/to/file.py', ...]
if cwd and len(cmd) >= 2 and cmd[0] == 'black':
for p in cmd[1:]:
fp = Path(cwd) / p
if fp.exists():
content = fp.read_text()
# Simulated formatting: normalize line endings and add a trailing comment
content = content.replace('\r\n', '\n')
if not content.endswith('\n'):
content += '\n'
content += '# _black_formatted\n'
fp.write_text(content)
return R()
def test_normalize_python_applies(monkeypatch, tmp_path):
repo_root = Path('.').resolve()
# Ensure black is reported available
monkeypatch.setattr('domin8.tools.pre_approval_checks._is_tool_available', lambda name: True if name == 'black' else False)
# Monkeypatch subprocess.run to our fake black that writes to cwd files
monkeypatch.setattr('domin8.tools.pre_approval_checks._run_subprocess', lambda cmd, cwd: _fake_black_run(cmd, cwd=cwd))
# Use an existing file
f = 'src/domin8/config.py'
res = normalize_files_with_formatters(repo_root, [f])
assert f in res
assert res[f]['formatted'] is True
assert res[f]['normalized_diff'] is not None
assert '# _black_formatted' in res[f]['normalized_diff']
def test_normalize_js_prettier(monkeypatch):
repo_root = Path('.').resolve()
monkeypatch.setattr('domin8.tools.pre_approval_checks._is_tool_available', lambda name: True if name == 'prettier' else False)
def _fake_prettier(cmd, cwd=None, capture_output=None, text=None, check=None):
class R:
returncode = 0
stdout = 'prettier'
stderr = ''
# Simulate formatting: append a comment to .js files
if cwd and '--write' in cmd:
for p in cmd[2:]:
fp = Path(cwd) / p
if fp.exists():
s = fp.read_text()
s = s + '\n// _prettier_formatted\n'
fp.write_text(s)
return R()
monkeypatch.setattr('domin8.tools.pre_approval_checks._run_subprocess', lambda cmd, cwd: _fake_prettier(cmd, cwd=cwd))
# Use a sample JS file: create temp JS file in repo for test
js_path = Path('tmp_test.js')
try:
js_path.write_text('function a(){return 1}')
res = normalize_files_with_formatters(repo_root, [str(js_path)])
assert str(js_path) in res
assert res[str(js_path)]['formatted'] is True
assert '// _prettier_formatted' in res[str(js_path)]['normalized_diff']
finally:
try:
js_path.unlink()
except Exception:
pass