blob: 17080fa31dc207dc2115beaa4231ac64709518bb [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
Chris McDonalde705d8e2020-04-17 09:29:08 -060022import pytest # pylint: disable=import-error
Mike Frysinger6db648e2018-07-24 19:57:58 -040023
Mike Frysinger079863c2014-10-09 23:16:46 -040024# We specifically set up a local server to connect to, so make sure we
25# delete any proxy settings that might screw that up. We also need to
26# do it here because modules that are imported below will implicitly
27# initialize with this proxy setting rather than dynamically pull it
28# on the fly :(.
Mike Frysinger92bdef52019-08-21 21:05:13 -040029# pylint: disable=wrong-import-position
Mike Frysinger079863c2014-10-09 23:16:46 -040030os.environ.pop('http_proxy', None)
31
Aviv Keshetb7519e12016-10-04 00:50:00 -070032from chromite.lib import constants
Mike Frysingerbbd1f112016-09-08 18:25:11 -040033
34# The isolateserver includes a bunch of third_party python packages that clash
35# with chromite's bundled third_party python packages (like oauth2client).
36# Since upload_symbols is not imported in to other parts of chromite, and there
37# are no deps in third_party we care about, purge the chromite copy. This way
38# we can use isolateserver for deduping.
39# TODO: If we ever sort out third_party/ handling and make it per-script opt-in,
40# we can purge this logic.
41third_party = os.path.join(constants.CHROMITE_DIR, 'third_party')
42while True:
43 try:
44 sys.path.remove(third_party)
45 except ValueError:
46 break
Mike Frysingerbbd1f112016-09-08 18:25:11 -040047del third_party
48
Ralph Nathan446aee92015-03-23 14:44:56 -070049from chromite.lib import cros_logging as logging
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -040050from chromite.lib import cros_test_lib
51from chromite.lib import osutils
52from chromite.lib import parallel
Mike Frysinger0a2fd922014-09-12 20:23:42 -070053from chromite.lib import remote_access
Mike Frysinger5e30a4b2014-02-12 20:23:04 -050054from chromite.scripts import cros_generate_breakpad_symbols
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -040055from chromite.scripts import upload_symbols
56
Mike Frysinger0c0efa22014-02-09 23:32:23 -050057
Mike Frysinger2688ef62020-02-16 00:00:46 -050058assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
59
60
Don Garretta28be6d2016-06-16 18:09:35 -070061class SymbolsTestBase(cros_test_lib.MockTempDirTestCase):
62 """Base class for most symbols tests."""
63
64 SLIM_CONTENT = """
65some junk
66"""
67
68 FAT_CONTENT = """
69STACK CFI 1234
70some junk
71STACK CFI 1234
72"""
73
74 def setUp(self):
75 # Make certain we don't use the network.
Mike Frysinger3dcacee2019-08-23 17:09:11 -040076 self.urlopen_mock = self.PatchObject(urllib.request, 'urlopen')
Mike Nichols90f7c152019-04-09 15:14:08 -060077 self.request_mock = self.PatchObject(upload_symbols, 'ExecRequest',
78 return_value={'uploadUrl':
79 'testurl',
80 'uploadKey':
81 'asdgasgas'})
Don Garretta28be6d2016-06-16 18:09:35 -070082
83 # Make 'uploads' go fast.
84 self.PatchObject(upload_symbols, 'SLEEP_DELAY', 0)
85 self.PatchObject(upload_symbols, 'INITIAL_RETRY_DELAY', 0)
86
87 # So our symbol file content doesn't have to be real.
88 self.PatchObject(cros_generate_breakpad_symbols, 'ReadSymsHeader',
89 return_value=cros_generate_breakpad_symbols.SymbolHeader(
90 os='os', cpu='cpu', id='id', name='name'))
91
92 self.working = os.path.join(self.tempdir, 'expand')
93 osutils.SafeMakedirs(self.working)
94
95 self.data = os.path.join(self.tempdir, 'data')
96 osutils.SafeMakedirs(self.data)
97
98 def createSymbolFile(self, filename, content=FAT_CONTENT, size=0,
99 status=None, dedupe=False):
100 fullname = os.path.join(self.data, filename)
101 osutils.SafeMakedirs(os.path.dirname(fullname))
102
103 # If a file size is given, force that to be the minimum file size. Create
104 # a sparse file so large files are practical.
105 with open(fullname, 'w+b') as f:
106 f.truncate(size)
107 f.seek(0)
Mike Frysingerac75f602019-11-14 23:18:51 -0500108 f.write(content.encode('utf-8'))
Don Garretta28be6d2016-06-16 18:09:35 -0700109
110 result = upload_symbols.SymbolFile(display_path=filename,
111 file_name=fullname)
112
113 if status:
114 result.status = status
115
116 if dedupe:
117 result.dedupe_item = upload_symbols.DedupeItem(result)
118 result.dedupe_push_state = 'push_state'
119
120 return result
121
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -0400122
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700123class SymbolServerRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
124 """HTTP handler for symbol POSTs"""
125
126 RESP_CODE = None
127 RESP_MSG = None
128
129 def do_POST(self):
130 """Handle a POST request"""
131 # Drain the data from the client. If we don't, we might write the response
132 # and close the socket before the client finishes, so they die with EPIPE.
133 clen = int(self.headers.get('Content-Length', '0'))
134 self.rfile.read(clen)
135
136 self.send_response(self.RESP_CODE, self.RESP_MSG)
137 self.end_headers()
138
Mike Frysingera4418152019-09-22 04:00:24 -0400139 # pylint: disable=arguments-differ
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700140 def log_message(self, *args, **kwargs):
141 """Stub the logger as it writes to stderr"""
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700142
143
Mike Frysinger3d465162019-08-28 00:40:23 -0400144class SymbolServer(socketserver.ThreadingTCPServer, BaseHTTPServer.HTTPServer):
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700145 """Simple HTTP server that forks each request"""
146
147
Chris McDonalde705d8e2020-04-17 09:29:08 -0600148@pytest.mark.usefixtures('singleton_manager')
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700149class UploadSymbolsServerTest(cros_test_lib.MockTempDirTestCase):
150 """Tests for UploadSymbols() and a local HTTP server"""
151
152 SYM_CONTENTS = """MODULE Linux arm 123-456 blkid
153PUBLIC 1471 0 main"""
154
155 def SpawnServer(self, RequestHandler):
156 """Spawn a new http server"""
Mike Frysinger06da5202014-09-26 17:30:33 -0500157 while True:
158 try:
159 port = remote_access.GetUnusedPort()
160 address = ('', port)
161 self.httpd = SymbolServer(address, RequestHandler)
162 break
163 except socket.error as e:
164 if e.errno == errno.EADDRINUSE:
165 continue
166 raise
Don Garretta28be6d2016-06-16 18:09:35 -0700167 self.server_url = 'http://localhost:%i/post/path' % port
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700168 self.httpd_pid = os.fork()
169 if self.httpd_pid == 0:
170 self.httpd.serve_forever(poll_interval=0.1)
171 sys.exit(0)
Mike Frysingerac75f602019-11-14 23:18:51 -0500172 # The child runs the server, so close the socket in the parent.
173 self.httpd.server_close()
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700174
175 def setUp(self):
176 self.httpd_pid = None
177 self.httpd = None
Don Garretta28be6d2016-06-16 18:09:35 -0700178 self.server_url = None
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700179 self.sym_file = os.path.join(self.tempdir, 'test.sym')
180 osutils.WriteFile(self.sym_file, self.SYM_CONTENTS)
181
Don Garretta28be6d2016-06-16 18:09:35 -0700182 # Stop sleeps and retries for these tests.
183 self.PatchObject(upload_symbols, 'SLEEP_DELAY', 0)
184 self.PatchObject(upload_symbols, 'INITIAL_RETRY_DELAY', 0)
185 self.PatchObject(upload_symbols, 'MAX_RETRIES', 0)
186
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700187 def tearDown(self):
188 # Only kill the server if we forked one.
189 if self.httpd_pid:
190 os.kill(self.httpd_pid, signal.SIGUSR1)
191
192 def testSuccess(self):
193 """The server returns success for all uploads"""
194 class Handler(SymbolServerRequestHandler):
195 """Always return 200"""
196 RESP_CODE = 200
Mike Nichols90f7c152019-04-09 15:14:08 -0600197 self.PatchObject(upload_symbols, 'ExecRequest',
198 return_value={'uploadUrl': 'testurl',
199 'uploadKey': 'testSuccess'})
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700200 self.SpawnServer(Handler)
Don Garretta28be6d2016-06-16 18:09:35 -0700201 ret = upload_symbols.UploadSymbols(
202 sym_paths=[self.sym_file] * 10,
203 upload_url=self.server_url,
Mike Nichols90f7c152019-04-09 15:14:08 -0600204 api_key='testSuccess')
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700205 self.assertEqual(ret, 0)
206
207 def testError(self):
208 """The server returns errors for all uploads"""
209 class Handler(SymbolServerRequestHandler):
Mike Nichols90f7c152019-04-09 15:14:08 -0600210 """All connections error"""
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700211 RESP_CODE = 500
212 RESP_MSG = 'Internal Server Error'
213
214 self.SpawnServer(Handler)
Don Garretta28be6d2016-06-16 18:09:35 -0700215 ret = upload_symbols.UploadSymbols(
216 sym_paths=[self.sym_file] * 10,
217 upload_url=self.server_url,
Mike Nichols90f7c152019-04-09 15:14:08 -0600218 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700219 self.assertEqual(ret, 10)
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700220
221 def testHungServer(self):
222 """The server chokes, but we recover"""
223 class Handler(SymbolServerRequestHandler):
224 """All connections choke forever"""
Mike Nichols137e82d2019-05-15 18:40:34 -0600225 self.PatchObject(upload_symbols, 'ExecRequest',
226 return_value={'pairs': []})
227
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700228 def do_POST(self):
229 while True:
230 time.sleep(1000)
231
232 self.SpawnServer(Handler)
233 with mock.patch.object(upload_symbols, 'GetUploadTimeout') as m:
Don Garretta28be6d2016-06-16 18:09:35 -0700234 m.return_value = 0.01
Mike Frysinger58312e92014-03-18 04:18:36 -0400235 ret = upload_symbols.UploadSymbols(
Don Garretta28be6d2016-06-16 18:09:35 -0700236 sym_paths=[self.sym_file] * 10,
237 upload_url=self.server_url,
Mike Nichols137e82d2019-05-15 18:40:34 -0600238 timeout=m.return_value,
Mike Nichols90f7c152019-04-09 15:14:08 -0600239 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700240 self.assertEqual(ret, 10)
Aviv Keshetd1f04632014-05-09 11:33:46 -0700241
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -0400242
Don Garretta28be6d2016-06-16 18:09:35 -0700243class UploadSymbolsHelpersTest(cros_test_lib.TestCase):
244 """Test assorted helper functions and classes."""
Don Garretta28be6d2016-06-16 18:09:35 -0700245 def testIsTarball(self):
246 notTar = [
247 '/foo/bar/test.bin',
248 '/foo/bar/test.tar.bin',
249 '/foo/bar/test.faketar.gz',
250 '/foo/bar/test.nottgz',
Mike Frysinger0c0efa22014-02-09 23:32:23 -0500251 ]
Mike Frysinger0c0efa22014-02-09 23:32:23 -0500252
Don Garretta28be6d2016-06-16 18:09:35 -0700253 isTar = [
254 '/foo/bar/test.tar',
255 '/foo/bar/test.bin.tar',
256 '/foo/bar/test.bin.tar.bz2',
257 '/foo/bar/test.bin.tar.gz',
258 '/foo/bar/test.bin.tar.xz',
259 '/foo/bar/test.tbz2',
260 '/foo/bar/test.tbz',
261 '/foo/bar/test.tgz',
262 '/foo/bar/test.txz',
263 ]
Mike Frysinger0c0efa22014-02-09 23:32:23 -0500264
Don Garretta28be6d2016-06-16 18:09:35 -0700265 for p in notTar:
266 self.assertFalse(upload_symbols.IsTarball(p))
267
268 for p in isTar:
269 self.assertTrue(upload_symbols.IsTarball(p))
270
271 def testBatchGenerator(self):
272 result = upload_symbols.BatchGenerator([], 2)
273 self.assertEqual(list(result), [])
274
Mike Frysinger66848312019-07-03 02:12:39 -0400275 # BatchGenerator accepts iterators, so passing it here is safe.
276 # pylint: disable=range-builtin-not-iterating
Mike Frysinger79cca962019-06-13 15:26:53 -0400277 result = upload_symbols.BatchGenerator(range(6), 2)
Don Garretta28be6d2016-06-16 18:09:35 -0700278 self.assertEqual(list(result), [[0, 1], [2, 3], [4, 5]])
279
Mike Frysinger79cca962019-06-13 15:26:53 -0400280 result = upload_symbols.BatchGenerator(range(7), 2)
Don Garretta28be6d2016-06-16 18:09:35 -0700281 self.assertEqual(list(result), [[0, 1], [2, 3], [4, 5], [6]])
282
283 # Prove that we are streaming the results, not generating them all at once.
284 result = upload_symbols.BatchGenerator(itertools.repeat(0), 2)
Mike Frysinger67d90242019-07-03 19:03:58 -0400285 self.assertEqual(next(result), [0, 0])
Don Garretta28be6d2016-06-16 18:09:35 -0700286
287
288class FindSymbolFilesTest(SymbolsTestBase):
289 """Test FindSymbolFiles."""
290 def setUp(self):
291 self.symfile = self.createSymbolFile('root.sym').file_name
292 self.innerfile = self.createSymbolFile(
293 os.path.join('nested', 'inner.sym')).file_name
294
295 # CreateTarball is having issues outside the chroot from open file tests.
296 #
297 # self.tarball = os.path.join(self.tempdir, 'syms.tar.gz')
298 # cros_build_lib.CreateTarball(
299 # 'syms.tar.gz', self.tempdir, inputs=(self.data))
300
301 def testEmpty(self):
302 symbols = list(upload_symbols.FindSymbolFiles(
303 self.working, []))
304 self.assertEqual(symbols, [])
305
306 def testFile(self):
307 symbols = list(upload_symbols.FindSymbolFiles(
308 self.working, [self.symfile]))
309
310 self.assertEqual(len(symbols), 1)
311 sf = symbols[0]
312
313 self.assertEqual(sf.display_name, 'root.sym')
314 self.assertEqual(sf.display_path, self.symfile)
315 self.assertEqual(sf.file_name, self.symfile)
316 self.assertEqual(sf.status, upload_symbols.SymbolFile.INITIAL)
317 self.assertEqual(sf.FileSize(), len(self.FAT_CONTENT))
318
319 def testDir(self):
320 symbols = list(upload_symbols.FindSymbolFiles(
321 self.working, [self.data]))
322
323 self.assertEqual(len(symbols), 2)
324 root = symbols[0]
325 nested = symbols[1]
326
327 self.assertEqual(root.display_name, 'root.sym')
328 self.assertEqual(root.display_path, 'root.sym')
329 self.assertEqual(root.file_name, self.symfile)
330 self.assertEqual(root.status, upload_symbols.SymbolFile.INITIAL)
331 self.assertEqual(root.FileSize(), len(self.FAT_CONTENT))
332
333 self.assertEqual(nested.display_name, 'inner.sym')
334 self.assertEqual(nested.display_path, 'nested/inner.sym')
335 self.assertEqual(nested.file_name, self.innerfile)
336 self.assertEqual(nested.status, upload_symbols.SymbolFile.INITIAL)
337 self.assertEqual(nested.FileSize(), len(self.FAT_CONTENT))
338
339
340class AdjustSymbolFileSizeTest(SymbolsTestBase):
341 """Test AdjustSymbolFileSize."""
342 def setUp(self):
343 self.slim = self.createSymbolFile('slim.sym', self.SLIM_CONTENT)
344 self.fat = self.createSymbolFile('fat.sym', self.FAT_CONTENT)
345
346 self.warn_mock = self.PatchObject(logging, 'PrintBuildbotStepWarnings')
347
348 def _testNotStripped(self, symbol, size=None, content=None):
349 start_file = symbol.file_name
350 after = upload_symbols.AdjustSymbolFileSize(
351 symbol, self.working, size)
352 self.assertIs(after, symbol)
353 self.assertEqual(after.file_name, start_file)
354 if content is not None:
355 self.assertEqual(osutils.ReadFile(after.file_name), content)
356
357 def _testStripped(self, symbol, size=None, content=None):
358 after = upload_symbols.AdjustSymbolFileSize(
359 symbol, self.working, size)
360 self.assertIs(after, symbol)
361 self.assertTrue(after.file_name.startswith(self.working))
362 if content is not None:
363 self.assertEqual(osutils.ReadFile(after.file_name), content)
364
365 def testSmall(self):
366 """Ensure that files smaller than the limit are not modified."""
367 self._testNotStripped(self.slim, 1024, self.SLIM_CONTENT)
368 self._testNotStripped(self.fat, 1024, self.FAT_CONTENT)
369
370 def testLarge(self):
371 """Ensure that files larger than the limit are modified."""
372 self._testStripped(self.slim, 1, self.SLIM_CONTENT)
373 self._testStripped(self.fat, 1, self.SLIM_CONTENT)
374
375 def testMixed(self):
376 """Test mix of large and small."""
377 strip_size = len(self.SLIM_CONTENT) + 1
378
379 self._testNotStripped(self.slim, strip_size, self.SLIM_CONTENT)
380 self._testStripped(self.fat, strip_size, self.SLIM_CONTENT)
381
382 def testSizeWarnings(self):
383 large = self.createSymbolFile(
384 'large.sym', content=self.SLIM_CONTENT,
385 size=upload_symbols.CRASH_SERVER_FILE_LIMIT*2)
386
387 # Would like to Strip as part of this test, but that really copies all
388 # of the sparse file content, which is too expensive for a unittest.
389 self._testNotStripped(large, None, None)
390
391 self.assertEqual(self.warn_mock.call_count, 1)
392
393
Mike Nichols137e82d2019-05-15 18:40:34 -0600394class DeduplicateTest(SymbolsTestBase):
395 """Test server Deduplication."""
396 def setUp(self):
397 self.PatchObject(upload_symbols, 'ExecRequest',
398 return_value={'pairs': [
399 {'status': 'FOUND',
400 'symbolId':
401 {'debugFile': 'sym1_sym',
402 'debugId': 'BEAA9BE'}},
403 {'status': 'FOUND',
404 'symbolId':
405 {'debugFile': 'sym2_sym',
406 'debugId': 'B6B1A36'}},
407 {'status': 'MISSING',
408 'symbolId':
409 {'debugFile': 'sym3_sym',
410 'debugId': 'D4FC0FC'}}]})
411
412 def testFindDuplicates(self):
413 # The first two symbols will be duplicate, the third new.
414 sym1 = self.createSymbolFile('sym1.sym')
415 sym1.header = cros_generate_breakpad_symbols.SymbolHeader('cpu', 'BEAA9BE',
416 'sym1_sym', 'os')
417 sym2 = self.createSymbolFile('sym2.sym')
418 sym2.header = cros_generate_breakpad_symbols.SymbolHeader('cpu', 'B6B1A36',
419 'sym2_sym', 'os')
420 sym3 = self.createSymbolFile('sym3.sym')
421 sym3.header = cros_generate_breakpad_symbols.SymbolHeader('cpu', 'D4FC0FC',
422 'sym3_sym', 'os')
423
424 result = upload_symbols.FindDuplicates((sym1, sym2, sym3), 'fake_url',
425 api_key='testkey')
426 self.assertEqual(list(result), [sym1, sym2, sym3])
427
428 self.assertEqual(sym1.status, upload_symbols.SymbolFile.DUPLICATE)
429 self.assertEqual(sym2.status, upload_symbols.SymbolFile.DUPLICATE)
430 self.assertEqual(sym3.status, upload_symbols.SymbolFile.INITIAL)
431
432
Don Garrettdeb2e032016-07-06 16:44:14 -0700433class PerformSymbolFilesUploadTest(SymbolsTestBase):
Don Garretta28be6d2016-06-16 18:09:35 -0700434 """Test PerformSymbolFile, and it's helper methods."""
435 def setUp(self):
Don Garrettdeb2e032016-07-06 16:44:14 -0700436 self.sym_initial = self.createSymbolFile(
437 'initial.sym')
438 self.sym_error = self.createSymbolFile(
439 'error.sym', status=upload_symbols.SymbolFile.ERROR)
440 self.sym_duplicate = self.createSymbolFile(
441 'duplicate.sym', status=upload_symbols.SymbolFile.DUPLICATE)
442 self.sym_uploaded = self.createSymbolFile(
443 'uploaded.sym', status=upload_symbols.SymbolFile.UPLOADED)
Don Garretta28be6d2016-06-16 18:09:35 -0700444
445 def testGetUploadTimeout(self):
446 """Test GetUploadTimeout helper function."""
447 # Timeout for small file.
Don Garrettdeb2e032016-07-06 16:44:14 -0700448 self.assertEqual(upload_symbols.GetUploadTimeout(self.sym_initial),
Don Garretta28be6d2016-06-16 18:09:35 -0700449 upload_symbols.UPLOAD_MIN_TIMEOUT)
450
Ian Barkley-Yeung22ba8122020-02-05 15:39:02 -0800451 # Timeout for 512M file.
452 large = self.createSymbolFile('large.sym', size=(512 * 1024 * 1024))
453 self.assertEqual(upload_symbols.GetUploadTimeout(large), 15 * 60)
Don Garretta28be6d2016-06-16 18:09:35 -0700454
455 def testUploadSymbolFile(self):
Mike Nichols90f7c152019-04-09 15:14:08 -0600456 upload_symbols.UploadSymbolFile('fake_url', self.sym_initial,
457 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700458 # TODO: Examine mock in more detail to make sure request is correct.
Mike Nichols137e82d2019-05-15 18:40:34 -0600459 self.assertEqual(self.request_mock.call_count, 3)
Don Garretta28be6d2016-06-16 18:09:35 -0700460
Don Garrettdeb2e032016-07-06 16:44:14 -0700461 def testPerformSymbolsFileUpload(self):
Don Garretta28be6d2016-06-16 18:09:35 -0700462 """We upload on first try."""
Don Garrettdeb2e032016-07-06 16:44:14 -0700463 symbols = [self.sym_initial]
Don Garretta28be6d2016-06-16 18:09:35 -0700464
Don Garrettdeb2e032016-07-06 16:44:14 -0700465 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600466 symbols, 'fake_url', api_key='testkey')
Don Garrettdeb2e032016-07-06 16:44:14 -0700467
468 self.assertEqual(list(result), symbols)
469 self.assertEqual(self.sym_initial.status,
470 upload_symbols.SymbolFile.UPLOADED)
Mike Nichols137e82d2019-05-15 18:40:34 -0600471 self.assertEqual(self.request_mock.call_count, 3)
Don Garretta28be6d2016-06-16 18:09:35 -0700472
Don Garrettdeb2e032016-07-06 16:44:14 -0700473 def testPerformSymbolsFileUploadFailure(self):
Don Garretta28be6d2016-06-16 18:09:35 -0700474 """All network requests fail."""
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400475 self.request_mock.side_effect = IOError('network failure')
Don Garrettdeb2e032016-07-06 16:44:14 -0700476 symbols = [self.sym_initial]
Don Garretta28be6d2016-06-16 18:09:35 -0700477
Don Garrettdeb2e032016-07-06 16:44:14 -0700478 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600479 symbols, 'fake_url', api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700480
Don Garrettdeb2e032016-07-06 16:44:14 -0700481 self.assertEqual(list(result), symbols)
482 self.assertEqual(self.sym_initial.status, upload_symbols.SymbolFile.ERROR)
Mike Nichols90f7c152019-04-09 15:14:08 -0600483 self.assertEqual(self.request_mock.call_count, 7)
Don Garretta28be6d2016-06-16 18:09:35 -0700484
Don Garrettdeb2e032016-07-06 16:44:14 -0700485 def testPerformSymbolsFileUploadTransisentFailure(self):
Don Garretta28be6d2016-06-16 18:09:35 -0700486 """We fail once, then succeed."""
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400487 self.urlopen_mock.side_effect = (IOError('network failure'), None)
Don Garrettdeb2e032016-07-06 16:44:14 -0700488 symbols = [self.sym_initial]
Don Garretta28be6d2016-06-16 18:09:35 -0700489
Don Garrettdeb2e032016-07-06 16:44:14 -0700490 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600491 symbols, 'fake_url', api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700492
Don Garrettdeb2e032016-07-06 16:44:14 -0700493 self.assertEqual(list(result), symbols)
494 self.assertEqual(self.sym_initial.status,
495 upload_symbols.SymbolFile.UPLOADED)
Mike Nichols137e82d2019-05-15 18:40:34 -0600496 self.assertEqual(self.request_mock.call_count, 3)
Don Garrettdeb2e032016-07-06 16:44:14 -0700497
498 def testPerformSymbolsFileUploadMixed(self):
499 """Upload symbols in mixed starting states.
500
501 Demonstrate that INITIAL and ERROR are uploaded, but DUPLICATE/UPLOADED are
502 ignored.
503 """
504 symbols = [self.sym_initial, self.sym_error,
505 self.sym_duplicate, self.sym_uploaded]
506
507 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600508 symbols, 'fake_url', api_key='testkey')
Don Garrettdeb2e032016-07-06 16:44:14 -0700509
510 #
511 self.assertEqual(list(result), symbols)
512 self.assertEqual(self.sym_initial.status,
513 upload_symbols.SymbolFile.UPLOADED)
514 self.assertEqual(self.sym_error.status,
515 upload_symbols.SymbolFile.UPLOADED)
516 self.assertEqual(self.sym_duplicate.status,
517 upload_symbols.SymbolFile.DUPLICATE)
518 self.assertEqual(self.sym_uploaded.status,
519 upload_symbols.SymbolFile.UPLOADED)
Mike Nichols137e82d2019-05-15 18:40:34 -0600520 self.assertEqual(self.request_mock.call_count, 6)
Don Garrettdeb2e032016-07-06 16:44:14 -0700521
522
523 def testPerformSymbolsFileUploadErrorOut(self):
524 """Demonstate we exit only after X errors."""
525
526 symbol_count = upload_symbols.MAX_TOTAL_ERRORS_FOR_RETRY + 10
527 symbols = []
528 fail_file = None
529
530 # potentially twice as many errors as we should attempt.
Mike Frysinger79cca962019-06-13 15:26:53 -0400531 for _ in range(symbol_count):
Don Garrettdeb2e032016-07-06 16:44:14 -0700532 # Each loop will get unique SymbolFile instances that use the same files.
533 fail = self.createSymbolFile('fail.sym')
534 fail_file = fail.file_name
535 symbols.append(self.createSymbolFile('pass.sym'))
536 symbols.append(fail)
537
538 # Mock out UploadSymbolFile and fail for fail.sym files.
Mike Nichols90f7c152019-04-09 15:14:08 -0600539 def failSome(_url, symbol, _api_key):
Don Garrettdeb2e032016-07-06 16:44:14 -0700540 if symbol.file_name == fail_file:
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400541 raise IOError('network failure')
Don Garrettdeb2e032016-07-06 16:44:14 -0700542
Luigi Semenzato5104f3c2016-10-12 12:37:42 -0700543 upload_mock = self.PatchObject(upload_symbols, 'UploadSymbolFile',
544 side_effect=failSome)
545 upload_mock.__name__ = 'UploadSymbolFileMock2'
Don Garrettdeb2e032016-07-06 16:44:14 -0700546
547 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600548 symbols, 'fake_url', api_key='testkey')
Don Garrettdeb2e032016-07-06 16:44:14 -0700549
550 self.assertEqual(list(result), symbols)
551
552 passed = sum(s.status == upload_symbols.SymbolFile.UPLOADED
553 for s in symbols)
554 failed = sum(s.status == upload_symbols.SymbolFile.ERROR
555 for s in symbols)
556 skipped = sum(s.status == upload_symbols.SymbolFile.INITIAL
557 for s in symbols)
558
559 # Shows we all pass.sym files worked until limit hit.
560 self.assertEqual(passed, upload_symbols.MAX_TOTAL_ERRORS_FOR_RETRY)
561
562 # Shows we all fail.sym files failed until limit hit.
563 self.assertEqual(failed, upload_symbols.MAX_TOTAL_ERRORS_FOR_RETRY)
564
565 # Shows both pass/fail were skipped after limit hit.
566 self.assertEqual(skipped, 10 * 2)
Don Garretta28be6d2016-06-16 18:09:35 -0700567
568
Chris McDonalde705d8e2020-04-17 09:29:08 -0600569@pytest.mark.usefixtures('singleton_manager')
Don Garretta28be6d2016-06-16 18:09:35 -0700570class UploadSymbolsTest(SymbolsTestBase):
571 """Test UploadSymbols, along with most helper methods."""
572 def setUp(self):
573 # Results gathering.
574 self.failure_file = os.path.join(self.tempdir, 'failures.txt')
575
576 def testUploadSymbolsEmpty(self):
577 """Upload dir is empty."""
Mike Nichols137e82d2019-05-15 18:40:34 -0600578 result = upload_symbols.UploadSymbols([self.data], 'fake_url')
Don Garretta28be6d2016-06-16 18:09:35 -0700579
Mike Frysinger2d589a12019-08-25 14:15:12 -0400580 self.assertEqual(result, 0)
Don Garretta28be6d2016-06-16 18:09:35 -0700581 self.assertEqual(self.urlopen_mock.call_count, 0)
582
583 def testUploadSymbols(self):
584 """Upload a few files."""
585 self.createSymbolFile('slim.sym', self.SLIM_CONTENT)
586 self.createSymbolFile(os.path.join('nested', 'inner.sym'))
587 self.createSymbolFile('fat.sym', self.FAT_CONTENT)
588
589 result = upload_symbols.UploadSymbols(
Mike Nichols90f7c152019-04-09 15:14:08 -0600590 [self.data], 'fake_url',
591 failed_list=self.failure_file, strip_cfi=len(self.SLIM_CONTENT)+1,
592 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700593
Mike Frysinger2d589a12019-08-25 14:15:12 -0400594 self.assertEqual(result, 0)
Mike Nichols137e82d2019-05-15 18:40:34 -0600595 self.assertEqual(self.request_mock.call_count, 10)
Mike Frysinger2d589a12019-08-25 14:15:12 -0400596 self.assertEqual(osutils.ReadFile(self.failure_file), '')
Don Garretta28be6d2016-06-16 18:09:35 -0700597
598 def testUploadSymbolsLimited(self):
599 """Upload a few files."""
600 self.createSymbolFile('slim.sym', self.SLIM_CONTENT)
601 self.createSymbolFile(os.path.join('nested', 'inner.sym'))
602 self.createSymbolFile('fat.sym', self.FAT_CONTENT)
603
604 result = upload_symbols.UploadSymbols(
Mike Nichols90f7c152019-04-09 15:14:08 -0600605 [self.data], 'fake_url', upload_limit=2,
606 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700607
Mike Frysinger2d589a12019-08-25 14:15:12 -0400608 self.assertEqual(result, 0)
Mike Nichols137e82d2019-05-15 18:40:34 -0600609 self.assertEqual(self.request_mock.call_count, 7)
Mike Frysingerf2fa7d62017-12-14 18:33:59 -0500610 self.assertNotExists(self.failure_file)
Don Garretta28be6d2016-06-16 18:09:35 -0700611
612 def testUploadSymbolsFailures(self):
613 """Upload a few files."""
614 self.createSymbolFile('pass.sym')
615 fail = self.createSymbolFile('fail.sym')
616
Mike Nichols90f7c152019-04-09 15:14:08 -0600617 def failSome(_url, symbol, _api_key):
Don Garretta28be6d2016-06-16 18:09:35 -0700618 if symbol.file_name == fail.file_name:
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400619 raise IOError('network failure')
Don Garretta28be6d2016-06-16 18:09:35 -0700620
621 # Mock out UploadSymbolFile so it's easy to see which file to fail for.
622 upload_mock = self.PatchObject(upload_symbols, 'UploadSymbolFile',
623 side_effect=failSome)
Luigi Semenzato5104f3c2016-10-12 12:37:42 -0700624 # Mock __name__ for logging.
625 upload_mock.__name__ = 'UploadSymbolFileMock'
Don Garretta28be6d2016-06-16 18:09:35 -0700626
627 result = upload_symbols.UploadSymbols(
Mike Nichols90f7c152019-04-09 15:14:08 -0600628 [self.data], 'fake_url',
629 failed_list=self.failure_file, api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700630
Mike Frysinger2d589a12019-08-25 14:15:12 -0400631 self.assertEqual(result, 1)
Don Garretta28be6d2016-06-16 18:09:35 -0700632 self.assertEqual(upload_mock.call_count, 8)
Mike Frysinger2d589a12019-08-25 14:15:12 -0400633 self.assertEqual(osutils.ReadFile(self.failure_file), 'fail.sym\n')
Don Garretta28be6d2016-06-16 18:09:35 -0700634
Don Garretta28be6d2016-06-16 18:09:35 -0700635# TODO: We removed --network integration tests.
Mike Frysinger0c0efa22014-02-09 23:32:23 -0500636
637
Mike Frysingerea838d12014-12-08 11:55:32 -0500638def main(_argv):
Mike Frysinger27e21b72018-07-12 14:20:21 -0400639 # pylint: disable=protected-access
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -0400640 # Set timeouts small so that if the unit test hangs, it won't hang for long.
641 parallel._BackgroundTask.STARTUP_TIMEOUT = 5
642 parallel._BackgroundTask.EXIT_TIMEOUT = 5
643
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -0400644 # Run the tests.
Mike Frysingerba167372015-01-21 10:37:03 -0500645 cros_test_lib.main(level='info', module=__name__)