1# Copyright 2024 The Pigweed Authors 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); you may not 4# use this file except in compliance with the License. You may obtain a copy of 5# the License at 6# 7# https://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12# License for the specific language governing permissions and limitations under 13# the License. 14"""Unit tests for bazel_checks.py.""" 15 16import os 17import pathlib 18import shutil 19import tempfile 20import unittest 21from unittest import mock 22 23from pw_presubmit import presubmit, build, bazel_checks 24 25 26def _write_two_targets_to_stdout(*args, stdout=None, **kwargs): 27 del args, kwargs # Unused. 28 if stdout is None: 29 return 30 31 stdout.write("//one:target\n//other:target\n") 32 33 34def _write_nothing_to_stdout(*args, stdout=None, **kwargs): 35 del args, kwargs # Unused. 36 if stdout is None: 37 return 38 stdout.close() 39 40 41class IncludePresubmitCheckTest(unittest.TestCase): 42 """Tests of the include_presubmit_check.""" 43 44 def setUp(self): 45 fd, self.failure_summary_log = tempfile.mkstemp() 46 os.close(fd) 47 self.output_dir = tempfile.mkdtemp() 48 49 self.ctx = mock.MagicMock() 50 self.ctx.failed = False 51 self.ctx.failure_summary_log = pathlib.Path(self.failure_summary_log) 52 self.ctx.output_dir = pathlib.Path(self.output_dir) 53 54 def tearDown(self): 55 os.remove(self.failure_summary_log) 56 shutil.rmtree(self.output_dir) 57 58 @mock.patch.object( 59 build, 'bazel', autospec=True, side_effect=_write_two_targets_to_stdout 60 ) 61 def test_query_returns_two_targets(self, _): 62 check = bazel_checks.includes_presubmit_check('//...') 63 self.assertEqual(check(self.ctx), presubmit.PresubmitResult.FAIL) 64 self.assertIn('//one:target', self.ctx.failure_summary_log.read_text()) 65 self.assertIn( 66 '//other:target', self.ctx.failure_summary_log.read_text() 67 ) 68 69 @mock.patch.object( 70 build, 'bazel', autospec=True, side_effect=_write_nothing_to_stdout 71 ) 72 def test_query_returns_nothing(self, _): 73 check = bazel_checks.includes_presubmit_check('//...') 74 self.assertEqual(check(self.ctx), presubmit.PresubmitResult.PASS) 75 self.assertNotIn( 76 '//one:target', self.ctx.failure_summary_log.read_text() 77 ) 78 self.assertNotIn( 79 '//other:target', self.ctx.failure_summary_log.read_text() 80 ) 81 82 83if __name__ == "__main__": 84 unittest.main() 85