Skip to content

Commit

Permalink
refactoring data_parser.py
Browse files Browse the repository at this point in the history
  • Loading branch information
DmGorokhov committed Apr 8, 2023
1 parent 2156cc6 commit 565acfe
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 8 deletions.
38 changes: 31 additions & 7 deletions gendiff/diff_units/data_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
11 changes: 10 additions & 1 deletion tests/test_gendiff.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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')),
Expand Down

0 comments on commit 565acfe

Please sign in to comment.