aboutsummaryrefslogtreecommitdiff
path: root/rh/hooks_unittest.py
blob: 03f45ca2e9752e86f47a6211b07eb2e644be5b3c (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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
#!/usr/bin/env python3
# Copyright 2016 The Android Open Source Project
#
# 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
#
#      http://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.

"""Unittests for the hooks module."""

import os
import sys
import unittest
from unittest import mock

_path = os.path.realpath(__file__ + '/../..')
if sys.path[0] != _path:
    sys.path.insert(0, _path)
del _path

# We have to import our local modules after the sys.path tweak.  We can't use
# relative imports because this is an executable program, not a module.
# pylint: disable=wrong-import-position
import rh
import rh.config
import rh.hooks


class HooksDocsTests(unittest.TestCase):
    """Make sure all hook features are documented.

    Note: These tests are a bit hokey in that they parse README.md.  But they
    get the job done, so that's all that matters right?
    """

    def setUp(self):
        self.readme = os.path.join(os.path.dirname(os.path.dirname(
            os.path.realpath(__file__))), 'README.md')

    def _grab_section(self, section):
        """Extract the |section| text out of the readme."""
        ret = []
        in_section = False
        with open(self.readme, encoding='utf-8') as fp:
            for line in fp:
                if not in_section:
                    # Look for the section like "## [Tool Paths]".
                    if (line.startswith('#') and
                            line.lstrip('#').strip() == section):
                        in_section = True
                else:
                    # Once we hit the next section (higher or lower), break.
                    if line[0] == '#':
                        break
                    ret.append(line)
        return ''.join(ret)

    def testBuiltinHooks(self):
        """Verify builtin hooks are documented."""
        data = self._grab_section('[Builtin Hooks]')
        for hook in rh.hooks.BUILTIN_HOOKS:
            self.assertIn(f'* `{hook}`:', data,
                          msg=f'README.md missing docs for hook "{hook}"')

    def testToolPaths(self):
        """Verify tools are documented."""
        data = self._grab_section('[Tool Paths]')
        for tool in rh.hooks.TOOL_PATHS:
            self.assertIn(f'* `{tool}`:', data,
                          msg=f'README.md missing docs for tool "{tool}"')

    def testPlaceholders(self):
        """Verify placeholder replacement vars are documented."""
        data = self._grab_section('Placeholders')
        for var in rh.hooks.Placeholders.vars():
            self.assertIn('* `${' + var + '}`:', data,
                          msg=f'README.md missing docs for var "{var}"')


class PlaceholderTests(unittest.TestCase):
    """Verify behavior of replacement variables."""

    def setUp(self):
        self._saved_environ = os.environ.copy()
        os.environ.update({
            'PREUPLOAD_COMMIT_MESSAGE': 'commit message',
            'PREUPLOAD_COMMIT': '5c4c293174bb61f0f39035a71acd9084abfa743d',
        })
        self.replacer = rh.hooks.Placeholders(
            [rh.git.RawDiffEntry(file=x)
             for x in ['path1/file1', 'path2/file2']])

    def tearDown(self):
        os.environ.clear()
        os.environ.update(self._saved_environ)

    def testVars(self):
        """Light test for the vars inspection generator."""
        ret = list(self.replacer.vars())
        self.assertGreater(len(ret), 4)
        self.assertIn('PREUPLOAD_COMMIT', ret)

    @mock.patch.object(rh.git, 'find_repo_root', return_value='/ ${BUILD_OS}')
    def testExpandVars(self, _m):
        """Verify the replacement actually works."""
        input_args = [
            # Verify ${REPO_ROOT} is updated, but not REPO_ROOT.
            # We also make sure that things in ${REPO_ROOT} are not double
            # expanded (which is why the return includes ${BUILD_OS}).
            '${REPO_ROOT}/some/prog/REPO_ROOT/ok',
            # Verify lists are merged rather than inserted.
            '${PREUPLOAD_FILES}',
            # Verify each file is preceded with '--file=' prefix.
            '--file=${PREUPLOAD_FILES_PREFIXED}',
            # Verify each file is preceded with '--file' argument.
            '--file',
            '${PREUPLOAD_FILES_PREFIXED}',
            # Verify values with whitespace don't expand into multiple args.
            '${PREUPLOAD_COMMIT_MESSAGE}',
            # Verify multiple values get replaced.
            '${PREUPLOAD_COMMIT}^${PREUPLOAD_COMMIT_MESSAGE}',
            # Unknown vars should be left alone.
            '${THIS_VAR_IS_GOOD}',
        ]
        output_args = self.replacer.expand_vars(input_args)
        exp_args = [
            '/ ${BUILD_OS}/some/prog/REPO_ROOT/ok',
            'path1/file1',
            'path2/file2',
            '--file=path1/file1',
            '--file=path2/file2',
            '--file',
            'path1/file1',
            '--file',
            'path2/file2',
            'commit message',
            '5c4c293174bb61f0f39035a71acd9084abfa743d^commit message',
            '${THIS_VAR_IS_GOOD}',
        ]
        self.assertEqual(output_args, exp_args)

    def testTheTester(self):
        """Make sure we have a test for every variable."""
        for var in self.replacer.vars():
            self.assertIn(f'test{var}', dir(self),
                          msg=f'Missing unittest for variable {var}')

    def testPREUPLOAD_COMMIT_MESSAGE(self):
        """Verify handling of PREUPLOAD_COMMIT_MESSAGE."""
        self.assertEqual(self.replacer.get('PREUPLOAD_COMMIT_MESSAGE'),
                         'commit message')

    def testPREUPLOAD_COMMIT(self):
        """Verify handling of PREUPLOAD_COMMIT."""
        self.assertEqual(self.replacer.get('PREUPLOAD_COMMIT'),
                         '5c4c293174bb61f0f39035a71acd9084abfa743d')

    def testPREUPLOAD_FILES(self):
        """Verify handling of PREUPLOAD_FILES."""
        self.assertEqual(self.replacer.get('PREUPLOAD_FILES'),
                         ['path1/file1', 'path2/file2'])

    @mock.patch.object(rh.git, 'find_repo_root', return_value='/repo!')
    def testREPO_ROOT(self, m):
        """Verify handling of REPO_ROOT."""
        self.assertEqual(self.replacer.get('REPO_ROOT'), m.return_value)

    @mock.patch.object(rh.hooks, '_get_build_os_name', return_value='vapier os')
    def testBUILD_OS(self, m):
        """Verify handling of BUILD_OS."""
        self.assertEqual(self.replacer.get('BUILD_OS'), m.return_value)


class ExclusionScopeTests(unittest.TestCase):
    """Verify behavior of ExclusionScope class."""

    def testEmpty(self):
        """Verify the in operator for an empty scope."""
        scope = rh.hooks.ExclusionScope([])
        self.assertNotIn('external/*', scope)

    def testGlob(self):
        """Verify the in operator for a scope using wildcards."""
        scope = rh.hooks.ExclusionScope(['vendor/*', 'external/*'])
        self.assertIn('external/tools', scope)

    def testRegex(self):
        """Verify the in operator for a scope using regular expressions."""
        scope = rh.hooks.ExclusionScope(['^vendor/(?!google)',
                                         'external/*'])
        self.assertIn('vendor/', scope)
        self.assertNotIn('vendor/google/', scope)
        self.assertIn('vendor/other/', scope)


class HookOptionsTests(unittest.TestCase):
    """Verify behavior of HookOptions object."""

    @mock.patch.object(rh.hooks, '_get_build_os_name', return_value='vapier os')
    def testExpandVars(self, m):
        """Verify expand_vars behavior."""
        # Simple pass through.
        args = ['who', 'goes', 'there ?']
        self.assertEqual(args, rh.hooks.HookOptions.expand_vars(args))

        # At least one replacement.  Most real testing is in PlaceholderTests.
        args = ['who', 'goes', 'there ?', '${BUILD_OS} is great']
        exp_args = ['who', 'goes', 'there ?', f'{m.return_value} is great']
        self.assertEqual(exp_args, rh.hooks.HookOptions.expand_vars(args))

    def testArgs(self):
        """Verify args behavior."""
        # Verify initial args to __init__ has higher precedent.
        args = ['start', 'args']
        options = rh.hooks.HookOptions('hook name', args, {})
        self.assertEqual(options.args(), args)
        self.assertEqual(options.args(default_args=['moo']), args)

        # Verify we fall back to default_args.
        args = ['default', 'args']
        options = rh.hooks.HookOptions('hook name', [], {})
        self.assertEqual(options.args(), [])
        self.assertEqual(options.args(default_args=args), args)

    def testToolPath(self):
        """Verify tool_path behavior."""
        options = rh.hooks.HookOptions('hook name', [], {
            'cpplint': 'my cpplint',
        })
        # Check a builtin (and not overridden) tool.
        self.assertEqual(options.tool_path('pylint'), 'pylint')
        # Check an overridden tool.
        self.assertEqual(options.tool_path('cpplint'), 'my cpplint')
        # Check an unknown tool fails.
        self.assertRaises(AssertionError, options.tool_path, 'extra_tool')


class UtilsTests(unittest.TestCase):
    """Verify misc utility functions."""

    def testRunCommand(self):
        """Check _run behavior."""
        # Most testing is done against the utils.RunCommand already.
        # pylint: disable=protected-access
        ret = rh.hooks._run(['true'])
        self.assertEqual(ret.returncode, 0)

    def testBuildOs(self):
        """Check _get_build_os_name behavior."""
        # Just verify it returns something and doesn't crash.
        # pylint: disable=protected-access
        ret = rh.hooks._get_build_os_name()
        self.assertTrue(isinstance(ret, str))
        self.assertNotEqual(ret, '')

    def testGetHelperPath(self):
        """Check get_helper_path behavior."""
        # Just verify it doesn't crash.  It's a dirt simple func.
        ret = rh.hooks.get_helper_path('booga')
        self.assertTrue(isinstance(ret, str))
        self.assertNotEqual(ret, '')



@mock.patch.object(rh.utils, 'run')
@mock.patch.object(rh.hooks, '_check_cmd', return_value=['check_cmd'])
class BuiltinHooksTests(unittest.TestCase):
    """Verify the builtin hooks."""

    def setUp(self):
        self.project = rh.Project(name='project-name', dir='/.../repo/dir',
                                  remote='remote')
        self.options = rh.hooks.HookOptions('hook name', [], {})

    def _test_commit_messages(self, func, accept, msgs, files=None):
        """Helper for testing commit message hooks.

        Args:
          func: The hook function to test.
          accept: Whether all the |msgs| should be accepted.
          msgs: List of messages to test.
          files: List of files to pass to the hook.
        """
        if files:
            diff = [rh.git.RawDiffEntry(file=x) for x in files]
        else:
            diff = []
        for desc in msgs:
            ret = func(self.project, 'commit', desc, diff, options=self.options)
            if accept:
                self.assertFalse(
                    bool(ret), msg='Should have accepted: {{{' + desc + '}}}')
            else:
                self.assertTrue(
                    bool(ret), msg='Should have rejected: {{{' + desc + '}}}')

    def _test_file_filter(self, mock_check, func, files):
        """Helper for testing hooks that filter by files and run external tools.

        Args:
          mock_check: The mock of _check_cmd.
          func: The hook function to test.
          files: A list of files that we'd check.
        """
        # First call should do nothing as there are no files to check.
        ret = func(self.project, 'commit', 'desc', (), options=self.options)
        self.assertIsNone(ret)
        self.assertFalse(mock_check.called)

        # Second call should include some checks.
        diff = [rh.git.RawDiffEntry(file=x) for x in files]
        ret = func(self.project, 'commit', 'desc', diff, options=self.options)
        self.assertEqual(ret, mock_check.return_value)

    def testTheTester(self, _mock_check, _mock_run):
        """Make sure we have a test for every hook."""
        for hook in rh.hooks.BUILTIN_HOOKS:
            self.assertIn(f'test_{hook}', dir(self),
                          msg=f'Missing unittest for builtin hook {hook}')

    def test_bpfmt(self, mock_check, _mock_run):
        """Verify the bpfmt builtin hook."""
        # First call should do nothing as there are no files to check.
        ret = rh.hooks.check_bpfmt(
            self.project, 'commit', 'desc', (), options=self.options)
        self.assertIsNone(ret)
        self.assertFalse(mock_check.called)

        # Second call will have some results.
        diff = [rh.git.RawDiffEntry(file='Android.bp')]
        ret = rh.hooks.check_bpfmt(
            self.project, 'commit', 'desc', diff, options=self.options)
        self.assertIsNotNone(ret)

    def test_checkpatch(self, mock_check, _mock_run):
        """Verify the checkpatch builtin hook."""
        ret = rh.hooks.check_checkpatch(
            self.project, 'commit', 'desc', (), options=self.options)
        self.assertEqual(ret, mock_check.return_value)

    def test_clang_format(self, mock_check, _mock_run):
        """Verify the clang_format builtin hook."""
        ret = rh.hooks.check_clang_format(
            self.project, 'commit', 'desc', (), options=self.options)
        self.assertEqual(ret, mock_check.return_value)

    def test_google_java_format(self, mock_check, _mock_run):
        """Verify the google_java_format builtin hook."""
        ret = rh.hooks.check_google_java_format(
            self.project, 'commit', 'desc', (), options=self.options)
        self.assertEqual(ret, mock_check.return_value)

    def test_commit_msg_bug_field(self, _mock_check, _mock_run):
        """Verify the commit_msg_bug_field builtin hook."""
        # Check some good messages.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_bug_field, True, (
                'subj\n\nBug: 1234\n',
                'subj\n\nBug: 1234\nChange-Id: blah\n',
            ))

        # Check some bad messages.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_bug_field, False, (
                'subj',
                'subj\n\nBUG=1234\n',
                'subj\n\nBUG: 1234\n',
                'subj\n\nBug: N/A\n',
                'subj\n\nBug:\n',
            ))

    def test_commit_msg_changeid_field(self, _mock_check, _mock_run):
        """Verify the commit_msg_changeid_field builtin hook."""
        # Check some good messages.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_changeid_field, True, (
                'subj\n\nChange-Id: I1234\n',
            ))

        # Check some bad messages.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_changeid_field, False, (
                'subj',
                'subj\n\nChange-Id: 1234\n',
                'subj\n\nChange-ID: I1234\n',
            ))

    def test_commit_msg_prebuilt_apk_fields(self, _mock_check, _mock_run):
        """Verify the check_commit_msg_prebuilt_apk_fields builtin hook."""
        # Commits without APKs should pass.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_prebuilt_apk_fields,
            True,
            (
                'subj\nTest: test case\nBug: bug id\n',
            ),
            ['foo.cpp', 'bar.py',]
        )

        # Commits with APKs and all the required messages should pass.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_prebuilt_apk_fields,
            True,
            (
                ('Test App\n\nbar.apk\npackage: name=\'com.foo.bar\'\n'
                 'versionCode=\'1001\'\nversionName=\'1.0.1001-A\'\n'
                 'platformBuildVersionName=\'\'\ncompileSdkVersion=\'28\'\n'
                 'compileSdkVersionCodename=\'9\'\nsdkVersion:\'16\'\n'
                 'targetSdkVersion:\'28\'\n\nBuilt here:\n'
                 'http://foo.bar.com/builder\n\n'
                 'This build IS suitable for public release.\n\n'
                 'Bug: 123\nTest: test\nChange-Id: XXXXXXX\n'),
                ('Test App\n\nBuilt here:\nhttp://foo.bar.com/builder\n\n'
                 'This build IS NOT suitable for public release.\n\n'
                 'bar.apk\npackage: name=\'com.foo.bar\'\n'
                 'versionCode=\'1001\'\nversionName=\'1.0.1001-A\'\n'
                 'platformBuildVersionName=\'\'\ncompileSdkVersion=\'28\'\n'
                 'compileSdkVersionCodename=\'9\'\nsdkVersion:\'16\'\n'
                 'targetSdkVersion:\'28\'\n\nBug: 123\nTest: test\n'
                 'Change-Id: XXXXXXX\n'),
                ('Test App\n\nbar.apk\npackage: name=\'com.foo.bar\'\n'
                 'versionCode=\'1001\'\nversionName=\'1.0.1001-A\'\n'
                 'platformBuildVersionName=\'\'\ncompileSdkVersion=\'28\'\n'
                 'compileSdkVersionCodename=\'9\'\nsdkVersion:\'16\'\n'
                 'targetSdkVersion:\'28\'\n\nBuilt here:\n'
                 'http://foo.bar.com/builder\n\n'
                 'This build IS suitable for preview release but IS NOT '
                 'suitable for public release.\n\n'
                 'Bug: 123\nTest: test\nChange-Id: XXXXXXX\n'),
                ('Test App\n\nbar.apk\npackage: name=\'com.foo.bar\'\n'
                 'versionCode=\'1001\'\nversionName=\'1.0.1001-A\'\n'
                 'platformBuildVersionName=\'\'\ncompileSdkVersion=\'28\'\n'
                 'compileSdkVersionCodename=\'9\'\nsdkVersion:\'16\'\n'
                 'targetSdkVersion:\'28\'\n\nBuilt here:\n'
                 'http://foo.bar.com/builder\n\n'
                 'This build IS NOT suitable for preview or public release.\n\n'
                 'Bug: 123\nTest: test\nChange-Id: XXXXXXX\n'),
            ),
            ['foo.apk', 'bar.py',]
        )

        # Commits with APKs and without all the required messages should fail.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_prebuilt_apk_fields,
            False,
            (
                'subj\nTest: test case\nBug: bug id\n',
                # Missing 'package'.
                ('Test App\n\nbar.apk\n'
                 'versionCode=\'1001\'\nversionName=\'1.0.1001-A\'\n'
                 'platformBuildVersionName=\'\'\ncompileSdkVersion=\'28\'\n'
                 'compileSdkVersionCodename=\'9\'\nsdkVersion:\'16\'\n'
                 'targetSdkVersion:\'28\'\n\nBuilt here:\n'
                 'http://foo.bar.com/builder\n\n'
                 'This build IS suitable for public release.\n\n'
                 'Bug: 123\nTest: test\nChange-Id: XXXXXXX\n'),
                # Missing 'sdkVersion'.
                ('Test App\n\nbar.apk\npackage: name=\'com.foo.bar\'\n'
                 'versionCode=\'1001\'\nversionName=\'1.0.1001-A\'\n'
                 'platformBuildVersionName=\'\'\ncompileSdkVersion=\'28\'\n'
                 'compileSdkVersionCodename=\'9\'\n'
                 'targetSdkVersion:\'28\'\n\nBuilt here:\n'
                 'http://foo.bar.com/builder\n\n'
                 'This build IS suitable for public release.\n\n'
                 'Bug: 123\nTest: test\nChange-Id: XXXXXXX\n'),
                # Missing 'targetSdkVersion'.
                ('Test App\n\nbar.apk\npackage: name=\'com.foo.bar\'\n'
                 'versionCode=\'1001\'\nversionName=\'1.0.1001-A\'\n'
                 'platformBuildVersionName=\'\'\ncompileSdkVersion=\'28\'\n'
                 'compileSdkVersionCodename=\'9\'\nsdkVersion:\'16\'\n'
                 'Built here:\nhttp://foo.bar.com/builder\n\n'
                 'This build IS suitable for public release.\n\n'
                 'Bug: 123\nTest: test\nChange-Id: XXXXXXX\n'),
                # Missing build location.
                ('Test App\n\nbar.apk\npackage: name=\'com.foo.bar\'\n'
                 'versionCode=\'1001\'\nversionName=\'1.0.1001-A\'\n'
                 'platformBuildVersionName=\'\'\ncompileSdkVersion=\'28\'\n'
                 'compileSdkVersionCodename=\'9\'\nsdkVersion:\'16\'\n'
                 'targetSdkVersion:\'28\'\n\n'
                 'This build IS suitable for public release.\n\n'
                 'Bug: 123\nTest: test\nChange-Id: XXXXXXX\n'),
                # Missing public release indication.
                ('Test App\n\nbar.apk\npackage: name=\'com.foo.bar\'\n'
                 'versionCode=\'1001\'\nversionName=\'1.0.1001-A\'\n'
                 'platformBuildVersionName=\'\'\ncompileSdkVersion=\'28\'\n'
                 'compileSdkVersionCodename=\'9\'\nsdkVersion:\'16\'\n'
                 'targetSdkVersion:\'28\'\n\nBuilt here:\n'
                 'http://foo.bar.com/builder\n\n'
                 'Bug: 123\nTest: test\nChange-Id: XXXXXXX\n'),
            ),
            ['foo.apk', 'bar.py',]
        )

    def test_commit_msg_test_field(self, _mock_check, _mock_run):
        """Verify the commit_msg_test_field builtin hook."""
        # Check some good messages.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_test_field, True, (
                'subj\n\nTest: i did done dood it\n',
            ))

        # Check some bad messages.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_test_field, False, (
                'subj',
                'subj\n\nTEST=1234\n',
                'subj\n\nTEST: I1234\n',
            ))

    def test_commit_msg_relnote_field_format(self, _mock_check, _mock_run):
        """Verify the commit_msg_relnote_field_format builtin hook."""
        # Check some good messages.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_relnote_field_format,
            True,
            (
                'subj',
                'subj\n\nTest: i did done dood it\nBug: 1234',
                'subj\n\nMore content\n\nTest: i did done dood it\nBug: 1234',
                'subj\n\nRelnote: This is a release note\nBug: 1234',
                'subj\n\nRelnote:This is a release note\nBug: 1234',
                'subj\n\nRelnote: This is a release note.\nBug: 1234',
                'subj\n\nRelnote: "This is a release note."\nBug: 1234',
                'subj\n\nRelnote: "This is a \\"release note\\"."\n\nBug: 1234',
                'subj\n\nRelnote: This is a release note.\nChange-Id: 1234',
                'subj\n\nRelnote: This is a release note.\n\nChange-Id: 1234',
                ('subj\n\nRelnote: "This is a release note."\n\n'
                 'Change-Id: 1234'),
                ('subj\n\nRelnote: This is a release note.\n\n'
                 'It has more info, but it is not part of the release note'
                 '\nChange-Id: 1234'),
                ('subj\n\nRelnote: "This is a release note.\n'
                 'It contains a correct second line."'),
                ('subj\n\nRelnote:"This is a release note.\n'
                 'It contains a correct second line."'),
                ('subj\n\nRelnote: "This is a release note.\n'
                 'It contains a correct second line.\n'
                 'And even a third line."\n'
                 'Bug: 1234'),
                ('subj\n\nRelnote: "This is a release note.\n'
                 'It contains a correct second line.\n'
                 '\\"Quotes\\" are even used on the third line."\n'
                 'Bug: 1234'),
                ('subj\n\nRelnote: This is release note 1.\n'
                 'Relnote: This is release note 2.\n'
                 'Bug: 1234'),
                ('subj\n\nRelnote: This is release note 1.\n'
                 'Relnote: "This is release note 2, and it\n'
                 'contains a correctly formatted third line."\n'
                 'Bug: 1234'),
                ('subj\n\nRelnote: "This is release note 1 with\n'
                 'a correctly formatted second line."\n\n'
                 'Relnote: "This is release note 2, and it\n'
                 'contains a correctly formatted second line."\n'
                 'Bug: 1234'),
                ('subj\n\nRelnote: "This is a release note with\n'
                 'a correctly formatted second line."\n\n'
                 'Bug: 1234'
                 'Here is some extra "quoted" content.'),
                ('subj\n\nRelnote: """This is a release note.\n\n'
                 'This relnote contains an empty line.\n'
                 'Then a non-empty line.\n\n'
                 'And another empty line."""\n\n'
                 'Bug: 1234'),
                ('subj\n\nRelnote: """This is a release note.\n\n'
                 'This relnote contains an empty line.\n'
                 'Then an acceptable "quoted" line.\n\n'
                 'And another empty line."""\n\n'
                 'Bug: 1234'),
                ('subj\n\nRelnote: """This is a release note."""\n\n'
                 'Bug: 1234'),
                ('subj\n\nRelnote: """This is a release note.\n'
                 'It has a second line."""\n\n'
                 'Bug: 1234'),
                ('subj\n\nRelnote: """This is a release note.\n'
                 'It has a second line, but does not end here.\n'
                 '"""\n\n'
                 'Bug: 1234'),
                ('subj\n\nRelnote: """This is a release note.\n'
                 '"It" has a second line, but does not end here.\n'
                 '"""\n\n'
                 'Bug: 1234'),
                ('subj\n\nRelnote: "This is a release note.\n'
                 'It has a second line, but does not end here.\n'
                 '"\n\n'
                 'Bug: 1234'),
            ))

        # Check some bad messages.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_relnote_field_format,
            False,
            (
                'subj\n\nReleaseNote: This is a release note.\n',
                'subj\n\nRelnotes: This is a release note.\n',
                'subj\n\nRel-note: This is a release note.\n',
                'subj\n\nrelnoTes: This is a release note.\n',
                'subj\n\nrel-Note: This is a release note.\n',
                'subj\n\nRelnote: "This is a "release note"."\nBug: 1234',
                'subj\n\nRelnote: This is a "release note".\nBug: 1234',
                ('subj\n\nRelnote: This is a release note.\n'
                 'It contains an incorrect second line.'),
                ('subj\n\nRelnote: "This is a release note.\n'
                 'It contains multiple lines.\n'
                 'But it does not provide an ending quote.\n'),
                ('subj\n\nRelnote: "This is a release note.\n'
                 'It contains multiple lines but no closing quote.\n'
                 'Test: my test "hello world"\n'),
                ('subj\n\nRelnote: This is release note 1.\n'
                 'Relnote: "This is release note 2, and it\n'
                 'contains an incorrectly formatted third line.\n'
                 'Bug: 1234'),
                ('subj\n\nRelnote: This is release note 1 with\n'
                 'an incorrectly formatted second line.\n\n'
                 'Relnote: "This is release note 2, and it\n'
                 'contains a correctly formatted second line."\n'
                 'Bug: 1234'),
                ('subj\n\nRelnote: "This is release note 1 with\n'
                 'a correctly formatted second line."\n\n'
                 'Relnote: This is release note 2, and it\n'
                 'contains an incorrectly formatted second line.\n'
                 'Bug: 1234'),
                ('subj\n\nRelnote: "This is a release note.\n'
                 'It contains a correct second line.\n'
                 'But incorrect "quotes" on the third line."\n'
                 'Bug: 1234'),
                ('subj\n\nRelnote: """This is a release note.\n'
                 'It has a second line, but no closing triple quote.\n\n'
                 'Bug: 1234'),
                ('subj\n\nRelnote: "This is a release note.\n'
                 '"It" has a second line, but does not end here.\n'
                 '"\n\n'
                 'Bug: 1234'),
            ))

    def test_commit_msg_relnote_for_current_txt(self, _mock_check, _mock_run):
        """Verify the commit_msg_relnote_for_current_txt builtin hook."""
        diff_without_current_txt = ['bar/foo.txt',
                                    'foo.cpp',
                                    'foo.java',
                                    'foo_current.java',
                                    'foo_current.txt',
                                    'baz/current.java',
                                    'baz/foo_current.txt']
        diff_with_current_txt = diff_without_current_txt + ['current.txt']
        diff_with_subdir_current_txt = \
            diff_without_current_txt + ['foo/current.txt']
        diff_with_experimental_current_txt = \
            diff_without_current_txt + ['public_plus_experimental_current.txt']
        # Check some good messages.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_relnote_for_current_txt,
            True,
            (
                'subj\n\nRelnote: This is a release note\n',
                'subj\n\nRelnote: This is a release note.\n\nChange-Id: 1234',
                ('subj\n\nRelnote: This is release note 1 with\n'
                 'an incorrectly formatted second line.\n\n'
                 'Relnote: "This is release note 2, and it\n'
                 'contains a correctly formatted second line."\n'
                 'Bug: 1234'),
            ),
            files=diff_with_current_txt,
        )
        # Check some good messages.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_relnote_for_current_txt,
            True,
            (
                'subj\n\nRelnote: This is a release note\n',
                'subj\n\nRelnote: This is a release note.\n\nChange-Id: 1234',
                ('subj\n\nRelnote: This is release note 1 with\n'
                 'an incorrectly formatted second line.\n\n'
                 'Relnote: "This is release note 2, and it\n'
                 'contains a correctly formatted second line."\n'
                 'Bug: 1234'),
            ),
            files=diff_with_experimental_current_txt,
        )
        # Check some good messages.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_relnote_for_current_txt,
            True,
            (
                'subj\n\nRelnote: This is a release note\n',
                'subj\n\nRelnote: This is a release note.\n\nChange-Id: 1234',
                ('subj\n\nRelnote: This is release note 1 with\n'
                 'an incorrectly formatted second line.\n\n'
                 'Relnote: "This is release note 2, and it\n'
                 'contains a correctly formatted second line."\n'
                 'Bug: 1234'),
            ),
            files=diff_with_subdir_current_txt,
        )
        # Check some good messages.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_relnote_for_current_txt,
            True,
            (
                'subj',
                'subj\nBug: 12345\nChange-Id: 1234',
                'subj\n\nRelnote: This is a release note\n',
                'subj\n\nRelnote: This is a release note.\n\nChange-Id: 1234',
                ('subj\n\nRelnote: This is release note 1 with\n'
                 'an incorrectly formatted second line.\n\n'
                 'Relnote: "This is release note 2, and it\n'
                 'contains a correctly formatted second line."\n'
                 'Bug: 1234'),
            ),
            files=diff_without_current_txt,
        )
        # Check some bad messages.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_relnote_for_current_txt,
            False,
            (
                'subj'
                'subj\nBug: 12345\nChange-Id: 1234',
            ),
            files=diff_with_current_txt,
        )
        # Check some bad messages.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_relnote_for_current_txt,
            False,
            (
                'subj'
                'subj\nBug: 12345\nChange-Id: 1234',
            ),
            files=diff_with_experimental_current_txt,
        )
        # Check some bad messages.
        self._test_commit_messages(
            rh.hooks.check_commit_msg_relnote_for_current_txt,
            False,
            (
                'subj'
                'subj\nBug: 12345\nChange-Id: 1234',
            ),
            files=diff_with_subdir_current_txt,
        )

    def test_cpplint(self, mock_check, _mock_run):
        """Verify the cpplint builtin hook."""
        self._test_file_filter(mock_check, rh.hooks.check_cpplint,
                               ('foo.cpp', 'foo.cxx'))

    def test_gofmt(self, mock_check, _mock_run):
        """Verify the gofmt builtin hook."""
        # First call should do nothing as there are no files to check.
        ret = rh.hooks.check_gofmt(
            self.project, 'commit', 'desc', (), options=self.options)
        self.assertIsNone(ret)
        self.assertFalse(mock_check.called)

        # Second call will have some results.
        diff = [rh.git.RawDiffEntry(file='foo.go')]
        ret = rh.hooks.check_gofmt(
            self.project, 'commit', 'desc', diff, options=self.options)
        self.assertIsNotNone(ret)

    def test_jsonlint(self, mock_check, _mock_run):
        """Verify the jsonlint builtin hook."""
        # First call should do nothing as there are no files to check.
        ret = rh.hooks.check_json(
            self.project, 'commit', 'desc', (), options=self.options)
        self.assertIsNone(ret)
        self.assertFalse(mock_check.called)

        # TODO: Actually pass some valid/invalid json data down.

    def test_pylint(self, mock_check, _mock_run):
        """Verify the pylint builtin hook."""
        self._test_file_filter(mock_check, rh.hooks.check_pylint2,
                               ('foo.py',))

    def test_pylint2(self, mock_check, _mock_run):
        """Verify the pylint2 builtin hook."""
        self._test_file_filter(mock_check, rh.hooks.check_pylint2,
                               ('foo.py',))

    def test_pylint3(self, mock_check, _mock_run):
        """Verify the pylint3 builtin hook."""
        self._test_file_filter(mock_check, rh.hooks.check_pylint3,
                               ('foo.py',))

    def test_rustfmt(self, mock_check, _mock_run):
        # First call should do nothing as there are no files to check.
        ret = rh.hooks.check_rustfmt(
            self.project, 'commit', 'desc', (), options=self.options)
        self.assertEqual(ret, None)
        self.assertFalse(mock_check.called)

        # Second call will have some results.
        diff = [rh.git.RawDiffEntry(file='lib.rs')]
        ret = rh.hooks.check_rustfmt(
            self.project, 'commit', 'desc', diff, options=self.options)
        self.assertNotEqual(ret, None)

    def test_xmllint(self, mock_check, _mock_run):
        """Verify the xmllint builtin hook."""
        self._test_file_filter(mock_check, rh.hooks.check_xmllint,
                               ('foo.xml',))

    def test_android_test_mapping_format(self, mock_check, _mock_run):
        """Verify the android_test_mapping_format builtin hook."""
        # First call should do nothing as there are no files to check.
        ret = rh.hooks.check_android_test_mapping(
            self.project, 'commit', 'desc', (), options=self.options)
        self.assertIsNone(ret)
        self.assertFalse(mock_check.called)

        # Second call will have some results.
        diff = [rh.git.RawDiffEntry(file='TEST_MAPPING')]
        ret = rh.hooks.check_android_test_mapping(
            self.project, 'commit', 'desc', diff, options=self.options)
        self.assertIsNotNone(ret)

    def test_aidl_format(self, mock_check, _mock_run):
        """Verify the aidl_format builtin hook."""
        # First call should do nothing as there are no files to check.
        ret = rh.hooks.check_aidl_format(
            self.project, 'commit', 'desc', (), options=self.options)
        self.assertIsNone(ret)
        self.assertFalse(mock_check.called)

        # Second call will have some results.
        diff = [rh.git.RawDiffEntry(file='IFoo.go')]
        ret = rh.hooks.check_gofmt(
            self.project, 'commit', 'desc', diff, options=self.options)
        self.assertIsNotNone(ret)


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