Skip to content

Commit

Permalink
fix: config_file decorator creates config related to the script direc…
Browse files Browse the repository at this point in the history
…tory, not in current directory
  • Loading branch information
umanamente committed Jul 28, 2024
1 parent 44e2cc1 commit d16057d
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/configmodel/Decorators.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
# -*- coding: utf-8 -*-
import inspect
import os

from configmodel.Logger import Log

from configmodel import ConfigModel
Expand All @@ -14,7 +17,16 @@ def decorator(cls):
"""
:type cls: ConfigModel
"""
cls._register_as_static_config(filename=filename)
# check if file path is relative
if not os.path.isabs(filename):
# file must be relative to the same directory as the script using the decorator
client_script_path = inspect.getfile(cls)
client_script_dir = os.path.dirname(client_script_path)
abs_file_path = os.path.join(client_script_dir, filename)
else:
abs_file_path = filename

cls._register_as_static_config(filename=abs_file_path)
return cls

return decorator
Expand Down
37 changes: 37 additions & 0 deletions tests/test_ConfigModel.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
import unittest

__author__ = "Vasily Maslyukov"
Expand Down Expand Up @@ -367,6 +368,42 @@ class NestedConfig(ConfigModel):
val = RootConfig.NestedConfig.nested_value
mock_get_value.assert_called_with(["nested_config", "renamed_nested_value"])

def test_decorator_filename_same_directory(self):
"""
Check that @config_file decorator creates a file in the same directory as the script
"""
# change current directory to the temp directory
import tempfile
temp_dir = tempfile.mkdtemp()

assert temp_dir is not None
assert os.path.isdir(temp_dir)

current_dir = os.getcwd()

# add cleanup action
def _cleanup_action():
# change current directory back to the original directory
os.chdir(current_dir)
# remove temp directory
os.rmdir(temp_dir)
self.addCleanup(_cleanup_action)

# change current directory to the temp directory
os.chdir(temp_dir)

@config_file(TEST_CONFIG_FILE)
class StaticConfig(ConfigModel):
product_key = "1234"
secret = "abcd"

# check that file was created in the same directory as the script
config_filename = StaticConfig._get_instance()._serializer.filename
script_dir = os.path.dirname(os.path.realpath(__file__))
expected_file_path = os.path.join(script_dir, TEST_CONFIG_FILE)

self.assertEqual(expected_file_path, config_filename, "Config file was not created in the same directory as the script")


if __name__ == '__main__':
unittest.main()
Expand Down

0 comments on commit d16057d

Please sign in to comment.