diff --git a/commitizen/commands/check.py b/commitizen/commands/check.py index d60c36840f..455681a69e 100644 --- a/commitizen/commands/check.py +++ b/commitizen/commands/check.py @@ -1,5 +1,6 @@ import os import re +import sys from typing import Dict, Optional from commitizen import factory, git, out @@ -32,9 +33,12 @@ def __init__(self, config: BaseConfig, arguments: Dict[str, str], cwd=os.getcwd( self.cz = factory.commiter_factory(self.config) def _valid_command_argument(self): - if not ( - bool(self.commit_msg_file) ^ bool(self.commit_msg) ^ bool(self.rev_range) - ): + sources = ( + bool(self.commit_msg_file) + bool(self.commit_msg) + bool(self.rev_range) + ) + if sources == 0 and not os.isatty(0): + self.commit_msg: Optional[str] = sys.stdin.read() + elif sources != 1: raise InvalidCommandArgumentError( ( "One and only one argument is required for check command! " diff --git a/tests/commands/test_check_command.py b/tests/commands/test_check_command.py index f2bb99a0ca..95eb007238 100644 --- a/tests/commands/test_check_command.py +++ b/tests/commands/test_check_command.py @@ -1,4 +1,5 @@ import sys +from io import StringIO from typing import List import pytest @@ -190,12 +191,12 @@ def test_check_a_range_of_git_commits_and_failed(config, mocker): error_mock.assert_called_once() -@pytest.mark.parametrize( - "args", [{"rev_range": "HEAD~10..master", "commit_msg_file": "some_file"}, {}] -) -def test_check_command_with_invalid_argment(args, config): +def test_check_command_with_invalid_argment(config): with pytest.raises(InvalidCommandArgumentError) as excinfo: - commands.Check(config=config, arguments=args) + commands.Check( + config=config, + arguments={"commit_msg_file": "some_file", "rev_range": "HEAD~10..master"}, + ) assert "One and only one argument is required for check command!" in str( excinfo.value ) @@ -245,3 +246,23 @@ def test_check_command_with_invalid_message(config, mocker): with pytest.raises(InvalidCommitMessageError): check_cmd() error_mock.assert_called_once() + + +def test_check_command_with_pipe_message(mocker, capsys): + testargs = ["cz", "check"] + mocker.patch.object(sys, "argv", testargs) + mocker.patch("sys.stdin", StringIO("fix(scope): some commit message")) + + cli.main() + out, _ = capsys.readouterr() + assert "Commit validation: successful!" in out + + +def test_check_command_with_pipe_message_and_failed(mocker): + testargs = ["cz", "check"] + mocker.patch.object(sys, "argv", testargs) + mocker.patch("sys.stdin", StringIO("bad commit message")) + + with pytest.raises(InvalidCommitMessageError) as excinfo: + cli.main() + assert "commit validation: failed!" in str(excinfo.value)