gclient_test.py 32.8 KB
Newer Older
1
#!/usr/bin/env python
2
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 4 5 6 7 8 9 10 11
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Unit tests for gclient.py.

See gclient_smoketest.py for integration tests.
"""

import Queue
12
import copy
13 14 15 16 17
import logging
import os
import sys
import unittest

18
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
19 20

import gclient
21
import gclient_utils
22
from testing_support import trial_dir
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46


def write(filename, content):
  """Writes the content of a file and create the directories as needed."""
  filename = os.path.abspath(filename)
  dirname = os.path.dirname(filename)
  if not os.path.isdir(dirname):
    os.makedirs(dirname)
  with open(filename, 'w') as f:
    f.write(content)


class SCMMock(object):
  def __init__(self, unit_test, url):
    self.unit_test = unit_test
    self.url = url

  def RunCommand(self, command, options, args, file_list):
    self.unit_test.assertEquals('None', command)
    self.unit_test.processed.put(self.url)

  def FullUrlForRelativeUrl(self, url):
    return self.url + url

47
  # pylint: disable=R0201
48
  def DoesRemoteURLMatch(self, _):
49 50
    return True

51
  def GetActualRemoteURL(self, _):
52 53
    return self.url

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

class GclientTest(trial_dir.TestCase):
  def setUp(self):
    super(GclientTest, self).setUp()
    self.processed = Queue.Queue()
    self.previous_dir = os.getcwd()
    os.chdir(self.root_dir)
    # Manual mocks.
    self._old_createscm = gclient.gclient_scm.CreateSCM
    gclient.gclient_scm.CreateSCM = self._createscm
    self._old_sys_stdout = sys.stdout
    sys.stdout = gclient.gclient_utils.MakeFileAutoFlush(sys.stdout)
    sys.stdout = gclient.gclient_utils.MakeFileAnnotated(sys.stdout)

  def tearDown(self):
    self.assertEquals([], self._get_processed())
    gclient.gclient_scm.CreateSCM = self._old_createscm
    sys.stdout = self._old_sys_stdout
    os.chdir(self.previous_dir)
    super(GclientTest, self).tearDown()

75
  def _createscm(self, parsed_url, root_dir, name, out_fh=None, out_cb=None):
76 77 78 79 80
    self.assertTrue(parsed_url.startswith('svn://example.com/'), parsed_url)
    self.assertTrue(root_dir.startswith(self.root_dir), root_dir)
    return SCMMock(self, parsed_url)

  def testDependencies(self):
81
    self._dependencies('1')
82 83

  def testDependenciesJobs(self):
84 85 86 87
    self._dependencies('1000')

  def _dependencies(self, jobs):
    """Verifies that dependencies are processed in the right order.
88

89 90 91 92
    e.g. if there is a dependency 'src' and another 'src/third_party/bar', that
    bar isn't fetched until 'src' is done.
    Also test that a From() dependency should not be processed when it is listed
    as a requirement.
93

