download_from_google_storage_unittests.py 15.8 KB
Newer Older
1 2 3 4
#!/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.
5
# pylint: disable=protected-access
6 7 8 9 10 11 12 13

"""Unit tests for download_from_google_storage.py."""

import optparse
import os
import Queue
import shutil
import sys
14
import tarfile
15 16 17 18
import tempfile
import threading
import unittest

19

20 21 22 23 24 25 26 27
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import upload_to_google_storage
import download_from_google_storage

# ../third_party/gsutil/gsutil
GSUTIL_DEFAULT_PATH = os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
28
    'gsutil.py')
29 30 31 32
TEST_DIR = os.path.dirname(os.path.abspath(__file__))


class GsutilMock(object):
33
  def __init__(self, path, boto_path, timeout=None):
34 35 36 37 38 39 40
    self.path = path
    self.timeout = timeout
    self.boto_path = boto_path
    self.expected = []
    self.history = []
    self.lock = threading.Lock()

41 42
  def add_expected(self, return_code, out, err, fn=None):
    self.expected.append((return_code, out, err, fn))
43 44 45 46 47 48 49 50

  def append_history(self, method, args):
    self.history.append((method, args))

  def call(self, *args):
    with self.lock:
      self.append_history('call', args)
      if self.expected:
51 52 53 54
        code, _out, _err, fn = self.expected.pop(0)
        if fn:
          fn()
        return code
55 56 57 58 59 60 61
      else:
        return 0

  def check_call(self, *args):
    with self.lock:
      self.append_history('check_call', args)
      if self.expected:
62 63 64 65
        code, out, err, fn = self.expected.pop(0)
        if fn:
          fn()
        return code, out, err
66 67 68 69
      else:
        return (0, '', '')


70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
class ChangedWorkingDirectory(object):
  def __init__(self, working_directory):
    self._old_cwd = ''
    self._working_directory = working_directory

  def __enter__(self):
    self._old_cwd = os.getcwd()
    print "Enter directory = ", self._working_directory
    os.chdir(self._working_directory)

  def __exit__(self, *_):
    print "Enter directory = ", self._old_cwd
    os.chdir(self._old_cwd)


85 86 87 88 89 90 91 92 93
class GstoolsUnitTests(unittest.TestCase):
  def setUp(self):
    self.temp_dir = tempfile.mkdtemp(prefix='gstools_test')
    self.base_path = os.path.join(self.temp_dir, 'test_files')
    shutil.copytree(os.path.join(TEST_DIR, 'gstools'), self.base_path)

  def cleanUp(self):
    shutil.rmtree(self.temp_dir)

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
  def test_validate_tar_file(self):
    lorem_ipsum = os.path.join(self.base_path, 'lorem_ipsum.txt')
    with ChangedWorkingDirectory(self.base_path):
      # Sanity ok check.
      tar_dir = 'ok_dir'
      os.makedirs(os.path.join(self.base_path, tar_dir))
      tar = 'good.tar.gz'
      lorem_ipsum_copy = os.path.join(tar_dir, 'lorem_ipsum.txt')
      shutil.copyfile(lorem_ipsum, lorem_ipsum_copy)
      with tarfile.open(tar, 'w:gz') as tar:
        tar.add(lorem_ipsum_copy)
        self.assertTrue(
            download_from_google_storage._validate_tar_file(tar, tar_dir))

      # Test no links.
      tar_dir_link = 'for_tar_link'
      os.makedirs(tar_dir_link)
      link = os.path.join(tar_dir_link, 'link')
      os.symlink(lorem_ipsum, link)
      tar_with_links = 'with_links.tar.gz'
      with tarfile.open(tar_with_links, 'w:gz') as tar:
        tar.add(link)
        self.assertFalse(
            download_from_google_storage._validate_tar_file(tar, tar_dir_link))

      # Test not outside.
      tar_dir_outside = 'outside_tar'
      os.makedirs(tar_dir_outside)
      tar_with_outside = 'with_outside.tar.gz'
      with tarfile.open(tar_with_outside, 'w:gz') as tar:
        tar.add(lorem_ipsum)
        self.assertFalse(
            download_from_google_storage._validate_tar_file(tar,
                                                            tar_dir_outside))
      # Test no ..
      tar_with_dotdot = 'with_dotdot.tar.gz'
      dotdot_file = os.path.join(tar_dir, '..', tar_dir, 'lorem_ipsum.txt')
      with tarfile.open(tar_with_dotdot, 'w:gz') as tar:
        tar.add(dotdot_file)
        self.assertFalse(
            download_from_google_storage._validate_tar_file(tar,
                                                            tar_dir))

137
  def test_gsutil(self):
