Skip to content
Snippets Groups Projects
Commit 5a847958 authored by Hussain Kanafani's avatar Hussain Kanafani
Browse files

util methods with unit tests added

parent 29288690
No related branches found
No related tags found
No related merge requests found
from unittest import TestCase
import unittest.mock as mock
from utils import digits_in_string, make_directory, read_json
import random
import os.path as osp
import os
import json
class TestUtils(TestCase):
def setUp(self):
self.current_dir = os.getcwd()
def tearDown(self):
for dir in os.listdir(self.current_dir):
if (osp.isdir(dir)):
os.rmdir(dir)
def test_digits_in_string(self):
txt = 'video10'
digit = 10
self.assertEqual(digits_in_string(txt), int(digit))
self.assertEqual(type(digits_in_string(txt)), int)
def test_make_directory(self):
dir = os.path.join(self.current_dir, 'test_dir' + str(random.randint(1, 10000)))
print(dir)
dir = make_directory(dir)
self.assertTrue(osp.exists(dir), False)
def test_open_json_file(self):
# test valid JSON
read_data = json.dumps({'a': 1, 'b': 2, 'c': 3})
mock_open = mock.mock_open(read_data=read_data)
with mock.patch('builtins.open', mock_open):
result = read_json('file')
self.assertEqual({'a': 1, 'b': 2, 'c': 3}, result)
# test invalid JSON
read_data = ''
mock_open = mock.mock_open(read_data=read_data)
with mock.patch("builtins.open", mock_open):
with self.assertRaises(ValueError) as context:
read_json('file')
self.assertEqual(
'file is not valid', str(context.exception))
# test file does not exist
with self.assertRaises(IOError) as context:
read_json('null')
self.assertEqual(
'null does not exist.', str(context.exception))
utils.py 0 → 100644
import re
import json
import os
def read_json(file_path):
try:
with open(file_path, 'r') as f:
try:
return json.load(f)
except ValueError:
raise ValueError('{} is not valid'.format(file_path))
except IOError:
raise IOError('{} does not exist.'.format(file_path))
def write_json(obj, file_path):
make_directory(os.path.dirname(file_path))
with open(file_path, 'w') as f:
json.dump(obj, f)
def digits_in_string(text):
non_digit = re.compile("\D")
return int(non_digit.sub("", text))
def make_directory(directory):
if not os.path.exists(directory):
try:
os.makedirs(directory)
except OSError as err:
raise
return directory
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment