blob: 52f858d7477e4ff852680ea035be5924775d2595 [file] [log] [blame]
Mike Frysingere58c0e22017-10-04 15:43:30 -04001# -*- coding: utf-8 -*-
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -04002# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Mike Frysingereb753bf2013-11-22 16:05:35 -05006"""Unittests for upload_symbols.py"""
7
Mike Frysinger7f9be142014-01-15 02:16:42 -05008from __future__ import print_function
9
Mike Frysinger06da5202014-09-26 17:30:33 -050010import errno
Don Garretta28be6d2016-06-16 18:09:35 -070011import itertools
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -040012import os
Mike Frysinger0a2fd922014-09-12 20:23:42 -070013import signal
Mike Frysinger06da5202014-09-26 17:30:33 -050014import socket
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -040015import sys
Aviv Keshetd1f04632014-05-09 11:33:46 -070016import time
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -040017
Mike Frysinger6db648e2018-07-24 19:57:58 -040018import mock
Mike Frysinger3d465162019-08-28 00:40:23 -040019from six.moves import BaseHTTPServer
20from six.moves import socketserver
Mike Frysinger3dcacee2019-08-23 17:09:11 -040021from six.moves import urllib
Mike Frysinger6db648e2018-07-24 19:57:58 -040022
Mike Frysinger079863c2014-10-09 23:16:46 -040023# We specifically set up a local server to connect to, so make sure we
24# delete any proxy settings that might screw that up. We also need to
25# do it here because modules that are imported below will implicitly
26# initialize with this proxy setting rather than dynamically pull it
27# on the fly :(.
Mike Frysinger92bdef52019-08-21 21:05:13 -040028# pylint: disable=wrong-import-position
Mike Frysinger079863c2014-10-09 23:16:46 -040029os.environ.pop('http_proxy', None)
30
Aviv Keshetb7519e12016-10-04 00:50:00 -070031from chromite.lib import constants
Mike Frysingerbbd1f112016-09-08 18:25:11 -040032
33# The isolateserver includes a bunch of third_party python packages that clash
34# with chromite's bundled third_party python packages (like oauth2client).
35# Since upload_symbols is not imported in to other parts of chromite, and there
36# are no deps in third_party we care about, purge the chromite copy. This way
37# we can use isolateserver for deduping.
38# TODO: If we ever sort out third_party/ handling and make it per-script opt-in,
39# we can purge this logic.
40third_party = os.path.join(constants.CHROMITE_DIR, 'third_party')
41while True:
42 try:
43 sys.path.remove(third_party)
44 except ValueError:
45 break
Mike Frysingerbbd1f112016-09-08 18:25:11 -040046del third_party
47
Ralph Nathan446aee92015-03-23 14:44:56 -070048from chromite.lib import cros_logging as logging
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -040049from chromite.lib import cros_test_lib
50from chromite.lib import osutils
51from chromite.lib import parallel
Mike Frysinger0a2fd922014-09-12 20:23:42 -070052from chromite.lib import remote_access
Mike Frysinger5e30a4b2014-02-12 20:23:04 -050053from chromite.scripts import cros_generate_breakpad_symbols
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -040054from chromite.scripts import upload_symbols
55
Mike Frysinger0c0efa22014-02-09 23:32:23 -050056
Don Garretta28be6d2016-06-16 18:09:35 -070057class SymbolsTestBase(cros_test_lib.MockTempDirTestCase):
58 """Base class for most symbols tests."""
59
60 SLIM_CONTENT = """
61some junk
62"""
63
64 FAT_CONTENT = """
65STACK CFI 1234
66some junk
67STACK CFI 1234
68"""
69
70 def setUp(self):
71 # Make certain we don't use the network.
Mike Frysinger3dcacee2019-08-23 17:09:11 -040072 self.urlopen_mock = self.PatchObject(urllib.request, 'urlopen')
Mike Nichols90f7c152019-04-09 15:14:08 -060073 self.request_mock = self.PatchObject(upload_symbols, 'ExecRequest',
74 return_value={'uploadUrl':
75 'testurl',
76 'uploadKey':
77 'asdgasgas'})
Don Garretta28be6d2016-06-16 18:09:35 -070078
79 # Make 'uploads' go fast.
80 self.PatchObject(upload_symbols, 'SLEEP_DELAY', 0)
81 self.PatchObject(upload_symbols, 'INITIAL_RETRY_DELAY', 0)
82
83 # So our symbol file content doesn't have to be real.
84 self.PatchObject(cros_generate_breakpad_symbols, 'ReadSymsHeader',
85 return_value=cros_generate_breakpad_symbols.SymbolHeader(
86 os='os', cpu='cpu', id='id', name='name'))
87
88 self.working = os.path.join(self.tempdir, 'expand')
89 osutils.SafeMakedirs(self.working)
90
91 self.data = os.path.join(self.tempdir, 'data')
92 osutils.SafeMakedirs(self.data)
93
94 def createSymbolFile(self, filename, content=FAT_CONTENT, size=0,
95 status=None, dedupe=False):
96 fullname = os.path.join(self.data, filename)
97 osutils.SafeMakedirs(os.path.dirname(fullname))
98
99 # If a file size is given, force that to be the minimum file size. Create
100 # a sparse file so large files are practical.
101 with open(fullname, 'w+b') as f:
102 f.truncate(size)
103 f.seek(0)
104 f.write(content)
105
106 result = upload_symbols.SymbolFile(display_path=filename,
107 file_name=fullname)
108
109 if status:
110 result.status = status
111
112 if dedupe:
113 result.dedupe_item = upload_symbols.DedupeItem(result)
114 result.dedupe_push_state = 'push_state'
115
116 return result
117
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -0400118
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700119class SymbolServerRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
120 """HTTP handler for symbol POSTs"""
121
122 RESP_CODE = None
123 RESP_MSG = None
124
125 def do_POST(self):
126 """Handle a POST request"""
127 # Drain the data from the client. If we don't, we might write the response
128 # and close the socket before the client finishes, so they die with EPIPE.
129 clen = int(self.headers.get('Content-Length', '0'))
130 self.rfile.read(clen)
131
132 self.send_response(self.RESP_CODE, self.RESP_MSG)
133 self.end_headers()
134
Mike Frysingera4418152019-09-22 04:00:24 -0400135 # pylint: disable=arguments-differ
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700136 def log_message(self, *args, **kwargs):
137 """Stub the logger as it writes to stderr"""
138 pass
139
140
Mike Frysinger3d465162019-08-28 00:40:23 -0400141class SymbolServer(socketserver.ThreadingTCPServer, BaseHTTPServer.HTTPServer):
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700142 """Simple HTTP server that forks each request"""
143
144
145class UploadSymbolsServerTest(cros_test_lib.MockTempDirTestCase):
146 """Tests for UploadSymbols() and a local HTTP server"""
147
148 SYM_CONTENTS = """MODULE Linux arm 123-456 blkid
149PUBLIC 1471 0 main"""
150
151 def SpawnServer(self, RequestHandler):
152 """Spawn a new http server"""
Mike Frysinger06da5202014-09-26 17:30:33 -0500153 while True:
154 try:
155 port = remote_access.GetUnusedPort()
156 address = ('', port)
157 self.httpd = SymbolServer(address, RequestHandler)
158 break
159 except socket.error as e:
160 if e.errno == errno.EADDRINUSE:
161 continue
162 raise
Don Garretta28be6d2016-06-16 18:09:35 -0700163 self.server_url = 'http://localhost:%i/post/path' % port
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700164 self.httpd_pid = os.fork()
165 if self.httpd_pid == 0:
166 self.httpd.serve_forever(poll_interval=0.1)
167 sys.exit(0)
168
169 def setUp(self):
170 self.httpd_pid = None
171 self.httpd = None
Don Garretta28be6d2016-06-16 18:09:35 -0700172 self.server_url = None
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700173 self.sym_file = os.path.join(self.tempdir, 'test.sym')
174 osutils.WriteFile(self.sym_file, self.SYM_CONTENTS)
175
Don Garretta28be6d2016-06-16 18:09:35 -0700176 # Stop sleeps and retries for these tests.
177 self.PatchObject(upload_symbols, 'SLEEP_DELAY', 0)
178 self.PatchObject(upload_symbols, 'INITIAL_RETRY_DELAY', 0)
179 self.PatchObject(upload_symbols, 'MAX_RETRIES', 0)
180
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700181 def tearDown(self):
182 # Only kill the server if we forked one.
183 if self.httpd_pid:
184 os.kill(self.httpd_pid, signal.SIGUSR1)
185
186 def testSuccess(self):
187 """The server returns success for all uploads"""
188 class Handler(SymbolServerRequestHandler):
189 """Always return 200"""
190 RESP_CODE = 200
Mike Nichols90f7c152019-04-09 15:14:08 -0600191 self.PatchObject(upload_symbols, 'ExecRequest',
192 return_value={'uploadUrl': 'testurl',
193 'uploadKey': 'testSuccess'})
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700194 self.SpawnServer(Handler)
Don Garretta28be6d2016-06-16 18:09:35 -0700195 ret = upload_symbols.UploadSymbols(
196 sym_paths=[self.sym_file] * 10,
197 upload_url=self.server_url,
Mike Nichols90f7c152019-04-09 15:14:08 -0600198 api_key='testSuccess')
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700199 self.assertEqual(ret, 0)
200
201 def testError(self):
202 """The server returns errors for all uploads"""
203 class Handler(SymbolServerRequestHandler):
Mike Nichols90f7c152019-04-09 15:14:08 -0600204 """All connections error"""
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700205 RESP_CODE = 500
206 RESP_MSG = 'Internal Server Error'
207
208 self.SpawnServer(Handler)
Don Garretta28be6d2016-06-16 18:09:35 -0700209 ret = upload_symbols.UploadSymbols(
210 sym_paths=[self.sym_file] * 10,
211 upload_url=self.server_url,
Mike Nichols90f7c152019-04-09 15:14:08 -0600212 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700213 self.assertEqual(ret, 10)
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700214
215 def testHungServer(self):
216 """The server chokes, but we recover"""
217 class Handler(SymbolServerRequestHandler):
218 """All connections choke forever"""
Mike Nichols137e82d2019-05-15 18:40:34 -0600219 self.PatchObject(upload_symbols, 'ExecRequest',
220 return_value={'pairs': []})
221
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700222 def do_POST(self):
223 while True:
224 time.sleep(1000)
225
226 self.SpawnServer(Handler)
227 with mock.patch.object(upload_symbols, 'GetUploadTimeout') as m:
Don Garretta28be6d2016-06-16 18:09:35 -0700228 m.return_value = 0.01
Mike Frysinger58312e92014-03-18 04:18:36 -0400229 ret = upload_symbols.UploadSymbols(
Don Garretta28be6d2016-06-16 18:09:35 -0700230 sym_paths=[self.sym_file] * 10,
231 upload_url=self.server_url,
Mike Nichols137e82d2019-05-15 18:40:34 -0600232 timeout=m.return_value,
Mike Nichols90f7c152019-04-09 15:14:08 -0600233 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700234 self.assertEqual(ret, 10)
Aviv Keshetd1f04632014-05-09 11:33:46 -0700235
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -0400236
Don Garretta28be6d2016-06-16 18:09:35 -0700237class UploadSymbolsHelpersTest(cros_test_lib.TestCase):
238 """Test assorted helper functions and classes."""
Don Garretta28be6d2016-06-16 18:09:35 -0700239 def testIsTarball(self):
240 notTar = [
241 '/foo/bar/test.bin',
242 '/foo/bar/test.tar.bin',
243 '/foo/bar/test.faketar.gz',
244 '/foo/bar/test.nottgz',
Mike Frysinger0c0efa22014-02-09 23:32:23 -0500245 ]
Mike Frysinger0c0efa22014-02-09 23:32:23 -0500246
Don Garretta28be6d2016-06-16 18:09:35 -0700247 isTar = [
248 '/foo/bar/test.tar',
249 '/foo/bar/test.bin.tar',
250 '/foo/bar/test.bin.tar.bz2',
251 '/foo/bar/test.bin.tar.gz',
252 '/foo/bar/test.bin.tar.xz',
253 '/foo/bar/test.tbz2',
254 '/foo/bar/test.tbz',
255 '/foo/bar/test.tgz',
256 '/foo/bar/test.txz',
257 ]
Mike Frysinger0c0efa22014-02-09 23:32:23 -0500258
Don Garretta28be6d2016-06-16 18:09:35 -0700259 for p in notTar:
260 self.assertFalse(upload_symbols.IsTarball(p))
261
262 for p in isTar:
263 self.assertTrue(upload_symbols.IsTarball(p))
264
265 def testBatchGenerator(self):
266 result = upload_symbols.BatchGenerator([], 2)
267 self.assertEqual(list(result), [])
268
Mike Frysinger66848312019-07-03 02:12:39 -0400269 # BatchGenerator accepts iterators, so passing it here is safe.
270 # pylint: disable=range-builtin-not-iterating
Mike Frysinger79cca962019-06-13 15:26:53 -0400271 result = upload_symbols.BatchGenerator(range(6), 2)
Don Garretta28be6d2016-06-16 18:09:35 -0700272 self.assertEqual(list(result), [[0, 1], [2, 3], [4, 5]])
273
Mike Frysinger79cca962019-06-13 15:26:53 -0400274 result = upload_symbols.BatchGenerator(range(7), 2)
Don Garretta28be6d2016-06-16 18:09:35 -0700275 self.assertEqual(list(result), [[0, 1], [2, 3], [4, 5], [6]])
276
277 # Prove that we are streaming the results, not generating them all at once.
278 result = upload_symbols.BatchGenerator(itertools.repeat(0), 2)
Mike Frysinger67d90242019-07-03 19:03:58 -0400279 self.assertEqual(next(result), [0, 0])
Don Garretta28be6d2016-06-16 18:09:35 -0700280
281
282class FindSymbolFilesTest(SymbolsTestBase):
283 """Test FindSymbolFiles."""
284 def setUp(self):
285 self.symfile = self.createSymbolFile('root.sym').file_name
286 self.innerfile = self.createSymbolFile(
287 os.path.join('nested', 'inner.sym')).file_name
288
289 # CreateTarball is having issues outside the chroot from open file tests.
290 #
291 # self.tarball = os.path.join(self.tempdir, 'syms.tar.gz')
292 # cros_build_lib.CreateTarball(
293 # 'syms.tar.gz', self.tempdir, inputs=(self.data))
294
295 def testEmpty(self):
296 symbols = list(upload_symbols.FindSymbolFiles(
297 self.working, []))
298 self.assertEqual(symbols, [])
299
300 def testFile(self):
301 symbols = list(upload_symbols.FindSymbolFiles(
302 self.working, [self.symfile]))
303
304 self.assertEqual(len(symbols), 1)
305 sf = symbols[0]
306
307 self.assertEqual(sf.display_name, 'root.sym')
308 self.assertEqual(sf.display_path, self.symfile)
309 self.assertEqual(sf.file_name, self.symfile)
310 self.assertEqual(sf.status, upload_symbols.SymbolFile.INITIAL)
311 self.assertEqual(sf.FileSize(), len(self.FAT_CONTENT))
312
313 def testDir(self):
314 symbols = list(upload_symbols.FindSymbolFiles(
315 self.working, [self.data]))
316
317 self.assertEqual(len(symbols), 2)
318 root = symbols[0]
319 nested = symbols[1]
320
321 self.assertEqual(root.display_name, 'root.sym')
322 self.assertEqual(root.display_path, 'root.sym')
323 self.assertEqual(root.file_name, self.symfile)
324 self.assertEqual(root.status, upload_symbols.SymbolFile.INITIAL)
325 self.assertEqual(root.FileSize(), len(self.FAT_CONTENT))
326
327 self.assertEqual(nested.display_name, 'inner.sym')
328 self.assertEqual(nested.display_path, 'nested/inner.sym')
329 self.assertEqual(nested.file_name, self.innerfile)
330 self.assertEqual(nested.status, upload_symbols.SymbolFile.INITIAL)
331 self.assertEqual(nested.FileSize(), len(self.FAT_CONTENT))
332
333
334class AdjustSymbolFileSizeTest(SymbolsTestBase):
335 """Test AdjustSymbolFileSize."""
336 def setUp(self):
337 self.slim = self.createSymbolFile('slim.sym', self.SLIM_CONTENT)
338 self.fat = self.createSymbolFile('fat.sym', self.FAT_CONTENT)
339
340 self.warn_mock = self.PatchObject(logging, 'PrintBuildbotStepWarnings')
341
342 def _testNotStripped(self, symbol, size=None, content=None):
343 start_file = symbol.file_name
344 after = upload_symbols.AdjustSymbolFileSize(
345 symbol, self.working, size)
346 self.assertIs(after, symbol)
347 self.assertEqual(after.file_name, start_file)
348 if content is not None:
349 self.assertEqual(osutils.ReadFile(after.file_name), content)
350
351 def _testStripped(self, symbol, size=None, content=None):
352 after = upload_symbols.AdjustSymbolFileSize(
353 symbol, self.working, size)
354 self.assertIs(after, symbol)
355 self.assertTrue(after.file_name.startswith(self.working))
356 if content is not None:
357 self.assertEqual(osutils.ReadFile(after.file_name), content)
358
359 def testSmall(self):
360 """Ensure that files smaller than the limit are not modified."""
361 self._testNotStripped(self.slim, 1024, self.SLIM_CONTENT)
362 self._testNotStripped(self.fat, 1024, self.FAT_CONTENT)
363
364 def testLarge(self):
365 """Ensure that files larger than the limit are modified."""
366 self._testStripped(self.slim, 1, self.SLIM_CONTENT)
367 self._testStripped(self.fat, 1, self.SLIM_CONTENT)
368
369 def testMixed(self):
370 """Test mix of large and small."""
371 strip_size = len(self.SLIM_CONTENT) + 1
372
373 self._testNotStripped(self.slim, strip_size, self.SLIM_CONTENT)
374 self._testStripped(self.fat, strip_size, self.SLIM_CONTENT)
375
376 def testSizeWarnings(self):
377 large = self.createSymbolFile(
378 'large.sym', content=self.SLIM_CONTENT,
379 size=upload_symbols.CRASH_SERVER_FILE_LIMIT*2)
380
381 # Would like to Strip as part of this test, but that really copies all
382 # of the sparse file content, which is too expensive for a unittest.
383 self._testNotStripped(large, None, None)
384
385 self.assertEqual(self.warn_mock.call_count, 1)
386
387
Mike Nichols137e82d2019-05-15 18:40:34 -0600388class DeduplicateTest(SymbolsTestBase):
389 """Test server Deduplication."""
390 def setUp(self):
391 self.PatchObject(upload_symbols, 'ExecRequest',
392 return_value={'pairs': [
393 {'status': 'FOUND',
394 'symbolId':
395 {'debugFile': 'sym1_sym',
396 'debugId': 'BEAA9BE'}},
397 {'status': 'FOUND',
398 'symbolId':
399 {'debugFile': 'sym2_sym',
400 'debugId': 'B6B1A36'}},
401 {'status': 'MISSING',
402 'symbolId':
403 {'debugFile': 'sym3_sym',
404 'debugId': 'D4FC0FC'}}]})
405
406 def testFindDuplicates(self):
407 # The first two symbols will be duplicate, the third new.
408 sym1 = self.createSymbolFile('sym1.sym')
409 sym1.header = cros_generate_breakpad_symbols.SymbolHeader('cpu', 'BEAA9BE',
410 'sym1_sym', 'os')
411 sym2 = self.createSymbolFile('sym2.sym')
412 sym2.header = cros_generate_breakpad_symbols.SymbolHeader('cpu', 'B6B1A36',
413 'sym2_sym', 'os')
414 sym3 = self.createSymbolFile('sym3.sym')
415 sym3.header = cros_generate_breakpad_symbols.SymbolHeader('cpu', 'D4FC0FC',
416 'sym3_sym', 'os')
417
418 result = upload_symbols.FindDuplicates((sym1, sym2, sym3), 'fake_url',
419 api_key='testkey')
420 self.assertEqual(list(result), [sym1, sym2, sym3])
421
422 self.assertEqual(sym1.status, upload_symbols.SymbolFile.DUPLICATE)
423 self.assertEqual(sym2.status, upload_symbols.SymbolFile.DUPLICATE)
424 self.assertEqual(sym3.status, upload_symbols.SymbolFile.INITIAL)
425
426
Don Garrettdeb2e032016-07-06 16:44:14 -0700427class PerformSymbolFilesUploadTest(SymbolsTestBase):
Don Garretta28be6d2016-06-16 18:09:35 -0700428 """Test PerformSymbolFile, and it's helper methods."""
429 def setUp(self):
Don Garrettdeb2e032016-07-06 16:44:14 -0700430 self.sym_initial = self.createSymbolFile(
431 'initial.sym')
432 self.sym_error = self.createSymbolFile(
433 'error.sym', status=upload_symbols.SymbolFile.ERROR)
434 self.sym_duplicate = self.createSymbolFile(
435 'duplicate.sym', status=upload_symbols.SymbolFile.DUPLICATE)
436 self.sym_uploaded = self.createSymbolFile(
437 'uploaded.sym', status=upload_symbols.SymbolFile.UPLOADED)
Don Garretta28be6d2016-06-16 18:09:35 -0700438
439 def testGetUploadTimeout(self):
440 """Test GetUploadTimeout helper function."""
441 # Timeout for small file.
Don Garrettdeb2e032016-07-06 16:44:14 -0700442 self.assertEqual(upload_symbols.GetUploadTimeout(self.sym_initial),
Don Garretta28be6d2016-06-16 18:09:35 -0700443 upload_symbols.UPLOAD_MIN_TIMEOUT)
444
445 # Timeout for 300M file.
446 large = self.createSymbolFile('large.sym', size=(300 * 1024 * 1024))
Ryo Hashimotof864c0e2017-02-14 12:46:08 +0900447 self.assertEqual(upload_symbols.GetUploadTimeout(large), 771)
Don Garretta28be6d2016-06-16 18:09:35 -0700448
449 def testUploadSymbolFile(self):
Mike Nichols90f7c152019-04-09 15:14:08 -0600450 upload_symbols.UploadSymbolFile('fake_url', self.sym_initial,
451 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700452 # TODO: Examine mock in more detail to make sure request is correct.
Mike Nichols137e82d2019-05-15 18:40:34 -0600453 self.assertEqual(self.request_mock.call_count, 3)
Don Garretta28be6d2016-06-16 18:09:35 -0700454
Don Garrettdeb2e032016-07-06 16:44:14 -0700455 def testPerformSymbolsFileUpload(self):
Don Garretta28be6d2016-06-16 18:09:35 -0700456 """We upload on first try."""
Don Garrettdeb2e032016-07-06 16:44:14 -0700457 symbols = [self.sym_initial]
Don Garretta28be6d2016-06-16 18:09:35 -0700458
Don Garrettdeb2e032016-07-06 16:44:14 -0700459 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600460 symbols, 'fake_url', api_key='testkey')
Don Garrettdeb2e032016-07-06 16:44:14 -0700461
462 self.assertEqual(list(result), symbols)
463 self.assertEqual(self.sym_initial.status,
464 upload_symbols.SymbolFile.UPLOADED)
Mike Nichols137e82d2019-05-15 18:40:34 -0600465 self.assertEqual(self.request_mock.call_count, 3)
Don Garretta28be6d2016-06-16 18:09:35 -0700466
Don Garrettdeb2e032016-07-06 16:44:14 -0700467 def testPerformSymbolsFileUploadFailure(self):
Don Garretta28be6d2016-06-16 18:09:35 -0700468 """All network requests fail."""
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400469 self.request_mock.side_effect = IOError('network failure')
Don Garrettdeb2e032016-07-06 16:44:14 -0700470 symbols = [self.sym_initial]
Don Garretta28be6d2016-06-16 18:09:35 -0700471
Don Garrettdeb2e032016-07-06 16:44:14 -0700472 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600473 symbols, 'fake_url', api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700474
Don Garrettdeb2e032016-07-06 16:44:14 -0700475 self.assertEqual(list(result), symbols)
476 self.assertEqual(self.sym_initial.status, upload_symbols.SymbolFile.ERROR)
Mike Nichols90f7c152019-04-09 15:14:08 -0600477 self.assertEqual(self.request_mock.call_count, 7)
Don Garretta28be6d2016-06-16 18:09:35 -0700478
Don Garrettdeb2e032016-07-06 16:44:14 -0700479 def testPerformSymbolsFileUploadTransisentFailure(self):
Don Garretta28be6d2016-06-16 18:09:35 -0700480 """We fail once, then succeed."""
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400481 self.urlopen_mock.side_effect = (IOError('network failure'), None)
Don Garrettdeb2e032016-07-06 16:44:14 -0700482 symbols = [self.sym_initial]
Don Garretta28be6d2016-06-16 18:09:35 -0700483
Don Garrettdeb2e032016-07-06 16:44:14 -0700484 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600485 symbols, 'fake_url', api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700486
Don Garrettdeb2e032016-07-06 16:44:14 -0700487 self.assertEqual(list(result), symbols)
488 self.assertEqual(self.sym_initial.status,
489 upload_symbols.SymbolFile.UPLOADED)
Mike Nichols137e82d2019-05-15 18:40:34 -0600490 self.assertEqual(self.request_mock.call_count, 3)
Don Garrettdeb2e032016-07-06 16:44:14 -0700491
492 def testPerformSymbolsFileUploadMixed(self):
493 """Upload symbols in mixed starting states.
494
495 Demonstrate that INITIAL and ERROR are uploaded, but DUPLICATE/UPLOADED are
496 ignored.
497 """
498 symbols = [self.sym_initial, self.sym_error,
499 self.sym_duplicate, self.sym_uploaded]
500
501 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600502 symbols, 'fake_url', api_key='testkey')
Don Garrettdeb2e032016-07-06 16:44:14 -0700503
504 #
505 self.assertEqual(list(result), symbols)
506 self.assertEqual(self.sym_initial.status,
507 upload_symbols.SymbolFile.UPLOADED)
508 self.assertEqual(self.sym_error.status,
509 upload_symbols.SymbolFile.UPLOADED)
510 self.assertEqual(self.sym_duplicate.status,
511 upload_symbols.SymbolFile.DUPLICATE)
512 self.assertEqual(self.sym_uploaded.status,
513 upload_symbols.SymbolFile.UPLOADED)
Mike Nichols137e82d2019-05-15 18:40:34 -0600514 self.assertEqual(self.request_mock.call_count, 6)
Don Garrettdeb2e032016-07-06 16:44:14 -0700515
516
517 def testPerformSymbolsFileUploadErrorOut(self):
518 """Demonstate we exit only after X errors."""
519
520 symbol_count = upload_symbols.MAX_TOTAL_ERRORS_FOR_RETRY + 10
521 symbols = []
522 fail_file = None
523
524 # potentially twice as many errors as we should attempt.
Mike Frysinger79cca962019-06-13 15:26:53 -0400525 for _ in range(symbol_count):
Don Garrettdeb2e032016-07-06 16:44:14 -0700526 # Each loop will get unique SymbolFile instances that use the same files.
527 fail = self.createSymbolFile('fail.sym')
528 fail_file = fail.file_name
529 symbols.append(self.createSymbolFile('pass.sym'))
530 symbols.append(fail)
531
532 # Mock out UploadSymbolFile and fail for fail.sym files.
Mike Nichols90f7c152019-04-09 15:14:08 -0600533 def failSome(_url, symbol, _api_key):
Don Garrettdeb2e032016-07-06 16:44:14 -0700534 if symbol.file_name == fail_file:
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400535 raise IOError('network failure')
Don Garrettdeb2e032016-07-06 16:44:14 -0700536
Luigi Semenzato5104f3c2016-10-12 12:37:42 -0700537 upload_mock = self.PatchObject(upload_symbols, 'UploadSymbolFile',
538 side_effect=failSome)
539 upload_mock.__name__ = 'UploadSymbolFileMock2'
Don Garrettdeb2e032016-07-06 16:44:14 -0700540
541 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600542 symbols, 'fake_url', api_key='testkey')
Don Garrettdeb2e032016-07-06 16:44:14 -0700543
544 self.assertEqual(list(result), symbols)
545
546 passed = sum(s.status == upload_symbols.SymbolFile.UPLOADED
547 for s in symbols)
548 failed = sum(s.status == upload_symbols.SymbolFile.ERROR
549 for s in symbols)
550 skipped = sum(s.status == upload_symbols.SymbolFile.INITIAL
551 for s in symbols)
552
553 # Shows we all pass.sym files worked until limit hit.
554 self.assertEqual(passed, upload_symbols.MAX_TOTAL_ERRORS_FOR_RETRY)
555
556 # Shows we all fail.sym files failed until limit hit.
557 self.assertEqual(failed, upload_symbols.MAX_TOTAL_ERRORS_FOR_RETRY)
558
559 # Shows both pass/fail were skipped after limit hit.
560 self.assertEqual(skipped, 10 * 2)
Don Garretta28be6d2016-06-16 18:09:35 -0700561
562
563class UploadSymbolsTest(SymbolsTestBase):
564 """Test UploadSymbols, along with most helper methods."""
565 def setUp(self):
566 # Results gathering.
567 self.failure_file = os.path.join(self.tempdir, 'failures.txt')
568
569 def testUploadSymbolsEmpty(self):
570 """Upload dir is empty."""
Mike Nichols137e82d2019-05-15 18:40:34 -0600571 result = upload_symbols.UploadSymbols([self.data], 'fake_url')
Don Garretta28be6d2016-06-16 18:09:35 -0700572
Mike Frysinger2d589a12019-08-25 14:15:12 -0400573 self.assertEqual(result, 0)
Don Garretta28be6d2016-06-16 18:09:35 -0700574 self.assertEqual(self.urlopen_mock.call_count, 0)
575
576 def testUploadSymbols(self):
577 """Upload a few files."""
578 self.createSymbolFile('slim.sym', self.SLIM_CONTENT)
579 self.createSymbolFile(os.path.join('nested', 'inner.sym'))
580 self.createSymbolFile('fat.sym', self.FAT_CONTENT)
581
582 result = upload_symbols.UploadSymbols(
Mike Nichols90f7c152019-04-09 15:14:08 -0600583 [self.data], 'fake_url',
584 failed_list=self.failure_file, strip_cfi=len(self.SLIM_CONTENT)+1,
585 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700586
Mike Frysinger2d589a12019-08-25 14:15:12 -0400587 self.assertEqual(result, 0)
Mike Nichols137e82d2019-05-15 18:40:34 -0600588 self.assertEqual(self.request_mock.call_count, 10)
Mike Frysinger2d589a12019-08-25 14:15:12 -0400589 self.assertEqual(osutils.ReadFile(self.failure_file), '')
Don Garretta28be6d2016-06-16 18:09:35 -0700590
591 def testUploadSymbolsLimited(self):
592 """Upload a few files."""
593 self.createSymbolFile('slim.sym', self.SLIM_CONTENT)
594 self.createSymbolFile(os.path.join('nested', 'inner.sym'))
595 self.createSymbolFile('fat.sym', self.FAT_CONTENT)
596
597 result = upload_symbols.UploadSymbols(
Mike Nichols90f7c152019-04-09 15:14:08 -0600598 [self.data], 'fake_url', upload_limit=2,
599 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700600
Mike Frysinger2d589a12019-08-25 14:15:12 -0400601 self.assertEqual(result, 0)
Mike Nichols137e82d2019-05-15 18:40:34 -0600602 self.assertEqual(self.request_mock.call_count, 7)
Mike Frysingerf2fa7d62017-12-14 18:33:59 -0500603 self.assertNotExists(self.failure_file)
Don Garretta28be6d2016-06-16 18:09:35 -0700604
605 def testUploadSymbolsFailures(self):
606 """Upload a few files."""
607 self.createSymbolFile('pass.sym')
608 fail = self.createSymbolFile('fail.sym')
609
Mike Nichols90f7c152019-04-09 15:14:08 -0600610 def failSome(_url, symbol, _api_key):
Don Garretta28be6d2016-06-16 18:09:35 -0700611 if symbol.file_name == fail.file_name:
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400612 raise IOError('network failure')
Don Garretta28be6d2016-06-16 18:09:35 -0700613
614 # Mock out UploadSymbolFile so it's easy to see which file to fail for.
615 upload_mock = self.PatchObject(upload_symbols, 'UploadSymbolFile',
616 side_effect=failSome)
Luigi Semenzato5104f3c2016-10-12 12:37:42 -0700617 # Mock __name__ for logging.
618 upload_mock.__name__ = 'UploadSymbolFileMock'
Don Garretta28be6d2016-06-16 18:09:35 -0700619
620 result = upload_symbols.UploadSymbols(
Mike Nichols90f7c152019-04-09 15:14:08 -0600621 [self.data], 'fake_url',
622 failed_list=self.failure_file, api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700623
Mike Frysinger2d589a12019-08-25 14:15:12 -0400624 self.assertEqual(result, 1)
Don Garretta28be6d2016-06-16 18:09:35 -0700625 self.assertEqual(upload_mock.call_count, 8)
Mike Frysinger2d589a12019-08-25 14:15:12 -0400626 self.assertEqual(osutils.ReadFile(self.failure_file), 'fail.sym\n')
Don Garretta28be6d2016-06-16 18:09:35 -0700627
Don Garretta28be6d2016-06-16 18:09:35 -0700628# TODO: We removed --network integration tests.
Mike Frysinger0c0efa22014-02-09 23:32:23 -0500629
630
Mike Frysingerea838d12014-12-08 11:55:32 -0500631def main(_argv):
Mike Frysinger27e21b72018-07-12 14:20:21 -0400632 # pylint: disable=protected-access
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -0400633 # Set timeouts small so that if the unit test hangs, it won't hang for long.
634 parallel._BackgroundTask.STARTUP_TIMEOUT = 5
635 parallel._BackgroundTask.EXIT_TIMEOUT = 5
636
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -0400637 # Run the tests.
Mike Frysingerba167372015-01-21 10:37:03 -0500638 cros_test_lib.main(level='info', module=__name__)