aboutsummaryrefslogtreecommitdiff
path: root/llvm_tools/patch_manager_unittest.py
blob: 69bb683ea23c336765b128efe0d6ab65fdcad65e (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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Unit tests when handling patches."""

from __future__ import print_function

import json
import os
import subprocess
import unittest
import unittest.mock as mock

import patch_manager
from failure_modes import FailureModes
from test_helpers import CallCountsToMockFunctions
from test_helpers import CreateTemporaryJsonFile
from test_helpers import WritePrettyJsonFile


class PatchManagerTest(unittest.TestCase):
  """Test class when handling patches of packages."""

  # Simulate behavior of 'os.path.isdir()' when the path is not a directory.
  @mock.patch.object(os.path, 'isdir', return_value=False)
  def testInvalidDirectoryPassedAsCommandLineArgument(self, mock_isdir):
    test_dir = '/some/path/that/is/not/a/directory'

    # Verify the exception is raised when the command line argument for
    # '--filesdir_path' or '--src_path' is not a directory.
    with self.assertRaises(ValueError) as err:
      patch_manager.is_directory(test_dir)

    self.assertEqual(
        str(err.exception), 'Path is not a directory: '
        '%s' % test_dir)

    mock_isdir.assert_called_once()

  # Simulate the behavior of 'os.path.isdir()' when a path to a directory is
  # passed as the command line argument for '--filesdir_path' or '--src_path'.
  @mock.patch.object(os.path, 'isdir', return_value=True)
  def testValidDirectoryPassedAsCommandLineArgument(self, mock_isdir):
    test_dir = '/some/path/that/is/a/directory'

    self.assertEqual(patch_manager.is_directory(test_dir), test_dir)

    mock_isdir.assert_called_once()

  # Simulate behavior of 'os.path.isfile()' when the patch metadata file is does
  # not exist.
  @mock.patch.object(os.path, 'isfile', return_value=False)
  def testInvalidPathToPatchMetadataFilePassedAsCommandLineArgument(
      self, mock_isfile):

    abs_path_to_patch_file = '/abs/path/to/PATCHES.json'

    # Verify the exception is raised when the command line argument for
    # '--patch_metadata_file' does not exist or is not a file.
    with self.assertRaises(ValueError) as err:
      patch_manager.is_patch_metadata_file(abs_path_to_patch_file)

    self.assertEqual(
        str(err.exception), 'Invalid patch metadata file provided: '
        '%s' % abs_path_to_patch_file)

    mock_isfile.assert_called_once()

  # Simulate the behavior of 'os.path.isfile()' when the path to the patch
  # metadata file exists and is a file.
  @mock.patch.object(os.path, 'isfile', return_value=True)
  def testPatchMetadataFileDoesNotEndInJson(self, mock_isfile):
    abs_path_to_patch_file = '/abs/path/to/PATCHES'

    # Verify the exception is raises when the command line argument for
    # '--patch_metadata_file' exists and is a file but does not end in
    # '.json'.
    with self.assertRaises(ValueError) as err:
      patch_manager.is_patch_metadata_file(abs_path_to_patch_file)

    self.assertEqual(
        str(err.exception), 'Patch metadata file does not end in ".json": '
        '%s' % abs_path_to_patch_file)

    mock_isfile.assert_called_once()

  # Simulate the behavior of 'os.path.isfile()' when the command line argument
  # for '--patch_metadata_file' exists and is a file.
  @mock.patch.object(os.path, 'isfile', return_value=True)
  def testValidPatchMetadataFilePassedAsCommandLineArgument(self, mock_isfile):
    abs_path_to_patch_file = '/abs/path/to/PATCHES.json'

    self.assertEqual(
        patch_manager.is_patch_metadata_file(abs_path_to_patch_file),
        '%s' % abs_path_to_patch_file)

    mock_isfile.assert_called_once()

  # Simulate behavior of 'os.path.isdir()' when the path to $FILESDIR
  # does not exist.
  @mock.patch.object(os.path, 'isdir', return_value=False)
  def testInvalidPathToFilesDirWhenConstructingPathToPatch(self, mock_isdir):
    abs_path_to_filesdir = '/abs/path/to/filesdir'

    rel_patch_path = 'cherry/fixes_stdout.patch'

    # Verify the exception is raised when the the absolute path to $FILESDIR of
    # a package is not a directory.
    with self.assertRaises(ValueError) as err:
      patch_manager.GetPathToPatch(abs_path_to_filesdir, rel_patch_path)

    self.assertEqual(
        str(err.exception), 'Invalid path to $FILESDIR provided: '
        '%s' % abs_path_to_filesdir)

    mock_isdir.assert_called_once()

  # Simulate behavior of 'os.path.isdir()' when the absolute path to the
  # $FILESDIR of a package exists and is a directory.
  @mock.patch.object(os.path, 'isdir', return_value=True)
  # Simulate the behavior of 'os.path.isfile()' when the absolute path to the
  # patch does not exist.
  @mock.patch.object(os.path, 'isfile', return_value=False)
  def testConstructedPathToPatchDoesNotExist(self, mock_isfile, mock_isdir):
    abs_path_to_filesdir = '/abs/path/to/filesdir'

    rel_patch_path = 'cherry/fixes_stdout.patch'

    abs_patch_path = os.path.join(abs_path_to_filesdir, rel_patch_path)

    # Verify the exception is raised when the absolute path to the patch does
    # not exist.
    with self.assertRaises(ValueError) as err:
      patch_manager.GetPathToPatch(abs_path_to_filesdir, rel_patch_path)

    self.assertEqual(
        str(err.exception), 'The absolute path %s to the patch %s does not '
        'exist' % (abs_patch_path, rel_patch_path))

    mock_isdir.assert_called_once()

    mock_isfile.assert_called_once()

  # Simulate behavior of 'os.path.isdir()' when the absolute path to the
  # $FILESDIR of a package exists and is a directory.
  @mock.patch.object(os.path, 'isdir', return_value=True)
  # Simulate behavior of 'os.path.isfile()' when the absolute path to the
  # patch exists and is a file.
  @mock.patch.object(os.path, 'isfile', return_value=True)
  def testConstructedPathToPatchSuccessfully(self, mock_isfile, mock_isdir):
    abs_path_to_filesdir = '/abs/path/to/filesdir'

    rel_patch_path = 'cherry/fixes_stdout.patch'

    abs_patch_path = os.path.join(abs_path_to_filesdir, rel_patch_path)

    self.assertEqual(
        patch_manager.GetPathToPatch(abs_path_to_filesdir, rel_patch_path),
        abs_patch_path)

    mock_isdir.assert_called_once()

    mock_isfile.assert_called_once()

  def testSuccessfullyGetPatchMetadataForPatchWithNoMetadata(self):
    expected_patch_metadata = 0, None, False

    test_patch = {
        'comment': 'Redirects output to stdout',
        'rel_patch_path': 'cherry/fixes_stdout.patch'
    }

    self.assertEqual(
        patch_manager.GetPatchMetadata(test_patch), expected_patch_metadata)

  def testSuccessfullyGetPatchMetdataForPatchWithSomeMetadata(self):
    expected_patch_metadata = 0, 1000, False

    test_patch = {
        'comment': 'Redirects output to stdout',
        'rel_patch_path': 'cherry/fixes_stdout.patch',
        'version_range': {
            'until': 1000,
        }
    }

    self.assertEqual(
        patch_manager.GetPatchMetadata(test_patch), expected_patch_metadata)

  def testFailedToApplyPatchWhenInvalidSrcPathIsPassedIn(self):
    src_path = '/abs/path/to/src'

    abs_patch_path = '/abs/path/to/filesdir/cherry/fixes_stdout.patch'

    # Verify the exception is raised when the absolute path to the unpacked
    # sources of a package is not a directory.
    with self.assertRaises(ValueError) as err:
      patch_manager.ApplyPatch(src_path, abs_patch_path)

      self.assertEqual(
          str(err.exception), 'Invalid src path provided: %s' % src_path)

  # Simulate behavior of 'os.path.isdir()' when the absolute path to the
  # unpacked sources of the package is valid and exists.
  @mock.patch.object(os.path, 'isdir', return_value=True)
  def testFailedToApplyPatchWhenPatchPathIsInvalid(self, mock_isdir):
    src_path = '/abs/path/to/src'

    abs_patch_path = '/abs/path/to/filesdir/cherry/fixes_stdout.patch'

    # Verify the exception is raised when the absolute path to the patch does
    # not exist or is not a file.
    with self.assertRaises(ValueError) as err:
      patch_manager.ApplyPatch(src_path, abs_patch_path)

    self.assertEqual(
        str(err.exception), 'Invalid patch file provided: '
        '%s' % abs_patch_path)

    mock_isdir.assert_called_once()

  # Simulate behavior of 'os.path.isdir()' when the absolute path to the
  # unpacked sources of the package is valid and exists.
  @mock.patch.object(os.path, 'isdir', return_value=True)
  @mock.patch.object(os.path, 'isfile', return_value=True)
  # Simulate behavior of 'os.path.isfile()' when the absolute path to the
  # patch exists and is a file.
  @mock.patch.object(patch_manager, 'check_output')
  def testFailedToApplyPatchInDryRun(self, mock_dry_run, mock_isfile,
                                     mock_isdir):

    # Simulate behavior of 'subprocess.check_output()' when '--dry-run'
    # fails on the applying patch.
    def FailedToApplyPatch(test_patch_cmd):
      # First argument is the return error code, the second argument is the
      # command that was run, and the third argument is the output.
      raise subprocess.CalledProcessError(1, test_patch_cmd, None)

    mock_dry_run.side_effect = FailedToApplyPatch

    src_path = '/abs/path/to/src'

    abs_patch_path = '/abs/path/to/filesdir/cherry/fixes_stdout.patch'

    self.assertEqual(patch_manager.ApplyPatch(src_path, abs_patch_path), False)

    mock_isdir.assert_called_once()

    mock_isfile.assert_called_once()

    mock_dry_run.assert_called_once()

  # Simulate behavior of 'os.path.isdir()' when the absolute path to the
  # unpacked sources of the package is valid and exists.
  @mock.patch.object(os.path, 'isdir', return_value=True)
  @mock.patch.object(os.path, 'isfile', return_value=True)
  # Simulate behavior of 'os.path.isfile()' when the absolute path to the
  # patch exists and is a file.
  @mock.patch.object(patch_manager, 'check_output')
  def testSuccessfullyAppliedPatch(self, mock_dry_run, mock_isfile, mock_isdir):
    src_path = '/abs/path/to/src'

    abs_patch_path = '/abs/path/to/filesdir/cherry/fixes_stdout.patch'

    self.assertEqual(patch_manager.ApplyPatch(src_path, abs_patch_path), True)

    mock_isdir.assert_called_once()

    mock_isfile.assert_called_once()

    self.assertEqual(mock_dry_run.call_count, 2)

  def testFailedToUpdatePatchMetadataFileWhenPatchFileNotEndInJson(self):
    patch = [{
        'comment': 'Redirects output to stdout',
        'rel_patch_path': 'cherry/fixes_output.patch',
        'version_range': {
            'from': 10,
        },
    }]

    abs_patch_path = '/abs/path/to/filesdir/PATCHES'

    # Verify the exception is raised when the absolute path to the patch
    # metadata file does not end in '.json'.
    with self.assertRaises(ValueError) as err:
      patch_manager.UpdatePatchMetadataFile(abs_patch_path, patch)

    self.assertEqual(
        str(err.exception), 'File does not end in ".json": '
        '%s' % abs_patch_path)

  def testSuccessfullyUpdatedPatchMetadataFile(self):
    test_updated_patch_metadata = [{
        'comment': 'Redirects output to stdout',
        'rel_patch_path': 'cherry/fixes_output.patch',
        'version_range': {
            'from': 10,
        }
    }]

    expected_patch_metadata = {
        'comment': 'Redirects output to stdout',
        'rel_patch_path': 'cherry/fixes_output.patch',
        'version_range': {
            'from': 10,
        }
    }

    with CreateTemporaryJsonFile() as json_test_file:
      patch_manager.UpdatePatchMetadataFile(json_test_file,
                                            test_updated_patch_metadata)

      # Make sure the updated patch metadata was written into the temporary
      # .json file.
      with open(json_test_file) as patch_file:
        patch_contents = json.load(patch_file)

        self.assertEqual(len(patch_contents), 1)

        self.assertDictEqual(patch_contents[0], expected_patch_metadata)

  @mock.patch.object(patch_manager, 'GetPathToPatch')
  def testExceptionThrownWhenHandlingPatches(self, mock_get_path_to_patch):
    filesdir_path = '/abs/path/to/filesdir'

    abs_patch_path = '/abs/path/to/filesdir/cherry/fixes_output.patch'

    rel_patch_path = 'cherry/fixes_output.patch'

    # Simulate behavior of 'GetPathToPatch()' when the absolute path to the
    # patch does not exist.
    def PathToPatchDoesNotExist(filesdir_path, rel_patch_path):
      raise ValueError('The absolute path to %s does not exist' % os.path.join(
          filesdir_path, rel_patch_path))

    # Use the test function to simulate the behavior of 'GetPathToPatch()'.
    mock_get_path_to_patch.side_effect = PathToPatchDoesNotExist

    test_patch_metadata = [{
        'comment': 'Redirects output to stdout',
        'rel_patch_path': rel_patch_path,
        'version_range': {
            'from': 10,
        }
    }]

    with CreateTemporaryJsonFile() as json_test_file:
      # Write the test patch metadata to the temporary .json file.
      with open(json_test_file, 'w') as json_file:
        WritePrettyJsonFile(test_patch_metadata, json_file)

      src_path = '/some/path/to/src'

      revision = 1000

      # Verify the exception is raised when the absolute path to a patch does
      # not exist.
      with self.assertRaises(ValueError) as err:
        patch_manager.HandlePatches(revision, json_test_file, filesdir_path,
                                    src_path, FailureModes.FAIL)

    self.assertEqual(
        str(err.exception),
        'The absolute path to %s does not exist' % abs_patch_path)

    mock_get_path_to_patch.assert_called_once_with(filesdir_path,
                                                   rel_patch_path)

  @mock.patch.object(patch_manager, 'GetPathToPatch')
  # Simulate behavior for 'ApplyPatch()' when an applicable patch failed to
  # apply.
  @mock.patch.object(patch_manager, 'ApplyPatch', return_value=False)
  def testExceptionThrownOnAFailedPatchInFailMode(self, mock_apply_patch,
                                                  mock_get_path_to_patch):
    filesdir_path = '/abs/path/to/filesdir'

    abs_patch_path = '/abs/path/to/filesdir/cherry/fixes_output.patch'

    rel_patch_path = 'cherry/fixes_output.patch'

    # Simulate behavior for 'GetPathToPatch()' when successfully constructed the
    # absolute path to the patch and the patch exists.
    mock_get_path_to_patch.return_value = abs_patch_path

    test_patch_metadata = [{
        'comment': 'Redirects output to stdout',
        'rel_patch_path': rel_patch_path,
        'version_range': {
            'from': 1000,
        },
    }]

    with CreateTemporaryJsonFile() as json_test_file:
      # Write the test patch metadata to the temporary .json file.
      with open(json_test_file, 'w') as json_file:
        WritePrettyJsonFile(test_patch_metadata, json_file)

      src_path = '/some/path/to/src'

      revision = 1000

      patch_name = 'fixes_output.patch'

      # Verify the exception is raised when the mode is 'fail' and an applicable
      # patch fails to apply.
      with self.assertRaises(ValueError) as err:
        patch_manager.HandlePatches(revision, json_test_file, filesdir_path,
                                    src_path, FailureModes.FAIL)

        self.assertEqual(
            str(err.exception), 'Failed to apply patch: %s' % patch_name)

    mock_get_path_to_patch.assert_called_once_with(filesdir_path,
                                                   rel_patch_path)

    mock_apply_patch.assert_called_once_with(src_path, abs_patch_path)

  @mock.patch.object(patch_manager, 'GetPathToPatch')
  @mock.patch.object(patch_manager, 'ApplyPatch')
  def testSomePatchesFailedToApplyInContinueMode(self, mock_apply_patch,
                                                 mock_get_path_to_patch):

    test_patch_1 = {
        'comment': 'Redirects output to stdout',
        'rel_patch_path': 'cherry/fixes_output.patch',
        'version_range': {
            'from': 1000,
            'until': 1250
        }
    }

    test_patch_2 = {
        'comment': 'Fixes input',
        'rel_patch_path': 'cherry/fixes_input.patch',
        'version_range': {
            'from': 1000
        }
    }

    test_patch_3 = {
        'comment': 'Adds a warning',
        'rel_patch_path': 'add_warning.patch',
        'version_range': {
            'from': 750,
            'until': 1500
        }
    }

    test_patch_4 = {
        'comment': 'Adds a helper function',
        'rel_patch_path': 'add_helper.patch',
        'version_range': {
            'from': 20,
            'until': 900
        }
    }

    test_patch_metadata = [
        test_patch_1, test_patch_2, test_patch_3, test_patch_4
    ]

    abs_path_to_filesdir = '/abs/path/to/filesdir'

    # Simulate behavior for 'GetPathToPatch()' when successfully constructed the
    # absolute path to the patch and the patch exists.
    @CallCountsToMockFunctions
    def MultipleCallsToGetPatchPath(call_count, filesdir_path, rel_patch_path):
      self.assertEqual(filesdir_path, abs_path_to_filesdir)

      if call_count < 4:
        self.assertEqual(rel_patch_path,
                         test_patch_metadata[call_count]['rel_patch_path'])

        return os.path.join(abs_path_to_filesdir,
                            test_patch_metadata[call_count]['rel_patch_path'])

      assert False, 'Unexpectedly called more than 4 times.'

    # Simulate behavior for 'ApplyPatch()' when applying multiple applicable
    # patches.
    @CallCountsToMockFunctions
    def MultipleCallsToApplyPatches(call_count, _src_path, path_to_patch):
      if call_count < 3:
        self.assertEqual(
            path_to_patch,
            os.path.join(abs_path_to_filesdir,
                         test_patch_metadata[call_count]['rel_patch_path']))

        # Simulate that the first patch successfully applied.
        return call_count == 0

      # 'ApplyPatch()' was called more times than expected (3 times).
      assert False, 'Unexpectedly called more than 3 times.'

    # Use test functions to simulate behavior.
    mock_get_path_to_patch.side_effect = MultipleCallsToGetPatchPath
    mock_apply_patch.side_effect = MultipleCallsToApplyPatches

    expected_applied_patches = ['fixes_output.patch']
    expected_failed_patches = ['fixes_input.patch', 'add_warning.patch']
    expected_non_applicable_patches = ['add_helper.patch']

    expected_patch_info_dict = {
        'applied_patches': expected_applied_patches,
        'failed_patches': expected_failed_patches,
        'non_applicable_patches': expected_non_applicable_patches,
        'disabled_patches': [],
        'removed_patches': [],
        'modified_metadata': None
    }

    with CreateTemporaryJsonFile() as json_test_file:
      # Write the test patch metadata to the temporary .json file.
      with open(json_test_file, 'w') as json_file:
        WritePrettyJsonFile(test_patch_metadata, json_file)

      src_path = '/some/path/to/src/'

      revision = 1000

      patch_info = patch_manager.HandlePatches(revision, json_test_file,
                                               abs_path_to_filesdir, src_path,
                                               FailureModes.CONTINUE)

    self.assertDictEqual(patch_info._asdict(), expected_patch_info_dict)

    self.assertEqual(mock_get_path_to_patch.call_count, 4)

    self.assertEqual(mock_apply_patch.call_count, 3)

  @mock.patch.object(patch_manager, 'GetPathToPatch')
  @mock.patch.object(patch_manager, 'ApplyPatch')
  def testSomePatchesAreDisabled(self, mock_apply_patch,
                                 mock_get_path_to_patch):

    test_patch_1 = {
        'comment': 'Redirects output to stdout',
        'rel_patch_path': 'cherry/fixes_output.patch',
        'version_range': {
            'from': 1000,
            'until': 1190
        }
    }

    test_patch_2 = {
        'comment': 'Fixes input',
        'rel_patch_path': 'cherry/fixes_input.patch',
        'version_range': {
            'from': 1000
        }
    }

    test_patch_3 = {
        'comment': 'Adds a warning',
        'rel_patch_path': 'add_warning.patch',
        'version_range': {
            'from': 750,
            'until': 1500
        }
    }

    test_patch_4 = {
        'comment': 'Adds a helper function',
        'rel_patch_path': 'add_helper.patch',
        'version_range': {
            'from': 20,
            'until': 2000
        }
    }

    test_patch_metadata = [
        test_patch_1, test_patch_2, test_patch_3, test_patch_4
    ]

    abs_path_to_filesdir = '/abs/path/to/filesdir'

    # Simulate behavior for 'GetPathToPatch()' when successfully constructed the
    # absolute path to the patch and the patch exists.
    @CallCountsToMockFunctions
    def MultipleCallsToGetPatchPath(call_count, filesdir_path, rel_patch_path):
      self.assertEqual(filesdir_path, abs_path_to_filesdir)

      if call_count < 4:
        self.assertEqual(rel_patch_path,
                         test_patch_metadata[call_count]['rel_patch_path'])

        return os.path.join(abs_path_to_filesdir,
                            test_patch_metadata[call_count]['rel_patch_path'])

      # 'GetPathToPatch()' was called more times than expected (4 times).
      assert False, 'Unexpectedly called more than 4 times.'

    # Simulate behavior for 'ApplyPatch()' when applying multiple applicable
    # patches.
    @CallCountsToMockFunctions
    def MultipleCallsToApplyPatches(call_count, _src_path, path_to_patch):
      if call_count < 3:
        self.assertEqual(
            path_to_patch,
            os.path.join(abs_path_to_filesdir,
                         test_patch_metadata[call_count + 1]['rel_patch_path']))

        # Simulate that the second patch applied successfully.
        return call_count == 1

      # 'ApplyPatch()' was called more times than expected (3 times).
      assert False, 'Unexpectedly called more than 3 times.'

    # Use test functions to simulate behavior.
    mock_get_path_to_patch.side_effect = MultipleCallsToGetPatchPath
    mock_apply_patch.side_effect = MultipleCallsToApplyPatches

    expected_applied_patches = ['add_warning.patch']
    expected_failed_patches = ['fixes_input.patch', 'add_helper.patch']
    expected_disabled_patches = ['fixes_input.patch', 'add_helper.patch']
    expected_non_applicable_patches = ['fixes_output.patch']

    # Assigned 'None' for now, but it is expected that the patch metadata file
    # will be modified, so the 'expected_patch_info_dict's' value for the
    # key 'modified_metadata' will get updated to the temporary .json file once
    # the file is created.
    expected_modified_metadata_file = None

    expected_patch_info_dict = {
        'applied_patches': expected_applied_patches,
        'failed_patches': expected_failed_patches,
        'non_applicable_patches': expected_non_applicable_patches,
        'disabled_patches': expected_disabled_patches,
        'removed_patches': [],
        'modified_metadata': expected_modified_metadata_file
    }

    with CreateTemporaryJsonFile() as json_test_file:
      # Write the test patch metadata to the temporary .json file.
      with open(json_test_file, 'w') as json_file:
        WritePrettyJsonFile(test_patch_metadata, json_file)

      expected_patch_info_dict['modified_metadata'] = json_test_file

      src_path = '/some/path/to/src/'

      revision = 1200

      patch_info = patch_manager.HandlePatches(revision, json_test_file,
                                               abs_path_to_filesdir, src_path,
                                               FailureModes.DISABLE_PATCHES)

      self.assertDictEqual(patch_info._asdict(), expected_patch_info_dict)

      # 'test_patch_1' and 'test_patch_3' were not modified/disabled, so their
      # dictionary is the same, but 'test_patch_2' and 'test_patch_4' were
      # disabled, so their 'end_version' would be set to 1200, which was the
      # value passed into 'HandlePatches()' for the 'svn_version'.
      test_patch_2['end_version'] = 1200
      test_patch_4['end_version'] = 1200

      expected_json_file = [
          test_patch_1, test_patch_2, test_patch_3, test_patch_4
      ]

      # Make sure the updated patch metadata was written into the temporary
      # .json file.
      with open(json_test_file) as patch_file:
        new_json_file_contents = json.load(patch_file)

        self.assertListEqual(new_json_file_contents, expected_json_file)

    self.assertEqual(mock_get_path_to_patch.call_count, 4)

    self.assertEqual(mock_apply_patch.call_count, 3)

  @mock.patch.object(patch_manager, 'GetPathToPatch')
  @mock.patch.object(patch_manager, 'ApplyPatch')
  def testSomePatchesAreRemoved(self, mock_apply_patch, mock_get_path_to_patch):
    # For the 'remove_patches' mode, this patch is expected to be in the
    # 'non_applicable_patches' list and 'removed_patches' list because
    # the 'svn_version' (1500) >= 'end_version' (1190).
    test_patch_1 = {
        'comment': 'Redirects output to stdout',
        'rel_patch_path': 'cherry/fixes_output.patch',
        'version_range': {
            'from': 1000,
            'until': 1190
        }
    }

    # For the 'remove_patches' mode, this patch is expected to be in the
    # 'applicable_patches' list (which is the list that the .json file will be
    # updated with) because the 'svn_version' < 'inf' (this patch does not have
    # an 'end_version' value which implies 'end_version' == 'inf').
    test_patch_2 = {
        'comment': 'Fixes input',
        'rel_patch_path': 'cherry/fixes_input.patch',
        'version_range': {
            'from': 1000
        }
    }

    # For the 'remove_patches' mode, this patch is expected to be in the
    # 'non_applicable_patches' list and 'removed_patches' list because
    # the 'svn_version' (1500) >= 'end_version' (1500).
    test_patch_3 = {
        'comment': 'Adds a warning',
        'rel_patch_path': 'add_warning.patch',
        'version_range': {
            'from': 750,
            'until': 1500
        }
    }

    # For the 'remove_patches' mode, this patch is expected to be in the
    # 'non_applicable_patches' list and 'removed_patches' list because
    # the 'svn_version' (1500) >= 'end_version' (1400).
    test_patch_4 = {
        'comment': 'Adds a helper function',
        'rel_patch_path': 'add_helper.patch',
        'version_range': {
            'from': 20,
            'until': 1400
        }
    }

    test_patch_metadata = [
        test_patch_1, test_patch_2, test_patch_3, test_patch_4
    ]

    abs_path_to_filesdir = '/abs/path/to/filesdir'

    # Simulate behavior for 'GetPathToPatch()' when successfully constructed the
    # absolute path to the patch and the patch exists.
    @CallCountsToMockFunctions
    def MultipleCallsToGetPatchPath(call_count, filesdir_path, rel_patch_path):
      self.assertEqual(filesdir_path, abs_path_to_filesdir)

      if call_count < 4:
        self.assertEqual(rel_patch_path,
                         test_patch_metadata[call_count]['rel_patch_path'])

        return os.path.join(abs_path_to_filesdir,
                            test_patch_metadata[call_count]['rel_patch_path'])

      assert False, 'Unexpectedly called more than 4 times.'

    # Use the test function to simulate behavior of 'GetPathToPatch()'.
    mock_get_path_to_patch.side_effect = MultipleCallsToGetPatchPath

    expected_applied_patches = []
    expected_failed_patches = []
    expected_disabled_patches = []
    expected_non_applicable_patches = [
        'fixes_output.patch', 'add_warning.patch', 'add_helper.patch'
    ]
    expected_removed_patches = [
        '/abs/path/to/filesdir/cherry/fixes_output.patch',
        '/abs/path/to/filesdir/add_warning.patch',
        '/abs/path/to/filesdir/add_helper.patch'
    ]

    # Assigned 'None' for now, but it is expected that the patch metadata file
    # will be modified, so the 'expected_patch_info_dict's' value for the
    # key 'modified_metadata' will get updated to the temporary .json file once
    # the file is created.
    expected_modified_metadata_file = None

    expected_patch_info_dict = {
        'applied_patches': expected_applied_patches,
        'failed_patches': expected_failed_patches,
        'non_applicable_patches': expected_non_applicable_patches,
        'disabled_patches': expected_disabled_patches,
        'removed_patches': expected_removed_patches,
        'modified_metadata': expected_modified_metadata_file
    }

    with CreateTemporaryJsonFile() as json_test_file:
      # Write the test patch metadata to the temporary .json file.
      with open(json_test_file, 'w') as json_file:
        WritePrettyJsonFile(test_patch_metadata, json_file)

      expected_patch_info_dict['modified_metadata'] = json_test_file

      abs_path_to_filesdir = '/abs/path/to/filesdir'

      src_path = '/some/path/to/src/'

      revision = 1500

      patch_info = patch_manager.HandlePatches(revision, json_test_file,
                                               abs_path_to_filesdir, src_path,
                                               FailureModes.REMOVE_PATCHES)

      self.assertDictEqual(patch_info._asdict(), expected_patch_info_dict)

      # 'test_patch_2' was an applicable patch, so this patch will be the only
      # patch that is in temporary .json file. The other patches were not
      # applicable (they failed the applicable check), so they will not be in
      # the .json file.
      expected_json_file = [test_patch_2]

      # Make sure the updated patch metadata was written into the temporary
      # .json file.
      with open(json_test_file) as patch_file:
        new_json_file_contents = json.load(patch_file)

        self.assertListEqual(new_json_file_contents, expected_json_file)

    self.assertEqual(mock_get_path_to_patch.call_count, 4)

    mock_apply_patch.assert_not_called()

  @mock.patch.object(patch_manager, 'GetPathToPatch')
  @mock.patch.object(patch_manager, 'ApplyPatch')
  def testSuccessfullyDidNotRemoveAFuturePatch(self, mock_apply_patch,
                                               mock_get_path_to_patch):

    # For the 'remove_patches' mode, this patch is expected to be in the
    # 'non_applicable_patches' list and 'removed_patches' list because
    # the 'svn_version' (1200) >= 'end_version' (1190).
    test_patch_1 = {
        'comment': 'Redirects output to stdout',
        'rel_patch_path': 'cherry/fixes_output.patch',
        'version_range': {
            'from': 1000,
            'until': 1190
        }
    }

    # For the 'remove_patches' mode, this patch is expected to be in the
    # 'applicable_patches' list (which is the list that the .json file will be
    # updated with) because the 'svn_version' < 'inf' (this patch does not have
    # an 'end_version' value which implies 'end_version' == 'inf').
    test_patch_2 = {
        'comment': 'Fixes input',
        'rel_patch_path': 'cherry/fixes_input.patch',
        'version_range': {
            'from': 1000,
        }
    }

    # For the 'remove_patches' mode, this patch is expected to be in the
    # 'applicable_patches' list because 'svn_version' >= 'start_version' and
    # 'svn_version' < 'end_version'.
    test_patch_3 = {
        'comment': 'Adds a warning',
        'rel_patch_path': 'add_warning.patch',
        'version_range': {
            'from': 750,
            'until': 1500
        }
    }

    # For the 'remove_patches' mode, this patch is expected to be in the
    # 'applicable_patches' list because the patch is from the future (e.g.
    # 'start_version' > 'svn_version' (1200), so it should NOT be removed.
    test_patch_4 = {
        'comment': 'Adds a helper function',
        'rel_patch_path': 'add_helper.patch',
        'version_range': {
            'from': 1600,
            'until': 2000
        }
    }

    test_patch_metadata = [
        test_patch_1, test_patch_2, test_patch_3, test_patch_4
    ]

    abs_path_to_filesdir = '/abs/path/to/filesdir'

    # Simulate behavior for 'GetPathToPatch()' when successfully constructed the
    # absolute path to the patch and the patch exists.
    @CallCountsToMockFunctions
    def MultipleCallsToGetPatchPath(call_count, filesdir_path, rel_patch_path):
      self.assertEqual(filesdir_path, abs_path_to_filesdir)

      if call_count < 4:
        self.assertEqual(rel_patch_path,
                         test_patch_metadata[call_count]['rel_patch_path'])

        return os.path.join(abs_path_to_filesdir,
                            test_patch_metadata[call_count]['rel_patch_path'])

      # 'GetPathToPatch()' was called more times than expected (4 times).
      assert False, 'Unexpectedly called more than 4 times.'

    # Use the test function to simulate behavior of 'GetPathToPatch()'.
    mock_get_path_to_patch.side_effect = MultipleCallsToGetPatchPath

    expected_applied_patches = []
    expected_failed_patches = []
    expected_disabled_patches = []

    # 'add_helper.patch' is still a 'non applicable' patch meaning it does not
    # apply in revision 1200 but it will NOT be removed because it is a future
    # patch.
    expected_non_applicable_patches = ['fixes_output.patch', 'add_helper.patch']
    expected_removed_patches = [
        '/abs/path/to/filesdir/cherry/fixes_output.patch'
    ]

    # Assigned 'None' for now, but it is expected that the patch metadata file
    # will be modified, so the 'expected_patch_info_dict's' value for the
    # key 'modified_metadata' will get updated to the temporary .json file once
    # the file is created.
    expected_modified_metadata_file = None

    expected_patch_info_dict = {
        'applied_patches': expected_applied_patches,
        'failed_patches': expected_failed_patches,
        'non_applicable_patches': expected_non_applicable_patches,
        'disabled_patches': expected_disabled_patches,
        'removed_patches': expected_removed_patches,
        'modified_metadata': expected_modified_metadata_file
    }

    with CreateTemporaryJsonFile() as json_test_file:
      # Write the test patch metadata to the temporary .json file.
      with open(json_test_file, 'w') as json_file:
        WritePrettyJsonFile(test_patch_metadata, json_file)

      expected_patch_info_dict['modified_metadata'] = json_test_file

      src_path = '/some/path/to/src/'

      revision = 1200

      patch_info = patch_manager.HandlePatches(revision, json_test_file,
                                               abs_path_to_filesdir, src_path,
                                               FailureModes.REMOVE_PATCHES)

      self.assertDictEqual(patch_info._asdict(), expected_patch_info_dict)

      # 'test_patch_2' was an applicable patch, so this patch will be the only
      # patch that is in temporary .json file. The other patches were not
      # applicable (they failed the applicable check), so they will not be in
      # the .json file.
      expected_json_file = [test_patch_2, test_patch_3, test_patch_4]

      # Make sure the updated patch metadata was written into the temporary
      # .json file.
      with open(json_test_file) as patch_file:
        new_json_file_contents = json.load(patch_file)

        self.assertListEqual(new_json_file_contents, expected_json_file)

    self.assertEqual(mock_get_path_to_patch.call_count, 4)

    mock_apply_patch.assert_not_called()


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