summaryrefslogtreecommitdiffstats
path: root/tools/isolate/isolate_test.py
blob: 7eaefc3e1726bfb39fb8702df6cb79e7a55c6792 (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
#!/usr/bin/env python
# Copyright (c) 2012 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.

import cStringIO
import hashlib
import json
import logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
import unittest

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
VERBOSE = False


class CalledProcessError(subprocess.CalledProcessError):
  """Makes 2.6 version act like 2.7"""
  def __init__(self, returncode, cmd, output, cwd):
    super(CalledProcessError, self).__init__(returncode, cmd)
    self.output = output
    self.cwd = cwd

  def __str__(self):
    return super(CalledProcessError, self).__str__() + (
        '\n'
        'cwd=%s\n%s') % (self.cwd, self.output)


class Isolate(unittest.TestCase):
  def setUp(self):
    # The reason is that isolate_test.py --ok is run in a temporary directory
    # without access to isolate.py
    import isolate
    self.isolate = isolate
    self.tempdir = tempfile.mkdtemp()
    self.result = os.path.join(self.tempdir, 'result')
    if VERBOSE:
      print

  def tearDown(self):
    shutil.rmtree(self.tempdir)

  def _expected_tree(self, files):
    self.assertEquals(sorted(files), sorted(os.listdir(self.tempdir)))

  def _expected_result(self, with_hash, files, args, read_only):
    if sys.platform == 'win32':
      mode = lambda _: 420
    else:
      # 4 modes are supported, 0755 (rwx), 0644 (rw), 0555 (rx), 0444 (r)
      min_mode = 0444
      if not read_only:
        min_mode |= 0200
      def mode(filename):
        return (min_mode | 0111) if filename.endswith('.py') else min_mode
    expected = {
      u'command':
        [unicode(sys.executable)] +
          [unicode(x) for x in args],
      u'files': dict((unicode(f), {u'mode': mode(f)}) for f in files),
      u'relative_cwd': u'.',
      u'read_only': False,
    }
    if with_hash:
      for filename in expected[u'files']:
        # Calculate our hash.
        h = hashlib.sha1()
        h.update(open(os.path.join(ROOT_DIR, filename), 'rb').read())
        expected[u'files'][filename][u'sha-1'] = h.hexdigest()

    actual = json.load(open(self.result, 'rb'))
    self.assertEquals(expected, actual)
    return expected

  def _execute(self, args, need_output=False):
    cmd = [
      sys.executable, os.path.join(ROOT_DIR, 'isolate.py'),
      '--root', ROOT_DIR,
      '--result', self.result,
    ]
    if need_output or not VERBOSE:
      stdout = subprocess.PIPE
      stderr = subprocess.STDOUT
    else:
      cmd.extend(['-v'] * 3)
      stdout = None
      stderr = None
    cwd = ROOT_DIR
    p = subprocess.Popen(
        cmd + args,
        stdout=stdout,
        stderr=stderr,
        cwd=cwd,
        universal_newlines=True)
    out = p.communicate()[0]
    if p.returncode:
      raise CalledProcessError(p.returncode, cmd, out, cwd)
    return out

  def test_help_modes(self):
    # Check coherency in the help and implemented modes.
    p = subprocess.Popen(
        [sys.executable, os.path.join(ROOT_DIR, 'isolate.py'), '--help'],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        cwd=ROOT_DIR)
    out = p.communicate()[0].splitlines()
    self.assertEquals(0, p.returncode)
    out = out[out.index('') + 1:]
    out = out[:out.index('')]
    modes = [re.match(r'^  (\w+) .+', l) for l in out]
    modes = tuple(m.group(1) for m in modes if m)
    # Keep the list hard coded.
    expected = ('check', 'hashtable', 'remap', 'run', 'trace')
    self.assertEquals(expected, modes)
    self.assertEquals(expected, modes)
    for mode in modes:
      self.assertTrue(hasattr(self, 'test_%s' % mode), mode)
    self._expected_tree([])

  def test_check(self):
    cmd = [
      '--mode', 'check',
      'isolate_test.py',
    ]
    self._execute(cmd)
    self._expected_tree(['result'])
    self._expected_result(
        False,
        ['isolate_test.py'],
        [os.path.join('.', 'isolate_test.py')],
        False)

  def test_check_non_existant(self):
    cmd = [
      '--mode', 'check',
      'NonExistentFile',
    ]
    try:
      self._execute(cmd)
      self.fail()
    except subprocess.CalledProcessError:
      pass
    self._expected_tree([])

  def test_check_directory_no_slash(self):
    cmd = [
        '--mode', 'check',
        # Trailing slash missing.
        os.path.join('data', 'isolate'),
    ]
    try:
      self._execute(cmd)
      self.fail()
    except subprocess.CalledProcessError:
      pass
    self._expected_tree([])

  def test_check_abs_path(self):
    cmd = [
      '--mode', 'check',
      'isolate_test.py',
      '--',
      os.path.join(ROOT_DIR, 'isolate_test.py'),
    ]
    self._execute(cmd)
    self._expected_tree(['result'])
    self._expected_result(
        False, ['isolate_test.py'], ['isolate_test.py'], False)

  def test_hashtable(self):
    cmd = [
      '--mode', 'hashtable',
      '--outdir', self.tempdir,
      'isolate_test.py',
      os.path.join('data', 'isolate') + os.path.sep,
    ]
    self._execute(cmd)
    files = [
      'isolate_test.py',
      os.path.join('data', 'isolate', 'test_file1.txt'),
      os.path.join('data', 'isolate', 'test_file2.txt'),
    ]
    data = self._expected_result(
        True, files, [os.path.join('.', 'isolate_test.py')], False)
    self._expected_tree(
        [f['sha-1'] for f in data['files'].itervalues()] + ['result'])

  def test_remap(self):
    cmd = [
      '--mode', 'remap',
      '--outdir', self.tempdir,
      'isolate_test.py',
    ]
    self._execute(cmd)
    self._expected_tree(['isolate_test.py', 'result'])
    self._expected_result(
        False,
        ['isolate_test.py'],
        [os.path.join('.', 'isolate_test.py')],
        False)

  def test_run(self):
    cmd = [
      '--mode', 'run',
      'isolate_test.py',
      '--',
      sys.executable, 'isolate_test.py', '--ok',
    ]
    self._execute(cmd)
    self._expected_tree(['result'])
    # cmd[0] is not generated from infiles[0] so it's not using a relative path.
    self._expected_result(
        False, ['isolate_test.py'], ['isolate_test.py', '--ok'], False)

  def test_run_fail(self):
    cmd = [
      '--mode', 'run',
      'isolate_test.py',
      '--',
      sys.executable, 'isolate_test.py', '--fail',
    ]
    try:
      self._execute(cmd)
      self.fail()
    except subprocess.CalledProcessError:
      pass
    self._expected_tree([])

  def test_trace(self):
    cmd = [
      '--mode', 'trace',
      'isolate_test.py',
      '--',
      sys.executable, os.path.join(ROOT_DIR, 'isolate_test.py'), '--ok',
    ]
    out = self._execute(cmd, True)
    expected_tree = ['result', 'result.log']
    if sys.platform == 'win32':
      expected_tree.append('result.log.etl')
    self._expected_tree(expected_tree)
    # The 'result.log' log is OS-specific so we can't read it but we can read
    # the gyp result.
    # cmd[0] is not generated from infiles[0] so it's not using a relative path.
    self._expected_result(
        False, ['isolate_test.py'], ['isolate_test.py', '--ok'], False)

    expected_value = {
      'conditions': [
        ['OS=="%s"' % self.isolate.trace_inputs.get_flavor(), {
          'variables': {
            'isolate_files': [
              '<(DEPTH)/isolate_test.py',
            ],
          },
        }],
      ],
    }
    expected_buffer = cStringIO.StringIO()
    self.isolate.trace_inputs.pretty_print(expected_value, expected_buffer)
    self.assertEquals(expected_buffer.getvalue(), out)


def main():
  global VERBOSE
  VERBOSE = '-v' in sys.argv
  level = logging.DEBUG if VERBOSE else logging.ERROR
  logging.basicConfig(level=level)
  if len(sys.argv) == 1:
    unittest.main()
  if sys.argv[1] == '--ok':
    return 0
  if sys.argv[1] == '--fail':
    return 1

  unittest.main()


if __name__ == '__main__':
  sys.exit(main())