Debian Codegraph @

bin/ci/test/test_update_tag.py

raw
1 import sys
2 import subprocess
3 import yaml
4 import pytest
5
6 from textwrap import dedent
7 from unittest.mock import patch
8
9 from bin.ci.update_tag import (
10 from_component_to_build_tag,
11 filter_components,
12 from_component_to_tag_var,
13 from_script_name_to_component,
14 from_script_name_to_tag_var,
15 load_image_tags_yaml,
16 update_image_tag_in_yaml,
17 run_build_script,
18 main,
19 PATHS,
20 )
21
22
23 @pytest.fixture
24 def temp_image_tags_file(tmp_path, monkeypatch):
25 """
26 Fixture that creates a temporary YAML file (to simulate conditional_tags)
27 and updates the global variable accordingly.
28 """
29 # Create a temporary test file
30 temp_file = tmp_path / "conditional-build-image-tags.yml"
31 temp_file.write_text(yaml.dump({"variables": {}}))
32
33 # Create a copy of the original PATHS values
34 original_conditional_tags = PATHS.conditional_tags
35
36 # Patch the PATHS instance with our test file
37 PATHS.conditional_tags = temp_file
38
39 # Yield the test file for the test to use
40 yield temp_file
41
42 # Restore the original value after the test
43 PATHS.conditional_tags = original_conditional_tags
44
45
46 @pytest.fixture
47 def temp_container_ci_file(tmp_path, monkeypatch):
48 """
49 Fixture that creates a temporary container CI file (to simulate container_ci)
50 and updates the global variable accordingly.
51 """
52 # Create a temporary test file
53 temp_file = tmp_path / "container-ci.yml"
54 temp_file.touch()
55
56 # Create a copy of the original PATHS values
57 original_container_ci = PATHS.container_ci
58
59 # Patch the PATHS instance with our test file
60 PATHS.container_ci = temp_file
61
62 # Yield the test file for the test to use
63 yield temp_file
64
65 # Restore the original value after the test
66 PATHS.container_ci = original_container_ci
67
68
69 @pytest.fixture
70 def mock_container_dir(tmp_path, monkeypatch):
71 """
72 Fixture that creates a dummy container directory and build script.
73 """
74 # Create a dummy container directory
75 container_dir = tmp_path / "container"
76 container_dir.mkdir()
77
78 # Create a dummy setup-test-env.sh file
79 dummy_setup_path = tmp_path / "setup-test-env.sh"
80 dummy_setup_path.write_text("echo Setup")
81
82 # Save original values
83 original_container_dir = PATHS.container_dir
84 original_setup_test_env = PATHS.setup_test_env
85
86 # Patch the PATHS instance
87 PATHS.container_dir = container_dir
88 PATHS.setup_test_env = dummy_setup_path
89
90 # Yield the directory for the test to use
91 yield container_dir
92
93 # Restore original values
94 PATHS.container_dir = original_container_dir
95 PATHS.setup_test_env = original_setup_test_env
96
97
98 @pytest.fixture
99 def mock_build_script(mock_container_dir):
100 """
101 Fixture that creates a dummy build script in the container directory.
102 """
103 build_script = mock_container_dir / "build-foo.sh"
104 return build_script
105
106
107 ###############################################################################
108 # Tests for argument parsing and helper functions
109 ###############################################################################
110
111
112 @pytest.mark.parametrize(
113 "component, expected_tag_var",
114 [
115 ("foo", "FOO_TAG"),
116 ("my-component", "MY_COMPONENT_TAG"),
117 ("foo-bar-baz", "FOO_BAR_BAZ_TAG"),
118 ],
119 )
120 def test_from_component_to_tag_var(component, expected_tag_var):
121 """
122 Test that from_component_to_tag_var returns the correct tag variable name.
123 """
124 assert from_component_to_tag_var(component) == expected_tag_var
125
126
127 @pytest.mark.parametrize(
128 "component, expected_build_tag",
129 [
130 ("foo", "CONDITIONAL_BUILD_FOO_TAG"),
131 ("my-component", "CONDITIONAL_BUILD_MY_COMPONENT_TAG"),
132 ("foo-bar-baz", "CONDITIONAL_BUILD_FOO_BAR_BAZ_TAG"),
133 ],
134 )
135 def test_from_component_to_build_tag(component, expected_build_tag):
136 """
137 Test that from_component_to_build_tag returns the correct build tag name.
138 """
139 assert from_component_to_build_tag(component) == expected_build_tag
140
141
142 @pytest.mark.parametrize(
143 "script_name, expected_component",
144 [
145 ("build-foo.sh", "foo"),
146 ("build-my-component.sh", "my-component"),
147 ("build-foo-bar-baz.sh", "foo-bar-baz"),
148 ],
149 )
150 def test_from_script_name_to_component(script_name, expected_component):
151 """
152 Test that from_script_name_to_component returns the correct component name.
153 """
154 assert from_script_name_to_component(script_name) == expected_component
155
156
157 @pytest.mark.parametrize(
158 "script_name, expected_tag_var",
159 [
160 ("build-foo.sh", "FOO_TAG"),
161 ("build-my-component.sh", "MY_COMPONENT_TAG"),
162 ("build-foo-bar-baz.sh", "FOO_BAR_BAZ_TAG"),
163 ],
164 )
165 def test_from_script_name_to_tag_var(script_name, expected_tag_var):
166 """
167 Test that from_script_name_to_tag_var returns the correct tag variable name.
168 """
169 assert from_script_name_to_tag_var(script_name) == expected_tag_var
170
171
172 def test_filter_components():
173 """
174 Test that filter_components returns only components that match an include regex
175 and do not match any exclude regex. If includes is empty, an empty list is returned.
176 """
177 components = ["alpha", "beta", "gamma", "delta"]
178
179 # When includes is empty, should return an empty list.
180 assert filter_components(components, [], []) == []
181
182 # Test includes only.
183 # Components that start with 'a' or 'b'
184 expected = ["alpha", "beta"]
185 result = filter_components(components, ["^[a-b].*$"], [])
186 assert result == expected
187
188 # Test with an exclude that filters out "alpha" (which matches "lph").
189 result = filter_components(components, ["^[a-b].*$"], ["^.*lph.*$"])
190 # "alpha" is removed.
191 assert result == ["beta"]
192
193
194 @pytest.mark.parametrize(
195 "component, tag",
196 [
197 # Basic case
198 ("test", "new_tag"),
199 # Component with hyphen
200 ("my-component", "v1.2.3"),
201 # Uppercase component name
202 ("UpperCase", "123"),
203 # Numbers in component name
204 ("123service", "build-456"),
205 ],
206 )
207 def test_update_image_tag_in_yaml(component, tag, temp_image_tags_file):
208 """
209 Test multiple updates with different component names and tags, verifying:
210 1. Correct variable name generation
211 2. Proper tag value storage
212 3. Maintained sorting of variables
213 """
214 # Initial update
215 update_image_tag_in_yaml(component, tag)
216
217 data = load_image_tags_yaml()
218 expected_var = from_component_to_build_tag(component)
219 assert data["variables"][expected_var] == tag
220
221 # Add second component and verify both exist
222 update_image_tag_in_yaml("another_component", "secondary_tag")
223 updated_data = load_image_tags_yaml()
224
225 assert from_component_to_build_tag("another_component") in updated_data["variables"]
226 assert updated_data["variables"][expected_var] == tag # Original value remains
227
228 # Verify sorting
229 variables = list(data["variables"].keys())
230 assert len(updated_data["variables"]) == len(variables) + 1
231 assert variables == sorted(variables), "Variables are not alphabetically sorted"
232
233
234 def test_if_run_extracts_the_tag_from_stdout(monkeypatch, mock_build_script):
235 """
236 Test that run_build_script returns the tag (last stdout line) when the build
237 script executes successfully.
238 """
239 mock_build_script.write_text("#!/bin/bash\necho Build script\necho new_tag")
240 # Create a fake subprocess.CompletedProcess to simulate a successful build.
241 fake_result = subprocess.CompletedProcess(
242 args=[], returncode=0, stdout="line1\nnew_tag", stderr=""
243 )
244 monkeypatch.setattr(subprocess, "run", lambda *args, **kwargs: fake_result)
245
246 tag = run_build_script("foo", check_only=False)
247 assert tag == "new_tag"
248
249
250 def test_running_real_process_works(monkeypatch, mock_build_script):
251 """
252 Test that run_build_script returns the tag (last stdout line) when the build
253 script executes successfully.
254 """
255 mock_build_script.write_text("echo Build script\necho new_tag")
256 tag = run_build_script("foo", check_only=False)
257 assert tag == "new_tag"
258
259
260 ###############################################################################
261 # Tests for main() argument features
262 ###############################################################################
263
264
265 def setup_build_script_and_container_ci_file(container_dir, container_ci_file, comp):
266 tag_var = from_component_to_build_tag(comp)
267 build_check_var = from_component_to_tag_var(comp)
268 build_script_path = container_dir / f"build-{comp}.sh"
269 build_script_path.write_text(
270 dedent(
271 f"""
272 #!/bin/bash
273 ci_tag_build_time_check {tag_var}
274 echo "new_tag"
275 """
276 )
277 )
278 container_ci_file.write_text(
279 container_ci_file.read_text()
280 + dedent(
281 f"""
282 .container-builds-{comp}:
283 variables:
284 {tag_var}: "${{{build_check_var}}}"
285 """
286 )
287 )
288
289
290 def test_main_list(monkeypatch, capsys, mock_container_dir, temp_container_ci_file):
291 """
292 Test that when the --list argument is provided, main() prints all detected
293 components
294 """
295 # Monkeypatch find_components to return a known list.
296 for comp in ["comp-a", "comp-b"]:
297 setup_build_script_and_container_ci_file(mock_container_dir, temp_container_ci_file, comp)
298 # Set sys.argv to simulate passing --list.
299 monkeypatch.setattr(sys, "argv", ["bin/ci/update_tag.py", "--list"])
300
301 main()
302
303 captured = capsys.readouterr().out
304 assert "Detected components:" in captured
305 assert "comp-a" in captured
306 assert "comp-b" in captured
307
308
309 def test_main_check(monkeypatch, temp_image_tags_file, temp_container_ci_file):
310 """
311 Test that when --check is provided, main() calls run_build_script in check mode.
312 """
313
314 with patch(
315 "bin.ci.update_tag.run_build_script", return_value="dummy_tag"
316 ) as mock_run_build_script:
317 # Simulate command line: --check compX
318 monkeypatch.setattr(sys, "argv", ["bin/ci/update_tag.py", "--check", "comp-x"])
319
320 main()
321 # Verify run_build_script was called with check_only=True.
322 assert mock_run_build_script.call_count == 1
323 assert "comp-x" in mock_run_build_script.call_args.args[0]
324 assert mock_run_build_script.call_args.kwargs["check_only"] is True
325
326
327 EXIT_CODE_SCENARIOS = {
328 "unbound_variable": (
329 "line 2: UNDEFINED_VARIABLE: unbound variable",
330 127,
331 3,
332 "Please set the variable UNDEFINED_VARIABLE",
333 ),
334 "build script error": (
335 "",
336 50,
337 50,
338 "",
339 ),
340 "tag_mismatch": (
341 "Tag mismatch for foo.",
342 2,
343 2,
344 "Tag mismatch for foo.",
345 ),
346 }
347
348
349 @pytest.mark.parametrize(
350 "stderr_content, script_returncode, expected_exit_code, expected_error_message",
351 EXIT_CODE_SCENARIOS.values(),
352 ids=list(EXIT_CODE_SCENARIOS.keys()),
353 )
354 def test_build_script_error_exit_codes(
355 monkeypatch,
356 mock_build_script,
357 capsys,
358 stderr_content,
359 script_returncode,
360 expected_exit_code,
361 expected_error_message,
362 ):
363 """
364 Test that build script errors generate appropriate exit codes:
365 1 - Unhandled error in this script
366 2 - Tag mismatch when using --check
367 3 - Unbound variable error in build script
368 x - Build script failed with return code x
369 """
370 # Create a build script that will fail
371 mock_build_script.write_text("#!/bin/bash\necho 'This will fail'")
372
373 # Create a fake subprocess.CompletedProcess to simulate a failed build
374 fake_result = subprocess.CompletedProcess(
375 args=[], returncode=script_returncode, stdout="", stderr=stderr_content
376 )
377 monkeypatch.setattr(subprocess, "run", lambda *args, **kwargs: fake_result)
378 monkeypatch.setattr(sys, "argv", ["bin/ci/update_tag.py", "--check", "foo"])
379 monkeypatch.setattr("bin.ci.update_tag.get_current_tag_value", lambda *args: "current_tag")
380
381 # Mock sys.exit to capture the exit code instead of exiting the test
382 with pytest.raises(SystemExit) as e:
383 main()
384
385 # Check for expected error message if one is specified
386 if expected_error_message:
387 captured = capsys.readouterr()
388 assert expected_error_message in captured.err
389
390 # Verify correct exit code
391 assert e.value.code == expected_exit_code