about summary refs log tree commit diff
diff options
context:
space:
mode:
authorBonfaceKilz2021-02-12 15:49:19 +0300
committerBonfaceKilz2021-02-12 15:50:44 +0300
commitfcf6fbdaaae460bed917b73db033a3d063443389 (patch)
tree85033fc8cf05e89a0a4cbd5dd5d422480029958b
parentec5cb3e65df225cd589ea63effb0a26b4201c428 (diff)
downloadgenenetwork3-fcf6fbdaaae460bed917b73db033a3d063443389.tar.gz
Add new procedure to return a python dict from a json file
* gn3/file_utils.py (jsonfile_to_dict): New procedure
* tests/unit/test_file_utils.py: New test-cases.
-rw-r--r--gn3/file_utils.py10
-rw-r--r--tests/unit/test_file_utils.py15
2 files changed, 25 insertions, 0 deletions
diff --git a/gn3/file_utils.py b/gn3/file_utils.py
index 36e3b6d..79e6854 100644
--- a/gn3/file_utils.py
+++ b/gn3/file_utils.py
@@ -1,8 +1,10 @@
 """Procedures that operate on files/ directories"""
 import hashlib
+import json
 import os
 
 from functools import partial
+from typing import Dict
 
 
 def get_dir_hash(directory: str) -> str:
@@ -34,3 +36,11 @@ Otherwise return ENVIRON_VAR/ROOT_DIR/FILE_NAME.
         if os.path.isfile(_file):
             return _file
     raise FileNotFoundError
+
+
+def jsonfile_to_dict(json_file: str) -> Dict:
+    """Give a JSON_FILE, return a python dict"""
+    with open(json_file) as _file:
+        data = json.load(_file)
+        return data
+    raise FileNotFoundError
diff --git a/tests/unit/test_file_utils.py b/tests/unit/test_file_utils.py
index 231dcd0..a54680d 100644
--- a/tests/unit/test_file_utils.py
+++ b/tests/unit/test_file_utils.py
@@ -3,6 +3,7 @@ import os
 import unittest
 
 from unittest import mock
+from gn3.file_utils import jsonfile_to_dict
 from gn3.file_utils import lookup_file
 from gn3.file_utils import get_dir_hash
 
@@ -48,3 +49,17 @@ class TestFileUtils(unittest.TestCase):
                           "GENENETWORK_FILES",
                           "genotype_files",
                           "genotype.txt")
+
+    def test_jsonfile_to_dict(self):
+        """Test that a json file is parsed correctly"""""
+        json_file = os.path.join(os.path.dirname(__file__),
+                                 "test_data", "metadata.json")
+        self.assertEqual("Longer description",
+                         jsonfile_to_dict(json_file).get("description"))
+
+    def test_jsonfile_to_dict_nonexistent_file(self):
+        """Test that a ValueError is raised when the json file is
+non-existent"""
+        self.assertRaises(FileNotFoundError,
+                          jsonfile_to_dict,
+                          "/non-existent-dir")