Skip to content

Commit b4ea89a

Browse files
committed
Add: Allow to load a config from a string
This new method is mostly for testing purposes to allow providing a config via a string inside a test.
1 parent 232e20d commit b4ea89a

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

autohooks/config.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,20 @@ def from_dict(config_dict: Dict[str, Any]) -> "AutohooksConfig":
134134
)
135135
return AutohooksConfig(settings=settings, config=config)
136136

137+
@staticmethod
138+
def from_string(content: str) -> "AutohooksConfig":
139+
"""
140+
Load an AutohooksConfig from a string
141+
142+
Args:
143+
content: The content of the config
144+
145+
Returns:
146+
A new AutohooksConfig
147+
"""
148+
config_dict = tomlkit.loads(content)
149+
return AutohooksConfig.from_dict(config_dict)
150+
137151
@staticmethod
138152
def from_toml(toml_file: Path) -> "AutohooksConfig":
139153
"""
@@ -145,8 +159,7 @@ def from_toml(toml_file: Path) -> "AutohooksConfig":
145159
Returns:
146160
A new AutohooksConfig
147161
"""
148-
config_dict = tomlkit.loads(toml_file.read_text())
149-
return AutohooksConfig.from_dict(config_dict)
162+
return AutohooksConfig.from_string(toml_file.read_text())
150163

151164

152165
def load_config_from_pyproject_toml(

tests/test_config.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,27 @@ def test_load_from_non_existing_toml_file(self):
4242

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

45+
def test_load_from_string(self):
46+
config = AutohooksConfig.from_string(
47+
"""
48+
[tool.autohooks]
49+
pre-commit = ["foo", "bar"]
50+
"""
51+
)
52+
53+
self.assertTrue(config.has_autohooks_config())
54+
55+
self.assertListEqual(
56+
config.get_pre_commit_script_names(), ["foo", "bar"]
57+
)
58+
59+
def test_load_from_empty_string(self):
60+
config = AutohooksConfig.from_string("")
61+
62+
self.assertFalse(config.has_autohooks_config())
63+
64+
self.assertEqual(config.get_pre_commit_script_names(), [])
65+
4566
def test_empty_config(self):
4667
config = AutohooksConfig()
4768

0 commit comments

Comments
 (0)