1# Copyright (C) 2023 The Android Open Source Project 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://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, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14import textwrap 15import unittest 16 17from go_allowlists import GoAllowlistManipulator 18 19 20class GoListLocatorTest(unittest.TestCase): 21 def setUp(self) -> None: 22 self.allowlists = GoAllowlistManipulator( 23 textwrap.dedent( 24 """\ 25 import blah 26 package blue 27 type X 28 var ( 29 empty = []string{ 30 } 31 more = []string{ 32 "a", 33 "b", // comment 34 } 35 Bp2buildDefaultConfig = Bp2BuildConfig{ 36 "some_dir": Bp2BuildDefaultFalse 37 } 38 ) 39 """ 40 ).splitlines(keepends=True) 41 ) 42 self.original_size = len(self.allowlists.lines) 43 44 def test_no_existing(self): 45 with self.assertRaises(RuntimeError): 46 self.allowlists.locate("non-existing") 47 48 def test_empty_list(self): 49 empty = self.allowlists.locate("empty") 50 self.assertNotEqual(-1, empty.begin) 51 self.assertNotEqual(-1, empty.end) 52 self.assertEqual(empty.begin, empty.end) 53 self.assertFalse("a" in empty) 54 55 def test_add_to_empty_list(self): 56 empty = self.allowlists.locate("empty") 57 more = self.allowlists.locate("more") 58 begin = more.begin 59 end = more.end 60 empty.prepend(["a-1", "a-2"]) 61 self.assertEqual(2, empty.end - empty.begin) 62 self.assertTrue("a-1" in empty) 63 self.assertTrue("a-2" in empty) 64 self.assertEqual(self.original_size + 2, len(self.allowlists.lines)) 65 with self.subTest("subsequent sibling lists are re-indexed"): 66 self.assertEqual(self.original_size + 2, len(self.allowlists.lines)) 67 self.assertEqual(begin + 2, more.begin) 68 self.assertEqual(end + 2, more.end) 69 70 def test_non_empty_list(self): 71 empty = self.allowlists.locate("empty") 72 begin = empty.begin 73 end = empty.end 74 more = self.allowlists.locate("more") 75 self.assertEqual(2, more.end - more.begin) 76 self.assertTrue("a" in more) 77 self.assertTrue("b" in more) 78 with self.subTest("preceding sibling lists are NOT re-indexed"): 79 self.assertEqual(begin, empty.begin) 80 self.assertEqual(end, empty.end) 81 82 83if __name__ == "__main__": 84 unittest.main() 85