From 565acfe9bfe51acf67b21d96121eabb34b105af1 Mon Sep 17 00:00:00 2001 From: Dmitry Gorokhov Date: Sat, 8 Apr 2023 10:51:45 +0300 Subject: [PATCH] refactoring data_parser.py --- gendiff/diff_units/data_parser.py | 38 +++++++++++++++++++++++++------ tests/test_gendiff.py | 11 ++++++++- 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/gendiff/diff_units/data_parser.py b/gendiff/diff_units/data_parser.py index c822402..8a5892c 100644 --- a/gendiff/diff_units/data_parser.py +++ b/gendiff/diff_units/data_parser.py @@ -2,12 +2,36 @@ from yaml import safe_load -def read_file(filepath): +def get_format(filepath): + if filepath.endswith('.json'): + format = 'json' + elif filepath.endswith('.yaml') or filepath.endswith('.yml'): + format = 'yaml' + else: + format = 'other format' + return format + + +def parse_json(filepath): with open(filepath, 'r') as filedata: - if filepath.endswith('.json'): - data = json.load(filedata) - elif filepath.endswith('.yaml') or filepath.endswith('.yml'): - data = safe_load(filedata) - else: - raise Exception('Files should be json or yaml format') + data = json.load(filedata) return data + + +def parse_yaml(filepath): + with open(filepath, 'r') as filedata: + data = safe_load(filedata) + return data + + +def read_file(filepath): + format = get_format(filepath) + + match format: + case 'json': + parsed_data = parse_json(filepath) + case 'yaml': + parsed_data = parse_yaml(filepath) + case 'other format': + raise Exception('Files should be json or yaml format') + return parsed_data diff --git a/tests/test_gendiff.py b/tests/test_gendiff.py index d0c8298..c182b74 100644 --- a/tests/test_gendiff.py +++ b/tests/test_gendiff.py @@ -5,7 +5,7 @@ from gendiff.cli import parse_args -from gendiff.diff_units.data_parser import read_file +from gendiff.diff_units.data_parser import read_file, get_format from gendiff.diff_units.data_comparator import (get_diff, get_key_name, get_children, get_value, get_old_value, get_status, @@ -52,6 +52,15 @@ def test_parse_args(): assert args2 == ('file3', 'file4', 'stylish') +@pytest.mark.parametrize('filepath, format', + [('some_file.json', 'json'), + ('some_file.yaml', 'yaml'), + ('some_file.yml', 'yaml'), + ('some_file.txt', 'other format')]) +def test_get_format(filepath, format): + assert get_format(filepath) == format + + data_pasred_cases = [ ('file1.json', read_json('file1.json')), ('file1.yml', read_yaml('file1.yml')),