94 95 96
    Args:
      |jobs| is the number of parallel jobs simulated.
    """
97
    parser = gclient.OptionParser()
98 99 100 101 102 103
    options, args = parser.parse_args(['--jobs', jobs])
    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo", "url": "svn://example.com/foo" },\n'
        '  { "name": "bar", "url": "svn://example.com/bar" },\n'
104
        '  { "name": "bar/empty", "url": "svn://example.com/bar_empty" },\n'
105 106 107 108 109
        ']')
    write(
        os.path.join('foo', 'DEPS'),
        'deps = {\n'
        '  "foo/dir1": "/dir1",\n'
110
        # This one will depend on dir1/dir2 in bar.
111 112
        '  "foo/dir1/dir2/dir3": "/dir1/dir2/dir3",\n'
        '  "foo/dir1/dir2/dir3/dir4": "/dir1/dir2/dir3/dir4",\n'
113 114
        '  "foo/dir1/dir2/dir5/dir6":\n'
        '    From("foo/dir1/dir2/dir3/dir4", "foo/dir1/dir2"),\n'
115 116 117 118
        '}')
    write(
        os.path.join('bar', 'DEPS'),
        'deps = {\n'
119
        # There is two foo/dir1/dir2. This one is fetched as bar/dir1/dir2.
120 121
        '  "foo/dir1/dir2": "/dir1/dir2",\n'
        '}')
122 123 124 125
    write(
        os.path.join('bar/empty', 'DEPS'),
        'deps = {\n'
        '}')
126 127 128 129 130 131
    # Test From()
    write(
        os.path.join('foo/dir1/dir2/dir3/dir4', 'DEPS'),
        'deps = {\n'
        # This one should not be fetched or set as a requirement.
        '  "foo/dir1/dir2/dir5": "svn://example.com/x",\n'
132
        # This foo/dir1/dir2 points to a different url than the one in bar.
133 134
        '  "foo/dir1/dir2": "/dir1/another",\n'
        '}')
135 136 137 138 139 140

    obj = gclient.GClient.LoadCurrentConfig(options)
    self._check_requirements(obj.dependencies[0], {})
    self._check_requirements(obj.dependencies[1], {})
    obj.RunOnDeps('None', args)
    actual = self._get_processed()
141 142 143 144 145 146 147 148 149 150 151 152 153 154
    first_3 = [
        'svn://example.com/bar',
        'svn://example.com/bar_empty',
        'svn://example.com/foo',
    ]
    if jobs != 1:
      # We don't care of the ordering of these items except that bar must be
      # before bar/empty.
      self.assertTrue(
          actual.index('svn://example.com/bar') <
          actual.index('svn://example.com/bar_empty'))
      self.assertEquals(first_3, sorted(actual[0:3]))
    else:
      self.assertEquals(first_3, actual[0:3])
155 156 157
    self.assertEquals(
        [
          'svn://example.com/foo/dir1',
158
          'svn://example.com/bar/dir1/dir2',
159 160
          'svn://example.com/foo/dir1/dir2/dir3',
          'svn://example.com/foo/dir1/dir2/dir3/dir4',
161
          'svn://example.com/foo/dir1/dir2/dir3/dir4/dir1/another',
162
        ],
163
        actual[3:])
164

165
    self.assertEquals(3, len(obj.dependencies))
166 167 168
    self.assertEquals('foo', obj.dependencies[0].name)
    self.assertEquals('bar', obj.dependencies[1].name)
    self.assertEquals('bar/empty', obj.dependencies[2].name)
169 170 171
    self._check_requirements(
        obj.dependencies[0],
        {
172 173 174 175 176 177 178 179 180
          'foo/dir1': ['bar', 'bar/empty', 'foo'],
          'foo/dir1/dir2/dir3':
              ['bar', 'bar/empty', 'foo', 'foo/dir1', 'foo/dir1/dir2'],
          'foo/dir1/dir2/dir3/dir4':
              [ 'bar', 'bar/empty', 'foo', 'foo/dir1', 'foo/dir1/dir2',
                'foo/dir1/dir2/dir3'],
          'foo/dir1/dir2/dir5/dir6':
              [ 'bar', 'bar/empty', 'foo', 'foo/dir1', 'foo/dir1/dir2',
                'foo/dir1/dir2/dir3/dir4'],
181
        })
182 183 184 185 186 187 188 189
    self._check_requirements(
        obj.dependencies[1],
        {
          'foo/dir1/dir2': ['bar', 'bar/empty', 'foo', 'foo/dir1'],
        })
    self._check_requirements(
        obj.dependencies[2],
        {})
190 191 192 193 194 195
    self._check_requirements(
        obj,
        {
          'foo': [],
          'bar': [],
          'bar/empty': ['bar'],
196 197 198 199
        })

  def _check_requirements(self, solution, expected):
    for dependency in solution.dependencies:
200 201 202
      e = expected.pop(dependency.name)
      a = sorted(dependency.requirements)
      self.assertEquals(e, a, (dependency.name, e, a))
203 204 205
    self.assertEquals({}, expected)

  def _get_processed(self):
206
    """Retrieves the item in the order they were processed."""
207 208 209 210 211 212 213 214
    items = []
    try:
      while True:
        items.append(self.processed.get_nowait())
    except Queue.Empty:
      pass
    return items

215 216 217 218
  def testAutofix(self):
    # Invalid urls causes pain when specifying requirements. Make sure it's
    # auto-fixed.
    d = gclient.Dependency(
219
        None, 'name', 'proto://host/path/@revision', None, None, None, None,
220 221
        None, '', True)
    self.assertEquals('proto://host/path@revision', d.url)
222

223
  def testStr(self):
224
    parser = gclient.OptionParser()
225 226
    options, _ = parser.parse_args([])
    obj = gclient.GClient('foo', options)
227 228 229
    obj.add_dependencies_and_close(
        [
          gclient.Dependency(
230
            obj, 'foo', 'url', None, None, None, None, None, 'DEPS', True),
231
          gclient.Dependency(
232
            obj, 'bar', 'url', None, None, None, None, None, 'DEPS', True),
233 234 235 236 237 238
        ],
        [])
    obj.dependencies[0].add_dependencies_and_close(
        [
          gclient.Dependency(
            obj.dependencies[0], 'foo/dir1', 'url', None, None, None, None,
239
            None, 'DEPS', True),
240 241 242
          gclient.Dependency(
            obj.dependencies[0], 'foo/dir2',
            gclient.GClientKeywords.FromImpl('bar'), None, None, None, None,
243
            None, 'DEPS', True),
244 245 246
          gclient.Dependency(
            obj.dependencies[0], 'foo/dir3',
            gclient.GClientKeywords.FileImpl('url'), None, None, None, None,
247
            None, 'DEPS', True),
248 249 250 251
        ],
        [])
    # Make sure __str__() works fine.
    # pylint: disable=W0212
252
    obj.dependencies[0]._file_list.append('foo')
253
    str_obj = str(obj)
254
    self.assertEquals(471, len(str_obj), '%d\n%s' % (len(str_obj), str_obj))
255

256 257 258 259
  def testHooks(self):
    topdir = self.root_dir
    gclient_fn = os.path.join(topdir, '.gclient')
    fh = open(gclient_fn, 'w')
260
    print >> fh, 'solutions = [{"name":"top","url":"svn://example.com/top"}]'
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    fh.close()
    subdir_fn = os.path.join(topdir, 'top')
    os.mkdir(subdir_fn)
    deps_fn = os.path.join(subdir_fn, 'DEPS')
    fh = open(deps_fn, 'w')
    hooks = [{'pattern':'.', 'action':['cmd1', 'arg1', 'arg2']}]
    print >> fh, 'hooks = %s' % repr(hooks)
    fh.close()

    fh = open(os.path.join(subdir_fn, 'fake.txt'), 'w')
    print >> fh, 'bogus content'
    fh.close()

    os.chdir(topdir)

276
    parser = gclient.OptionParser()
277 278 279
    options, _ = parser.parse_args([])
    options.force = True
    client = gclient.GClient.LoadCurrentConfig(options)
280
    work_queue = gclient_utils.ExecutionQueue(options.jobs, None, False)
281 282 283 284 285
    for s in client.dependencies:
      work_queue.enqueue(s)
    work_queue.flush({}, None, [], options=options)
    self.assertEqual(client.GetHooks(options), [x['action'] for x in hooks])

286 287 288 289 290
  def testCustomHooks(self):
    topdir = self.root_dir
    gclient_fn = os.path.join(topdir, '.gclient')
    fh = open(gclient_fn, 'w')
    extra_hooks = [{'name': 'append', 'pattern':'.', 'action':['supercmd']}]
291
    print >> fh, ('solutions = [{"name":"top","url":"svn://example.com/top",'
292
        '"custom_hooks": %s},' ) % repr(extra_hooks + [{'name': 'skip'}])
293
    print >> fh, '{"name":"bottom","url":"svn://example.com/bottom"}]'
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
    fh.close()
    subdir_fn = os.path.join(topdir, 'top')
    os.mkdir(subdir_fn)
    deps_fn = os.path.join(subdir_fn, 'DEPS')
    fh = open(deps_fn, 'w')
    hooks = [{'pattern':'.', 'action':['cmd1', 'arg1', 'arg2']}]
    hooks.append({'pattern':'.', 'action':['cmd2', 'arg1', 'arg2']})
    skip_hooks = [
        {'name': 'skip', 'pattern':'.', 'action':['cmd3', 'arg1', 'arg2']}]
    skip_hooks.append(
        {'name': 'skip', 'pattern':'.', 'action':['cmd4', 'arg1', 'arg2']})
    print >> fh, 'hooks = %s' % repr(hooks + skip_hooks)
    fh.close()

    # Make sure the custom hooks for that project don't affect the next one.
    subdir_fn = os.path.join(topdir, 'bottom')
    os.mkdir(subdir_fn)
    deps_fn = os.path.join(subdir_fn, 'DEPS')
    fh = open(deps_fn, 'w')
    sub_hooks = [{'pattern':'.', 'action':['response1', 'yes1', 'yes2']}]
    sub_hooks.append(
        {'name': 'skip', 'pattern':'.', 'action':['response2', 'yes', 'sir']})
    print >> fh, 'hooks = %s' % repr(sub_hooks)
    fh.close()

    fh = open(os.path.join(subdir_fn, 'fake.txt'), 'w')
    print >> fh, 'bogus content'
    fh.close()

    os.chdir(topdir)

325
    parser = gclient.OptionParser()
326 327 328 329 330 331 332 333 334 335
    options, _ = parser.parse_args([])
    options.force = True
    client = gclient.GClient.LoadCurrentConfig(options)
    work_queue = gclient_utils.ExecutionQueue(options.jobs, None, False)
    for s in client.dependencies:
      work_queue.enqueue(s)
    work_queue.flush({}, None, [], options=options)
    self.assertEqual(client.GetHooks(options),
                     [x['action'] for x in hooks + extra_hooks + sub_hooks])

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
  def testTargetOS(self):
    """Verifies that specifying a target_os pulls in all relevant dependencies.

    The target_os variable allows specifying the name of an additional OS which
    should be considered when selecting dependencies from a DEPS' deps_os. The
    value will be appended to the _enforced_os tuple.
    """

    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo",\n'
        '    "url": "svn://example.com/foo",\n'
        '  }]\n'
        'target_os = ["baz"]')
    write(
        os.path.join('foo', 'DEPS'),
        'deps = {\n'
        '  "foo/dir1": "/dir1",'
        '}\n'
        'deps_os = {\n'
        '  "unix": { "foo/dir2": "/dir2", },\n'
        '  "baz": { "foo/dir3": "/dir3", },\n'
        '}')

361
    parser = gclient.OptionParser()
362 363 364 365 366
    options, _ = parser.parse_args(['--jobs', '1'])
    options.deps_os = "unix"

    obj = gclient.GClient.LoadCurrentConfig(options)
    self.assertEqual(['baz', 'unix'], sorted(obj.enforced_os))
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
  def testTargetOsWithTargetOsOnly(self):
    """Verifies that specifying a target_os and target_os_only pulls in only
    the relevant dependencies.

    The target_os variable allows specifying the name of an additional OS which
    should be considered when selecting dependencies from a DEPS' deps_os. With
    target_os_only also set, the _enforced_os tuple will be set to only the
    target_os value.
    """

    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo",\n'
        '    "url": "svn://example.com/foo",\n'
        '  }]\n'
        'target_os = ["baz"]\n'
        'target_os_only = True')
    write(
        os.path.join('foo', 'DEPS'),
        'deps = {\n'
        '  "foo/dir1": "/dir1",'
        '}\n'
        'deps_os = {\n'
        '  "unix": { "foo/dir2": "/dir2", },\n'
        '  "baz": { "foo/dir3": "/dir3", },\n'
        '}')

396
    parser = gclient.OptionParser()
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
    options, _ = parser.parse_args(['--jobs', '1'])
    options.deps_os = "unix"

    obj = gclient.GClient.LoadCurrentConfig(options)
    self.assertEqual(['baz'], sorted(obj.enforced_os))

  def testTargetOsOnlyWithoutTargetOs(self):
    """Verifies that specifying a target_os_only without target_os_only raises
    an exception.
    """

    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo",\n'
        '    "url": "svn://example.com/foo",\n'
        '  }]\n'
        'target_os_only = True')
    write(
        os.path.join('foo', 'DEPS'),
        'deps = {\n'
        '  "foo/dir1": "/dir1",'
        '}\n'
        'deps_os = {\n'
        '  "unix": { "foo/dir2": "/dir2", },\n'
        '}')

424
    parser = gclient.OptionParser()
425 426 427 428 429 430 431 432 433 434
    options, _ = parser.parse_args(['--jobs', '1'])
    options.deps_os = "unix"

    exception_raised = False
    try:
      gclient.GClient.LoadCurrentConfig(options)
    except gclient_utils.Error:
      exception_raised = True
    self.assertTrue(exception_raised)

435 436 437 438 439 440 441 442 443 444 445 446 447 448
  def testTargetOsInDepsFile(self):
    """Verifies that specifying a target_os value in a DEPS file pulls in all
    relevant dependencies.

    The target_os variable in a DEPS file allows specifying the name of an
    additional OS which should be considered when selecting dependencies from a
    DEPS' deps_os. The value will be appended to the _enforced_os tuple.
    """

    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo",\n'
        '    "url": "svn://example.com/foo",\n'
449 450 451
        '  },\n'
        '  { "name": "bar",\n'
        '    "url": "svn://example.com/bar",\n'
452 453 454 455 456 457 458 459 460
        '  }]\n')
    write(
        os.path.join('foo', 'DEPS'),
        'target_os = ["baz"]\n'
        'deps_os = {\n'
        '  "unix": { "foo/unix": "/unix", },\n'
        '  "baz": { "foo/baz": "/baz", },\n'
        '  "jaz": { "foo/jaz": "/jaz", },\n'
        '}')
461 462 463 464 465 466 467
    write(
        os.path.join('bar', 'DEPS'),
        'deps_os = {\n'
        '  "unix": { "bar/unix": "/unix", },\n'
        '  "baz": { "bar/baz": "/baz", },\n'
        '  "jaz": { "bar/jaz": "/jaz", },\n'
        '}')
468

469
    parser = gclient.OptionParser()
470 471 472 473 474 475 476 477
    options, _ = parser.parse_args(['--jobs', '1'])
    options.deps_os = 'unix'

    obj = gclient.GClient.LoadCurrentConfig(options)
    obj.RunOnDeps('None', [])
    self.assertEqual(['unix'], sorted(obj.enforced_os))
    self.assertEquals(
        [
478 479
          'svn://example.com/bar',
          'svn://example.com/bar/unix',
480 481 482 483 484
          'svn://example.com/foo',
          'svn://example.com/foo/baz',
          'svn://example.com/foo/unix',
          ],
        sorted(self._get_processed()))
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
  def testUpdateWithOsDeps(self):
    """Verifies that complicated deps_os constructs result in the
    correct data also with multple operating systems. Also see
    testDepsOsOverrideDepsInDepsFile."""

    test_data = [
      # Tuples of deps, deps_os, os_list and expected_deps.
      (
        # OS doesn't need module.
        {'foo': 'default_foo'},
        {'os1': { 'foo': None } },
        ['os1'],
        {'foo': None}
        ),
      (
        # OS wants a different version of module.
        {'foo': 'default_foo'},
        {'os1': { 'foo': 'os1_foo'} },
        ['os1'],
        {'foo': 'os1_foo'}
        ),
      (
        # OS with no overrides at all.
        {'foo': 'default_foo'},
        {'os1': { 'foo': None } },
        ['os2'],
        {'foo': 'default_foo'}
        ),
      (
        # One OS doesn't need module, one OS wants the default.
        {'foo': 'default_foo'},
        {'os1': { 'foo': None },
         'os2': {}},
        ['os1', 'os2'],
        {'foo': 'default_foo'}
        ),
      (
        # One OS doesn't need module, another OS wants a special version.
        {'foo': 'default_foo'},
        {'os1': { 'foo': None },
         'os2': { 'foo': 'os2_foo'}},
        ['os1', 'os2'],
        {'foo': 'os2_foo'}
        ),
      (
        # One OS wants to add a module.
        {'foo': 'default_foo'},
        {'os1': { 'bar': 'os1_bar' }},
        ['os1'],
        {'foo': 'default_foo',
         'bar': 'os1_bar'}
        ),
      (
        # One OS wants to add a module. One doesn't care.
        {'foo': 'default_foo'},
        {'os1': { 'bar': 'os1_bar' }},
        ['os1', 'os2'],
        {'foo': 'default_foo',
         'bar': 'os1_bar'}
        ),
      (
        # Two OSes want to add a module with the same definition.
        {'foo': 'default_foo'},
        {'os1': { 'bar': 'os12_bar' },
         'os2': { 'bar': 'os12_bar' }},
        ['os1', 'os2'],
        {'foo': 'default_foo',
         'bar': 'os12_bar'}
        ),
      ]
    for deps, deps_os, target_os_list, expected_deps in test_data:
      orig_deps = copy.deepcopy(deps)
      result = gclient.Dependency.MergeWithOsDeps(deps, deps_os, target_os_list)
      self.assertEqual(result, expected_deps)
      self.assertEqual(deps, orig_deps)

562 563 564 565 566 567 568 569 570

  def testLateOverride(self):
    """Verifies expected behavior of LateOverride."""
    url = "git@github.com:dart-lang/spark.git"
    d = gclient.Dependency(None, 'name', 'url',
                           None, None, None, None, None, '', True)
    late_url = d.LateOverride(url)
    self.assertEquals(url, late_url)

571
  def testDepsOsOverrideDepsInDepsFile(self):
572 573
    """Verifies that a 'deps_os' path can override a 'deps' path. Also
    see testUpdateWithOsDeps above.
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
    """

    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo",\n'
        '    "url": "svn://example.com/foo",\n'
        '  },]\n')
    write(
        os.path.join('foo', 'DEPS'),
        'target_os = ["baz"]\n'
        'deps = {\n'
        '  "foo/src": "/src",\n' # This path is to be overridden by similar path
                                 # in deps_os['unix'].
        '}\n'
        'deps_os = {\n'
        '  "unix": { "foo/unix": "/unix",'
        '            "foo/src": "/src_unix"},\n'
592 593
        '  "baz": { "foo/baz": "/baz",\n'
        '           "foo/src": None},\n'
594 595 596
        '  "jaz": { "foo/jaz": "/jaz", },\n'
        '}')

597
    parser = gclient.OptionParser()
598 599 600 601 602 603 604 605 606 607 608 609 610 611
    options, _ = parser.parse_args(['--jobs', '1'])
    options.deps_os = 'unix'

    obj = gclient.GClient.LoadCurrentConfig(options)
    obj.RunOnDeps('None', [])
    self.assertEqual(['unix'], sorted(obj.enforced_os))
    self.assertEquals(
        [
          'svn://example.com/foo',
          'svn://example.com/foo/baz',
          'svn://example.com/foo/src_unix',
          'svn://example.com/foo/unix',
          ],
        sorted(self._get_processed()))
612

613
  def testRecursionOverride(self):
614
    """Verifies gclient respects the |recursion| var syntax.