138
    gsutil = download_from_google_storage.Gsutil(GSUTIL_DEFAULT_PATH, None)
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
    self.assertEqual(gsutil.path, GSUTIL_DEFAULT_PATH)
    code, _, err = gsutil.check_call()
    self.assertEqual(code, 0)
    self.assertEqual(err, '')

  def test_get_sha1(self):
    lorem_ipsum = os.path.join(self.base_path, 'lorem_ipsum.txt')
    self.assertEqual(
        download_from_google_storage.get_sha1(lorem_ipsum),
        '7871c8e24da15bad8b0be2c36edc9dc77e37727f')

  def test_get_md5(self):
    lorem_ipsum = os.path.join(self.base_path, 'lorem_ipsum.txt')
    self.assertEqual(
        upload_to_google_storage.get_md5(lorem_ipsum),
        '634d7c1ed3545383837428f031840a1e')

  def test_get_md5_cached_read(self):
    lorem_ipsum = os.path.join(self.base_path, 'lorem_ipsum.txt')
    # Use a fake 'stale' MD5 sum.  Expected behavior is to return stale sum.
    self.assertEqual(
        upload_to_google_storage.get_md5_cached(lorem_ipsum),
        '734d7c1ed3545383837428f031840a1e')

  def test_get_md5_cached_write(self):
    lorem_ipsum2 = os.path.join(self.base_path, 'lorem_ipsum2.txt')
    lorem_ipsum2_md5 = os.path.join(self.base_path, 'lorem_ipsum2.txt.md5')
    if os.path.exists(lorem_ipsum2_md5):
      os.remove(lorem_ipsum2_md5)
    # Use a fake 'stale' MD5 sum.  Expected behavior is to return stale sum.
    self.assertEqual(
        upload_to_google_storage.get_md5_cached(lorem_ipsum2),
        '4c02d1eb455a0f22c575265d17b84b6d')
    self.assertTrue(os.path.exists(lorem_ipsum2_md5))
    self.assertEqual(
        open(lorem_ipsum2_md5, 'rb').read(),
        '4c02d1eb455a0f22c575265d17b84b6d')
    os.remove(lorem_ipsum2_md5)  # Clean up.
    self.assertFalse(os.path.exists(lorem_ipsum2_md5))


class DownloadTests(unittest.TestCase):
  def setUp(self):
182
    self.gsutil = GsutilMock(GSUTIL_DEFAULT_PATH, None)
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    self.temp_dir = tempfile.mkdtemp(prefix='gstools_test')
    self.checkout_test_files = os.path.join(
        TEST_DIR, 'gstools', 'download_test_data')
    self.base_path = os.path.join(
        self.temp_dir, 'download_test_data')
    shutil.copytree(self.checkout_test_files, self.base_path)
    self.base_url = 'gs://sometesturl'
    self.parser = optparse.OptionParser()
    self.queue = Queue.Queue()
    self.ret_codes = Queue.Queue()
    self.lorem_ipsum = os.path.join(self.base_path, 'lorem_ipsum.txt')
    self.lorem_ipsum_sha1 = '7871c8e24da15bad8b0be2c36edc9dc77e37727f'
    self.maxDiff = None

  def cleanUp(self):
    shutil.rmtree(self.temp_dir)

  def test_enumerate_files_non_recursive(self):
    queue_size = download_from_google_storage.enumerate_work_queue(
202
        self.base_path, self.queue, True, False, False, None, False, False)
203 204 205 206 207 208 209 210 211 212
    expected_queue = [
        ('e6c4fbd4fe7607f3e6ebf68b2ea4ef694da7b4fe',
            os.path.join(self.base_path, 'rootfolder_text.txt')),
       ('7871c8e24da15bad8b0be2c36edc9dc77e37727f',
            os.path.join(self.base_path, 'uploaded_lorem_ipsum.txt'))]
    self.assertEqual(sorted(expected_queue), sorted(self.queue.queue))
    self.assertEqual(queue_size, 2)

  def test_enumerate_files_recursive(self):
    queue_size = download_from_google_storage.enumerate_work_queue(
213
        self.base_path, self.queue, True, True, False, None, False, False)
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
    expected_queue = [
        ('e6c4fbd4fe7607f3e6ebf68b2ea4ef694da7b4fe',
            os.path.join(self.base_path, 'rootfolder_text.txt')),
        ('7871c8e24da15bad8b0be2c36edc9dc77e37727f',
            os.path.join(self.base_path, 'uploaded_lorem_ipsum.txt')),
        ('b5415aa0b64006a95c0c409182e628881d6d6463',
            os.path.join(self.base_path, 'subfolder', 'subfolder_text.txt'))]
    self.assertEqual(sorted(expected_queue), sorted(self.queue.queue))
    self.assertEqual(queue_size, 3)

  def test_download_worker_single_file(self):
    sha1_hash = '7871c8e24da15bad8b0be2c36edc9dc77e37727f'
    input_filename = '%s/%s' % (self.base_url, sha1_hash)
    output_filename = os.path.join(self.base_path, 'uploaded_lorem_ipsum.txt')
    self.queue.put((sha1_hash, output_filename))
    self.queue.put((None, None))
    stdout_queue = Queue.Queue()
    download_from_google_storage._downloader_worker_thread(
        0, self.queue, False, self.base_url, self.gsutil,
233
        stdout_queue, self.ret_codes, True, False)
