42 """Test that missing shebang is added correctly."""
43 test_file = temp_project_root /
"test_missing_shebang.py"
45 "# -*- coding: utf-8 -*-\n"
52 changed, new_text, messages = fix_header_block(test_file, test_file.read_text(encoding=
"utf-8"), formatter_ctx_fix)
54 assert changed
is True
55 assert len(messages) > 0
56 assert new_text.startswith(
"#!/usr/bin/env python3\n")
60 """Test that missing encoding is added correctly."""
61 test_file = temp_project_root /
"test_missing_encoding.py"
63 "#!/usr/bin/env python3\n"
70 changed, new_text, messages = fix_header_block(test_file, test_file.read_text(encoding=
"utf-8"), formatter_ctx_fix)
72 assert changed
is True
73 lines = new_text.split(
'\n')
74 assert lines[1] ==
"# -*- coding: utf-8 -*-"
78 """Test that incorrect file path header is rewritten."""
79 test_file = temp_project_root /
"test_wrong_path.py"
81 "#!/usr/bin/env python3\n"
82 "# -*- coding: utf-8 -*-\n"
83 "# wrong/path/to/file.py\n"
89 changed, new_text, messages = fix_header_block(test_file, test_file.read_text(encoding=
"utf-8"), formatter_ctx_fix)
91 assert changed
is True
92 lines = new_text.split(
'\n')
93 assert "test_wrong_path.py" in lines[2]
97 """Test that format_file archives original before writing (archival moved to format_file)."""
99 test_file = temp_project_root /
"test_archive.py"
104 test_file.write_text(original_content, encoding=
"utf-8")
106 result = format_file(test_file, formatter_ctx_fix)
108 assert result[
"changed"]
is True
109 archive_dir = test_file.parent /
".formatter_archive"
110 assert archive_dir.exists()
111 backups = list(archive_dir.glob(
"test_archive.py.*"))
112 assert len(backups) == 1
113 assert backups[0].read_text(encoding=
"utf-8") == original_content
117 """Test that code below header is preserved exactly."""
118 test_file = temp_project_root /
"test_preserve.py"
119 code_content =
"""def my_function():
128 test_file.write_text(
134 changed, new_text, messages = fix_header_block(test_file, test_file.read_text(encoding=
"utf-8"), formatter_ctx_fix)
136 assert changed
is True
137 assert code_content
in new_text
141 """Test that dry-run mode doesn't modify files."""
142 test_file = temp_project_root /
"test_dryrun.py"
143 original_content =
"# Missing header\nprint('hello')\n"
144 test_file.write_text(original_content, encoding=
"utf-8")
146 changed, _, messages = fix_header_block(test_file, original_content, formatter_ctx)
148 assert changed
is True
149 assert test_file.read_text(encoding=
"utf-8") == original_content
153 """Test that correct headers are not modified."""
154 test_file = temp_project_root /
"test_correct.py"
156 "#!/usr/bin/env python3\n"
157 "# -*- coding: utf-8 -*-\n"
158 "# test_correct.py\n"
162 test_file.write_text(correct_content, encoding=
"utf-8")
164 changed, _, messages = fix_header_block(test_file, correct_content, formatter_ctx_fix)
166 assert changed
is False
167 assert len(messages) == 0