blob: fcc56b366bf2c0a2413b6c09f9f0f29022085b76 [file] [log] [blame]
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -04001# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Mike Frysingereb753bf2013-11-22 16:05:35 -05005"""Unittests for upload_symbols.py"""
6
Mike Frysinger06da5202014-09-26 17:30:33 -05007import errno
Mike Frysingere852b072021-05-21 12:39:03 -04008import http.server
Don Garretta28be6d2016-06-16 18:09:35 -07009import itertools
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -040010import os
Mike Frysinger0a2fd922014-09-12 20:23:42 -070011import signal
Mike Frysinger06da5202014-09-26 17:30:33 -050012import socket
Mike Frysingere852b072021-05-21 12:39:03 -040013import socketserver
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -040014import sys
Aviv Keshetd1f04632014-05-09 11:33:46 -070015import time
Mike Frysinger166fea02021-02-12 05:30:33 -050016from unittest import mock
Mike Frysingere852b072021-05-21 12:39:03 -040017import urllib.request
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -040018
Mike Frysinger40ffb532021-02-12 07:36:08 -050019import pytest # pylint: disable=import-error
Mike Frysinger40ffb532021-02-12 07:36:08 -050020
Mike Frysinger6db648e2018-07-24 19:57:58 -040021
Mike Frysinger079863c2014-10-09 23:16:46 -040022# We specifically set up a local server to connect to, so make sure we
23# delete any proxy settings that might screw that up. We also need to
24# do it here because modules that are imported below will implicitly
25# initialize with this proxy setting rather than dynamically pull it
26# on the fly :(.
Mike Frysinger92bdef52019-08-21 21:05:13 -040027# pylint: disable=wrong-import-position
Mike Frysinger079863c2014-10-09 23:16:46 -040028os.environ.pop('http_proxy', None)
29
Aviv Keshetb7519e12016-10-04 00:50:00 -070030from chromite.lib import constants
Mike Frysingerbbd1f112016-09-08 18:25:11 -040031
Mike Frysinger40ffb532021-02-12 07:36:08 -050032
Mike Frysingerbbd1f112016-09-08 18:25:11 -040033# 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)
Mike Frysingerac75f602019-11-14 23:18:51 -0500104 f.write(content.encode('utf-8'))
Don Garretta28be6d2016-06-16 18:09:35 -0700105
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 Frysingere852b072021-05-21 12:39:03 -0400119class SymbolServerRequestHandler(http.server.BaseHTTPRequestHandler):
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700120 """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"""
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700138
139
Mike Frysingere852b072021-05-21 12:39:03 -0400140class SymbolServer(socketserver.ThreadingTCPServer, http.server.HTTPServer):
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700141 """Simple HTTP server that forks each request"""
142
143
Chris McDonalde705d8e2020-04-17 09:29:08 -0600144@pytest.mark.usefixtures('singleton_manager')
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700145class 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)
Mike Frysingerac75f602019-11-14 23:18:51 -0500168 # The child runs the server, so close the socket in the parent.
169 self.httpd.server_close()
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700170
171 def setUp(self):
172 self.httpd_pid = None
173 self.httpd = None
Don Garretta28be6d2016-06-16 18:09:35 -0700174 self.server_url = None
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700175 self.sym_file = os.path.join(self.tempdir, 'test.sym')
176 osutils.WriteFile(self.sym_file, self.SYM_CONTENTS)
177
Don Garretta28be6d2016-06-16 18:09:35 -0700178 # Stop sleeps and retries for these tests.
179 self.PatchObject(upload_symbols, 'SLEEP_DELAY', 0)
180 self.PatchObject(upload_symbols, 'INITIAL_RETRY_DELAY', 0)
181 self.PatchObject(upload_symbols, 'MAX_RETRIES', 0)
182
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700183 def tearDown(self):
184 # Only kill the server if we forked one.
185 if self.httpd_pid:
186 os.kill(self.httpd_pid, signal.SIGUSR1)
187
188 def testSuccess(self):
189 """The server returns success for all uploads"""
190 class Handler(SymbolServerRequestHandler):
191 """Always return 200"""
192 RESP_CODE = 200
Mike Nichols90f7c152019-04-09 15:14:08 -0600193 self.PatchObject(upload_symbols, 'ExecRequest',
194 return_value={'uploadUrl': 'testurl',
195 'uploadKey': 'testSuccess'})
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700196 self.SpawnServer(Handler)
Don Garretta28be6d2016-06-16 18:09:35 -0700197 ret = upload_symbols.UploadSymbols(
198 sym_paths=[self.sym_file] * 10,
199 upload_url=self.server_url,
Mike Nichols90f7c152019-04-09 15:14:08 -0600200 api_key='testSuccess')
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700201 self.assertEqual(ret, 0)
202
203 def testError(self):
204 """The server returns errors for all uploads"""
205 class Handler(SymbolServerRequestHandler):
Mike Nichols90f7c152019-04-09 15:14:08 -0600206 """All connections error"""
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700207 RESP_CODE = 500
208 RESP_MSG = 'Internal Server Error'
209
210 self.SpawnServer(Handler)
Don Garretta28be6d2016-06-16 18:09:35 -0700211 ret = upload_symbols.UploadSymbols(
212 sym_paths=[self.sym_file] * 10,
213 upload_url=self.server_url,
Mike Nichols90f7c152019-04-09 15:14:08 -0600214 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700215 self.assertEqual(ret, 10)
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700216
217 def testHungServer(self):
218 """The server chokes, but we recover"""
219 class Handler(SymbolServerRequestHandler):
220 """All connections choke forever"""
Mike Nichols137e82d2019-05-15 18:40:34 -0600221 self.PatchObject(upload_symbols, 'ExecRequest',
222 return_value={'pairs': []})
223
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700224 def do_POST(self):
225 while True:
226 time.sleep(1000)
227
228 self.SpawnServer(Handler)
229 with mock.patch.object(upload_symbols, 'GetUploadTimeout') as m:
Don Garretta28be6d2016-06-16 18:09:35 -0700230 m.return_value = 0.01
Mike Frysinger58312e92014-03-18 04:18:36 -0400231 ret = upload_symbols.UploadSymbols(
Don Garretta28be6d2016-06-16 18:09:35 -0700232 sym_paths=[self.sym_file] * 10,
233 upload_url=self.server_url,
Mike Nichols137e82d2019-05-15 18:40:34 -0600234 timeout=m.return_value,
Mike Nichols90f7c152019-04-09 15:14:08 -0600235 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700236 self.assertEqual(ret, 10)
Aviv Keshetd1f04632014-05-09 11:33:46 -0700237
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -0400238
Don Garretta28be6d2016-06-16 18:09:35 -0700239class UploadSymbolsHelpersTest(cros_test_lib.TestCase):
240 """Test assorted helper functions and classes."""
Don Garretta28be6d2016-06-16 18:09:35 -0700241 def testIsTarball(self):
242 notTar = [
243 '/foo/bar/test.bin',
244 '/foo/bar/test.tar.bin',
245 '/foo/bar/test.faketar.gz',
246 '/foo/bar/test.nottgz',
Mike Frysinger0c0efa22014-02-09 23:32:23 -0500247 ]
Mike Frysinger0c0efa22014-02-09 23:32:23 -0500248
Don Garretta28be6d2016-06-16 18:09:35 -0700249 isTar = [
250 '/foo/bar/test.tar',
251 '/foo/bar/test.bin.tar',
252 '/foo/bar/test.bin.tar.bz2',
253 '/foo/bar/test.bin.tar.gz',
254 '/foo/bar/test.bin.tar.xz',
255 '/foo/bar/test.tbz2',
256 '/foo/bar/test.tbz',
257 '/foo/bar/test.tgz',
258 '/foo/bar/test.txz',
259 ]
Mike Frysinger0c0efa22014-02-09 23:32:23 -0500260
Don Garretta28be6d2016-06-16 18:09:35 -0700261 for p in notTar:
262 self.assertFalse(upload_symbols.IsTarball(p))
263
264 for p in isTar:
265 self.assertTrue(upload_symbols.IsTarball(p))
266
267 def testBatchGenerator(self):
268 result = upload_symbols.BatchGenerator([], 2)
269 self.assertEqual(list(result), [])
270
Mike Frysinger66848312019-07-03 02:12:39 -0400271 # BatchGenerator accepts iterators, so passing it here is safe.
272 # pylint: disable=range-builtin-not-iterating
Mike Frysinger79cca962019-06-13 15:26:53 -0400273 result = upload_symbols.BatchGenerator(range(6), 2)
Don Garretta28be6d2016-06-16 18:09:35 -0700274 self.assertEqual(list(result), [[0, 1], [2, 3], [4, 5]])
275
Mike Frysinger79cca962019-06-13 15:26:53 -0400276 result = upload_symbols.BatchGenerator(range(7), 2)
Don Garretta28be6d2016-06-16 18:09:35 -0700277 self.assertEqual(list(result), [[0, 1], [2, 3], [4, 5], [6]])
278
279 # Prove that we are streaming the results, not generating them all at once.
280 result = upload_symbols.BatchGenerator(itertools.repeat(0), 2)
Mike Frysinger67d90242019-07-03 19:03:58 -0400281 self.assertEqual(next(result), [0, 0])
Don Garretta28be6d2016-06-16 18:09:35 -0700282
283
284class FindSymbolFilesTest(SymbolsTestBase):
285 """Test FindSymbolFiles."""
286 def setUp(self):
287 self.symfile = self.createSymbolFile('root.sym').file_name
288 self.innerfile = self.createSymbolFile(
289 os.path.join('nested', 'inner.sym')).file_name
290
291 # CreateTarball is having issues outside the chroot from open file tests.
292 #
293 # self.tarball = os.path.join(self.tempdir, 'syms.tar.gz')
294 # cros_build_lib.CreateTarball(
295 # 'syms.tar.gz', self.tempdir, inputs=(self.data))
296
297 def testEmpty(self):
298 symbols = list(upload_symbols.FindSymbolFiles(
299 self.working, []))
300 self.assertEqual(symbols, [])
301
302 def testFile(self):
303 symbols = list(upload_symbols.FindSymbolFiles(
304 self.working, [self.symfile]))
305
306 self.assertEqual(len(symbols), 1)
307 sf = symbols[0]
308
309 self.assertEqual(sf.display_name, 'root.sym')
310 self.assertEqual(sf.display_path, self.symfile)
311 self.assertEqual(sf.file_name, self.symfile)
312 self.assertEqual(sf.status, upload_symbols.SymbolFile.INITIAL)
313 self.assertEqual(sf.FileSize(), len(self.FAT_CONTENT))
314
315 def testDir(self):
316 symbols = list(upload_symbols.FindSymbolFiles(
317 self.working, [self.data]))
318
319 self.assertEqual(len(symbols), 2)
320 root = symbols[0]
321 nested = symbols[1]
322
323 self.assertEqual(root.display_name, 'root.sym')
324 self.assertEqual(root.display_path, 'root.sym')
325 self.assertEqual(root.file_name, self.symfile)
326 self.assertEqual(root.status, upload_symbols.SymbolFile.INITIAL)
327 self.assertEqual(root.FileSize(), len(self.FAT_CONTENT))
328
329 self.assertEqual(nested.display_name, 'inner.sym')
330 self.assertEqual(nested.display_path, 'nested/inner.sym')
331 self.assertEqual(nested.file_name, self.innerfile)
332 self.assertEqual(nested.status, upload_symbols.SymbolFile.INITIAL)
333 self.assertEqual(nested.FileSize(), len(self.FAT_CONTENT))
334
335
336class AdjustSymbolFileSizeTest(SymbolsTestBase):
337 """Test AdjustSymbolFileSize."""
338 def setUp(self):
339 self.slim = self.createSymbolFile('slim.sym', self.SLIM_CONTENT)
340 self.fat = self.createSymbolFile('fat.sym', self.FAT_CONTENT)
341
342 self.warn_mock = self.PatchObject(logging, 'PrintBuildbotStepWarnings')
343
344 def _testNotStripped(self, symbol, size=None, content=None):
345 start_file = symbol.file_name
346 after = upload_symbols.AdjustSymbolFileSize(
347 symbol, self.working, size)
348 self.assertIs(after, symbol)
349 self.assertEqual(after.file_name, start_file)
350 if content is not None:
351 self.assertEqual(osutils.ReadFile(after.file_name), content)
352
353 def _testStripped(self, symbol, size=None, content=None):
354 after = upload_symbols.AdjustSymbolFileSize(
355 symbol, self.working, size)
356 self.assertIs(after, symbol)
357 self.assertTrue(after.file_name.startswith(self.working))
358 if content is not None:
359 self.assertEqual(osutils.ReadFile(after.file_name), content)
360
361 def testSmall(self):
362 """Ensure that files smaller than the limit are not modified."""
363 self._testNotStripped(self.slim, 1024, self.SLIM_CONTENT)
364 self._testNotStripped(self.fat, 1024, self.FAT_CONTENT)
365
366 def testLarge(self):
367 """Ensure that files larger than the limit are modified."""
368 self._testStripped(self.slim, 1, self.SLIM_CONTENT)
369 self._testStripped(self.fat, 1, self.SLIM_CONTENT)
370
371 def testMixed(self):
372 """Test mix of large and small."""
373 strip_size = len(self.SLIM_CONTENT) + 1
374
375 self._testNotStripped(self.slim, strip_size, self.SLIM_CONTENT)
376 self._testStripped(self.fat, strip_size, self.SLIM_CONTENT)
377
378 def testSizeWarnings(self):
379 large = self.createSymbolFile(
380 'large.sym', content=self.SLIM_CONTENT,
381 size=upload_symbols.CRASH_SERVER_FILE_LIMIT*2)
382
383 # Would like to Strip as part of this test, but that really copies all
384 # of the sparse file content, which is too expensive for a unittest.
385 self._testNotStripped(large, None, None)
386
387 self.assertEqual(self.warn_mock.call_count, 1)
388
389
Mike Nichols137e82d2019-05-15 18:40:34 -0600390class DeduplicateTest(SymbolsTestBase):
391 """Test server Deduplication."""
392 def setUp(self):
393 self.PatchObject(upload_symbols, 'ExecRequest',
394 return_value={'pairs': [
395 {'status': 'FOUND',
396 'symbolId':
397 {'debugFile': 'sym1_sym',
398 'debugId': 'BEAA9BE'}},
399 {'status': 'FOUND',
400 'symbolId':
401 {'debugFile': 'sym2_sym',
402 'debugId': 'B6B1A36'}},
403 {'status': 'MISSING',
404 'symbolId':
405 {'debugFile': 'sym3_sym',
406 'debugId': 'D4FC0FC'}}]})
407
408 def testFindDuplicates(self):
409 # The first two symbols will be duplicate, the third new.
410 sym1 = self.createSymbolFile('sym1.sym')
411 sym1.header = cros_generate_breakpad_symbols.SymbolHeader('cpu', 'BEAA9BE',
412 'sym1_sym', 'os')
413 sym2 = self.createSymbolFile('sym2.sym')
414 sym2.header = cros_generate_breakpad_symbols.SymbolHeader('cpu', 'B6B1A36',
415 'sym2_sym', 'os')
416 sym3 = self.createSymbolFile('sym3.sym')
417 sym3.header = cros_generate_breakpad_symbols.SymbolHeader('cpu', 'D4FC0FC',
418 'sym3_sym', 'os')
419
420 result = upload_symbols.FindDuplicates((sym1, sym2, sym3), 'fake_url',
421 api_key='testkey')
422 self.assertEqual(list(result), [sym1, sym2, sym3])
423
424 self.assertEqual(sym1.status, upload_symbols.SymbolFile.DUPLICATE)
425 self.assertEqual(sym2.status, upload_symbols.SymbolFile.DUPLICATE)
426 self.assertEqual(sym3.status, upload_symbols.SymbolFile.INITIAL)
427
428
Don Garrettdeb2e032016-07-06 16:44:14 -0700429class PerformSymbolFilesUploadTest(SymbolsTestBase):
Don Garretta28be6d2016-06-16 18:09:35 -0700430 """Test PerformSymbolFile, and it's helper methods."""
431 def setUp(self):
Don Garrettdeb2e032016-07-06 16:44:14 -0700432 self.sym_initial = self.createSymbolFile(
433 'initial.sym')
434 self.sym_error = self.createSymbolFile(
435 'error.sym', status=upload_symbols.SymbolFile.ERROR)
436 self.sym_duplicate = self.createSymbolFile(
437 'duplicate.sym', status=upload_symbols.SymbolFile.DUPLICATE)
438 self.sym_uploaded = self.createSymbolFile(
439 'uploaded.sym', status=upload_symbols.SymbolFile.UPLOADED)
Don Garretta28be6d2016-06-16 18:09:35 -0700440
441 def testGetUploadTimeout(self):
442 """Test GetUploadTimeout helper function."""
443 # Timeout for small file.
Don Garrettdeb2e032016-07-06 16:44:14 -0700444 self.assertEqual(upload_symbols.GetUploadTimeout(self.sym_initial),
Don Garretta28be6d2016-06-16 18:09:35 -0700445 upload_symbols.UPLOAD_MIN_TIMEOUT)
446
Ian Barkley-Yeung22ba8122020-02-05 15:39:02 -0800447 # Timeout for 512M file.
448 large = self.createSymbolFile('large.sym', size=(512 * 1024 * 1024))
449 self.assertEqual(upload_symbols.GetUploadTimeout(large), 15 * 60)
Don Garretta28be6d2016-06-16 18:09:35 -0700450
451 def testUploadSymbolFile(self):
Mike Nichols90f7c152019-04-09 15:14:08 -0600452 upload_symbols.UploadSymbolFile('fake_url', self.sym_initial,
453 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700454 # TODO: Examine mock in more detail to make sure request is correct.
Mike Nichols137e82d2019-05-15 18:40:34 -0600455 self.assertEqual(self.request_mock.call_count, 3)
Don Garretta28be6d2016-06-16 18:09:35 -0700456
Don Garrettdeb2e032016-07-06 16:44:14 -0700457 def testPerformSymbolsFileUpload(self):
Don Garretta28be6d2016-06-16 18:09:35 -0700458 """We upload on first try."""
Don Garrettdeb2e032016-07-06 16:44:14 -0700459 symbols = [self.sym_initial]
Don Garretta28be6d2016-06-16 18:09:35 -0700460
Don Garrettdeb2e032016-07-06 16:44:14 -0700461 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600462 symbols, 'fake_url', api_key='testkey')
Don Garrettdeb2e032016-07-06 16:44:14 -0700463
464 self.assertEqual(list(result), symbols)
465 self.assertEqual(self.sym_initial.status,
466 upload_symbols.SymbolFile.UPLOADED)
Mike Nichols137e82d2019-05-15 18:40:34 -0600467 self.assertEqual(self.request_mock.call_count, 3)
Don Garretta28be6d2016-06-16 18:09:35 -0700468
Don Garrettdeb2e032016-07-06 16:44:14 -0700469 def testPerformSymbolsFileUploadFailure(self):
Don Garretta28be6d2016-06-16 18:09:35 -0700470 """All network requests fail."""
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400471 self.request_mock.side_effect = IOError('network failure')
Don Garrettdeb2e032016-07-06 16:44:14 -0700472 symbols = [self.sym_initial]
Don Garretta28be6d2016-06-16 18:09:35 -0700473
Don Garrettdeb2e032016-07-06 16:44:14 -0700474 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600475 symbols, 'fake_url', api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700476
Don Garrettdeb2e032016-07-06 16:44:14 -0700477 self.assertEqual(list(result), symbols)
478 self.assertEqual(self.sym_initial.status, upload_symbols.SymbolFile.ERROR)
Mike Nichols2a6f86f2020-08-18 15:56:07 -0600479 self.assertEqual(self.request_mock.call_count, 6)
Don Garretta28be6d2016-06-16 18:09:35 -0700480
Don Garrettdeb2e032016-07-06 16:44:14 -0700481 def testPerformSymbolsFileUploadTransisentFailure(self):
Don Garretta28be6d2016-06-16 18:09:35 -0700482 """We fail once, then succeed."""
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400483 self.urlopen_mock.side_effect = (IOError('network failure'), None)
Don Garrettdeb2e032016-07-06 16:44:14 -0700484 symbols = [self.sym_initial]
Don Garretta28be6d2016-06-16 18:09:35 -0700485
Don Garrettdeb2e032016-07-06 16:44:14 -0700486 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600487 symbols, 'fake_url', api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700488
Don Garrettdeb2e032016-07-06 16:44:14 -0700489 self.assertEqual(list(result), symbols)
490 self.assertEqual(self.sym_initial.status,
491 upload_symbols.SymbolFile.UPLOADED)
Mike Nichols137e82d2019-05-15 18:40:34 -0600492 self.assertEqual(self.request_mock.call_count, 3)
Don Garrettdeb2e032016-07-06 16:44:14 -0700493
494 def testPerformSymbolsFileUploadMixed(self):
495 """Upload symbols in mixed starting states.
496
497 Demonstrate that INITIAL and ERROR are uploaded, but DUPLICATE/UPLOADED are
498 ignored.
499 """
500 symbols = [self.sym_initial, self.sym_error,
501 self.sym_duplicate, self.sym_uploaded]
502
503 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600504 symbols, 'fake_url', api_key='testkey')
Don Garrettdeb2e032016-07-06 16:44:14 -0700505
506 #
507 self.assertEqual(list(result), symbols)
508 self.assertEqual(self.sym_initial.status,
509 upload_symbols.SymbolFile.UPLOADED)
510 self.assertEqual(self.sym_error.status,
511 upload_symbols.SymbolFile.UPLOADED)
512 self.assertEqual(self.sym_duplicate.status,
513 upload_symbols.SymbolFile.DUPLICATE)
514 self.assertEqual(self.sym_uploaded.status,
515 upload_symbols.SymbolFile.UPLOADED)
Mike Nichols137e82d2019-05-15 18:40:34 -0600516 self.assertEqual(self.request_mock.call_count, 6)
Don Garrettdeb2e032016-07-06 16:44:14 -0700517
518
519 def testPerformSymbolsFileUploadErrorOut(self):
520 """Demonstate we exit only after X errors."""
521
522 symbol_count = upload_symbols.MAX_TOTAL_ERRORS_FOR_RETRY + 10
523 symbols = []
524 fail_file = None
525
526 # potentially twice as many errors as we should attempt.
Mike Frysinger79cca962019-06-13 15:26:53 -0400527 for _ in range(symbol_count):
Don Garrettdeb2e032016-07-06 16:44:14 -0700528 # Each loop will get unique SymbolFile instances that use the same files.
529 fail = self.createSymbolFile('fail.sym')
530 fail_file = fail.file_name
531 symbols.append(self.createSymbolFile('pass.sym'))
532 symbols.append(fail)
533
534 # Mock out UploadSymbolFile and fail for fail.sym files.
Mike Nichols90f7c152019-04-09 15:14:08 -0600535 def failSome(_url, symbol, _api_key):
Don Garrettdeb2e032016-07-06 16:44:14 -0700536 if symbol.file_name == fail_file:
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400537 raise IOError('network failure')
Don Garrettdeb2e032016-07-06 16:44:14 -0700538
Luigi Semenzato5104f3c2016-10-12 12:37:42 -0700539 upload_mock = self.PatchObject(upload_symbols, 'UploadSymbolFile',
540 side_effect=failSome)
541 upload_mock.__name__ = 'UploadSymbolFileMock2'
Don Garrettdeb2e032016-07-06 16:44:14 -0700542
543 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600544 symbols, 'fake_url', api_key='testkey')
Don Garrettdeb2e032016-07-06 16:44:14 -0700545
546 self.assertEqual(list(result), symbols)
547
548 passed = sum(s.status == upload_symbols.SymbolFile.UPLOADED
549 for s in symbols)
550 failed = sum(s.status == upload_symbols.SymbolFile.ERROR
551 for s in symbols)
552 skipped = sum(s.status == upload_symbols.SymbolFile.INITIAL
553 for s in symbols)
554
555 # Shows we all pass.sym files worked until limit hit.
556 self.assertEqual(passed, upload_symbols.MAX_TOTAL_ERRORS_FOR_RETRY)
557
558 # Shows we all fail.sym files failed until limit hit.
559 self.assertEqual(failed, upload_symbols.MAX_TOTAL_ERRORS_FOR_RETRY)
560
561 # Shows both pass/fail were skipped after limit hit.
562 self.assertEqual(skipped, 10 * 2)
Don Garretta28be6d2016-06-16 18:09:35 -0700563
564
Chris McDonalde705d8e2020-04-17 09:29:08 -0600565@pytest.mark.usefixtures('singleton_manager')
Don Garretta28be6d2016-06-16 18:09:35 -0700566class UploadSymbolsTest(SymbolsTestBase):
567 """Test UploadSymbols, along with most helper methods."""
568 def setUp(self):
569 # Results gathering.
570 self.failure_file = os.path.join(self.tempdir, 'failures.txt')
571
572 def testUploadSymbolsEmpty(self):
573 """Upload dir is empty."""
Mike Nichols137e82d2019-05-15 18:40:34 -0600574 result = upload_symbols.UploadSymbols([self.data], 'fake_url')
Don Garretta28be6d2016-06-16 18:09:35 -0700575
Mike Frysinger2d589a12019-08-25 14:15:12 -0400576 self.assertEqual(result, 0)
Don Garretta28be6d2016-06-16 18:09:35 -0700577 self.assertEqual(self.urlopen_mock.call_count, 0)
578
579 def testUploadSymbols(self):
580 """Upload a few files."""
581 self.createSymbolFile('slim.sym', self.SLIM_CONTENT)
582 self.createSymbolFile(os.path.join('nested', 'inner.sym'))
583 self.createSymbolFile('fat.sym', self.FAT_CONTENT)
584
585 result = upload_symbols.UploadSymbols(
Mike Nichols90f7c152019-04-09 15:14:08 -0600586 [self.data], 'fake_url',
587 failed_list=self.failure_file, strip_cfi=len(self.SLIM_CONTENT)+1,
588 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700589
Mike Frysinger2d589a12019-08-25 14:15:12 -0400590 self.assertEqual(result, 0)
Mike Nichols137e82d2019-05-15 18:40:34 -0600591 self.assertEqual(self.request_mock.call_count, 10)
Mike Frysinger2d589a12019-08-25 14:15:12 -0400592 self.assertEqual(osutils.ReadFile(self.failure_file), '')
Don Garretta28be6d2016-06-16 18:09:35 -0700593
594 def testUploadSymbolsLimited(self):
595 """Upload a few files."""
596 self.createSymbolFile('slim.sym', self.SLIM_CONTENT)
597 self.createSymbolFile(os.path.join('nested', 'inner.sym'))
598 self.createSymbolFile('fat.sym', self.FAT_CONTENT)
599
600 result = upload_symbols.UploadSymbols(
Mike Nichols90f7c152019-04-09 15:14:08 -0600601 [self.data], 'fake_url', upload_limit=2,
602 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700603
Mike Frysinger2d589a12019-08-25 14:15:12 -0400604 self.assertEqual(result, 0)
Mike Nichols137e82d2019-05-15 18:40:34 -0600605 self.assertEqual(self.request_mock.call_count, 7)
Mike Frysingerf2fa7d62017-12-14 18:33:59 -0500606 self.assertNotExists(self.failure_file)
Don Garretta28be6d2016-06-16 18:09:35 -0700607
608 def testUploadSymbolsFailures(self):
609 """Upload a few files."""
610 self.createSymbolFile('pass.sym')
611 fail = self.createSymbolFile('fail.sym')
612
Mike Nichols90f7c152019-04-09 15:14:08 -0600613 def failSome(_url, symbol, _api_key):
Don Garretta28be6d2016-06-16 18:09:35 -0700614 if symbol.file_name == fail.file_name:
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400615 raise IOError('network failure')
Don Garretta28be6d2016-06-16 18:09:35 -0700616
617 # Mock out UploadSymbolFile so it's easy to see which file to fail for.
618 upload_mock = self.PatchObject(upload_symbols, 'UploadSymbolFile',
619 side_effect=failSome)
Luigi Semenzato5104f3c2016-10-12 12:37:42 -0700620 # Mock __name__ for logging.
621 upload_mock.__name__ = 'UploadSymbolFileMock'
Don Garretta28be6d2016-06-16 18:09:35 -0700622
623 result = upload_symbols.UploadSymbols(
Mike Nichols90f7c152019-04-09 15:14:08 -0600624 [self.data], 'fake_url',
625 failed_list=self.failure_file, api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700626
Mike Frysinger2d589a12019-08-25 14:15:12 -0400627 self.assertEqual(result, 1)
Mike Nichols2a6f86f2020-08-18 15:56:07 -0600628 self.assertEqual(upload_mock.call_count, 7)
Mike Frysinger2d589a12019-08-25 14:15:12 -0400629 self.assertEqual(osutils.ReadFile(self.failure_file), 'fail.sym\n')
Don Garretta28be6d2016-06-16 18:09:35 -0700630
Don Garretta28be6d2016-06-16 18:09:35 -0700631# TODO: We removed --network integration tests.
Mike Frysinger0c0efa22014-02-09 23:32:23 -0500632
633
Mike Frysingerea838d12014-12-08 11:55:32 -0500634def main(_argv):
Mike Frysinger27e21b72018-07-12 14:20:21 -0400635 # pylint: disable=protected-access
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -0400636 # Set timeouts small so that if the unit test hangs, it won't hang for long.
637 parallel._BackgroundTask.STARTUP_TIMEOUT = 5
638 parallel._BackgroundTask.EXIT_TIMEOUT = 5
639
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -0400640 # Run the tests.
Mike Frysingerba167372015-01-21 10:37:03 -0500641 cros_test_lib.main(level='info', module=__name__)