[lang-ref] ( custom_error ) ( python )

def test_custom_error(capsys):
    # parser.error()
    import argparse

    # Intended use cases: raise a custom error in situations like these:
    # 1. Cross-argument consistency checks  <- this case
    # 2. Range validation for values (e.g., dates)

    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--day-of-month')
    parser.add_argument('--day-of-week')
    args = parser.parse_args(['--day-of-month=15', '--day-of-week=Fri'])

    with pytest.raises(SystemExit) as e:
        if args.day_of_month is not None and args.day_of_week is not None:
            parser.error(f'You cannot specify both day-of-month and day-of-week at the same time.')

            assert e.value.code == 2

            captured = capsys.readouterr()

            message = captured.err
            assert message.startswith('usage: ') # usage and error message