615 616

    We check several things here:
617
    - |recursion| = 3 sets recursion on the foo dep to exactly 3
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
      (we pull /fizz, but not /fuzz)
    - pulling foo/bar at recursion level 1 (in .gclient) is overriden by
      a later pull of foo/bar at recursion level 2 (in the dep tree)
    """
    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo", "url": "svn://example.com/foo" },\n'
        '  { "name": "foo/bar", "url": "svn://example.com/bar" },\n'
          ']')
    write(
        os.path.join('foo', 'DEPS'),
        'deps = {\n'
        '  "bar": "/bar",\n'
        '}\n'
        'recursion = 3')
    write(
        os.path.join('bar', 'DEPS'),
        'deps = {\n'
        '  "baz": "/baz",\n'
        '}')
    write(
        os.path.join('baz', 'DEPS'),
        'deps = {\n'
        '  "fizz": "/fizz",\n'
        '}')
    write(
        os.path.join('fizz', 'DEPS'),
        'deps = {\n'
        '  "fuzz": "/fuzz",\n'
        '}')

650
    options, _ = gclient.OptionParser().parse_args([])
651 652 653 654 655 656 657 658 659 660 661 662
    obj = gclient.GClient.LoadCurrentConfig(options)
    obj.RunOnDeps('None', [])
    self.assertEquals(
        [
          'svn://example.com/foo',
          'svn://example.com/bar',
          'svn://example.com/foo/bar',
          'svn://example.com/foo/bar/baz',
          'svn://example.com/foo/bar/baz/fizz',
        ],
        self._get_processed())

663 664
  def testRecursedepsOverride(self):
    """Verifies gclient respects the |recursedeps| var syntax.
