test_config_loader.py 16.2 KB
Newer Older
Baber's avatar
Baber committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
"""
Tests for the config loader pure functions.

Note: _import_function uses LRU caching, so file changes during runtime
won't be detected unless the cache is cleared.

Test coverage:
- _mk_function_ctor:
  - test_mk_function_ctor_with_resolve_false: no-op lambda when resolve=False
  - test_mk_function_ctor_with_resolve_true: actual function import when resolve=True
- _make_loader:
  - test_make_loader_creates_loader_class: creates YAML loader with !function support
  - test_make_loader_caching: loader classes cached by parameters
- _import_function:
  - test_import_local_module: imports from local .py files
  - test_import_nested_local_module: handles dot-separated nested paths
  - test_import_standard_module: falls back to standard library imports
  - test_import_caching: LRU cache behavior
  - test_import_mtime_sensitivity: cache behavior with file changes
- load():
  - test_load_simple_yaml: basic YAML parsing
  - test_load_with_function_resolved: !function tags resolved to callables
Baber's avatar
Baber committed
23
  - test_load_with_function_not_resolved: !function tags become strings
Baber's avatar
Baber committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
  - test_load_with_includes: include files merged, main values win
  - test_load_with_absolute_include: absolute path includes
  - test_load_without_includes_resolution: includes preserved when disabled
  - test_load_include_cycle_detection: circular includes raise error
  - test_load_multiple_includes: include order precedence (later includes override earlier, main overrides all)
  - test_load_recursive_includes: nested includes (main->inc1->inc2, main overrides inc1 overrides inc2)
  - test_load_expanduser_path: ~ paths expanded
"""

import tempfile
from pathlib import Path
from unittest.mock import MagicMock, patch

import pytest

from lm_eval.tasks._config_loader import (
    _Base,
Baber's avatar
Baber committed
41
    _import_func_in_yml,
Baber's avatar
Baber committed
42
43
    _make_loader,
    _mk_function_ctor,
Baber's avatar
Baber committed
44
    import_fun_from_str,
Baber's avatar
Baber committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
    load_yaml,
)


@pytest.fixture
def temp_dir():
    with tempfile.TemporaryDirectory() as td:
        yield Path(td)


@pytest.fixture
def yaml_file(temp_dir):
    def _create_yaml(content, filename="test.yaml"):
        file_path = temp_dir / filename
        file_path.write_text(content)
        return file_path

    return _create_yaml


@pytest.fixture
def python_module(temp_dir):
    def _create_module(content, filename="utils.py"):
        file_path = temp_dir / filename
        file_path.write_text(content)
        return file_path

    return _create_module


class TestMkFunctionCtor:
    """Tests for the YAML !function constructor factory."""

    def test_mk_function_ctor_with_resolve_false(self, temp_dir):
Baber's avatar
Baber committed
79
        """When resolve=False, should return a string."""
Baber's avatar
Baber committed
80
81
82
83
84
85
86
87
        ctor = _mk_function_ctor(temp_dir, resolve=False)

        loader = MagicMock()
        node = MagicMock()
        loader.construct_scalar.return_value = "module.function"

        result = ctor(loader, node)

Baber's avatar
Baber committed
88
        assert isinstance(result, str)
Baber's avatar
Baber committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138

    def test_mk_function_ctor_with_resolve_true(self, temp_dir, python_module):
        """When resolve=True, should import and return the actual function."""
        # Create a local module
        python_module("def test_func(x):\n    return x * 2\n")

        ctor = _mk_function_ctor(temp_dir, resolve=True)

        loader = MagicMock()
        node = MagicMock()
        loader.construct_scalar.return_value = "utils.test_func"

        result = ctor(loader, node)

        assert callable(result)
        assert result(5) == 10


class TestMakeLoader:
    """Tests for YAML loader class creation and caching."""

    def test_make_loader_creates_loader_class(self, temp_dir):
        loader_cls = _make_loader(temp_dir, resolve_funcs=True)

        assert issubclass(loader_cls, _Base)

        # !function constructor should be registered
        constructors = loader_cls.yaml_constructors
        assert "!function" in constructors

    def test_make_loader_caching(self, temp_dir):
        """Loader classes should be cached by parameters."""
        # Clear cache first
        _make_loader.cache_clear()

        loader1 = _make_loader(temp_dir, resolve_funcs=True)
        loader2 = _make_loader(temp_dir, resolve_funcs=True)
        loader3 = _make_loader(temp_dir, resolve_funcs=False)

        assert loader1 is loader2  # Same params = same class
        assert loader1 is not loader3  # Different params = different class


