aboutsummaryrefslogtreecommitdiff
path: root/pw_presubmit/py/keep_sorted_test.py
blob: 8d1742a7e1821736326e461e96dec690e93b53ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
#!/usr/bin/env python3
# Copyright 2022 The Pigweed Authors
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
"""Tests for keep_sorted."""

from pathlib import Path
import tempfile
import textwrap
from typing import Dict, Sequence
import unittest
from unittest.mock import MagicMock

from pw_presubmit import keep_sorted

# Only include these literals here so keep_sorted doesn't try to reorder later
# test lines.
START = keep_sorted.START
END = keep_sorted.END

# pylint: disable=attribute-defined-outside-init
# pylint: disable=too-many-public-methods


class TestKeepSorted(unittest.TestCase):
    """Test KeepSorted class"""

    def _run(self, contents: str) -> None:
        self.ctx = MagicMock()
        self.ctx.fail = MagicMock()

        with tempfile.TemporaryDirectory() as tempdir:
            path = Path(tempdir) / 'foo'

            with path.open('w') as outs:
                outs.write(contents)

            self.errors: Dict[Path, Sequence[str]] = {}

            # pylint: disable=protected-access
            self.sorter = keep_sorted._FileSorter(self.ctx, path, self.errors)

            # pylint: enable=protected-access

            self.sorter.sort()

            # Truncate the file so it's obvious whether write() changed
            # anything.
            with path.open('w') as outs:
                outs.write('')

            self.sorter.write(path)
            with path.open() as ins:
                self.contents = ins.read()

    def assert_errors(self):
        self.assertTrue(self.errors)

    def assert_no_errors(self):
        self.assertFalse(self.errors)

    def test_missing_end(self) -> None:
        with self.assertRaises(keep_sorted.KeepSortedParsingError):
            self._run(f'{START}\n')

    def test_missing_start(self) -> None:
        with self.assertRaises(keep_sorted.KeepSortedParsingError):
            self._run(f'{END}: end\n')

    def test_repeated_start(self) -> None:
        with self.assertRaises(keep_sorted.KeepSortedParsingError):
            self._run(f'{START}\n{START}\n')

    def test_unrecognized_directive(self) -> None:
        with self.assertRaises(keep_sorted.KeepSortedParsingError):
            self._run(f'{START} foo bar baz\n2\n1\n{END}\n')

    def test_repeated_valid_directive(self) -> None:
        with self.assertRaises(keep_sorted.KeepSortedParsingError):
            self._run(f'{START} ignore-case ignore-case\n2\n1\n{END}\n')

    def test_already_sorted(self) -> None:
        self._run(f'{START}\n1\n2\n3\n4\n{END}\n')
        self.assert_no_errors()
        self.assertEqual(self.contents, '')

    def test_not_sorted(self) -> None:
        self._run(f'{START}\n4\n3\n2\n1\n{END}\n')
        self.assert_errors()
        self.assertEqual(self.contents, f'{START}\n1\n2\n3\n4\n{END}\n')

    def test_prefix_sorted(self) -> None:
        self._run(f'foo\nbar\n{START}\n1\n2\n{END}\n')
        self.assert_no_errors()
        self.assertEqual(self.contents, '')

    def test_prefix_not_sorted(self) -> None:
        self._run(f'foo\nbar\n{START}\n2\n1\n{END}\n')
        self.assert_errors()
        self.assertEqual(self.contents, f'foo\nbar\n{START}\n1\n2\n{END}\n')

    def test_suffix_sorted(self) -> None:
        self._run(f'{START}\n1\n2\n{END}\nfoo\nbar\n')
        self.assert_no_errors()
        self.assertEqual(self.contents, '')

    def test_suffix_not_sorted(self) -> None:
        self._run(f'{START}\n2\n1\n{END}\nfoo\nbar\n')
        self.assert_errors()
        self.assertEqual(self.contents, f'{START}\n1\n2\n{END}\nfoo\nbar\n')

    def test_not_sorted_case_sensitive(self) -> None:
        self._run(f'{START}\na\nD\nB\nc\n{END}\n')
        self.assert_errors()
        self.assertEqual(self.contents, f'{START}\nB\nD\na\nc\n{END}\n')

    def test_not_sorted_case_insensitive(self) -> None:
        self._run(f'{START} ignore-case\na\nD\nB\nc\n{END}\n')
        self.assert_errors()
        self.assertEqual(
            self.contents, f'{START} ignore-case\na\nB\nc\nD\n{END}\n'
        )

    def test_remove_dupes(self) -> None:
        self._run(f'{START}\n1\n2\n2\n1\n{END}\n')
        self.assert_errors()
        self.assertEqual(self.contents, f'{START}\n1\n2\n{END}\n')

    def test_allow_dupes(self) -> None:
        self._run(f'{START} allow-dupes\n1\n2\n2\n1\n{END}\n')
        self.assert_errors()
        self.assertEqual(
            self.contents, f'{START} allow-dupes\n1\n1\n2\n2\n{END}\n'
        )

    def test_case_insensitive_dupes(self) -> None:
        self._run(f'{START} ignore-case\na\nB\nA\n{END}\n')
        self.assert_errors()
        self.assertEqual(
            self.contents, f'{START} ignore-case\nA\na\nB\n{END}\n'
        )

    def test_ignored_prefixes(self) -> None:
        self._run(f'{START} ignore-prefix=foo,bar\na\nb\nfoob\nbarc\n{END}\n')
        self.assert_no_errors()

    def test_ignored_longest_prefixes(self) -> None:
        self._run(f'{START} ignore-prefix=1,123\na\n123b\nb\n1c\n{END}\n')
        self.assert_no_errors()

    def test_ignored_prefixes_whitespace(self) -> None:
        self._run(
            f'{START} ignore-prefix=foo,bar\n' f' a\n b\n foob\n barc\n{END}\n'
        )
        self.assert_no_errors()

    def test_ignored_prefixes_insensitive(self) -> None:
        self._run(
            f'{START} ignore-prefix=foo,bar ignore-case\n'
            f'a\nB\nfooB\nbarc\n{END}\n'
        )
        self.assert_no_errors()

    def test_python_comment_marks_sorted(self) -> None:
        self._run(f'# {START}\n1\n2\n# {END}\n')
        self.assert_no_errors()

    def test_python_comment_marks_not_sorted(self) -> None:
        self._run(f'# {START}\n2\n1\n# {END}\n')
        self.assert_errors()
        self.assertEqual(self.contents, f'# {START}\n1\n2\n# {END}\n')

    def test_python_comment_sticky_sorted(self) -> None:
        self._run(f'# {START}\n# A\n1\n2\n# {END}\n')
        self.assert_no_errors()

    def test_python_comment_sticky_not_sorted(self) -> None:
        self._run(f'# {START}\n2\n# A\n1\n# {END}\n')
        self.assert_errors()
        self.assertEqual(self.contents, f'# {START}\n# A\n1\n2\n# {END}\n')

    def test_python_comment_sticky_disabled(self) -> None:
        self._run(f'# {START} sticky-comments=no\n1\n# B\n2\n# {END}\n')
        self.assert_errors()
        self.assertEqual(
            self.contents, f'# {START} sticky-comments=no\n# B\n1\n2\n# {END}\n'
        )

    def test_cpp_comment_marks_sorted(self) -> None:
        self._run(f'// {START}\n1\n2\n// {END}\n')
        self.assert_no_errors()

    def test_cpp_comment_marks_not_sorted(self) -> None:
        self._run(f'// {START}\n2\n1\n// {END}\n')
        self.assert_errors()
        self.assertEqual(self.contents, f'// {START}\n1\n2\n// {END}\n')

    def test_cpp_comment_sticky_sorted(self) -> None:
        self._run(f'// {START}\n1\n// B\n2\n// {END}\n')
        self.assert_no_errors()

    def test_cpp_comment_sticky_not_sorted(self) -> None:
        self._run(f'// {START}\n// B\n2\n1\n// {END}\n')
        self.assert_errors()
        self.assertEqual(self.contents, f'// {START}\n1\n// B\n2\n// {END}\n')

    def test_cpp_comment_sticky_disabled(self) -> None:
        self._run(f'// {START} sticky-comments=no\n1\n// B\n2\n// {END}\n')
        self.assert_errors()
        self.assertEqual(
            self.contents,
            f'// {START} sticky-comments=no\n// B\n1\n2\n// {END}\n',
        )

    def test_custom_comment_sticky_sorted(self) -> None:
        self._run(f'{START} sticky-comments=%\n1\n% B\n2\n{END}\n')
        self.assert_no_errors()

    def test_custom_comment_sticky_not_sorted(self) -> None:
        self._run(f'{START} sticky-comments=%\n% B\n2\n1\n{END}\n')
        self.assert_errors()
        self.assertEqual(
            self.contents, f'{START} sticky-comments=%\n1\n% B\n2\n{END}\n'
        )

    def test_multiline_comment_sticky_sorted(self) -> None:
        self._run(f'# {START}\n# B\n# A\n1\n2\n# {END}\n')
        self.assert_no_errors()

    def test_multiline_comment_sticky_not_sorted(self) -> None:
        self._run(f'# {START}\n# B\n# A\n2\n1\n# {END}\n')
        self.assert_errors()
        self.assertEqual(self.contents, f'# {START}\n1\n# B\n# A\n2\n# {END}\n')

    def test_comment_sticky_sorted_fallback_sorted(self) -> None:
        self._run(f'# {START}\n# A\n1\n# B\n1\n# {END}\n')
        self.assert_no_errors()

    def test_comment_sticky_sorted_fallback_not_sorted(self) -> None:
        self._run(f'# {START}\n# B\n1\n# A\n1\n# {END}\n')
        self.assert_errors()
        self.assertEqual(self.contents, f'# {START}\n# A\n1\n# B\n1\n# {END}\n')

    def test_comment_sticky_sorted_fallback_dupes(self) -> None:
        self._run(f'# {START} allow-dupes\n# A\n1\n# A\n1\n# {END}\n')
        self.assert_no_errors()

    def test_different_comment_sticky_not_sorted(self) -> None:
        self._run(f'# {START} sticky-comments=%\n% A\n1\n# B\n2\n# {END}\n')
        self.assert_errors()
        self.assertEqual(
            self.contents,
            f'# {START} sticky-comments=%\n# B\n% A\n1\n2\n# {END}\n',
        )

    def test_continuation_sorted(self) -> None:
        initial = textwrap.dedent(
            f"""
            # {START}
            baz
             abc
            foo
              bar
            # {END}
            """.lstrip(
                '\n'
            )
        )

        self._run(initial)
        self.assert_no_errors()

    def test_continuation_not_sorted(self) -> None:
        initial = textwrap.dedent(
            f"""
            # {START}
            foo
              bar
            baz
             abc
            # {END}
            """.lstrip(
                '\n'
            )
        )

        expected = textwrap.dedent(
            f"""
            # {START}
            baz
             abc
            foo
              bar
            # {END}
            """.lstrip(
                '\n'
            )
        )

        self._run(initial)
        self.assert_errors()
        self.assertEqual(self.contents, expected)

    def test_indented_continuation_sorted(self) -> None:
        # Intentionally not using textwrap.dedent().
        initial = f"""
        # {START}
        baz
         abc
        foo
          bar
        # {END}""".lstrip(
            '\n'
        )

        self._run(initial)
        self.assert_no_errors()

    def test_indented_continuation_not_sorted(self) -> None:
        # Intentionally not using textwrap.dedent().
        initial = f"""
        # {START}
        foo
          bar
        baz
         abc
        # {END}""".lstrip(
            '\n'
        )

        expected = f"""
        # {START}
        baz
         abc
        foo
          bar
        # {END}""".lstrip(
            '\n'
        )

        self._run(initial)
        self.assert_errors()
        self.assertEqual(self.contents, expected)


if __name__ == '__main__':
    unittest.main()