Skip to content

Commit a4053c7

Browse files
committed
better way to handle config init with invalid arguments
1 parent 52c2c0f commit a4053c7

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

atcodertools/codegen/code_gen_config.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,23 @@
44
INDENT_TYPE_TAB = 'tab'
55

66

7-
def _verify_indent_type(indent_type: str):
8-
# indent_type must be 'space' or 'tab'
9-
assert indent_type in [INDENT_TYPE_SPACE, INDENT_TYPE_TAB]
10-
return indent_type
7+
class ConfigInitError(Exception):
8+
pass
119

1210

1311
class CodeGenConfig:
1412
def __init__(self,
1513
indent_type: str = INDENT_TYPE_SPACE,
1614
indent_width: int = 4,
1715
):
18-
self.indent_type = _verify_indent_type(indent_type)
16+
17+
if indent_type not in [INDENT_TYPE_SPACE, INDENT_TYPE_TAB]:
18+
raise ConfigInitError("indent_type must be 'space' or 'tab'")
19+
20+
if indent_width < 0:
21+
raise ConfigInitError("indent_width must be a positive integer")
22+
23+
self.indent_type = indent_type
1924
self.indent_width = indent_width
2025

2126
def indent(self, depth):

tests/test_codegen.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import unittest
44
import os
55

6-
from atcodertools.codegen.code_gen_config import CodeGenConfig, INDENT_TYPE_SPACE
6+
from atcodertools.codegen.code_gen_config import CodeGenConfig, INDENT_TYPE_SPACE, ConfigInitError
77
from atcodertools.codegen.code_generator import CodeGenerator
88
from atcodertools.codegen.java_code_generator import JavaCodeGenerator
99
from atcodertools.codegen.cpp_code_generator import CppCodeGenerator
@@ -88,6 +88,17 @@ def test_load_code_gen_config(self):
8888
self.assertEqual(8, config.indent_width)
8989
self.assertEqual(INDENT_TYPE_SPACE, config.indent_type)
9090

91+
def test_init_code_gen_config_with_invalid_parameters(self):
92+
self._expect_error_when_init(indent_type='SPACE', indent_width=4)
93+
self._expect_error_when_init(indent_type='space', indent_width=-1)
94+
95+
def _expect_error_when_init(self, **kwargs):
96+
try:
97+
CodeGenConfig(**kwargs)
98+
self.fail("Must not reach here")
99+
except ConfigInitError:
100+
pass
101+
91102

92103
if __name__ == "__main__":
93104
unittest.main()

0 commit comments

Comments
 (0)