1# Copyright 2023 The Bazel Authors. All rights reserved. 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. 14 15import unittest 16 17from tools.private.update_deps.update_file import replace_snippet, unified_diff 18 19 20class TestReplaceSnippet(unittest.TestCase): 21 def test_replace_simple(self): 22 current = """\ 23Before the snippet 24 25# Start marker 26To be replaced 27It may have the '# Start marker' or '# End marker' in the middle, 28But it has to be in the beginning of the line to mark the end of a region. 29# End marker 30 31After the snippet 32""" 33 snippet = "Replaced" 34 got = replace_snippet( 35 current=current, 36 snippet="Replaced", 37 start_marker="# Start marker", 38 end_marker="# End marker", 39 ) 40 41 want = """\ 42Before the snippet 43 44# Start marker 45Replaced 46# End marker 47 48After the snippet 49""" 50 self.assertEqual(want, got) 51 52 def test_replace_indented(self): 53 current = """\ 54Before the snippet 55 56 # Start marker 57 To be replaced 58 # End marker 59 60After the snippet 61""" 62 got = replace_snippet( 63 current=current, 64 snippet=" Replaced", 65 start_marker="# Start marker", 66 end_marker="# End marker", 67 ) 68 69 want = """\ 70Before the snippet 71 72 # Start marker 73 Replaced 74 # End marker 75 76After the snippet 77""" 78 self.assertEqual(want, got) 79 80 def test_raises_if_start_is_not_found(self): 81 with self.assertRaises(RuntimeError) as exc: 82 replace_snippet( 83 current="foo", 84 snippet="", 85 start_marker="start", 86 end_marker="end", 87 ) 88 89 self.assertEqual(exc.exception.args[0], "Start marker 'start' was not found") 90 91 def test_raises_if_end_is_not_found(self): 92 with self.assertRaises(RuntimeError) as exc: 93 replace_snippet( 94 current="start", 95 snippet="", 96 start_marker="start", 97 end_marker="end", 98 ) 99 100 self.assertEqual(exc.exception.args[0], "End marker 'end' was not found") 101 102 103class TestUnifiedDiff(unittest.TestCase): 104 def test_diff(self): 105 give_a = """\ 106First line 107second line 108Third line 109""" 110 give_b = """\ 111First line 112Second line 113Third line 114""" 115 got = unified_diff("filename", give_a, give_b) 116 want = """\ 117--- a/filename 118+++ b/filename 119@@ -1,3 +1,3 @@ 120 First line 121-second line 122+Second line 123 Third line""" 124 self.assertEqual(want, got) 125 126 127if __name__ == "__main__": 128 unittest.main() 129