From 454b99899db4862637f2cbcf61258b0f4d0f543f Mon Sep 17 00:00:00 2001 From: Xianpeng Shen Date: Mon, 13 Oct 2025 00:16:58 +0300 Subject: [PATCH] fix: check user input config exist or not --- commit_check/config.py | 13 +++++++++---- commit_check/main.py | 10 +++++----- tests/config_test.py | 40 +++++++++++++++------------------------- tests/main_test.py | 23 +++++++++++++++++++++-- 4 files changed, 50 insertions(+), 36 deletions(-) diff --git a/commit_check/config.py b/commit_check/config.py index 5cd5c959..e197ec82 100644 --- a/commit_check/config.py +++ b/commit_check/config.py @@ -22,11 +22,16 @@ def load_config(path_hint: str = "") -> Dict[str, Any]: """Load and validate config from TOML file.""" if path_hint: p = Path(path_hint) - if p.exists(): - with open(p, "rb") as f: - return toml_load(f) + if not p.exists(): + raise FileNotFoundError(f"Specified config file not found: {path_hint}") + with open(p, "rb") as f: + return toml_load(f) + + # Check default config paths only when no specific path is provided for candidate in DEFAULT_CONFIG_PATHS: if candidate.exists(): with open(candidate, "rb") as f: return toml_load(f) - raise FileNotFoundError("No config file found (cchk.toml or commit-check.toml)") + + # Return empty config if no default config files found + return {} diff --git a/commit_check/main.py b/commit_check/main.py index 16f13952..c473a3ad 100644 --- a/commit_check/main.py +++ b/commit_check/main.py @@ -135,11 +135,8 @@ def main() -> int: stdin_reader = StdinReader() try: - # Load configuration (fallback to defaults when no file found) - try: - config_data = load_config(args.config) - except FileNotFoundError: - config_data = {} + # Load configuration + config_data = load_config(args.config) # Build validation rules from config rule_builder = RuleBuilder(config_data) @@ -220,6 +217,9 @@ def main() -> int: # Return appropriate exit code return 0 if result == ValidationResult.PASS else 1 + except FileNotFoundError as e: + print(f"Error: {e}", file=sys.stderr) + return 1 except Exception as e: print(f"Error: {e}", file=sys.stderr) return 1 diff --git a/tests/config_test.py b/tests/config_test.py index e062b4ff..83d9baa8 100644 --- a/tests/config_test.py +++ b/tests/config_test.py @@ -29,26 +29,12 @@ def test_load_config_with_path_hint(self): os.unlink(f.name) def test_load_config_with_nonexistent_path_hint(self): - """Test loading config when path hint doesn't exist, falls back to default paths.""" - # Create a temporary cchk.toml in current directory - config_content = b""" -[checks] -fallback = true -""" - original_cwd = os.getcwd() - with tempfile.TemporaryDirectory() as tmpdir: - os.chdir(tmpdir) - try: - # Create cchk.toml in temp directory - with open("cchk.toml", "wb") as f: - f.write(config_content) - - # Try to load with nonexistent path hint - config = load_config("nonexistent.toml") - assert "checks" in config - assert config["checks"]["fallback"] is True - finally: - os.chdir(original_cwd) + """Test loading config when path hint doesn't exist - should raise FileNotFoundError.""" + # Test that specifying a nonexistent config file raises an error + with pytest.raises( + FileNotFoundError, match="Specified config file not found: nonexistent.toml" + ): + load_config("nonexistent.toml") def test_load_config_default_cchk_toml(self): """Test loading config from default cchk.toml path.""" @@ -89,23 +75,27 @@ def test_load_config_default_commit_check_toml(self): os.chdir(original_cwd) def test_load_config_file_not_found(self): - """Test FileNotFoundError when no config files exist.""" + """Test returning empty config when no default config files exist.""" original_cwd = os.getcwd() with tempfile.TemporaryDirectory() as tmpdir: os.chdir(tmpdir) try: - with pytest.raises(FileNotFoundError, match="No config file found"): - load_config() + # Should return empty config when no default files exist + config = load_config() + assert config == {} finally: os.chdir(original_cwd) def test_load_config_file_not_found_with_invalid_path_hint(self): - """Test FileNotFoundError when path hint and default paths don't exist.""" + """Test FileNotFoundError when specified path hint doesn't exist.""" original_cwd = os.getcwd() with tempfile.TemporaryDirectory() as tmpdir: os.chdir(tmpdir) try: - with pytest.raises(FileNotFoundError, match="No config file found"): + with pytest.raises( + FileNotFoundError, + match="Specified config file not found: nonexistent.toml", + ): load_config("nonexistent.toml") finally: os.chdir(original_cwd) diff --git a/tests/main_test.py b/tests/main_test.py index 18512455..34d2e485 100644 --- a/tests/main_test.py +++ b/tests/main_test.py @@ -237,9 +237,9 @@ def test_main_with_invalid_config_file(self, mocker): "--message", # empty -> read from stdin ] - # This should not crash, just use default config + # This should fail with proper error message when config file doesn't exist result = main() - assert result == 0 + assert result == 1 # Removed problematic tests that had configuration dependency issues @@ -276,3 +276,22 @@ def test_main_error_handling_subprocess_failure(self, mocker, capsys): result = main() # Even if subprocess fails, main should not crash assert result in [0, 1] # Either passes or fails gracefully + + def test_nonexistent_config_file_error(self, capsys): + """Test that specifying a non-existent config file returns error.""" + sys.argv = [ + "commit-check", + "--config", + "/nonexistent/config.toml", + "--message", + "feat: test", + ] + + result = main() + assert result == 1 + + captured = capsys.readouterr() + assert ( + "Error: Specified config file not found: /nonexistent/config.toml" + in captured.err + )