blob: 9da2f4b09c5d6dcd7cc4d9aeff8e46dae4a73dcb [file] [log] [blame]
Ryan Beltran179d6bb2023-09-14 23:37:33 +00001# Copyright 2023 The ChromiumOS Authors
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Unit tests for lint_package script."""
6
7from chromite.lib import cros_test_lib
8from chromite.scripts import lint_package
9from chromite.service import toolchain
10
11
12class TestApplyFixes(cros_test_lib.MockTempDirTestCase):
13 """Unit tests for --apply-fixes."""
14
15 def fix_from_offsets(self, start, end, path="", edit=""):
16 return toolchain.SuggestedFix(
17 edit, toolchain.CodeLocation(path, "", 0, 0, None, None, start, end)
18 )
19
20 def fix_to_offsets(self, fix):
21 return (fix.location.start_offset, fix.location.end_offset)
22
23 def testHasOverlap(self):
24 prior_fixes = [
25 self.fix_from_offsets(0, 5),
26 self.fix_from_offsets(10, 15),
27 self.fix_from_offsets(20, 25),
28 self.fix_from_offsets(30, 30),
29 ]
30 no_overlaps = [
31 self.fix_from_offsets(40, 45),
32 self.fix_from_offsets(50, 55),
33 self.fix_from_offsets(60, 65),
34 self.fix_from_offsets(70, 70),
35 ]
36 overlaps = [
37 self.fix_from_offsets(0, 2),
38 self.fix_from_offsets(10, 10),
39 self.fix_from_offsets(25, 25),
40 self.fix_from_offsets(22, 902),
41 self.fix_from_offsets(30, 30),
42 self.fix_from_offsets(5, 5),
43 ]
44 prior_fixes_str = str([self.fix_to_offsets(f) for f in prior_fixes])
45 for fix in no_overlaps:
46 self.assertFalse(
47 lint_package.has_overlap(prior_fixes, [fix]),
48 "has_overlap returned true unepectedly for "
49 f"{self.fix_to_offsets(fix)} in {prior_fixes_str}",
50 )
51 for fix in overlaps:
52 self.assertTrue(
53 lint_package.has_overlap(prior_fixes, [fix]),
54 "has_overlap returned false unexpectedly for "
55 f"{self.fix_to_offsets(fix)} in {prior_fixes_str}",
56 )
57
58 self.assertTrue(
59 lint_package.has_overlap(prior_fixes, overlaps + no_overlaps)
60 )
61
62 self.assertTrue(
63 lint_package.has_overlap(prior_fixes, no_overlaps + overlaps)
64 )
65
66 def testApplyEdits(self):
67 prior_contents = "0123456789" * 5
68 edits = [
69 self.fix_from_offsets(0, 5, edit="abc"),
70 self.fix_from_offsets(8, 9, edit=""),
71 self.fix_from_offsets(10, 15, edit="hello world"),
72 self.fix_from_offsets(20, 25, edit=""),
73 self.fix_from_offsets(30, 30, edit="foo"),
74 self.fix_from_offsets(43, 48, edit="spam spam"),
75 ]
76 expected = (
77 "abc5679"
78 + "hello world56789"
79 + "56789"
80 + "foo0123456789"
81 + "012spam spam89"
82 )
83 self.assertEqual(
84 lint_package.apply_edits(prior_contents, edits), expected
85 )