234 235 236 237
    expected_calls = [
        ('check_call',
            ('ls', input_filename)),
        ('check_call',
238
            ('cp', input_filename, output_filename))]
239 240 241
    if sys.platform != 'win32':
      expected_calls.append(
          ('check_call',
242
           ('stat',
243
            'gs://sometesturl/7871c8e24da15bad8b0be2c36edc9dc77e37727f')))
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    expected_output = [
        '0> Downloading %s...' % output_filename]
    expected_ret_codes = []
    self.assertEqual(list(stdout_queue.queue), expected_output)
    self.assertEqual(self.gsutil.history, expected_calls)
    self.assertEqual(list(self.ret_codes.queue), expected_ret_codes)

  def test_download_worker_skips_file(self):
    sha1_hash = 'e6c4fbd4fe7607f3e6ebf68b2ea4ef694da7b4fe'
    output_filename = os.path.join(self.base_path, 'rootfolder_text.txt')
    self.queue.put((sha1_hash, output_filename))
    self.queue.put((None, None))
    stdout_queue = Queue.Queue()
    download_from_google_storage._downloader_worker_thread(
        0, self.queue, False, self.base_url, self.gsutil,
259
        stdout_queue, self.ret_codes, True, False)
260 261 262 263 264 265
    expected_output = [
        '0> File %s exists and SHA1 matches. Skipping.' % output_filename
    ]
    self.assertEqual(list(stdout_queue.queue), expected_output)
    self.assertEqual(self.gsutil.history, [])

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
  def test_download_extract_archive(self):
    # Generate a gzipped tarfile
    output_filename = os.path.join(self.base_path, 'subfolder.tar.gz')
    output_dirname = os.path.join(self.base_path, 'subfolder')
    extracted_filename = os.path.join(output_dirname, 'subfolder_text.txt')
    with tarfile.open(output_filename, 'w:gz') as tar:
      tar.add(output_dirname, arcname='subfolder')
    shutil.rmtree(output_dirname)
    sha1_hash = download_from_google_storage.get_sha1(output_filename)
    input_filename = '%s/%s' % (self.base_url, sha1_hash)
    self.queue.put((sha1_hash, output_filename))
    self.queue.put((None, None))
    stdout_queue = Queue.Queue()
    download_from_google_storage._downloader_worker_thread(
        0, self.queue, True, self.base_url, self.gsutil,
        stdout_queue, self.ret_codes, True, True, delete=False)
    expected_calls = [
        ('check_call',
            ('ls', input_filename)),
        ('check_call',
            ('cp', input_filename, output_filename))]
    if sys.platform != 'win32':
      expected_calls.append(
          ('check_call',
           ('stat',
            'gs://sometesturl/%s' % sha1_hash)))
    expected_output = [
        '0> Downloading %s...' % output_filename]
    expected_output.extend([
        '0> Extracting 3 entries from %s to %s' % (output_filename,
                                                   output_dirname)])
    expected_ret_codes = []
    self.assertEqual(list(stdout_queue.queue), expected_output)
    self.assertEqual(self.gsutil.history, expected_calls)
    self.assertEqual(list(self.ret_codes.queue), expected_ret_codes)
    self.assertTrue(os.path.exists(output_dirname))
    self.assertTrue(os.path.exists(extracted_filename))

304 305 306 307 308 309 310 311 312 313
  def test_download_worker_skips_not_found_file(self):
    sha1_hash = '7871c8e24da15bad8b0be2c36edc9dc77e37727f'
    input_filename = '%s/%s' % (self.base_url, sha1_hash)
    output_filename = os.path.join(self.base_path, 'uploaded_lorem_ipsum.txt')
    self.queue.put((sha1_hash, output_filename))
    self.queue.put((None, None))
    stdout_queue = Queue.Queue()
    self.gsutil.add_expected(1, '', '')  # Return error when 'ls' is called.
    download_from_google_storage._downloader_worker_thread(
        0, self.queue, False, self.base_url, self.gsutil,
314
        stdout_queue, self.ret_codes, True, False)
