blob: 61b3a1884046163d85bfed0e1e471f21b50d4a5c [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
Mike Frysinger2688ef62020-02-16 00:00:46 -050057assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
58
59
Don Garretta28be6d2016-06-16 18:09:35 -070060class SymbolsTestBase(cros_test_lib.MockTempDirTestCase):
61 """Base class for most symbols tests."""
62
63 SLIM_CONTENT = """
64some junk
65"""
66
67 FAT_CONTENT = """
68STACK CFI 1234
69some junk
70STACK CFI 1234
71"""
72
73 def setUp(self):
74 # Make certain we don't use the network.
Mike Frysinger3dcacee2019-08-23 17:09:11 -040075 self.urlopen_mock = self.PatchObject(urllib.request, 'urlopen')
Mike Nichols90f7c152019-04-09 15:14:08 -060076 self.request_mock = self.PatchObject(upload_symbols, 'ExecRequest',
77 return_value={'uploadUrl':
78 'testurl',
79 'uploadKey':
80 'asdgasgas'})
Don Garretta28be6d2016-06-16 18:09:35 -070081
82 # Make 'uploads' go fast.
83 self.PatchObject(upload_symbols, 'SLEEP_DELAY', 0)
84 self.PatchObject(upload_symbols, 'INITIAL_RETRY_DELAY', 0)
85
86 # So our symbol file content doesn't have to be real.
87 self.PatchObject(cros_generate_breakpad_symbols, 'ReadSymsHeader',
88 return_value=cros_generate_breakpad_symbols.SymbolHeader(
89 os='os', cpu='cpu', id='id', name='name'))
90
91 self.working = os.path.join(self.tempdir, 'expand')
92 osutils.SafeMakedirs(self.working)
93
94 self.data = os.path.join(self.tempdir, 'data')
95 osutils.SafeMakedirs(self.data)
96
97 def createSymbolFile(self, filename, content=FAT_CONTENT, size=0,
98 status=None, dedupe=False):
99 fullname = os.path.join(self.data, filename)
100 osutils.SafeMakedirs(os.path.dirname(fullname))
101
102 # If a file size is given, force that to be the minimum file size. Create
103 # a sparse file so large files are practical.
104 with open(fullname, 'w+b') as f:
105 f.truncate(size)
106 f.seek(0)
Mike Frysingerac75f602019-11-14 23:18:51 -0500107 f.write(content.encode('utf-8'))
Don Garretta28be6d2016-06-16 18:09:35 -0700108
109 result = upload_symbols.SymbolFile(display_path=filename,
110 file_name=fullname)
111
112 if status:
113 result.status = status
114
115 if dedupe:
116 result.dedupe_item = upload_symbols.DedupeItem(result)
117 result.dedupe_push_state = 'push_state'
118
119 return result
120
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -0400121
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700122class SymbolServerRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
123 """HTTP handler for symbol POSTs"""
124
125 RESP_CODE = None
126 RESP_MSG = None
127
128 def do_POST(self):
129 """Handle a POST request"""
130 # Drain the data from the client. If we don't, we might write the response
131 # and close the socket before the client finishes, so they die with EPIPE.
132 clen = int(self.headers.get('Content-Length', '0'))
133 self.rfile.read(clen)
134
135 self.send_response(self.RESP_CODE, self.RESP_MSG)
136 self.end_headers()
137
Mike Frysingera4418152019-09-22 04:00:24 -0400138 # pylint: disable=arguments-differ
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700139 def log_message(self, *args, **kwargs):
140 """Stub the logger as it writes to stderr"""
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700141
142
Mike Frysinger3d465162019-08-28 00:40:23 -0400143class SymbolServer(socketserver.ThreadingTCPServer, BaseHTTPServer.HTTPServer):
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700144 """Simple HTTP server that forks each request"""
145
146
147class UploadSymbolsServerTest(cros_test_lib.MockTempDirTestCase):
148 """Tests for UploadSymbols() and a local HTTP server"""
149
150 SYM_CONTENTS = """MODULE Linux arm 123-456 blkid
151PUBLIC 1471 0 main"""
152
153 def SpawnServer(self, RequestHandler):
154 """Spawn a new http server"""
Mike Frysinger06da5202014-09-26 17:30:33 -0500155 while True:
156 try:
157 port = remote_access.GetUnusedPort()
158 address = ('', port)
159 self.httpd = SymbolServer(address, RequestHandler)
160 break
161 except socket.error as e:
162 if e.errno == errno.EADDRINUSE:
163 continue
164 raise
Don Garretta28be6d2016-06-16 18:09:35 -0700165 self.server_url = 'http://localhost:%i/post/path' % port
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700166 self.httpd_pid = os.fork()
167 if self.httpd_pid == 0:
168 self.httpd.serve_forever(poll_interval=0.1)
169 sys.exit(0)
Mike Frysingerac75f602019-11-14 23:18:51 -0500170 # The child runs the server, so close the socket in the parent.
171 self.httpd.server_close()
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700172
173 def setUp(self):
174 self.httpd_pid = None
175 self.httpd = None
Don Garretta28be6d2016-06-16 18:09:35 -0700176 self.server_url = None
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700177 self.sym_file = os.path.join(self.tempdir, 'test.sym')
178 osutils.WriteFile(self.sym_file, self.SYM_CONTENTS)
179
Don Garretta28be6d2016-06-16 18:09:35 -0700180 # Stop sleeps and retries for these tests.
181 self.PatchObject(upload_symbols, 'SLEEP_DELAY', 0)
182 self.PatchObject(upload_symbols, 'INITIAL_RETRY_DELAY', 0)
183 self.PatchObject(upload_symbols, 'MAX_RETRIES', 0)
184
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700185 def tearDown(self):
186 # Only kill the server if we forked one.
187 if self.httpd_pid:
188 os.kill(self.httpd_pid, signal.SIGUSR1)
189
190 def testSuccess(self):
191 """The server returns success for all uploads"""
192 class Handler(SymbolServerRequestHandler):
193 """Always return 200"""
194 RESP_CODE = 200
Mike Nichols90f7c152019-04-09 15:14:08 -0600195 self.PatchObject(upload_symbols, 'ExecRequest',
196 return_value={'uploadUrl': 'testurl',
197 'uploadKey': 'testSuccess'})
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700198 self.SpawnServer(Handler)
Don Garretta28be6d2016-06-16 18:09:35 -0700199 ret = upload_symbols.UploadSymbols(
200 sym_paths=[self.sym_file] * 10,
201 upload_url=self.server_url,
Mike Nichols90f7c152019-04-09 15:14:08 -0600202 api_key='testSuccess')
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700203 self.assertEqual(ret, 0)
204
205 def testError(self):
206 """The server returns errors for all uploads"""
207 class Handler(SymbolServerRequestHandler):
Mike Nichols90f7c152019-04-09 15:14:08 -0600208 """All connections error"""
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700209 RESP_CODE = 500
210 RESP_MSG = 'Internal Server Error'
211
212 self.SpawnServer(Handler)
Don Garretta28be6d2016-06-16 18:09:35 -0700213 ret = upload_symbols.UploadSymbols(
214 sym_paths=[self.sym_file] * 10,
215 upload_url=self.server_url,
Mike Nichols90f7c152019-04-09 15:14:08 -0600216 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700217 self.assertEqual(ret, 10)
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700218
219 def testHungServer(self):
220 """The server chokes, but we recover"""
221 class Handler(SymbolServerRequestHandler):
222 """All connections choke forever"""
Mike Nichols137e82d2019-05-15 18:40:34 -0600223 self.PatchObject(upload_symbols, 'ExecRequest',
224 return_value={'pairs': []})
225
Mike Frysinger0a2fd922014-09-12 20:23:42 -0700226 def do_POST(self):
227 while True:
228 time.sleep(1000)
229
230 self.SpawnServer(Handler)
231 with mock.patch.object(upload_symbols, 'GetUploadTimeout') as m:
Don Garretta28be6d2016-06-16 18:09:35 -0700232 m.return_value = 0.01
Mike Frysinger58312e92014-03-18 04:18:36 -0400233 ret = upload_symbols.UploadSymbols(
Don Garretta28be6d2016-06-16 18:09:35 -0700234 sym_paths=[self.sym_file] * 10,
235 upload_url=self.server_url,
Mike Nichols137e82d2019-05-15 18:40:34 -0600236 timeout=m.return_value,
Mike Nichols90f7c152019-04-09 15:14:08 -0600237 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700238 self.assertEqual(ret, 10)
Aviv Keshetd1f04632014-05-09 11:33:46 -0700239
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -0400240
Don Garretta28be6d2016-06-16 18:09:35 -0700241class UploadSymbolsHelpersTest(cros_test_lib.TestCase):
242 """Test assorted helper functions and classes."""
Don Garretta28be6d2016-06-16 18:09:35 -0700243 def testIsTarball(self):
244 notTar = [
245 '/foo/bar/test.bin',
246 '/foo/bar/test.tar.bin',
247 '/foo/bar/test.faketar.gz',
248 '/foo/bar/test.nottgz',
Mike Frysinger0c0efa22014-02-09 23:32:23 -0500249 ]
Mike Frysinger0c0efa22014-02-09 23:32:23 -0500250
Don Garretta28be6d2016-06-16 18:09:35 -0700251 isTar = [
252 '/foo/bar/test.tar',
253 '/foo/bar/test.bin.tar',
254 '/foo/bar/test.bin.tar.bz2',
255 '/foo/bar/test.bin.tar.gz',
256 '/foo/bar/test.bin.tar.xz',
257 '/foo/bar/test.tbz2',
258 '/foo/bar/test.tbz',
259 '/foo/bar/test.tgz',
260 '/foo/bar/test.txz',
261 ]
Mike Frysinger0c0efa22014-02-09 23:32:23 -0500262
Don Garretta28be6d2016-06-16 18:09:35 -0700263 for p in notTar:
264 self.assertFalse(upload_symbols.IsTarball(p))
265
266 for p in isTar:
267 self.assertTrue(upload_symbols.IsTarball(p))
268
269 def testBatchGenerator(self):
270 result = upload_symbols.BatchGenerator([], 2)
271 self.assertEqual(list(result), [])
272
Mike Frysinger66848312019-07-03 02:12:39 -0400273 # BatchGenerator accepts iterators, so passing it here is safe.
274 # pylint: disable=range-builtin-not-iterating
Mike Frysinger79cca962019-06-13 15:26:53 -0400275 result = upload_symbols.BatchGenerator(range(6), 2)
Don Garretta28be6d2016-06-16 18:09:35 -0700276 self.assertEqual(list(result), [[0, 1], [2, 3], [4, 5]])
277
Mike Frysinger79cca962019-06-13 15:26:53 -0400278 result = upload_symbols.BatchGenerator(range(7), 2)
Don Garretta28be6d2016-06-16 18:09:35 -0700279 self.assertEqual(list(result), [[0, 1], [2, 3], [4, 5], [6]])
280
281 # Prove that we are streaming the results, not generating them all at once.
282 result = upload_symbols.BatchGenerator(itertools.repeat(0), 2)
Mike Frysinger67d90242019-07-03 19:03:58 -0400283 self.assertEqual(next(result), [0, 0])
Don Garretta28be6d2016-06-16 18:09:35 -0700284
285
286class FindSymbolFilesTest(SymbolsTestBase):
287 """Test FindSymbolFiles."""
288 def setUp(self):
289 self.symfile = self.createSymbolFile('root.sym').file_name
290 self.innerfile = self.createSymbolFile(
291 os.path.join('nested', 'inner.sym')).file_name
292
293 # CreateTarball is having issues outside the chroot from open file tests.
294 #
295 # self.tarball = os.path.join(self.tempdir, 'syms.tar.gz')
296 # cros_build_lib.CreateTarball(
297 # 'syms.tar.gz', self.tempdir, inputs=(self.data))
298
299 def testEmpty(self):
300 symbols = list(upload_symbols.FindSymbolFiles(
301 self.working, []))
302 self.assertEqual(symbols, [])
303
304 def testFile(self):
305 symbols = list(upload_symbols.FindSymbolFiles(
306 self.working, [self.symfile]))
307
308 self.assertEqual(len(symbols), 1)
309 sf = symbols[0]
310
311 self.assertEqual(sf.display_name, 'root.sym')
312 self.assertEqual(sf.display_path, self.symfile)
313 self.assertEqual(sf.file_name, self.symfile)
314 self.assertEqual(sf.status, upload_symbols.SymbolFile.INITIAL)
315 self.assertEqual(sf.FileSize(), len(self.FAT_CONTENT))
316
317 def testDir(self):
318 symbols = list(upload_symbols.FindSymbolFiles(
319 self.working, [self.data]))
320
321 self.assertEqual(len(symbols), 2)
322 root = symbols[0]
323 nested = symbols[1]
324
325 self.assertEqual(root.display_name, 'root.sym')
326 self.assertEqual(root.display_path, 'root.sym')
327 self.assertEqual(root.file_name, self.symfile)
328 self.assertEqual(root.status, upload_symbols.SymbolFile.INITIAL)
329 self.assertEqual(root.FileSize(), len(self.FAT_CONTENT))
330
331 self.assertEqual(nested.display_name, 'inner.sym')
332 self.assertEqual(nested.display_path, 'nested/inner.sym')
333 self.assertEqual(nested.file_name, self.innerfile)
334 self.assertEqual(nested.status, upload_symbols.SymbolFile.INITIAL)
335 self.assertEqual(nested.FileSize(), len(self.FAT_CONTENT))
336
337
338class AdjustSymbolFileSizeTest(SymbolsTestBase):
339 """Test AdjustSymbolFileSize."""
340 def setUp(self):
341 self.slim = self.createSymbolFile('slim.sym', self.SLIM_CONTENT)
342 self.fat = self.createSymbolFile('fat.sym', self.FAT_CONTENT)
343
344 self.warn_mock = self.PatchObject(logging, 'PrintBuildbotStepWarnings')
345
346 def _testNotStripped(self, symbol, size=None, content=None):
347 start_file = symbol.file_name
348 after = upload_symbols.AdjustSymbolFileSize(
349 symbol, self.working, size)
350 self.assertIs(after, symbol)
351 self.assertEqual(after.file_name, start_file)
352 if content is not None:
353 self.assertEqual(osutils.ReadFile(after.file_name), content)
354
355 def _testStripped(self, symbol, size=None, content=None):
356 after = upload_symbols.AdjustSymbolFileSize(
357 symbol, self.working, size)
358 self.assertIs(after, symbol)
359 self.assertTrue(after.file_name.startswith(self.working))
360 if content is not None:
361 self.assertEqual(osutils.ReadFile(after.file_name), content)
362
363 def testSmall(self):
364 """Ensure that files smaller than the limit are not modified."""
365 self._testNotStripped(self.slim, 1024, self.SLIM_CONTENT)
366 self._testNotStripped(self.fat, 1024, self.FAT_CONTENT)
367
368 def testLarge(self):
369 """Ensure that files larger than the limit are modified."""
370 self._testStripped(self.slim, 1, self.SLIM_CONTENT)
371 self._testStripped(self.fat, 1, self.SLIM_CONTENT)
372
373 def testMixed(self):
374 """Test mix of large and small."""
375 strip_size = len(self.SLIM_CONTENT) + 1
376
377 self._testNotStripped(self.slim, strip_size, self.SLIM_CONTENT)
378 self._testStripped(self.fat, strip_size, self.SLIM_CONTENT)
379
380 def testSizeWarnings(self):
381 large = self.createSymbolFile(
382 'large.sym', content=self.SLIM_CONTENT,
383 size=upload_symbols.CRASH_SERVER_FILE_LIMIT*2)
384
385 # Would like to Strip as part of this test, but that really copies all
386 # of the sparse file content, which is too expensive for a unittest.
387 self._testNotStripped(large, None, None)
388
389 self.assertEqual(self.warn_mock.call_count, 1)
390
391
Mike Nichols137e82d2019-05-15 18:40:34 -0600392class DeduplicateTest(SymbolsTestBase):
393 """Test server Deduplication."""
394 def setUp(self):
395 self.PatchObject(upload_symbols, 'ExecRequest',
396 return_value={'pairs': [
397 {'status': 'FOUND',
398 'symbolId':
399 {'debugFile': 'sym1_sym',
400 'debugId': 'BEAA9BE'}},
401 {'status': 'FOUND',
402 'symbolId':
403 {'debugFile': 'sym2_sym',
404 'debugId': 'B6B1A36'}},
405 {'status': 'MISSING',
406 'symbolId':
407 {'debugFile': 'sym3_sym',
408 'debugId': 'D4FC0FC'}}]})
409
410 def testFindDuplicates(self):
411 # The first two symbols will be duplicate, the third new.
412 sym1 = self.createSymbolFile('sym1.sym')
413 sym1.header = cros_generate_breakpad_symbols.SymbolHeader('cpu', 'BEAA9BE',
414 'sym1_sym', 'os')
415 sym2 = self.createSymbolFile('sym2.sym')
416 sym2.header = cros_generate_breakpad_symbols.SymbolHeader('cpu', 'B6B1A36',
417 'sym2_sym', 'os')
418 sym3 = self.createSymbolFile('sym3.sym')
419 sym3.header = cros_generate_breakpad_symbols.SymbolHeader('cpu', 'D4FC0FC',
420 'sym3_sym', 'os')
421
422 result = upload_symbols.FindDuplicates((sym1, sym2, sym3), 'fake_url',
423 api_key='testkey')
424 self.assertEqual(list(result), [sym1, sym2, sym3])
425
426 self.assertEqual(sym1.status, upload_symbols.SymbolFile.DUPLICATE)
427 self.assertEqual(sym2.status, upload_symbols.SymbolFile.DUPLICATE)
428 self.assertEqual(sym3.status, upload_symbols.SymbolFile.INITIAL)
429
430
Don Garrettdeb2e032016-07-06 16:44:14 -0700431class PerformSymbolFilesUploadTest(SymbolsTestBase):
Don Garretta28be6d2016-06-16 18:09:35 -0700432 """Test PerformSymbolFile, and it's helper methods."""
433 def setUp(self):
Don Garrettdeb2e032016-07-06 16:44:14 -0700434 self.sym_initial = self.createSymbolFile(
435 'initial.sym')
436 self.sym_error = self.createSymbolFile(
437 'error.sym', status=upload_symbols.SymbolFile.ERROR)
438 self.sym_duplicate = self.createSymbolFile(
439 'duplicate.sym', status=upload_symbols.SymbolFile.DUPLICATE)
440 self.sym_uploaded = self.createSymbolFile(
441 'uploaded.sym', status=upload_symbols.SymbolFile.UPLOADED)
Don Garretta28be6d2016-06-16 18:09:35 -0700442
443 def testGetUploadTimeout(self):
444 """Test GetUploadTimeout helper function."""
445 # Timeout for small file.
Don Garrettdeb2e032016-07-06 16:44:14 -0700446 self.assertEqual(upload_symbols.GetUploadTimeout(self.sym_initial),
Don Garretta28be6d2016-06-16 18:09:35 -0700447 upload_symbols.UPLOAD_MIN_TIMEOUT)
448
Ian Barkley-Yeung22ba8122020-02-05 15:39:02 -0800449 # Timeout for 512M file.
450 large = self.createSymbolFile('large.sym', size=(512 * 1024 * 1024))
451 self.assertEqual(upload_symbols.GetUploadTimeout(large), 15 * 60)
Don Garretta28be6d2016-06-16 18:09:35 -0700452
453 def testUploadSymbolFile(self):
Mike Nichols90f7c152019-04-09 15:14:08 -0600454 upload_symbols.UploadSymbolFile('fake_url', self.sym_initial,
455 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700456 # TODO: Examine mock in more detail to make sure request is correct.
Mike Nichols137e82d2019-05-15 18:40:34 -0600457 self.assertEqual(self.request_mock.call_count, 3)
Don Garretta28be6d2016-06-16 18:09:35 -0700458
Don Garrettdeb2e032016-07-06 16:44:14 -0700459 def testPerformSymbolsFileUpload(self):
Don Garretta28be6d2016-06-16 18:09:35 -0700460 """We upload on first try."""
Don Garrettdeb2e032016-07-06 16:44:14 -0700461 symbols = [self.sym_initial]
Don Garretta28be6d2016-06-16 18:09:35 -0700462
Don Garrettdeb2e032016-07-06 16:44:14 -0700463 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600464 symbols, 'fake_url', api_key='testkey')
Don Garrettdeb2e032016-07-06 16:44:14 -0700465
466 self.assertEqual(list(result), symbols)
467 self.assertEqual(self.sym_initial.status,
468 upload_symbols.SymbolFile.UPLOADED)
Mike Nichols137e82d2019-05-15 18:40:34 -0600469 self.assertEqual(self.request_mock.call_count, 3)
Don Garretta28be6d2016-06-16 18:09:35 -0700470
Don Garrettdeb2e032016-07-06 16:44:14 -0700471 def testPerformSymbolsFileUploadFailure(self):
Don Garretta28be6d2016-06-16 18:09:35 -0700472 """All network requests fail."""
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400473 self.request_mock.side_effect = IOError('network failure')
Don Garrettdeb2e032016-07-06 16:44:14 -0700474 symbols = [self.sym_initial]
Don Garretta28be6d2016-06-16 18:09:35 -0700475
Don Garrettdeb2e032016-07-06 16:44:14 -0700476 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600477 symbols, 'fake_url', api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700478
Don Garrettdeb2e032016-07-06 16:44:14 -0700479 self.assertEqual(list(result), symbols)
480 self.assertEqual(self.sym_initial.status, upload_symbols.SymbolFile.ERROR)
Mike Nichols90f7c152019-04-09 15:14:08 -0600481 self.assertEqual(self.request_mock.call_count, 7)
Don Garretta28be6d2016-06-16 18:09:35 -0700482
Don Garrettdeb2e032016-07-06 16:44:14 -0700483 def testPerformSymbolsFileUploadTransisentFailure(self):
Don Garretta28be6d2016-06-16 18:09:35 -0700484 """We fail once, then succeed."""
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400485 self.urlopen_mock.side_effect = (IOError('network failure'), None)
Don Garrettdeb2e032016-07-06 16:44:14 -0700486 symbols = [self.sym_initial]
Don Garretta28be6d2016-06-16 18:09:35 -0700487
Don Garrettdeb2e032016-07-06 16:44:14 -0700488 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600489 symbols, 'fake_url', api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700490
Don Garrettdeb2e032016-07-06 16:44:14 -0700491 self.assertEqual(list(result), symbols)
492 self.assertEqual(self.sym_initial.status,
493 upload_symbols.SymbolFile.UPLOADED)
Mike Nichols137e82d2019-05-15 18:40:34 -0600494 self.assertEqual(self.request_mock.call_count, 3)
Don Garrettdeb2e032016-07-06 16:44:14 -0700495
496 def testPerformSymbolsFileUploadMixed(self):
497 """Upload symbols in mixed starting states.
498
499 Demonstrate that INITIAL and ERROR are uploaded, but DUPLICATE/UPLOADED are
500 ignored.
501 """
502 symbols = [self.sym_initial, self.sym_error,
503 self.sym_duplicate, self.sym_uploaded]
504
505 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600506 symbols, 'fake_url', api_key='testkey')
Don Garrettdeb2e032016-07-06 16:44:14 -0700507
508 #
509 self.assertEqual(list(result), symbols)
510 self.assertEqual(self.sym_initial.status,
511 upload_symbols.SymbolFile.UPLOADED)
512 self.assertEqual(self.sym_error.status,
513 upload_symbols.SymbolFile.UPLOADED)
514 self.assertEqual(self.sym_duplicate.status,
515 upload_symbols.SymbolFile.DUPLICATE)
516 self.assertEqual(self.sym_uploaded.status,
517 upload_symbols.SymbolFile.UPLOADED)
Mike Nichols137e82d2019-05-15 18:40:34 -0600518 self.assertEqual(self.request_mock.call_count, 6)
Don Garrettdeb2e032016-07-06 16:44:14 -0700519
520
521 def testPerformSymbolsFileUploadErrorOut(self):
522 """Demonstate we exit only after X errors."""
523
524 symbol_count = upload_symbols.MAX_TOTAL_ERRORS_FOR_RETRY + 10
525 symbols = []
526 fail_file = None
527
528 # potentially twice as many errors as we should attempt.
Mike Frysinger79cca962019-06-13 15:26:53 -0400529 for _ in range(symbol_count):
Don Garrettdeb2e032016-07-06 16:44:14 -0700530 # Each loop will get unique SymbolFile instances that use the same files.
531 fail = self.createSymbolFile('fail.sym')
532 fail_file = fail.file_name
533 symbols.append(self.createSymbolFile('pass.sym'))
534 symbols.append(fail)
535
536 # Mock out UploadSymbolFile and fail for fail.sym files.
Mike Nichols90f7c152019-04-09 15:14:08 -0600537 def failSome(_url, symbol, _api_key):
Don Garrettdeb2e032016-07-06 16:44:14 -0700538 if symbol.file_name == fail_file:
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400539 raise IOError('network failure')
Don Garrettdeb2e032016-07-06 16:44:14 -0700540
Luigi Semenzato5104f3c2016-10-12 12:37:42 -0700541 upload_mock = self.PatchObject(upload_symbols, 'UploadSymbolFile',
542 side_effect=failSome)
543 upload_mock.__name__ = 'UploadSymbolFileMock2'
Don Garrettdeb2e032016-07-06 16:44:14 -0700544
545 result = upload_symbols.PerformSymbolsFileUpload(
Mike Nichols90f7c152019-04-09 15:14:08 -0600546 symbols, 'fake_url', api_key='testkey')
Don Garrettdeb2e032016-07-06 16:44:14 -0700547
548 self.assertEqual(list(result), symbols)
549
550 passed = sum(s.status == upload_symbols.SymbolFile.UPLOADED
551 for s in symbols)
552 failed = sum(s.status == upload_symbols.SymbolFile.ERROR
553 for s in symbols)
554 skipped = sum(s.status == upload_symbols.SymbolFile.INITIAL
555 for s in symbols)
556
557 # Shows we all pass.sym files worked until limit hit.
558 self.assertEqual(passed, upload_symbols.MAX_TOTAL_ERRORS_FOR_RETRY)
559
560 # Shows we all fail.sym files failed until limit hit.
561 self.assertEqual(failed, upload_symbols.MAX_TOTAL_ERRORS_FOR_RETRY)
562
563 # Shows both pass/fail were skipped after limit hit.
564 self.assertEqual(skipped, 10 * 2)
Don Garretta28be6d2016-06-16 18:09:35 -0700565
566
567class UploadSymbolsTest(SymbolsTestBase):
568 """Test UploadSymbols, along with most helper methods."""
569 def setUp(self):
570 # Results gathering.
571 self.failure_file = os.path.join(self.tempdir, 'failures.txt')
572
573 def testUploadSymbolsEmpty(self):
574 """Upload dir is empty."""
Mike Nichols137e82d2019-05-15 18:40:34 -0600575 result = upload_symbols.UploadSymbols([self.data], 'fake_url')
Don Garretta28be6d2016-06-16 18:09:35 -0700576
Mike Frysinger2d589a12019-08-25 14:15:12 -0400577 self.assertEqual(result, 0)
Don Garretta28be6d2016-06-16 18:09:35 -0700578 self.assertEqual(self.urlopen_mock.call_count, 0)
579
580 def testUploadSymbols(self):
581 """Upload a few files."""
582 self.createSymbolFile('slim.sym', self.SLIM_CONTENT)
583 self.createSymbolFile(os.path.join('nested', 'inner.sym'))
584 self.createSymbolFile('fat.sym', self.FAT_CONTENT)
585
586 result = upload_symbols.UploadSymbols(
Mike Nichols90f7c152019-04-09 15:14:08 -0600587 [self.data], 'fake_url',
588 failed_list=self.failure_file, strip_cfi=len(self.SLIM_CONTENT)+1,
589 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700590
Mike Frysinger2d589a12019-08-25 14:15:12 -0400591 self.assertEqual(result, 0)
Mike Nichols137e82d2019-05-15 18:40:34 -0600592 self.assertEqual(self.request_mock.call_count, 10)
Mike Frysinger2d589a12019-08-25 14:15:12 -0400593 self.assertEqual(osutils.ReadFile(self.failure_file), '')
Don Garretta28be6d2016-06-16 18:09:35 -0700594
595 def testUploadSymbolsLimited(self):
596 """Upload a few files."""
597 self.createSymbolFile('slim.sym', self.SLIM_CONTENT)
598 self.createSymbolFile(os.path.join('nested', 'inner.sym'))
599 self.createSymbolFile('fat.sym', self.FAT_CONTENT)
600
601 result = upload_symbols.UploadSymbols(
Mike Nichols90f7c152019-04-09 15:14:08 -0600602 [self.data], 'fake_url', upload_limit=2,
603 api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700604
Mike Frysinger2d589a12019-08-25 14:15:12 -0400605 self.assertEqual(result, 0)
Mike Nichols137e82d2019-05-15 18:40:34 -0600606 self.assertEqual(self.request_mock.call_count, 7)
Mike Frysingerf2fa7d62017-12-14 18:33:59 -0500607 self.assertNotExists(self.failure_file)
Don Garretta28be6d2016-06-16 18:09:35 -0700608
609 def testUploadSymbolsFailures(self):
610 """Upload a few files."""
611 self.createSymbolFile('pass.sym')
612 fail = self.createSymbolFile('fail.sym')
613
Mike Nichols90f7c152019-04-09 15:14:08 -0600614 def failSome(_url, symbol, _api_key):
Don Garretta28be6d2016-06-16 18:09:35 -0700615 if symbol.file_name == fail.file_name:
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400616 raise IOError('network failure')
Don Garretta28be6d2016-06-16 18:09:35 -0700617
618 # Mock out UploadSymbolFile so it's easy to see which file to fail for.
619 upload_mock = self.PatchObject(upload_symbols, 'UploadSymbolFile',
620 side_effect=failSome)
Luigi Semenzato5104f3c2016-10-12 12:37:42 -0700621 # Mock __name__ for logging.
622 upload_mock.__name__ = 'UploadSymbolFileMock'
Don Garretta28be6d2016-06-16 18:09:35 -0700623
624 result = upload_symbols.UploadSymbols(
Mike Nichols90f7c152019-04-09 15:14:08 -0600625 [self.data], 'fake_url',
626 failed_list=self.failure_file, api_key='testkey')
Don Garretta28be6d2016-06-16 18:09:35 -0700627
Mike Frysinger2d589a12019-08-25 14:15:12 -0400628 self.assertEqual(result, 1)
Don Garretta28be6d2016-06-16 18:09:35 -0700629 self.assertEqual(upload_mock.call_count, 8)
Mike Frysinger2d589a12019-08-25 14:15:12 -0400630 self.assertEqual(osutils.ReadFile(self.failure_file), 'fail.sym\n')
Don Garretta28be6d2016-06-16 18:09:35 -0700631
Don Garretta28be6d2016-06-16 18:09:35 -0700632# TODO: We removed --network integration tests.
Mike Frysinger0c0efa22014-02-09 23:32:23 -0500633
634
Mike Frysingerea838d12014-12-08 11:55:32 -0500635def main(_argv):
Mike Frysinger27e21b72018-07-12 14:20:21 -0400636 # pylint: disable=protected-access
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -0400637 # Set timeouts small so that if the unit test hangs, it won't hang for long.
638 parallel._BackgroundTask.STARTUP_TIMEOUT = 5
639 parallel._BackgroundTask.EXIT_TIMEOUT = 5
640
Mike Frysingerd5fcb3a2013-05-30 21:10:50 -0400641 # Run the tests.
Mike Frysingerba167372015-01-21 10:37:03 -0500642 cros_test_lib.main(level='info', module=__name__)