Skip to content

Commit

Permalink
Add: Allow to load a config from a string
Browse files Browse the repository at this point in the history
This new method is mostly for testing purposes to allow providing a
config via a string inside a test.
  • Loading branch information
bjoernricks committed Feb 4, 2025
1 parent 232e20d commit b4ea89a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
17 changes: 15 additions & 2 deletions autohooks/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,20 @@ def from_dict(config_dict: Dict[str, Any]) -> "AutohooksConfig":
)
return AutohooksConfig(settings=settings, config=config)

@staticmethod
def from_string(content: str) -> "AutohooksConfig":
"""
Load an AutohooksConfig from a string
Args:
content: The content of the config
Returns:
A new AutohooksConfig
"""
config_dict = tomlkit.loads(content)
return AutohooksConfig.from_dict(config_dict)

@staticmethod
def from_toml(toml_file: Path) -> "AutohooksConfig":
"""
Expand All @@ -145,8 +159,7 @@ def from_toml(toml_file: Path) -> "AutohooksConfig":
Returns:
A new AutohooksConfig
"""
config_dict = tomlkit.loads(toml_file.read_text())
return AutohooksConfig.from_dict(config_dict)
return AutohooksConfig.from_string(toml_file.read_text())


def load_config_from_pyproject_toml(
Expand Down
21 changes: 21 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,27 @@ def test_load_from_non_existing_toml_file(self):

self.assertEqual(len(config.get_pre_commit_script_names()), 0)

def test_load_from_string(self):
config = AutohooksConfig.from_string(
"""
[tool.autohooks]
pre-commit = ["foo", "bar"]
"""
)

self.assertTrue(config.has_autohooks_config())

self.assertListEqual(
config.get_pre_commit_script_names(), ["foo", "bar"]
)

def test_load_from_empty_string(self):
config = AutohooksConfig.from_string("")

self.assertFalse(config.has_autohooks_config())

self.assertEqual(config.get_pre_commit_script_names(), [])

def test_empty_config(self):
config = AutohooksConfig()

Expand Down

0 comments on commit b4ea89a

Please sign in to comment.