315
    expected_output = [
316
        '0> Failed to fetch file %s for %s, skipping. [Err: ]' % (
317 318 319 320 321 322 323
            input_filename, output_filename),
    ]
    expected_calls = [
        ('check_call',
            ('ls', input_filename))
    ]
    expected_ret_codes = [
324
        (1, 'Failed to fetch file %s for %s. [Err: ]' % (
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
            input_filename, output_filename))
    ]
    self.assertEqual(list(stdout_queue.queue), expected_output)
    self.assertEqual(self.gsutil.history, expected_calls)
    self.assertEqual(list(self.ret_codes.queue), expected_ret_codes)

  def test_download_cp_fails(self):
    sha1_hash = '7871c8e24da15bad8b0be2c36edc9dc77e37727f'
    input_filename = '%s/%s' % (self.base_url, sha1_hash)
    output_filename = os.path.join(self.base_path, 'uploaded_lorem_ipsum.txt')
    self.gsutil.add_expected(0, '', '')
    self.gsutil.add_expected(101, '', 'Test error message.')
    code = download_from_google_storage.download_from_google_storage(
        input_filename=sha1_hash,
        base_url=self.base_url,
        gsutil=self.gsutil,
        num_threads=1,
        directory=False,
        recursive=False,
        force=True,
        output=output_filename,
        ignore_errors=False,
347
        sha1_file=False,
348
        verbose=True,
349 350
        auto_platform=False,
        extract=False)
351 352 353 354
    expected_calls = [
        ('check_call',
            ('ls', input_filename)),
        ('check_call',
355
            ('cp', input_filename, output_filename))
356
    ]
357 358 359
    if sys.platform != 'win32':
      expected_calls.append(
          ('check_call',
360
           ('stat',
361
            'gs://sometesturl/7871c8e24da15bad8b0be2c36edc9dc77e37727f')))
362 363 364
    self.assertEqual(self.gsutil.history, expected_calls)
    self.assertEqual(code, 101)

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
  def test_corrupt_download(self):
    q = Queue.Queue()
    out_q = Queue.Queue()
    ret_codes = Queue.Queue()
    tmp_dir = tempfile.mkdtemp()
    sha1_hash = '7871c8e24da15bad8b0be2c36edc9dc77e37727f'
    output_filename = os.path.join(tmp_dir, 'lorem_ipsum.txt')
    q.put(('7871c8e24da15bad8b0be2c36edc9dc77e37727f', output_filename))
    q.put((None, None))
    def _write_bad_file():
      with open(output_filename, 'w') as f:
        f.write('foobar')
    self.gsutil.add_expected(0, '', '')
    self.gsutil.add_expected(0, '', '', _write_bad_file)
    download_from_google_storage._downloader_worker_thread(
380
        1, q, True, self.base_url, self.gsutil, out_q, ret_codes, True, False)
381 382 383 384 385 386 387 388 389 390
    self.assertTrue(q.empty())
    msg = ('1> ERROR remote sha1 (%s) does not match expected sha1 (%s).' %
           ('8843d7f92416211de9ebb963ff4ce28125932878', sha1_hash))
    self.assertEquals(out_q.get(), '1> Downloading %s...' % output_filename)
    self.assertEquals(out_q.get(), msg)
    self.assertEquals(ret_codes.get(), (20, msg))
    self.assertTrue(out_q.empty())
    self.assertTrue(ret_codes.empty())


391 392 393 394 395 396 397 398 399 400 401 402 403 404
  def test_download_directory_no_recursive_non_force(self):
    sha1_hash = '7871c8e24da15bad8b0be2c36edc9dc77e37727f'
    input_filename = '%s/%s' % (self.base_url, sha1_hash)
    output_filename = os.path.join(self.base_path, 'uploaded_lorem_ipsum.txt')
    code = download_from_google_storage.download_from_google_storage(
        input_filename=self.base_path,
        base_url=self.base_url,
        gsutil=self.gsutil,
        num_threads=1,
        directory=True,
        recursive=False,
        force=False,
        output=None,
        ignore_errors=False,
405
        sha1_file=False,
406
        verbose=True,
407 408
        auto_platform=False,
        extract=False)
409 410 411 412
    expected_calls = [
        ('check_call',
            ('ls', input_filename)),
        ('check_call',
413
            ('cp', input_filename, output_filename))]
414 415 416
    if sys.platform != 'win32':
      expected_calls.append(
          ('check_call',
417
           ('stat',
418
            'gs://sometesturl/7871c8e24da15bad8b0be2c36edc9dc77e37727f')))
419 420 421 422 423
    self.assertEqual(self.gsutil.history, expected_calls)
    self.assertEqual(code, 0)


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