class TestImportFunction:
    """Tests for dynamic function importing with mtime-based module caching."""

    def test_import_local_module(self, temp_dir, python_module):
        # Create a local module
        python_module("def local_func(x, y):\n    return x + y\n")

Baber's avatar
Baber committed
139
        func = _import_func_in_yml("utils.local_func", temp_dir)
Baber's avatar
Baber committed
140
141
142
143
144
145
146
147
148
149
150
151

        assert callable(func)
        assert func(2, 3) == 5

    def test_import_nested_local_module(self, temp_dir):
        """Should handle dot-separated paths for nested modules."""
        # Create nested directory structure
        (temp_dir / "sub").mkdir()
        (temp_dir / "sub" / "module.py").write_text(
            "def nested_func():\n    return 'nested'\n"
        )

Baber's avatar
Baber committed
152
        func = _import_func_in_yml("sub.module.nested_func", temp_dir)
Baber's avatar
Baber committed
153
154
155
156
157
158
159

        assert callable(func)
        assert func() == "nested"

    def test_import_standard_module(self, temp_dir):
        """Falls back to standard import for non-local modules."""
        # Import from standard library
Baber's avatar
Baber committed
160
        func = _import_func_in_yml("os.path.join", temp_dir)
Baber's avatar
Baber committed
161
162
163
164
165
166

        assert callable(func)
        assert func("a", "b") in ("a/b", "a\\b")  # Unix or Windows

    def test_import_caching(self, temp_dir, python_module):
        # Clear cache first
Baber's avatar
Baber committed
167
        _import_func_in_yml.cache_clear()
Baber's avatar
Baber committed
168
169
170

        python_module("def cached_func():\n    return 42\n")

Baber's avatar
Baber committed
171
172
        func1 = _import_func_in_yml("utils.cached_func", temp_dir)
        func2 = _import_func_in_yml("utils.cached_func", temp_dir)
Baber's avatar
Baber committed
173
174
175
176
177
178
179

        assert func1 is func2  # Cached

    def test_import_mtime_sensitivity(self, temp_dir):
        """Verifies LRU cache behavior - file changes require cache clear."""

        # Clear the LRU cache
Baber's avatar
Baber committed
180
        _import_func_in_yml.cache_clear()
Baber's avatar
Baber committed
181
182
183
184
185
186
187

        # Create a module
        module_path = temp_dir / "test_mtime.py"
        module_path.write_text("value = 1\n")

        # Import it
        import_key = "test_mtime.value"
Baber's avatar
Baber committed
188
        value1 = _import_func_in_yml(import_key, temp_dir)
Baber's avatar
Baber committed
189
190
        assert value1 == 1

Baber's avatar
Baber committed
191
        value2 = _import_func_in_yml(import_key, temp_dir)
Baber's avatar
Baber committed
192
193
        assert value2 == 1  # From cache

Baber's avatar
Baber committed
194
195
        _import_func_in_yml.cache_clear()
        value3 = _import_func_in_yml(import_key, temp_dir)
Baber's avatar
Baber committed
196
197
198
        assert value3 == 1  # Re-imported


