Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes an error when no config file present (assume default config) + tests #41

Merged
merged 4 commits into from
Jul 25, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 26 additions & 13 deletions src/sparc/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,29 +33,38 @@ class SparcClient:
-----------
module_names : list
Stores the list of modules that are automatically loaded from the <projectbase>/services directory.
config : ConfigParser
Config used for sparc.client


Methods:
--------
add_module(path, config, connect):
Adds and optionally connects to a module in a given path with configuration variables defined in config.
connect()
connect():
Connects all the modules by calling their connect() functions.
get_config():
Returns config used by sparc.client

"""

def __init__(self, config_file: str = "config/config.ini", connect: bool = True) -> None:
# Read config file
if not config_file:
raise RuntimeError("Configuration file not given")
def __init__(self, config_file: str = "config.ini", connect: bool = True) -> None:

config = ConfigParser()
# Try to find config file, if not available, provide default
self.config = ConfigParser()
self.config['global'] = {'default_profile' : 'default'}
self.config['default'] = {'pennsieve_profile_name' : 'pennsieve'}

if os.path.isfile(config_file):
config.read(config_file)
logging.debug(str(config))
current_config = config["global"]["default_profile"]
try:
self.config.read(config_file)
except Exception as e:
logging.warning("Configuration file not provided or incorrect, using default settings.")
pass

logging.debug("Using the following config:")
logging.debug(str(config[current_config]))
logging.debug(self.config.sections())
current_config = self.config["global"]["default_profile"]

logging.debug("Using the following config:" + current_config)
self.module_names = []

# iterate through the modules in the current package
Expand All @@ -64,7 +73,7 @@ def __init__(self, config_file: str = "config/config.ini", connect: bool = True)
for _, module_name, _ in iter_modules([package_dir]):
# import the module and iterate through its attributes
self.add_module(
f"{__package__}.services.{module_name}", config[current_config], connect
f"{__package__}.services.{module_name}", self.config[current_config], connect
)

def add_module(
Expand Down Expand Up @@ -118,3 +127,7 @@ def connect(self) -> bool:
if hasattr(module, "connect"):
getattr(self, module_name).connect()
return True

def get_config(self) -> ConfigParser:
"""Returns config for sparc.client"""
return self.config
athril marked this conversation as resolved.
Show resolved Hide resolved
35 changes: 22 additions & 13 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,40 @@

from sparc.client import SparcClient


# Test creating a default instance
def test_class(config_file):
c = SparcClient(connect=False, config_file=config_file)
assert len(c.module_names) > 0


# Config file tests
def test_config_non_existing(config_file=None):
with pytest.raises(RuntimeError):
a = SparcClient(config_file, connect=False)


# Test config file with incorrect section pointer
def test_config_no_section(test_resources_dir):
config_file = os.path.join(test_resources_dir, "dummy_config.ini")
with pytest.raises(KeyError):
a = SparcClient(config_file, connect=False)


# Config non existing config
def test_config_non_existing(config_file=None):
client = SparcClient(config_file, connect=False)
c = client.get_config()
assert c['global']['default_profile'] == 'default'
assert c['default']['pennsieve_profile_name'] == 'pennsieve'

# Test proper config provided
def test_get_config(test_resources_dir):
config_file = os.path.join(test_resources_dir, "config.ini")
client = SparcClient(config_file, connect=False)
c = client.get_config()
print(c.sections())
assert c['global']['default_profile'] == 'ci'
assert c['ci']['pennsieve_profile_name'] == 'ci'

# Test module addition
def test_failed_add_module(config_file):
client = SparcClient(connect=False, config_file=config_file)
with pytest.raises(ModuleNotFoundError):
client.add_module(paths="sparc.client.xyz", connect=False)


# Test using a config with the module
def test_add_module_connect(config_file):
sc = SparcClient(config_file=config_file, connect=False)

Expand All @@ -46,7 +55,7 @@ def test_add_module_connect(config_file):
assert d.init_config_arg == expected_module_config
assert d.connect_method_called is True


# Test adding a Pennsieve module
def test_add_pennsieve(config_file):
sc = SparcClient(config_file=config_file, connect=False)
assert "pennsieve" in sc.module_names
Expand All @@ -55,8 +64,8 @@ def test_add_pennsieve(config_file):

assert isinstance(sc.pennsieve, PennsieveService)


def test_connect(config_file, monkeypatch):
# Test connection to the module
def test_module_connect(config_file, monkeypatch):
sc = SparcClient(config_file=config_file, connect=False)
mock_connect_results = []

Expand Down
Loading