665 666

    This is what we mean to check here:
667
    - |recursedeps| = [...] on 2 levels means we pull exactly 3 deps
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
      (up to /fizz, but not /fuzz)
    - pulling foo/bar with no recursion (in .gclient) is overriden by
      a later pull of foo/bar with recursion (in the dep tree)
    - pulling foo/tar with no recursion (in .gclient) is no recursively
      pulled (taz is left out)
    """
    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo", "url": "svn://example.com/foo" },\n'
        '  { "name": "foo/bar", "url": "svn://example.com/bar" },\n'
        '  { "name": "foo/tar", "url": "svn://example.com/tar" },\n'
          ']')
    write(
        os.path.join('foo', 'DEPS'),
        'deps = {\n'
        '  "bar": "/bar",\n'
        '}\n'
686
        'recursedeps = ["bar"]')
687 688 689 690 691
    write(
        os.path.join('bar', 'DEPS'),
        'deps = {\n'
        '  "baz": "/baz",\n'
        '}\n'
692
        'recursedeps = ["baz"]')
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
    write(
        os.path.join('baz', 'DEPS'),
        'deps = {\n'
        '  "fizz": "/fizz",\n'
        '}')
    write(
        os.path.join('fizz', 'DEPS'),
        'deps = {\n'
        '  "fuzz": "/fuzz",\n'
        '}')
    write(
        os.path.join('tar', 'DEPS'),
        'deps = {\n'
        '  "taz": "/taz",\n'
        '}')

    options, _ = gclient.OptionParser().parse_args([])
    obj = gclient.GClient.LoadCurrentConfig(options)
    obj.RunOnDeps('None', [])
    self.assertEquals(
        [
          'svn://example.com/foo',
          'svn://example.com/bar',
          'svn://example.com/tar',
          'svn://example.com/foo/bar',
          'svn://example.com/foo/bar/baz',
          'svn://example.com/foo/bar/baz/fizz',
        ],
        self._get_processed())

723 724 725 726 727 728 729 730 731 732 733 734 735 736
  def testRecursedepsOverrideWithRelativePaths(self):
    """Verifies gclient respects |recursedeps| with relative paths."""

    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo", "url": "svn://example.com/foo" },\n'
          ']')
    write(
        os.path.join('foo', 'DEPS'),
        'use_relative_paths = True\n'
        'deps = {\n'
        '  "bar": "/bar",\n'
        '}\n'
737
        'recursedeps = ["bar"]')
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
    write(
        os.path.join('bar', 'DEPS'),
        'deps = {\n'
        '  "baz": "/baz",\n'
        '}')
    write(
        os.path.join('baz', 'DEPS'),
        'deps = {\n'
        '  "fizz": "/fizz",\n'
        '}')

    options, _ = gclient.OptionParser().parse_args([])
    obj = gclient.GClient.LoadCurrentConfig(options)
    obj.RunOnDeps('None', [])
    self.assertEquals(
        [
          'svn://example.com/foo',
          # use_relative_paths means the following dep evaluates with 'foo'
          # prepended.
          'svn://example.com/foo/bar',
        ],
        self._get_processed())

761 762
  def testRecursionOverridesRecursedeps(self):
    """Verifies gclient respects |recursion| over |recursedeps|.
