b7aead97223100b309cf99b666c36bf94a597dad
[WebKit-https.git] / Tools / Scripts / webkitpy / common / checkout / checkout_unittest.py
1 # Copyright (C) 2010 Google Inc. All rights reserved.
2 #
3 # Redistribution and use in source and binary forms, with or without
4 # modification, are permitted provided that the following conditions are
5 # met:
6 #
7 #    * Redistributions of source code must retain the above copyright
8 # notice, this list of conditions and the following disclaimer.
9 #    * Redistributions in binary form must reproduce the above
10 # copyright notice, this list of conditions and the following disclaimer
11 # in the documentation and/or other materials provided with the
12 # distribution.
13 #    * Neither the name of Google Inc. nor the names of its
14 # contributors may be used to endorse or promote products derived from
15 # this software without specific prior written permission.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 import codecs
30 import os
31 import shutil
32 import tempfile
33 import unittest2 as unittest
34
35 from .checkout import Checkout
36 from .changelog import ChangeLogEntry
37 from .scm import CommitMessage, SCMDetector
38 from .scm.scm_mock import MockSCM
39 from webkitpy.common.system.executive import Executive, ScriptError
40 from webkitpy.common.system.filesystem import FileSystem  # FIXME: This should not be needed.
41 from webkitpy.common.system.filesystem_mock import MockFileSystem
42 from webkitpy.common.system.executive_mock import MockExecutive
43 from webkitpy.common.system.outputcapture import OutputCapture
44 from webkitpy.thirdparty.mock import Mock
45
46
47 _changelog1entry1 = u"""2010-03-25  Tor Arne Vestb\u00f8  <vestbo@webkit.org>
48
49         Unreviewed build fix to un-break webkit-patch land.
50
51         Move commit_message_for_this_commit from scm to checkout
52         https://bugs.webkit.org/show_bug.cgi?id=36629
53
54         * Scripts/webkitpy/common/checkout/api.py: import scm.CommitMessage
55 """
56 _changelog1entry2 = u"""2010-03-25  Adam Barth  <abarth@webkit.org>
57
58         Reviewed by Eric Seidel.
59
60         Move commit_message_for_this_commit from scm to checkout
61         https://bugs.webkit.org/show_bug.cgi?id=36629
62
63         * Scripts/webkitpy/common/checkout/api.py:
64 """
65 _changelog1 = u"\n".join([_changelog1entry1, _changelog1entry2])
66 _changelog2 = u"""2010-03-25  Tor Arne Vestb\u00f8  <vestbo@webkit.org>
67
68         Unreviewed build fix to un-break webkit-patch land.
69
70         Second part of this complicated change by me, Tor Arne Vestb\u00f8!
71
72         * Path/To/Complicated/File: Added.
73
74 2010-03-25  Adam Barth  <abarth@webkit.org>
75
76         Reviewed by Eric Seidel.
77
78         Filler change.
79 """
80
81 class CommitMessageForThisCommitTest(unittest.TestCase):
82     expected_commit_message = u"""Unreviewed build fix to un-break webkit-patch land.
83
84 Tools: 
85
86 Move commit_message_for_this_commit from scm to checkout
87 https://bugs.webkit.org/show_bug.cgi?id=36629
88
89 * Scripts/webkitpy/common/checkout/api.py: import scm.CommitMessage
90
91 LayoutTests: 
92
93 Second part of this complicated change by me, Tor Arne Vestb\u00f8!
94
95 * Path/To/Complicated/File: Added.
96 """
97
98     def setUp(self):
99         # FIXME: This should not need to touch the filesystem, however
100         # ChangeLog is difficult to mock at current.
101         self.filesystem = FileSystem()
102         self.temp_dir = str(self.filesystem.mkdtemp(suffix="changelogs"))
103         self.old_cwd = self.filesystem.getcwd()
104         self.filesystem.chdir(self.temp_dir)
105
106         # Trick commit-log-editor into thinking we're in a Subversion working copy so it won't
107         # complain about not being able to figure out what SCM is in use.
108         # FIXME: VCSTools.pm is no longer so easily fooled.  It logs because "svn info" doesn't
109         # treat a bare .svn directory being part of an svn checkout.
110         self.filesystem.maybe_make_directory(".svn")
111
112         self.changelogs = map(self.filesystem.abspath, (self.filesystem.join("Tools", "ChangeLog"), self.filesystem.join("LayoutTests", "ChangeLog")))
113         for path, contents in zip(self.changelogs, (_changelog1, _changelog2)):
114             self.filesystem.maybe_make_directory(self.filesystem.dirname(path))
115             self.filesystem.write_text_file(path, contents)
116
117     def tearDown(self):
118         self.filesystem.rmtree(self.temp_dir)
119         self.filesystem.chdir(self.old_cwd)
120
121     def test_commit_message_for_this_commit(self):
122         executive = Executive()
123
124         def mock_run(*args, **kwargs):
125             # Note that we use a real Executive here, not a MockExecutive, so we can test that we're
126             # invoking commit-log-editor correctly.
127             env = os.environ.copy()
128             env['CHANGE_LOG_EMAIL_ADDRESS'] = 'vestbo@webkit.org'
129             kwargs['env'] = env
130             return executive.run_command(*args, **kwargs)
131
132         detector = SCMDetector(self.filesystem, executive)
133         real_scm = detector.detect_scm_system(self.old_cwd)
134
135         mock_scm = MockSCM()
136         mock_scm.run = mock_run
137         mock_scm.script_path = real_scm.script_path
138
139         checkout = Checkout(mock_scm)
140         checkout.modified_changelogs = lambda git_commit, changed_files=None: self.changelogs
141         commit_message = checkout.commit_message_for_this_commit(git_commit=None, return_stderr=True)
142         # Throw away the first line - a warning about unknown VCS root.
143         commit_message.message_lines = commit_message.message_lines[1:]
144         self.assertMultiLineEqual(commit_message.message(), self.expected_commit_message)
145
146
147 class CheckoutTest(unittest.TestCase):
148     def _make_checkout(self):
149         return Checkout(scm=MockSCM(), filesystem=MockFileSystem(), executive=MockExecutive())
150
151     def test_latest_entry_for_changelog_at_revision(self):
152         def mock_contents_at_revision(changelog_path, revision):
153             self.assertEqual(changelog_path, "foo")
154             self.assertEqual(revision, "bar")
155             # contents_at_revision is expected to return a byte array (str)
156             # so we encode our unicode ChangeLog down to a utf-8 stream.
157             # The ChangeLog utf-8 decoding should ignore invalid codepoints.
158             invalid_utf8 = "\255"
159             return _changelog1.encode("utf-8") + invalid_utf8
160         checkout = self._make_checkout()
161         checkout._scm.contents_at_revision = mock_contents_at_revision
162         entry = checkout._latest_entry_for_changelog_at_revision("foo", "bar")
163         self.assertMultiLineEqual(entry.contents(), _changelog1entry1)  # Pylint is confused about this line, pylint: disable=E1101
164
165     # FIXME: This tests a hack around our current changed_files handling.
166     # Right now changelog_entries_for_revision tries to fetch deleted files
167     # from revisions, resulting in a ScriptError exception.  Test that we
168     # recover from those and still return the other ChangeLog entries.
169     def test_changelog_entries_for_revision(self):
170         checkout = self._make_checkout()
171         checkout._scm.changed_files_for_revision = lambda revision: ['foo/ChangeLog', 'bar/ChangeLog']
172
173         def mock_latest_entry_for_changelog_at_revision(path, revision):
174             if path == "foo/ChangeLog":
175                 return 'foo'
176             raise ScriptError()
177
178         checkout._latest_entry_for_changelog_at_revision = mock_latest_entry_for_changelog_at_revision
179
180         # Even though fetching one of the entries failed, the other should succeed.
181         entries = checkout.changelog_entries_for_revision(1)
182         self.assertEqual(len(entries), 1)
183         self.assertEqual(entries[0], 'foo')
184
185     def test_commit_info_for_revision(self):
186         checkout = self._make_checkout()
187         checkout._scm.changed_files_for_revision = lambda revision: ['path/to/file', 'another/file']
188         checkout._scm.committer_email_for_revision = lambda revision, changed_files=None: "committer@example.com"
189         checkout.changelog_entries_for_revision = lambda revision, changed_files=None: [ChangeLogEntry(_changelog1entry1)]
190         commitinfo = checkout.commit_info_for_revision(4)
191         self.assertEqual(commitinfo.bug_id(), 36629)
192         self.assertEqual(commitinfo.author_name(), u"Tor Arne Vestb\u00f8")
193         self.assertEqual(commitinfo.author_email(), "vestbo@webkit.org")
194         self.assertIsNone(commitinfo.reviewer_text())
195         self.assertIsNone(commitinfo.reviewer())
196         self.assertEqual(commitinfo.committer_email(), "committer@example.com")
197         self.assertIsNone(commitinfo.committer())
198         self.assertEqual(commitinfo.to_json(), {
199             'bug_id': 36629,
200             'author_email': 'vestbo@webkit.org',
201             'changed_files': [
202                 'path/to/file',
203                 'another/file',
204             ],
205             'reviewer_text': None,
206             'author_name': u'Tor Arne Vestb\xf8',
207         })
208
209         checkout.changelog_entries_for_revision = lambda revision, changed_files=None: []
210         self.assertIsNone(checkout.commit_info_for_revision(1))
211
212     def test_bug_id_for_revision(self):
213         checkout = self._make_checkout()
214         checkout._scm.committer_email_for_revision = lambda revision: "committer@example.com"
215         checkout.changelog_entries_for_revision = lambda revision, changed_files=None: [ChangeLogEntry(_changelog1entry1)]
216         self.assertEqual(checkout.bug_id_for_revision(4), 36629)
217
218     def test_bug_id_for_this_commit(self):
219         checkout = self._make_checkout()
220         checkout.commit_message_for_this_commit = lambda git_commit, changed_files=None: CommitMessage(ChangeLogEntry(_changelog1entry1).contents().splitlines())
221         self.assertEqual(checkout.bug_id_for_this_commit(git_commit=None), 36629)
222
223     def test_modified_changelogs(self):
224         checkout = self._make_checkout()
225         checkout._scm.checkout_root = "/foo/bar"
226         checkout._scm.changed_files = lambda git_commit: ["file1", "ChangeLog", "relative/path/ChangeLog"]
227         expected_changlogs = ["/foo/bar/ChangeLog", "/foo/bar/relative/path/ChangeLog"]
228         self.assertEqual(checkout.modified_changelogs(git_commit=None), expected_changlogs)
229
230     def test_suggested_reviewers(self):
231         def mock_changelog_entries_for_revision(revision, changed_files=None):
232             if revision % 2 == 0:
233                 return [ChangeLogEntry(_changelog1entry1)]
234             return [ChangeLogEntry(_changelog1entry2)]
235
236         def mock_revisions_changing_file(path, limit=5):
237             if path.endswith("ChangeLog"):
238                 return [3]
239             return [4, 8]
240
241         checkout = self._make_checkout()
242         checkout._scm.checkout_root = "/foo/bar"
243         checkout._scm.changed_files = lambda git_commit: ["file1", "file2", "relative/path/ChangeLog"]
244         checkout._scm.revisions_changing_file = mock_revisions_changing_file
245         checkout.changelog_entries_for_revision = mock_changelog_entries_for_revision
246         reviewers = checkout.suggested_reviewers(git_commit=None)
247         reviewer_names = [reviewer.full_name for reviewer in reviewers]
248         self.assertEqual(reviewer_names, [u'Tor Arne Vestb\xf8'])
249
250     def test_apply_patch(self):
251         checkout = self._make_checkout()
252         checkout._executive = MockExecutive(should_log=True)
253         checkout._scm.script_path = lambda script: script
254         mock_patch = Mock()
255         mock_patch.contents = lambda: "foo"
256         mock_patch.reviewer = lambda: None
257         expected_logs = "MOCK run_command: ['svn-apply', '--force'], cwd=/mock-checkout, input=foo\n"
258         OutputCapture().assert_outputs(self, checkout.apply_patch, [mock_patch], expected_logs=expected_logs)