Baber's avatar
Baber committed
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
class TestImportFunFromStr:
    """Tests for import_fun_from_str function."""

    def test_import_from_absolute_path(self, temp_dir):
        """Test importing function from absolute path."""
        # Create a test module
        module_path = temp_dir / "test_module.py"
        module_path.write_text("def test_func(x):\n    return x * 2\n")

        # Import using absolute path
        func = import_fun_from_str(f"{module_path.with_suffix('')}.test_func")

        assert callable(func)
        assert func(5) == 10

    def test_import_with_py_extension(self, temp_dir):
        """Test importing when .py is included in the path."""
        # Create a test module
        module_path = temp_dir / "test_module.py"
        module_path.write_text("def test_func(x):\n    return x + 10\n")

        # Import with .py in the path
        func = import_fun_from_str(f"{module_path}.test_func")

        assert callable(func)
        assert func(5) == 15

    def test_import_nested_function(self, temp_dir):
        """Test importing from nested module structure."""
        # Create nested directory
        (temp_dir / "subdir").mkdir()
        module_path = temp_dir / "subdir" / "nested.py"
        module_path.write_text("def nested_func():\n    return 'nested'\n")

        # Import from nested path
        func = import_fun_from_str(f"{module_path.with_suffix('')}.nested_func")

        assert callable(func)
        assert func() == "nested"

    def test_import_missing_module(self, temp_dir):
        """Test error when module doesn't exist."""
        with pytest.raises(ImportError, match="Module file not found"):
            import_fun_from_str(f"{temp_dir}/nonexistent.test_func")

    def test_import_missing_function(self, temp_dir):
        """Test error when function doesn't exist in module."""
        module_path = temp_dir / "test_module.py"
        module_path.write_text("def other_func():\n    pass\n")

        with pytest.raises(AttributeError, match="Function 'missing_func' not found"):
            import_fun_from_str(f"{module_path.with_suffix('')}.missing_func")

    def test_import_invalid_format(self):
        """Test error with invalid path format."""
        with pytest.raises(ValueError, match="Invalid path format"):
            import_fun_from_str("/path/without/function")

    def test_import_caching(self, temp_dir):
        """Test that modules are cached by mtime."""
        # Clear any existing cache
        import sys

        keys_to_remove = [k for k in sys.modules if str(temp_dir) in k]
        for k in keys_to_remove:
            del sys.modules[k]

        module_path = temp_dir / "cached_module.py"
        module_path.write_text(
            "call_count = 0\ndef func():\n    global call_count\n    call_count += 1\n    return call_count\n"
        )

        # First import
        func1 = import_fun_from_str(f"{module_path.with_suffix('')}.func")
        _result1 = func1()

        # Second import should use cached module
        func2 = import_fun_from_str(f"{module_path.with_suffix('')}.func")
        result2 = func2()

        # Both should refer to the same module instance
        assert func1 is func2
        assert result2 == 2  # call_count incremented


Baber's avatar
Baber committed
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
class TestLoad:
    """Tests for the main YAML loading function with includes and function resolution."""

    def test_load_simple_yaml(self, yaml_file):
        content = """
task: test_task
description: A test task
metric: accuracy
"""
        file_path = yaml_file(content)

        result = load_yaml(file_path)

        assert result["task"] == "test_task"
        assert result["description"] == "A test task"
        assert result["metric"] == "accuracy"

    def test_load_with_function_resolved(self, yaml_file, python_module):
        # Create a module with a function
        python_module("def process_doc(doc):\n    return doc.upper()\n")

        content = """
task: test_task
doc_to_text: !function utils.process_doc
"""
        file_path = yaml_file(content)

Baber's avatar
Baber committed
311
        result = load_yaml(file_path, resolve_func=True)
Baber's avatar
Baber committed
312
313
314
315
316
317
318
319
320
321
322

        assert callable(result["doc_to_text"])
        assert result["doc_to_text"]("hello") == "HELLO"

    def test_load_with_function_not_resolved(self, yaml_file):
        content = """
task: test_task
doc_to_text: !function utils.process_doc
"""
        file_path = yaml_file(content)

Baber's avatar
Baber committed
323
        result = load_yaml(file_path, resolve_func=False)
Baber's avatar
Baber committed
324

Baber's avatar
Baber committed
325
326
327
328
        assert isinstance(result["doc_to_text"], str)
        # When resolve_functions=False, it returns the full path + function spec
        assert result["doc_to_text"].endswith("utils.process_doc")
        assert result["doc_to_text"] == str(file_path.parent / "utils.process_doc")
Baber's avatar
Baber committed
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347

    def test_load_with_includes(self, temp_dir, yaml_file):
        """Include files are merged with local values taking precedence."""
        # Create included file with shared_value: 42
        included_content = """
shared_metric: f1_score
shared_value: 42
"""
        yaml_file(included_content, "included.yaml")

        # Create main file that also defines shared_value: 100
        main_content = """
include:
  - included.yaml
task: main_task
shared_value: 100
"""
        main_path = yaml_file(main_content, "main.yaml")

Baber's avatar
Baber committed
348
        result = load_yaml(main_path, recursive=True)
Baber's avatar
Baber committed
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370

        assert result["task"] == "main_task"
        assert result["shared_metric"] == "f1_score"
        # Verify main file value (100) overrides included file value (42)
        assert result["shared_value"] == 100  # Local wins
        assert "include" not in result

    def test_load_with_absolute_include(self, temp_dir, yaml_file):
        # Create included file in different directory
        other_dir = temp_dir / "other"
        other_dir.mkdir()
        included_path = other_dir / "included.yaml"
        included_path.write_text("included_key: included_value\n")

        # Create main file with absolute path
        main_content = f"""
include:
  - {included_path}
main_key: main_value
"""
        main_path = yaml_file(main_content)