763 764 765 766

    |recursion| is set in a top-level DEPS file.  That value is meant
    to affect how many subdeps are parsed via recursion.

767
    |recursedeps| is set in each DEPS file to control whether or not
768 769 770
    to recurse into the immediate next subdep.

    This test verifies that if both syntaxes are mixed in a DEPS file,
771
    we disable |recursedeps| support and only obey |recursion|.
772 773 774

    Since this setting is evaluated per DEPS file, recursed DEPS
    files will each be re-evaluated according to the per DEPS rules.
775
    So a DEPS that only contains |recursedeps| could then override any
776 777 778 779 780 781
    previous |recursion| setting.  There is extra processing to ensure
    this does not happen.

    For this test to work correctly, we need to use a DEPS chain that
    only contains recursion controls in the top DEPS file.

782 783
    In foo, |recursion| and |recursedeps| are specified.  When we see
    |recursion|, we stop trying to use |recursedeps|.
784 785 786

    There are 2 constructions of DEPS here that are key to this test:

787
    (1) In foo, if we used |recursedeps| instead of |recursion|, we
788 789 790
        would also pull in bar.  Since bar's DEPS doesn't contain any
        recursion statements, we would stop processing at bar.

791
    (2) In fizz, if we used |recursedeps| at all, we should pull in
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
        fuzz.

    We expect to keep going past bar (satisfying 1) and we don't
    expect to pull in fuzz (satisfying 2).
    """
    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo", "url": "svn://example.com/foo" },\n'
        '  { "name": "foo/bar", "url": "svn://example.com/bar" },\n'
          ']')
    write(
        os.path.join('foo', 'DEPS'),
        'deps = {\n'
        '  "bar": "/bar",\n'
        '}\n'
        'recursion = 3\n'
809
        'recursedeps = ["bar"]')
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
    write(
        os.path.join('bar', 'DEPS'),
        'deps = {\n'
        '  "baz": "/baz",\n'
        '}')
    write(
        os.path.join('baz', 'DEPS'),
        'deps = {\n'
        '  "fizz": "/fizz",\n'
        '}')
    write(
        os.path.join('fizz', 'DEPS'),
        'deps = {\n'
        '  "fuzz": "/fuzz",\n'
        '}\n'
825
        'recursedeps = ["fuzz"]')
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
    write(
        os.path.join('fuzz', 'DEPS'),
        'deps = {\n'
        '  "tar": "/tar",\n'
        '}')

    options, _ = gclient.OptionParser().parse_args([])
    obj = gclient.GClient.LoadCurrentConfig(options)
    obj.RunOnDeps('None', [])
    self.assertEquals(
        [
          'svn://example.com/foo',
          'svn://example.com/bar',
          'svn://example.com/foo/bar',
          # Deps after this would have been skipped if we were obeying
841
          # |recursedeps|.
842 843 844
          'svn://example.com/foo/bar/baz',
          'svn://example.com/foo/bar/baz/fizz',
          # And this dep would have been picked up if we were obeying
845
          # |recursedeps|.
846 847 848 849
          # 'svn://example.com/foo/bar/baz/fuzz',
        ],
        self._get_processed())

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
  def testGitDeps(self):
    """Verifies gclient respects a .DEPS.git deps file.

    Along the way, we also test that if both DEPS and .DEPS.git are present,
    that gclient does not read the DEPS file.  This will reliably catch bugs
    where gclient is always hitting the wrong file (DEPS).
    """
    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo", "url": "svn://example.com/foo",\n'
        '    "deps_file" : ".DEPS.git",\n'
        '  },\n'
          ']')
    write(
        os.path.join('foo', '.DEPS.git'),
        'deps = {\n'
        '  "bar": "/bar",\n'
        '}')
    write(
        os.path.join('foo', 'DEPS'),
        'deps = {\n'
        '  "baz": "/baz",\n'
        '}')

    options, _ = gclient.OptionParser().parse_args([])
    obj = gclient.GClient.LoadCurrentConfig(options)
    obj.RunOnDeps('None', [])
    self.assertEquals(
        [
          'svn://example.com/foo',
          'svn://example.com/foo/bar',
        ],
        self._get_processed())

  def testGitDepsFallback(self):
    """Verifies gclient respects fallback to DEPS upon missing deps file."""
    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo", "url": "svn://example.com/foo",\n'
        '    "deps_file" : ".DEPS.git",\n'
        '  },\n'
          ']')
    write(
        os.path.join('foo', 'DEPS'),
        'deps = {\n'
        '  "bar": "/bar",\n'
        '}')

    options, _ = gclient.OptionParser().parse_args([])
    obj = gclient.GClient.LoadCurrentConfig(options)
    obj.RunOnDeps('None', [])
    self.assertEquals(
        [
          'svn://example.com/foo',
          'svn://example.com/foo/bar',
        ],
        self._get_processed())

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 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
  def testDepsFromNotAllowedHostsUnspecified(self):
    """Verifies gclient works fine with DEPS without allowed_hosts."""
    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo", "url": "svn://example.com/foo",\n'
        '    "deps_file" : ".DEPS.git",\n'
        '  },\n'
          ']')
    write(
        os.path.join('foo', 'DEPS'),
        'deps = {\n'
        '  "bar": "/bar",\n'
        '}')
    options, _ = gclient.OptionParser().parse_args([])
    obj = gclient.GClient.LoadCurrentConfig(options)
    obj.RunOnDeps('None', [])
    dep = obj.dependencies[0]
    self.assertEquals([], dep.findDepsFromNotAllowedHosts())
    self.assertEquals(frozenset(), dep.allowed_hosts)
    self._get_processed()

  def testDepsFromNotAllowedHostsOK(self):
    """Verifies gclient works fine with DEPS with proper allowed_hosts."""
    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo", "url": "svn://example.com/foo",\n'
        '    "deps_file" : ".DEPS.git",\n'
        '  },\n'
          ']')
    write(
        os.path.join('foo', '.DEPS.git'),
        'allowed_hosts = ["example.com"]\n'
        'deps = {\n'
        '  "bar": "svn://example.com/bar",\n'
        '}')
    options, _ = gclient.OptionParser().parse_args([])
    obj = gclient.GClient.LoadCurrentConfig(options)
    obj.RunOnDeps('None', [])
    dep = obj.dependencies[0]
    self.assertEquals([], dep.findDepsFromNotAllowedHosts())
    self.assertEquals(frozenset(['example.com']), dep.allowed_hosts)
    self._get_processed()

  def testDepsFromNotAllowedHostsBad(self):
    """Verifies gclient works fine with DEPS with proper allowed_hosts."""
    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo", "url": "svn://example.com/foo",\n'
        '    "deps_file" : ".DEPS.git",\n'
        '  },\n'
          ']')
    write(
        os.path.join('foo', '.DEPS.git'),
        'allowed_hosts = ["other.com"]\n'
        'deps = {\n'
        '  "bar": "svn://example.com/bar",\n'
        '}')
    options, _ = gclient.OptionParser().parse_args([])
    obj = gclient.GClient.LoadCurrentConfig(options)
    obj.RunOnDeps('None', [])
    dep = obj.dependencies[0]
    self.assertEquals(frozenset(['other.com']), dep.allowed_hosts)
    self.assertEquals([dep.dependencies[0]], dep.findDepsFromNotAllowedHosts())
    self._get_processed()

  def testDepsParseFailureWithEmptyAllowedHosts(self):
    """Verifies gclient fails with defined but empty allowed_hosts."""
    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo", "url": "svn://example.com/foo",\n'
        '    "deps_file" : ".DEPS.git",\n'
        '  },\n'
          ']')
    write(
        os.path.join('foo', 'DEPS'),
        'allowed_hosts = []\n'
        'deps = {\n'
        '  "bar": "/bar",\n'
        '}')
    options, _ = gclient.OptionParser().parse_args([])
    obj = gclient.GClient.LoadCurrentConfig(options)
    try:
      obj.RunOnDeps('None', [])
997
      self.fail()
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
    except gclient_utils.Error, e:
      self.assertIn('allowed_hosts must be', str(e))
    finally:
      self._get_processed()

  def testDepsParseFailureWithNonIterableAllowedHosts(self):
    """Verifies gclient fails with defined but non-iterable allowed_hosts."""
    write(
        '.gclient',
        'solutions = [\n'
        '  { "name": "foo", "url": "svn://example.com/foo",\n'
        '    "deps_file" : ".DEPS.git",\n'
        '  },\n'
          ']')
    write(
        os.path.join('foo', 'DEPS'),
        'allowed_hosts = None\n'
        'deps = {\n'
        '  "bar": "/bar",\n'
        '}')
    options, _ = gclient.OptionParser().parse_args([])
    obj = gclient.GClient.LoadCurrentConfig(options)
    try:
      obj.RunOnDeps('None', [])
1022
      self.fail()
1023 1024 1025 1026 1027
    except gclient_utils.Error, e:
      self.assertIn('allowed_hosts must be', str(e))
    finally:
      self._get_processed()

1028

1029
if __name__ == '__main__':
1030 1031 1032 1033
  sys.stdout = gclient_utils.MakeFileAutoFlush(sys.stdout)
  sys.stdout = gclient_utils.MakeFileAnnotated(sys.stdout, include_zero=True)
  sys.stderr = gclient_utils.MakeFileAutoFlush(sys.stderr)
  sys.stderr = gclient_utils.MakeFileAnnotated(sys.stderr, include_zero=True)
1034 1035 1036
  logging.basicConfig(
      level=[logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG][
        min(sys.argv.count('-v'), 3)],
1037 1038
      format='%(relativeCreated)4d %(levelname)5s %(module)13s('
              '%(lineno)d) %(message)s')
1039
  unittest.main()