diff options
author | BonfaceKilz | 2021-02-12 15:35:43 +0300 |
---|---|---|
committer | BonfaceKilz | 2021-02-12 15:50:37 +0300 |
commit | ec5cb3e65df225cd589ea63effb0a26b4201c428 (patch) | |
tree | 6e44c8399270a57332b50dcb3fbd9039e85fddbe | |
parent | 21a4a847456fde5fcc6072df0d0fc36992da283d (diff) | |
download | genenetwork3-ec5cb3e65df225cd589ea63effb0a26b4201c428.tar.gz |
Add new procedure for looking up files in a given ENV variable
* gn3/file_utils.py (lookup_file): New function.
* tests/unit/test_file_utils.py: New test cases for ^^.
-rw-r--r-- | gn3/file_utils.py | 16 | ||||
-rw-r--r-- | tests/unit/test_file_utils.py | 30 |
2 files changed, 46 insertions, 0 deletions
diff --git a/gn3/file_utils.py b/gn3/file_utils.py index 8e342c9..36e3b6d 100644 --- a/gn3/file_utils.py +++ b/gn3/file_utils.py @@ -18,3 +18,19 @@ def get_dir_hash(directory: str) -> str: md5hash.update(bytearray(hashlib.md5(buf).hexdigest(), "utf-8")) return md5hash.hexdigest() + + +def lookup_file(environ_var: str, + root_dir: str, + file_name: str) -> str: + """Look up FILE_NAME in the path defined by ENVIRON_VAR/ROOT_DIR/; If +ENVIRON_VAR/ROOT_DIR/FILE_NAME does not exist, raise an exception. +Otherwise return ENVIRON_VAR/ROOT_DIR/FILE_NAME. + + """ + _dir = os.environ.get(environ_var) + if _dir: + _file = os.path.join(_dir, root_dir, file_name) + if os.path.isfile(_file): + return _file + raise FileNotFoundError diff --git a/tests/unit/test_file_utils.py b/tests/unit/test_file_utils.py index e6109bb..231dcd0 100644 --- a/tests/unit/test_file_utils.py +++ b/tests/unit/test_file_utils.py @@ -2,6 +2,8 @@ import os import unittest +from unittest import mock +from gn3.file_utils import lookup_file from gn3.file_utils import get_dir_hash @@ -18,3 +20,31 @@ class TestFileUtils(unittest.TestCase): self.assertRaises(FileNotFoundError, get_dir_hash, "/non-existent-file") + + @mock.patch("os.path.isfile") + @mock.patch.dict(os.environ, {"GENENETWORK_FILES": "/tmp/"}) + def test_lookup_genotype_file_exists(self, mock_isfile): + """Test whether genotype file exists if file is present""" + mock_isfile.return_value = True + self.assertEqual(lookup_file("GENENETWORK_FILES", + "genotype_files", "genotype.txt"), + "/tmp/genotype_files/genotype.txt") + + @mock.patch("os.path.isfile") + @mock.patch.dict(os.environ, {"GENENETWORK_FILES": "/tmp"}) + def test_lookup_genotype_file_does_not_exist(self, mock_isfile): + """Test whether genotype file exists if file is absent""" + mock_isfile.return_value = False + self.assertRaises(FileNotFoundError, + lookup_file, + "GENENETWORK_FILES", + "genotype_files", + "genotype.txt") + + def test_lookup_genotype_file_env_does_not_exist(self): + """Test whether genotype file exists if GENENETWORK_FILES is absent""" + self.assertRaises(FileNotFoundError, + lookup_file, + "GENENETWORK_FILES", + "genotype_files", + "genotype.txt") |