Baber's avatar
Baber committed
371
        result = load_yaml(main_path, recursive=True)
Baber's avatar
Baber committed
372
373
374
375
376
377
378
379
380
381
382
383

        assert result["main_key"] == "main_value"
        assert result["included_key"] == "included_value"

    def test_load_without_includes_resolution(self, yaml_file):
        content = """
include:
  - other.yaml
task: test_task
"""
        file_path = yaml_file(content)

Baber's avatar
Baber committed
384
        result = load_yaml(file_path, recursive=False)
Baber's avatar
Baber committed
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477

        assert result["include"] == ["other.yaml"]
        assert result["task"] == "test_task"

    def test_load_include_cycle_detection(self, temp_dir, yaml_file):
        """Circular includes should raise ValueError."""
        # Create circular includes
        yaml_file("include:\n  - b.yaml\n", "a.yaml")
        yaml_file("include:\n  - c.yaml\n", "b.yaml")
        yaml_file("include:\n  - a.yaml\n", "c.yaml")

        with pytest.raises(ValueError, match="Include cycle"):
            load_yaml(temp_dir / "a.yaml")

    def test_load_multiple_includes(self, temp_dir, yaml_file):
        """Multiple includes are processed in order, later values override earlier."""
        # Create multiple included files
        yaml_file("key1: value1\n", "inc1.yaml")  # Sets key1 to "value1"
        yaml_file(
            "key2: value2\nmain_key: should_be_ignored\n", "inc2.yaml"
        )  # Tries to set main_key
        yaml_file(
            "key3: value3\nkey1: override\n", "inc3.yaml"
        )  # Overrides key1 to "override"

        # Include order matters: inc3 comes after inc1, so its key1 value wins
        main_content = """
include:
  - inc1.yaml
  - inc2.yaml
  - inc3.yaml
main_key: main_value
"""
        main_path = yaml_file(main_content)

        result = load_yaml(main_path)

        # Verify inc3's value overrides inc1's value for key1
        assert result["key1"] == "override"  # Last include wins
        assert result["key2"] == "value2"
        assert result["key3"] == "value3"
        # Verify main file's value is NOT overridden by inc2.yaml
        assert result["main_key"] == "main_value"  # Main file wins over includes

    def test_load_recursive_includes(self, temp_dir, yaml_file):
        """Includes can be recursive - inc1 can include inc2."""
        # Create inc2.yaml (deepest level)
        yaml_file(
            "deep_key: deep_value\nshared_key: from_inc2\nshared_middle: inc2_middle\n",
            "inc2.yaml",
        )

        # Create inc1.yaml that includes inc2.yaml
        inc1_content = """include:
  - inc2.yaml
middle_key: middle_value
shared_key: from_inc1
shared_middle: inc1_middle
"""
        yaml_file(inc1_content, "inc1.yaml")

        # Create main.yaml that includes inc1.yaml
        main_content = """include:
  - inc1.yaml
top_key: top_value
shared_key: from_main
"""
        main_path = yaml_file(main_content, "main.yaml")

        result = load_yaml(main_path)

        # All keys should be present
        assert result["deep_key"] == "deep_value"  # From inc2
        assert result["middle_key"] == "middle_value"  # From inc1
        assert result["top_key"] == "top_value"  # From main

        # Verify override order: main > inc1 > inc2
        assert result["shared_key"] == "from_main"  # Main wins
        assert result["shared_middle"] == "inc1_middle"  # inc1 wins over inc2
        assert "include" not in result  # Include directives removed

    def test_load_expanduser_path(self, yaml_file):
        """Verifies that load() calls expanduser() on paths with ~."""
        content = "test: value\n"
        file_path = yaml_file(content)

        # Mock expanduser to verify it's called and control the expansion
        with patch.object(Path, "expanduser") as mock_expand:
            mock_expand.return_value = file_path
            result = load_yaml("~/test.yaml")
            mock_expand.assert_called_once()

        assert result["test"] == "value"
Baber's avatar
Baber committed
478
479
480
481


if __name__ == "__main__":
    pytest.main([__file__, "-v", "--tb=short"])