Рефакторинг парсера команд

This commit is contained in:
Denis Fedoseev 2023-10-09 01:10:37 +03:00
parent dc4c035a53
commit 0b3e72109c
2 changed files with 74 additions and 8 deletions

View file

@ -1,13 +1,25 @@
import re
class CommandParser: class CommandParser:
@staticmethod @staticmethod
def parse(command_string): def parse(command_string):
parsed_command = command_string.split('_')
command = parsed_command[0] if not command_string:
value = parsed_command[1] raise ValueError("Empty command received!")
match command: if not isinstance(command_string, str):
case 'GET': raise ValueError("Command must be a sting!")
return {'command': command, 'value': value}
case _: if re.search('[^a-zA-Z0-9_\-]', command_string):
raise ValueError("Unknown command: "+command) raise ValueError('Only [a-zA-Z0-9_\-] allowed')
if re.search('^GET_.*', command_string):
parsed_command = command_string.split('_', 1)
command = parsed_command[0]
value = parsed_command[1]
return {'command': command, 'value': value}
else:
raise ValueError("Unknown command: " + command_string)

View file

@ -0,0 +1,54 @@
import unittest
from command_parser import CommandParser
class TestCommandParser(unittest.TestCase):
def test_empty_line(self):
with self.assertRaises(ValueError) as context:
CommandParser.parse('')
self.assertEqual('Empty command received!', str(context.exception))
def test_unknown_command(self):
with self.assertRaises(ValueError) as context:
CommandParser.parse('REALLY_UNKNOWN_COMMAND')
self.assertEqual('Unknown command: REALLY_UNKNOWN_COMMAND', str(context.exception))
def test_parse_get_command(self):
result = CommandParser.parse('GET_A')
self.assertEqual(result, {'command': 'GET', 'value': 'A'})
def test_parse_get_command_w_dual_underlines(self):
result = CommandParser.parse('GET_A_B')
self.assertEqual(result, {'command': 'GET', 'value': 'A_B'})
def test_invalid_command(self):
with self.assertRaises(ValueError) as context:
CommandParser.parse('NOT_GET_A')
self.assertEqual('Unknown command: NOT_GET_A', str(context.exception))
def test_invalid_command_string_type(self):
with self.assertRaises(ValueError) as context:
CommandParser.parse(b'some_cmd')
self.assertEqual('Command must be a sting!', str(context.exception))
def test_not_allowed_symbols_in_command_string(self):
with self.assertRaises(ValueError) as context:
CommandParser.parse('GET_!')
self.assertEqual('Only [a-zA-Z0-9_\-] allowed', str(context.exception))
def test_not_allowed_newline_in_command_string(self):
with self.assertRaises(ValueError) as context:
CommandParser.parse("GET_A\nGET_B")
self.assertEqual('Only [a-zA-Z0-9_\-] allowed', str(context.exception))
if __name__ == '__main__':
unittest.main()