def main(_argv): # Use our local copy of insns for testing as the main one is not # available in the public manifest. signing.INPUT_INSN_DIR = signing.TEST_INPUT_INSN_DIR # Run the tests. cros_test_lib.main(level='notice', module=__name__)
def main(_argv): # pylint: disable=W0212 # Set timeouts small so that if the unit test hangs, it won't hang for long. parallel._BackgroundTask.STARTUP_TIMEOUT = 5 parallel._BackgroundTask.EXIT_TIMEOUT = 5 # Run the tests. cros_test_lib.main(level='info', module=__name__)
def main(_argv): # Use our local copy of insns for testing as the main one is not available in # the public manifest. Even though _REL is a relative path, this works because # os.join leaves absolute paths on the right hand side alone. signing.INPUT_INSN_DIR_REL = signing.TEST_INPUT_INSN_DIR # Run the tests. cros_test_lib.main(level='notice', module=__name__)
def main(_argv): # pylint: disable=W0212 # Set timeouts small so that if the unit test hangs, it won't hang for long. parallel._BackgroundTask.STARTUP_TIMEOUT = 5 parallel._BackgroundTask.EXIT_TIMEOUT = 5 # We want to test retry behavior, so make sure we don't sleep. upload_symbols.INITIAL_RETRY_DELAY = 0 # Run the tests. cros_test_lib.main(level='info', module=__name__)
def FindTarget(target): """Turn the path into something we can import from the chromite tree. This supports a variety of ways of running chromite programs: # Loaded via depot_tools in $PATH. $ cros_sdk --help # Loaded via .../chromite/bin in $PATH. $ cros --help # No $PATH needed. $ ./bin/cros --help # Loaded via ~/bin in $PATH to chromite bin/ subdir. $ ln -s $PWD/bin/cros ~/bin; cros --help # No $PATH needed. $ ./cbuildbot/cbuildbot --help # No $PATH needed, but symlink inside of chromite dir. $ ln -s ./cbuildbot/cbuildbot; ./cbuildbot --help # Loaded via ~/bin in $PATH to non-chromite bin/ subdir. $ ln -s $PWD/cbuildbot/cbuildbot ~/bin/; cbuildbot --help # No $PATH needed, but a relative symlink to a symlink to the chromite dir. $ cd ~; ln -s bin/cbuildbot ./; ./cbuildbot --help Args: target: Path to the script we're trying to run. Returns: The module main functor. """ while True: # Walk back one symlink at a time until we get into the chromite dir. parent, base = os.path.split(target) parent = os.path.realpath(parent) if parent.startswith(CHROMITE_PATH): target = base break target = os.path.join(os.path.dirname(target), os.readlink(target)) assert parent.startswith(CHROMITE_PATH), ( 'could not figure out leading path\n' '\tparent: %s\n' '\tCHROMITE_PATH: %s' % (parent, CHROMITE_PATH)) parent = parent[len(CHROMITE_PATH):].split(os.sep) target = ['chromite'] + parent + [target] if target[-2] == 'bin': # Convert <path>/bin/foo -> <path>/scripts/foo. target[-2] = 'scripts' elif target[1] == 'bootstrap' and len(target) == 3: # Convert <git_repo>/bootstrap/foo -> <git_repo>/bootstrap/scripts/foo. target.insert(2, 'scripts') module = cros_import.ImportModule(target) # Run the module's main func if it has one. main = getattr(module, 'main', None) if main: return main # Is this a unittest? if target[-1].rsplit('_', 1)[-1] in ('test', 'unittest'): from chromite.lib import cros_test_lib return lambda _argv: cros_test_lib.main(module=module)
sys.exit(1) def _KeyboardInterrupt(self): sys.stdout.write(_GREETING) raise KeyboardInterrupt() def testExceptionRaising(self): # pylint: disable=E1101 self.StartPatcher(BackgroundTaskVerifier()) for fn in (self._SystemExit, self._KeyboardInterrupt): for task in (lambda: parallel.RunTasksInProcessPool(fn, [[]]), lambda: parallel.RunParallelSteps([fn])): output_str = ex_str = None with self.OutputCapturer() as capture: try: task() except parallel.BackgroundFailure as ex: output_str = capture.GetStdout() ex_str = str(ex) self.assertTrue('Traceback' in ex_str) self.assertEqual(output_str, _GREETING) if __name__ == '__main__': # Set timeouts small so that if the unit test hangs, it won't hang for long. parallel._BackgroundTask.STARTUP_TIMEOUT = 5 parallel._BackgroundTask.EXIT_TIMEOUT = 5 # Run the tests. cros_test_lib.main(level=logging.INFO)
def FindTarget(target): """Turn the path into something we can import from the chromite tree. This supports a variety of ways of running chromite programs: # Loaded via depot_tools in $PATH. $ cros_sdk --help # Loaded via .../chromite/bin in $PATH. $ cros --help # No $PATH needed. $ ./bin/cros --help # Loaded via ~/bin in $PATH to chromite bin/ subdir. $ ln -s $PWD/bin/cros ~/bin; cros --help # No $PATH needed. $ ./cbuildbot/cbuildbot --help # No $PATH needed, but symlink inside of chromite dir. $ ln -s ./cbuildbot/cbuildbot; ./cbuildbot --help # Loaded via ~/bin in $PATH to non-chromite bin/ subdir. $ ln -s $PWD/cbuildbot/cbuildbot ~/bin/; cbuildbot --help # No $PATH needed, but a relative symlink to a symlink to the chromite dir. $ cd ~; ln -s bin/cbuildbot ./; ./cbuildbot --help # External chromite module $ ln -s ../chromite/scripts/wrapper.py foo; ./foo Args: target: Path to the script we're trying to run. Returns: The module main functor. """ # We assume/require the script we're wrapping ends in a .py. full_path = target + '.py' while True: # Walk back one symlink at a time until we get into the chromite dir. parent, base = os.path.split(target) parent = os.path.realpath(parent) if parent.startswith(CHROMITE_PATH): target = base break target = os.path.join(os.path.dirname(target), os.readlink(target)) # If we walked all the way back to wrapper.py, it means we're trying to run # an external module. So we have to import it by filepath and not via the # chromite.xxx.yyy namespace. if target != 'wrapper.py': assert parent.startswith(CHROMITE_PATH), ( 'could not figure out leading path\n' '\tparent: %s\n' '\tCHROMITE_PATH: %s' % (parent, CHROMITE_PATH)) parent = parent[len(CHROMITE_PATH):].split(os.sep) target = ['chromite'] + parent + [target] if target[-2] == 'bin': # Convert <path>/bin/foo -> <path>/scripts/foo. target[-2] = 'scripts' elif target[1] == 'bootstrap' and len(target) == 3: # Convert <git_repo>/bootstrap/foo -> <git_repo>/bootstrap/scripts/foo. target.insert(2, 'scripts') try: module = cros_import.ImportModule(target) except ImportError as e: print('%s: could not import chromite module: %s: %s' % (sys.argv[0], full_path, e), file=sys.stderr) sys.exit(1) else: try: module = imp.load_source('main', full_path) except IOError as e: print('%s: could not import external module: %s: %s' % (sys.argv[0], full_path, e), file=sys.stderr) sys.exit(1) # Run the module's main func if it has one. main = getattr(module, 'main', None) if main: return main # Is this a unittest? if target[-1].rsplit('_', 1)[-1] in ('test', 'unittest'): from chromite.lib import cros_test_lib return lambda _argv: cros_test_lib.main(module=module)
cros_mark_as_stable.GitBranch.Checkout(self._branch) self.mox.VerifyAll() def testCheckoutNoCreate(self): # Test init with previous branch existing. self._branch.Exists(self._branch_name).AndReturn(True) cros_build_lib.RunCommandCaptureOutput( ['git', 'checkout', '-f', self._branch_name], print_cmd=False, cwd='.') self.mox.ReplayAll() cros_mark_as_stable.GitBranch.Checkout(self._branch) self.mox.VerifyAll() def testExists(self): branch = cros_mark_as_stable.GitBranch(self._branch_name, self._target_manifest_branch, '.') # Test if branch exists that is created result = cros_build_lib.CommandResult(output=self._branch_name + '\n') cros_build_lib.RunCommandCaptureOutput(['git', 'branch'], print_cmd=False, cwd='.').AndReturn(result) self.mox.ReplayAll() self.assertTrue(branch.Exists()) self.mox.VerifyAll() if __name__ == '__main__': cros_test_lib.main()
iterator = enumerate(config) else: self.assertTrue(os.path.isfile(path)) self.assertEqual(osutils.ReadFile(path, mode='rb'), configfs.Serialize(config)) return self.assertTrue(os.path.isdir(path)) for name, entry in iterator: childpath = os.path.join(path, str(name)) _CheckConfigRec(entry, childpath) _CheckConfigRec(config, os.path.join(output_dir, 'squashfs-root/v1')) @TestConfigs('test.json', 'test_arm.json') def testConfigV1Identity(self, config, output_dir): identity_path = os.path.join(output_dir, 'squashfs-root/v1/identity.json') self.assertTrue(os.path.isfile(identity_path)) with open(identity_path) as f: identity_data = json.load(f) for device_config, identity_config in zip( config['chromeos']['configs'], identity_data['chromeos']['configs']): self.assertEqual(set(identity_config.keys()), {'identity'}) self.assertEqual(device_config['identity'], identity_config['identity']) if __name__ == '__main__': cros_test_lib.main(module=__name__)
def FindTarget(target): """Turn the path into something we can import from the chromite tree. This supports a variety of ways of running chromite programs: # Loaded via depot_tools in $PATH. $ cros_sdk --help # Loaded via .../chromite/bin in $PATH. $ cros --help # No $PATH needed. $ ./bin/cros --help # Loaded via ~/bin in $PATH to chromite bin/ subdir. $ ln -s $PWD/bin/cros ~/bin; cros --help # No $PATH needed. $ ./cbuildbot/cbuildbot --help # No $PATH needed, but symlink inside of chromite dir. $ ln -s ./cbuildbot/cbuildbot; ./cbuildbot --help # Loaded via ~/bin in $PATH to non-chromite bin/ subdir. $ ln -s $PWD/cbuildbot/cbuildbot ~/bin/; cbuildbot --help # No $PATH needed, but a relative symlink to a symlink to the chromite dir. $ cd ~; ln -s bin/cbuildbot ./; ./cbuildbot --help # External chromite module $ ln -s ../chromite/scripts/wrapper.py foo; ./foo Args: target: Path to the script we're trying to run. Returns: The module main functor. """ # We assume/require the script we're wrapping ends in a .py. full_path = target + '.py' while True: # Walk back one symlink at a time until we get into the chromite dir. parent, base = os.path.split(target) parent = os.path.realpath(parent) if parent.startswith(CHROMITE_PATH): target = base break target = os.path.join(os.path.dirname(target), os.readlink(target)) # If we walked all the way back to wrapper.py, it means we're trying to run # an external module. So we have to import it by filepath and not via the # chromite.xxx.yyy namespace. if target != 'wrapper.py': assert parent.startswith(CHROMITE_PATH), ( 'could not figure out leading path\n' '\tparent: %s\n' '\tCHROMITE_PATH: %s' % (parent, CHROMITE_PATH)) parent = parent[len(CHROMITE_PATH):].split(os.sep) target = ['chromite'] + parent + [target] if target[1] == 'bin': # Convert chromite/bin/foo -> chromite/scripts/foo. # Since chromite/bin/ is in $PATH, we want to keep it clean. target[1] = 'scripts' try: module = importlib.import_module('.'.join(target)) except ImportError as e: print('%s: could not import chromite module: %s: %s' % (sys.argv[0], full_path, e), file=sys.stderr) raise else: try: # Python 3 way. # pylint: disable=deprecated-method,no-value-for-parameter from importlib.machinery import SourceFileLoader _loader = lambda *args: SourceFileLoader(*args).load_module() except ImportError: # Python 2 way. import imp _loader = imp.load_source try: module = _loader('main', full_path) except IOError as e: print('%s: could not import external module: %s: %s' % (sys.argv[0], full_path, e), file=sys.stderr) raise # Run the module's main func if it has one. main = getattr(module, 'main', None) if main: return main # Is this a unittest? if target[-1].rsplit('_', 1)[-1] in ('test', 'unittest'): from chromite.lib import cros_test_lib return lambda _argv: cros_test_lib.main(module=module)
def testBogustProjectNoDir(self): """Make sure --dir is detected even with --project.""" ret = pre_upload.direct_main(['--project', 'foooooooooo']) self.assertEqual(ret, 0) self.hooks_mock.assert_called_once_with( 'foooooooooo', proj_dir=os.getcwd(), commit_list=[], presubmit=mock.ANY) def testNoGitDir(self): """We should die when run on a non-git dir.""" self.assertRaises(pre_upload.BadInvocation, pre_upload.direct_main, ['--dir', self.tempdir]) def testNoDir(self): """We should die when run on a missing dir.""" self.assertRaises(pre_upload.BadInvocation, pre_upload.direct_main, ['--dir', os.path.join(self.tempdir, 'foooooooo')]) def testCommitList(self): """Any args on the command line should be treated as commits.""" commits = ['sha1', 'sha2', 'shaaaaaaaaaaaan'] ret = pre_upload.direct_main(commits) self.assertEqual(ret, 0) self.hooks_mock.assert_called_once_with( mock.ANY, proj_dir=mock.ANY, commit_list=commits, presubmit=mock.ANY) if __name__ == '__main__': cros_test_lib.main(module=__name__)
def main(_argv): # No need to make unittests sleep. alerts.SmtpServer.SMTP_RETRY_DELAY = 0 cros_test_lib.main(module=__name__)
self.assertFalse(self.mark_mock.called) self.assertEqual(urls, {}) def testGsError(self): """Verify random GS errors don't make us blow up entirely""" self.gs_mock.AddCmdResult(partial_mock.In('stat'), returncode=1, output='gobblety gook\n') with cros_test_lib.LoggingCapturer('chromite'): self.assertRaises(pushimage.PushError, pushimage.PushImage, '/src', 'test.board', 'R34-5126.0.0') class MainTests(cros_test_lib.MockTestCase): """Tests for main()""" def setUp(self): self.PatchObject(pushimage, 'PushImage') def testBasic(self): """Simple smoke test""" pushimage.main(['--board', 'test.board', '/src', '--yes']) if __name__ == '__main__': # Use our local copy of insns for testing as the main one is not # available in the public manifest. signing.INPUT_INSN_DIR = signing.TEST_INPUT_INSN_DIR # Run the tests. cros_test_lib.main(level=logging.INFO)
def main(_argv): gob_util.TRY_LIMIT = 1 cros_test_lib.main(module=__name__)
'bergman': 'the seventh seal'} } starting_dict = {'board-metadata': starting_per_board_dict} m = multiprocessing.Manager() metadata = metadata_lib.CBuildbotMetadata(metadata_dict=starting_dict, multiprocess_manager=m) extra_per_board_dict = { 'board-1': {'kurosawa': 'rashomon', 'coen brothers': 'fargo'}, 'board-3': {'hitchcock': 'north by northwest', 'coen brothers': 'the big lebowski'} } expected_dict = starting_per_board_dict # Write each per board key-value pair to metadata in a separate process. with parallel.BackgroundTaskRunner(metadata.UpdateBoardDictWithDict) as q: for board, board_dict in extra_per_board_dict.iteritems(): expected_dict.setdefault(board, {}).update(board_dict) for k, v in board_dict.iteritems(): q.put([board, {k: v}]) self.assertEqual(expected_dict, metadata.GetDict()['board-metadata']) if __name__ == '__main__': cros_test_lib.main(level=logging.DEBUG)
def main(_argv): cros_test_lib.main(level='info', module=__name__)
def main(_argv): # TODO(akeshet): Allow command line args to specify alternate CIDB instance # for testing. cros_test_lib.main(module=__name__)
csv = 'any.csv' token_file = self.tempfile creds_file = 'non-existing-file' mocked_creds = self.mox.CreateMock(gdata_lib.Creds) mocked_creds.auth_token_loaded = True self.mox.StubOutWithMock(ups, 'PrepareCreds') self.mox.StubOutWithMock(ups, 'LoadTable') self.mox.StubOutWithMock(mps, 'FinalizeTable') self.mox.StubOutWithMock(ups.Uploader, 'Upload') ups.PrepareCreds(creds_file, token_file, None, None).AndReturn(mocked_creds) ups.LoadTable(csv).AndReturn('csv_table') mps.FinalizeTable('csv_table') ups.Uploader.Upload(mox.IgnoreArg(), ws_name=ups.PKGS_WS_NAME) ups.Uploader.Upload(mox.IgnoreArg(), ws_name=ups.DEPS_WS_NAME) mocked_creds.StoreCredsIfNeeded(creds_file) mocked_creds.StoreAuthTokenIfNeeded(token_file) self.mox.ReplayAll() ups.main(['--cred-file=%s' % creds_file, '--auth-token-file=%s' % token_file, csv]) self.mox.VerifyAll() if __name__ == '__main__': cros_test_lib.main()
def main(_argv): cros_test_lib.main(level='debug', module=__name__)