summaryrefslogtreecommitdiffstats
path: root/tools/vim/tests/chromium.ycm_extra_conf_unittest.py
blob: b02dcf5c5d0308fb85e02640acca7c896b04165c (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
#!/usr/bin/env python

# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Tests for chromium.ycm_extra_conf.

These tests should be getting picked up by the PRESUBMIT.py in /tools/vim.
Currently the tests only run on Linux and require 'ninja' to be available on
PATH. Due to these requirements, the tests should only be run on upload.
"""

import imp
import os
import shutil
import stat
import string
import subprocess
import sys
import tempfile
import unittest

def CreateFile(path,
               copy_from = None,
               format_with = None,
               make_executable = False):
  """Creates a file.

  If a file already exists at |path|, it will be overwritten.

  Args:
    path: (String) Absolute path for file to be created.
    copy_from: (String or None) Absolute path to source file. If valid, the
               contents of this file will be written to |path|.
    format_with: (Dictionary or None) Only valid if |copy_from| is also valid.
               The contents of the file at |copy_from| will be passed through
               string.Formatter.vformat() with this parameter as the dictionary.
    make_executable: (Boolean) If true, |file| will be made executable.
  """
  if not os.path.isabs(path):
    raise Exception(
        'Argument |path| needs to be an absolute path. Got: "{}"'.format(path))
  with open(path, 'w') as f:
    if copy_from:
      with open(copy_from, 'r') as source:
        contents = source.read()
        if format_with:
          formatter = string.Formatter()
          contents = formatter.vformat(contents, None, format_with)
        f.write(contents)
  if make_executable:
    statinfo = os.stat(path)
    os.chmod(path, statinfo.st_mode | stat.S_IXUSR)

@unittest.skipIf(sys.platform.startswith('linux'),
                 'Tests are only valid on Linux.')
class Chromium_ycmExtraConfTest_NotOnLinux(unittest.TestCase):
  def testAlwaysFailsIfNotRunningOnLinux(self):
    self.fail('Changes to chromium.ycm_extra_conf.py currently need to be ' \
              'uploaded from Linux since the tests only run on Linux.')

@unittest.skipUnless(sys.platform.startswith('linux'),
                     'Tests are only valid on Linux.')
class Chromium_ycmExtraConfTest(unittest.TestCase):

  def SetUpFakeChromeTreeBelowPath(self):
    """Create fake Chromium source tree under self.test_root.

    The fake source tree has the following contents:

    <self.test_root>
      |  .gclient
      |
      +-- src
      |   |  DEPS
      |   |  three.cc
      |   |
      |   +-- .git
      |   |
      |   +-- include
      |       |
      |       +-- a
      |       |
      |       +-- b
      |
      +-- out
          |
          +-- Debug
                build.ninja
    """
    self.chrome_root = os.path.abspath(os.path.normpath(
        os.path.join(self.test_root, 'src')))
    self.out_dir = os.path.join(self.chrome_root, 'out', 'Debug')

    os.makedirs(self.chrome_root)
    os.makedirs(os.path.join(self.chrome_root, '.git'))
    os.makedirs(self.out_dir)
    os.makedirs(os.path.join(self.chrome_root, 'include', 'a'))
    os.makedirs(os.path.join(self.chrome_root, 'include', 'b'))

    CreateFile(os.path.join(self.test_root, '.gclient'))
    CreateFile(os.path.join(self.chrome_root, 'DEPS'))
    CreateFile(os.path.join(self.chrome_root, 'three.cc'))

    # Fake ninja build file. Applications of 'cxx' rule are tagged by which
    # source file was used as input so that the test can verify that the correct
    # build dependency was used.
    CreateFile(os.path.join(self.out_dir, 'build.ninja'),
               copy_from=os.path.join(self.test_data_path,
                                      'fake_build_ninja.txt'))

    # This is a fake clang++ like script that spits out some directories that
    # will be interpreted to be system include paths.
    CreateFile(os.path.join(self.chrome_root, 'fake-clang++'),
               copy_from=os.path.join(self.test_data_path,
                                      'fake-clang++.sh'),
               format_with={'chrome_root': self.chrome_root},
               make_executable=True)

  def NormalizeString(self, string):
    return string.replace(self.out_dir, '[OUT]').\
        replace(self.chrome_root, '[SRC]')

  def NormalizeStringsInList(self, list_of_strings):
    return [self.NormalizeString(s) for s in list_of_strings]

  def setUp(self):
    self.actual_chrome_root = os.path.normpath(
        os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../..'))
    sys.path.append(os.path.join(self.actual_chrome_root, 'tools', 'vim'))
    self.test_data_path = os.path.join(self.actual_chrome_root, 'tools', 'vim',
                                       'tests', 'data')
    self.ycm_extra_conf = imp.load_source('ycm_extra_conf',
                                          'chromium.ycm_extra_conf.py')
    self.test_root = tempfile.mkdtemp()
    self.SetUpFakeChromeTreeBelowPath()

  def tearDown(self):
    if self.test_root:
      shutil.rmtree(self.test_root)

  def testNinjaIsAvailable(self):
    p = subprocess.Popen(['ninja', '--version'], stdout=subprocess.PIPE)
    _, _ = p.communicate()
    self.assertFalse(p.returncode)

  def testFindChromeSrc(self):
    chrome_source = self.ycm_extra_conf.FindChromeSrcFromFilename(
        os.path.join(self.chrome_root, 'chrome', 'one.cpp'))
    self.assertEquals(chrome_source, self.chrome_root)

    chrome_source = self.ycm_extra_conf.FindChromeSrcFromFilename(
        os.path.join(self.chrome_root, 'one.cpp'))
    self.assertEquals(chrome_source, self.chrome_root)

  def testCommandLineForKnownCppFile(self):
    command_line = self.ycm_extra_conf.GetClangCommandLineFromNinjaForSource(
        self.out_dir, os.path.join(self.chrome_root, 'one.cpp'))
    self.assertEquals(
        command_line,
        '../../fake-clang++ -Ia -Itag-one ../../one.cpp -o obj/one.o')

  def testCommandLineForUnknownCppFile(self):
    command_line = self.ycm_extra_conf.GetClangCommandLineFromNinjaForSource(
        self.out_dir, os.path.join(self.chrome_root, 'unknown.cpp'))
    self.assertEquals(command_line, None)

  def testSystemIncludeDirectoryFlags(self):
    flags = self.ycm_extra_conf.SystemIncludeDirectoryFlags(
        os.path.join(self.chrome_root, 'fake-clang++'), [])
    flags = self.NormalizeStringsInList(flags)
    self.assertEquals(
        flags,
        ['-isystem', '[SRC]/include/a', '-isystem', '[SRC]/include/b'])

  def testGetClangOptionsForKnownCppFile(self):
    clang_options, sys_includes = \
        self.ycm_extra_conf.GetClangOptionsFromNinjaForFilename(
            self.chrome_root, os.path.join(self.chrome_root, 'one.cpp'))
    self.assertEquals(self.NormalizeStringsInList(clang_options), [
        '-I[SRC]',
        '-Wno-unknown-warning-option',
        '-I[OUT]/a',
        '-I[OUT]/tag-one'
        ])
    self.assertEquals(self.NormalizeStringsInList(sys_includes), [
        '-isystem', '[SRC]/include/a',
        '-isystem', '[SRC]/include/b'
        ])

  def testGetFlagsForFileForKnownCppFile(self):
    result = self.ycm_extra_conf.FlagsForFile(
        os.path.join(self.chrome_root, 'one.cpp'))
    self.assertTrue(result)
    self.assertTrue('do_cache' in result)
    self.assertTrue(result['do_cache'])
    self.assertTrue('flags' in result)
    self.assertEquals(self.NormalizeStringsInList(result['flags']), [
        '-DUSE_CLANG_COMPLETER',
        '-std=c++11',
        '-x', 'c++',
        '-I[SRC]',
        '-Wno-unknown-warning-option',
        '-I[OUT]/a',
        '-I[OUT]/tag-one',
        '-isystem', '[SRC]/include/a',
        '-isystem', '[SRC]/include/b'
        ])

  def testGetFlagsForFileForUnknownCppFile(self):
    result = self.ycm_extra_conf.FlagsForFile(
        os.path.join(self.chrome_root, 'nonexistent.cpp'))
    self.assertTrue(result)
    self.assertTrue('do_cache' in result)
    self.assertTrue(result['do_cache'])
    self.assertTrue('flags' in result)
    self.assertEquals(self.NormalizeStringsInList(result['flags']), [
        '-DUSE_CLANG_COMPLETER',
        '-std=c++11',
        '-x', 'c++',
        '-I[SRC]',
        '-Wno-unknown-warning-option',
        '-I[OUT]/a',
        '-I[OUT]/tag-default',
        '-isystem', '[SRC]/include/a',
        '-isystem', '[SRC]/include/b'
        ])

  def testGetFlagsForFileForUnknownHeaderFile(self):
    result = self.ycm_extra_conf.FlagsForFile(
        os.path.join(self.chrome_root, 'nonexistent.h'))
    self.assertTrue(result)
    self.assertTrue('do_cache' in result)
    self.assertTrue(result['do_cache'])
    self.assertTrue('flags' in result)
    self.assertEquals(self.NormalizeStringsInList(result['flags']), [
        '-DUSE_CLANG_COMPLETER',
        '-std=c++11',
        '-x', 'c++',
        '-I[SRC]',
        '-Wno-unknown-warning-option',
        '-I[OUT]/a',
        '-I[OUT]/tag-default',
        '-isystem', '[SRC]/include/a',
        '-isystem', '[SRC]/include/b'
        ])

  def testGetFlagsForFileForKnownHeaderFileWithAssociatedCppFile(self):
    result = self.ycm_extra_conf.FlagsForFile(
        os.path.join(self.chrome_root, 'three.h'))
    self.assertTrue(result)
    self.assertTrue('do_cache' in result)
    self.assertTrue(result['do_cache'])
    self.assertTrue('flags' in result)
    self.assertEquals(self.NormalizeStringsInList(result['flags']), [
        '-DUSE_CLANG_COMPLETER',
        '-std=c++11',
        '-x', 'c++',
        '-I[SRC]',
        '-Wno-unknown-warning-option',
        '-I[OUT]/a',
        '-I[OUT]/tag-three',
        '-isystem', '[SRC]/include/a',
        '-isystem', '[SRC]/include/b'
        ])

  def testSourceFileWithNonClangOutputs(self):
    # Verify assumption that four.cc has non-compiler-output listed as the first
    # output.
    p = subprocess.Popen(['ninja', '-C', self.out_dir, '-t',
                          'query', '../../four.cc'],
                         stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    stdout, _ = p.communicate()
    self.assertFalse(p.returncode)
    self.assertEquals(stdout,
                      '../../four.cc:\n'
                      '  outputs:\n'
                      '    obj/linker-output.o\n'
                      '    obj/four.o\n')

    result = self.ycm_extra_conf.FlagsForFile(
        os.path.join(self.chrome_root, 'four.cc'))
    self.assertTrue(result)
    self.assertTrue('do_cache' in result)
    self.assertTrue(result['do_cache'])
    self.assertTrue('flags' in result)
    self.assertEquals(self.NormalizeStringsInList(result['flags']), [
        '-DUSE_CLANG_COMPLETER',
        '-std=c++11',
        '-x', 'c++',
        '-I[SRC]',
        '-Wno-unknown-warning-option',
        '-I[OUT]/a',
        '-I[OUT]/tag-four',
        '-isystem', '[SRC]/include/a',
        '-isystem', '[SRC]/include/b'
        ])

  def testSourceFileWithOnlyNonClangOutputs(self):
    result = self.ycm_extra_conf.FlagsForFile(
        os.path.join(self.chrome_root, 'five.cc'))
    self.assertTrue(result)
    self.assertTrue('do_cache' in result)
    self.assertTrue(result['do_cache'])
    self.assertTrue('flags' in result)
    self.assertEquals(self.NormalizeStringsInList(result['flags']), [
        '-DUSE_CLANG_COMPLETER',
        '-std=c++11',
        '-x', 'c++',
        '-I[SRC]',
        '-Wno-unknown-warning-option',
        '-I[OUT]/a',
        '-I[OUT]/tag-default',
        '-isystem', '[SRC]/include/a',
        '-isystem', '[SRC]/include/b'
        ])

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