Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
79
80
81
82
83
84
85
86
87
88
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
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
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""End-to-end tests for the top-level build() orchestrator.
 
Combines focused unit tests with a fixture-driven runner over the
``build-*`` cases in ``testcases/``. Generated files are compared
against the ``expected/<generator>/`` golden tree using
``canonicalize`` (content-equivalence, not byte-for-byte), so
host-dependent ``__str_N`` numbering / ordering / sha256 markers don't
cause spurious failures. See ``golden_compare.py``.
"""
 
from __future__ import annotations
 
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
 
_THIS_DIR = Path(__file__).resolve().parent
_PARENT_DIR = _THIS_DIR.parent.parent
if str(_PARENT_DIR) not in sys.path:
    sys.path.insert(0, str(_PARENT_DIR))
 
from golden_compare import canonicalize, read_tree  # noqa: E402
from wgsl_template import build  # noqa: E402
from wgsl_template.errors import WgslTemplateError  # noqa: E402
from wgsl_template.types import SourceDir  # noqa: E402
 
_TESTCASES_DIR = _THIS_DIR / "testcases"
 
_SUPPORTED_GENERATORS = {"static-cpp", "static-cpp-literal"}
 
 
def _write(path: Path, content: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(content.encode("utf-8"))
 
 
def _walk_files(root: Path) -> list[str]:
    """Return every file under ``root`` as a sorted POSIX path
    relative to ``root``."""
    out: list[str] = []
    for dirpath, _dirs, files in os.walk(root):
        for f in files:
            full = Path(dirpath) / f
            out.append(full.relative_to(root).as_posix())
    out.sort()
    return out
 
 
# ----------------------------------------------------------------------
# Focused unit tests
# ----------------------------------------------------------------------
 
 
class BuildIdempotentWriteTest(unittest.TestCase):
    def test_variable_dereference_is_deferred_until_use(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            src = root / "src"
            out = root / "out"
            _write(
                src / "conditional.wgsl.template",
                "#use .rank\n#param has_output\n#if has_output\nlet rank = output.rank;\n#endif\n",
            )
 
            build(source_dirs=[src], out_dir=out, generator="static-cpp-literal")
            generated = (out / "generated/conditional.h").read_text(encoding="utf-8")
 
            self.assertIn("auto* __var_output = params.var_output;", generated)
            self.assertNotIn("*params.var_output", generated)
            self.assertIn("if (__param_has_output) {", generated)
            self.assertIn("__var_output->Rank()", generated)
 
    def test_unchanged_file_is_not_rewritten(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            src = root / "src"
            out = root / "out"
            _write(src / "a.wgsl.template", "a\n")
 
            # First build.
            build(
                source_dirs=[src],
                out_dir=out,
                generator="static-cpp-literal",
            )
            mtimes_before = {p: (out / p).stat().st_mtime_ns for p in _walk_files(out)}
            self.assertTrue(mtimes_before, "expected files in output dir")
 
            # Second build with identical sources — files must not be rewritten.
            build(
                source_dirs=[src],
                out_dir=out,
                generator="static-cpp-literal",
            )
            mtimes_after = {p: (out / p).stat().st_mtime_ns for p in _walk_files(out)}
            self.assertEqual(mtimes_before, mtimes_after)
 
    def test_changed_file_is_rewritten(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            src = root / "src"
            out = root / "out"
            _write(src / "a.wgsl.template", "a\n")
 
            build(source_dirs=[src], out_dir=out, generator="static-cpp-literal")
            content_before = (out / "generated/a.h").read_bytes()
 
            _write(src / "a.wgsl.template", "completely different\n")
            build(source_dirs=[src], out_dir=out, generator="static-cpp-literal")
            content_after = (out / "generated/a.h").read_bytes()
 
            self.assertNotEqual(content_before, content_after)
 
 
class BuildCleanFlagTest(unittest.TestCase):
    def test_clean_removes_existing_files(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            src = root / "src"
            out = root / "out"
            _write(src / "a.wgsl.template", "a\n")
            _write(out / "stale.h", "STALE\n")
 
            build(source_dirs=[src], out_dir=out, generator="static-cpp-literal", clean=True)
            self.assertFalse((out / "stale.h").exists())
            self.assertTrue((out / "generated/a.h").exists())
 
 
class BuildErrorsTest(unittest.TestCase):
    def test_empty_source_dirs_raises(self) -> None:
        with self.assertRaises(WgslTemplateError):
            build(source_dirs=[], out_dir="/tmp/anywhere")
 
 
# ----------------------------------------------------------------------
# Fixture-driven tests against the build-* cases
# ----------------------------------------------------------------------
 
 
def _build_fixture_suite() -> unittest.TestSuite:
    suite = unittest.TestSuite()
    if not _TESTCASES_DIR.is_dir():
        return suite
 
    for entry in sorted(os.listdir(_TESTCASES_DIR)):
        case_dir = _TESTCASES_DIR / entry
        if not case_dir.is_dir():
            continue
        if not entry.startswith("build-"):
            continue
        config_path = case_dir / "test-config.json"
        if not config_path.is_file():
            continue
        try:
            config = json.loads(config_path.read_text(encoding="utf-8"))
        except json.JSONDecodeError:
            continue
        if config.get("disabled"):
            continue
        if config.get("type") != "build":
            continue
 
        # Filter generators down to ones we support.
        gen_cfg = config.get("generators") or {}
        applicable = {name: cfg for name, cfg in gen_cfg.items() if name in _SUPPORTED_GENERATORS}
        if not applicable:
            continue
 
        case_class = _make_build_case(case_dir, config, applicable)
        suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(case_class))
    return suite
 
 
def _make_build_case(case_dir: Path, config: dict, applicable: dict) -> type:
    case_name = case_dir.name
    template_ext = config.get("templateExt") or ".wgsl.template"
    source_dirs_cfg = config.get("sourceDirs")
 
    class _Case(unittest.TestCase):
        def __init__(self, methodName: str = "runTest") -> None:
            super().__init__(methodName)
            self._dir = case_dir
            self._template_ext = template_ext
            self._source_dirs_cfg = source_dirs_cfg
            self._applicable = applicable
 
        def __str__(self) -> str:
            return f"fixture[{case_name}]"
 
        def runTest(self) -> None:  # noqa: N802
            src_dir = self._dir / "src"
            expected_dir = self._dir / "expected"
            self.assertTrue(src_dir.is_dir(), f"missing src dir: {src_dir}")
            self.assertTrue(expected_dir.is_dir(), f"missing expected dir: {expected_dir}")
 
            for gen_name, gen_cfg in self._applicable.items():
                with tempfile.TemporaryDirectory() as tmp:
                    out_dir = Path(tmp)
 
                    if self._source_dirs_cfg:
                        sources: list = []
                        for d in self._source_dirs_cfg:
                            if isinstance(d, str):
                                sources.append(src_dir / d)
                            else:
                                sources.append(
                                    SourceDir(
                                        path=str(src_dir / d["path"]),
                                        alias=d.get("alias"),
                                    )
                                )
                    else:
                        sources = [src_dir]
 
                    expects_error = gen_cfg.get("expectsError")
                    try:
                        build(
                            source_dirs=sources,
                            out_dir=out_dir,
                            template_ext=self._template_ext,
                            generator=gen_name,
                        )
                    except Exception as e:
                        if expects_error:
                            if isinstance(expects_error, str):
                                self.assertIn(expects_error, str(e))
                            return
                        raise
 
                    if expects_error:
                        self.fail(f"{gen_name}: expected error containing {expects_error!r} but build succeeded")
 
                    expected_gen = expected_dir / gen_name
                    self.assertTrue(
                        expected_gen.is_dir(),
                        f"missing expected/{gen_name} dir for {case_name}",
                    )
 
                    actual_files = _walk_files(out_dir)
                    expected_files = _walk_files(expected_gen)
 
                    self.assertEqual(
                        actual_files,
                        expected_files,
                        f"{case_name} ({gen_name}): file set mismatch\n"
                        f"actual:   {actual_files}\n"
                        f"expected: {expected_files}",
                    )
 
                    # Compare in canonical form (see golden_compare).
                    actual_canon = canonicalize(read_tree(out_dir))
                    expected_canon = canonicalize(read_tree(expected_gen))
 
                    for rel in expected_files:
                        self.assertEqual(
                            actual_canon[rel],
                            expected_canon[rel],
                            f"{case_name} ({gen_name}): {rel} differs (after canonicalization)\n"
                            f"actual:\n{actual_canon[rel]!r}\n"
                            f"expected:\n{expected_canon[rel]!r}",
                        )
 
    _Case.__name__ = f"BuildFixture_{case_name.replace('-', '_')}"
    _Case.__qualname__ = _Case.__name__
    return _Case
 
 
def load_tests(loader, standard_tests, pattern):
    standard_tests.addTests(_build_fixture_suite())
    return standard_tests
 
 
if __name__ == "__main__":  # pragma: no cover
    unittest.main(verbosity=2)