How to use kill method in Puppeteer

Best JavaScript code snippet using puppeteer

test_async_process.py

Source:test_async_process.py Github

copy

Full Screen

...164 return_value=pid),\165 mock.patch.object(self.proc, '_kill_process_and_wait'166 ) as mock_kill_process_and_wait,\167 mock.patch.object(self.proc, '_process'):168 self.proc._kill(signal.SIGKILL)169 self.assertIsNone(self.proc._kill_event)170 self.assertFalse(self.proc._is_running)171 self.assertIsNone(self.proc._pid)172 mock_kill_event.send.assert_called_once_with()173 if pid:174 mock_kill_process_and_wait.assert_called_once_with(175 pid, signal.SIGKILL, None)176 def _test__kill_process_and_wait(self, pid, expected,177 exception_message=None,178 kill_signal=signal.SIGKILL):179 self.proc.run_as_root = True180 if exception_message:181 exc = RuntimeError(exception_message)182 else:...

Full Screen

Full Screen

killBufferCommands.py

Source:killBufferCommands.py Github

copy

Full Screen

...57 return58 undoType = 'backward-kill-sentence'59 self.beginCommand(w, undoType=undoType)60 i2 = s.rfind('.', 0, i) + 161 self.kill(event, i2, i + 1, undoType=undoType)62 w.setInsertPoint(i2)63 self.endCommand(changed=True, setLabel=True)64 #@+node:ekr.20150514063305.413: *3* backwardKillWord & killWord65 @cmd('backward-kill-word')66 def backwardKillWord(self, event):67 """Kill the previous word."""68 c = self.c69 w = self.editWidget(event)70 if w:71 self.beginCommand(w, undoType='backward-kill-word')72 c.editCommands.backwardWord(event)73 self.killWordHelper(event)74 @cmd('kill-word')75 def killWord(self, event):76 """Kill the word containing the cursor."""77 w = self.editWidget(event)78 if w:79 self.beginCommand(w, undoType='kill-word')80 self.killWordHelper(event)81 def killWordHelper(self, event):82 c = self.c83 e = c.editCommands84 w = e.editWidget(event)85 if w:86 # self.killWs(event)87 e.extendToWord(event)88 i, j = w.getSelectionRange()89 self.kill(event, i, j, undoType=None)90 self.endCommand(changed=True, setLabel=True)91 #@+node:ekr.20150514063305.414: *3* clearKillRing92 @cmd('clear-kill-ring')93 def clearKillRing(self, event=None):94 """Clear the kill ring."""95 g.app.globalKillbuffer = []96 #@+node:ekr.20150514063305.415: *3* getClipboard97 def getClipboard(self):98 """Return the contents of the clipboard."""99 try:100 ctxt = g.app.gui.getTextFromClipboard()101 if not g.app.globalKillBuffer or ctxt != self.last_clipboard:102 self.last_clipboard = ctxt103 if not g.app.globalKillBuffer or g.app.globalKillBuffer[0] != ctxt:104 return ctxt105 except Exception:106 g.es_exception()107 return None108 #@+node:ekr.20150514063305.416: *3* class iterateKillBuffer109 class KillBufferIterClass:110 """Returns a list of positions in a subtree, possibly including the root of the subtree."""111 #@+others112 #@+node:ekr.20150514063305.417: *4* __init__ & __iter__ (iterateKillBuffer)113 def __init__(self, c):114 """Ctor for KillBufferIterClass class."""115 self.c = c116 self.index = 0 # The index of the next item to be returned.117 def __iter__(self):118 return self119 #@+node:ekr.20150514063305.418: *4* __next__120 def __next__(self):121 commands = self.c.killBufferCommands122 aList = g.app.globalKillBuffer # commands.killBuffer123 if not aList:124 self.index = 0125 return None126 if commands.reset is None:127 i = self.index128 else:129 i = commands.reset130 commands.reset = None131 if i < 0 or i >= len(aList): i = 0132 val = aList[i]133 self.index = i + 1134 return val135 #@-others136 def iterateKillBuffer(self):137 return self.KillBufferIterClass(self.c)138 #@+node:ekr.20150514063305.419: *3* kill (helper)139 def kill(self, event, frm, to, force=False, undoType=None):140 """A helper method for all kill commands."""141 w = self.editWidget(event)142 if not w: return143 # 2016/03/05: all kill commands kill selected text, if it exists.144 if not force:145 # Delete the selection range if it spans a line.146 i, j = w.getSelectionRange()147 s = w.get(i, j)148 if s.find('\n') > -1:149 frm, to = i, j150 s = w.get(frm, to)151 if undoType:152 self.beginCommand(w, undoType=undoType)153 self.addToKillBuffer(s)154 g.app.gui.replaceClipboardWith(s)155 w.delete(frm, to)156 w.setInsertPoint(frm)157 if undoType:158 self.endCommand(changed=True, setLabel=True)159 #@+node:ekr.20150514063305.420: *3* killToEndOfLine160 @cmd('kill-to-end-of-line')161 def killToEndOfLine(self, event):162 """Kill from the cursor to end of the line."""163 w = self.editWidget(event)164 if not w: return165 s = w.getAllText()166 ins = w.getInsertPoint()167 i, j = g.getLine(s, ins)168 if ins >= len(s) and g.match(s, j - 1, '\n'):169 # Kill the trailing newline of the body text.170 i = max(0, len(s) - 1)171 j = len(s)172 elif ins + 1 < j and s[ins : j - 1].strip() and g.match(s, j - 1, '\n'):173 # Kill the line, but not the newline.174 i, j = ins, j - 1175 elif g.match(s, j - 1, '\n'):176 i = ins # Kill the newline in the present line.177 else:178 i = j179 if i < j:180 self.kill(event, i, j, undoType='kill-line')181 #@+node:ekr.20150514063305.421: *3* KillLine182 @cmd('kill-line')183 def killLine(self, event):184 """Kill the line containing the cursor."""185 w = self.editWidget(event)186 if not w: return187 s = w.getAllText()188 ins = w.getInsertPoint()189 i, j = g.getLine(s, ins)190 if ins >= len(s) and g.match(s, j - 1, '\n'):191 # Kill the trailing newline of the body text.192 i = max(0, len(s) - 1)193 j = len(s)194 elif j > i + 1 and g.match(s, j - 1, '\n'):195 # Kill the line, but not the newline.196 j -= 1197 else:198 pass # Kill the newline in the present line.199 self.kill(event, i, j, undoType='kill-line')200 #@+node:ekr.20150514063305.422: *3* killRegion & killRegionSave & helper201 @cmd('kill-region')202 def killRegion(self, event):203 """Kill the text selection."""204 self.killRegionHelper(event, deleteFlag=True)205 @cmd('kill-region-save')206 def killRegionSave(self, event):207 """Add the selected text to the kill ring, but do not delete it."""208 self.killRegionHelper(event, deleteFlag=False)209 def killRegionHelper(self, event, deleteFlag):210 w = self.editWidget(event)211 if not w: return212 i, j = w.getSelectionRange()213 if i == j: return214 s = w.getSelectedText()215 if deleteFlag:216 self.beginCommand(w, undoType='kill-region')217 w.delete(i, j)218 self.endCommand(changed=True, setLabel=True)219 self.addToKillBuffer(s)220 g.app.gui.replaceClipboardWith(s)221 # self.removeRKeys(w)222 #@+node:ekr.20150514063305.423: *3* killSentence223 @cmd('kill-sentence')224 def killSentence(self, event):225 """Kill the sentence containing the cursor."""226 w = self.editWidget(event)227 if not w:228 return229 s = w.getAllText()230 ins = w.getInsertPoint()231 i = s.find('.', ins)232 if i == -1:233 return234 undoType = 'kill-sentence'235 self.beginCommand(w, undoType=undoType)236 i2 = s.rfind('.', 0, ins) + 1237 self.kill(event, i2, i + 1, undoType=undoType)238 w.setInsertPoint(i2)239 self.endCommand(changed=True, setLabel=True)240 #@+node:ekr.20150514063305.424: *3* killWs241 @cmd('kill-ws')242 def killWs(self, event, undoType='kill-ws'):243 """Kill whitespace."""244 ws = ''245 w = self.editWidget(event)246 if not w: return247 s = w.getAllText()248 i = j = ins = w.getInsertPoint()249 while i >= 0 and s[i] in (' ', '\t'):250 i -= 1251 if i < ins: i += 1...

Full Screen

Full Screen

async_process.py

Source:async_process.py Github

copy

Full Screen

...113 """114 kill_signal = kill_signal or getattr(signal, 'SIGKILL', signal.SIGTERM)115 if self._is_running:116 LOG.debug('Halting async process [%s].', self.cmd)117 self._kill(kill_signal, kill_timeout)118 else:119 raise AsyncProcessException(_('Process is not running.'))120 if block:121 common_utils.wait_until_true(lambda: not self.is_active())122 def _spawn(self):123 """Spawn a process and its watchers."""124 self._is_running = True125 self._pid = None126 self._kill_event = eventlet.event.Event()127 self._process, cmd = utils.create_process(self._cmd,128 run_as_root=self.run_as_root)129 self._watchers = []130 for reader in (self._read_stdout, self._read_stderr):131 # Pass the stop event directly to the greenthread to132 # ensure that assignment of a new event to the instance133 # attribute does not prevent the greenthread from using134 # the original event.135 watcher = eventlet.spawn(self._watch_process,136 reader,137 self._kill_event)138 self._watchers.append(watcher)139 @property140 def pid(self):141 if self._process:142 if not self._pid:143 self._pid = utils.get_root_helper_child_pid(144 self._process.pid,145 self.cmd_without_namespace,146 run_as_root=self.run_as_root)147 return self._pid148 def _kill(self, kill_signal, kill_timeout=None):149 """Kill the process and the associated watcher greenthreads."""150 pid = self.pid151 if pid:152 self._is_running = False153 self._pid = None154 self._kill_process_and_wait(pid, kill_signal, kill_timeout)155 # Halt the greenthreads if they weren't already.156 if self._kill_event:157 self._kill_event.send()158 self._kill_event = None159 def _kill_process_and_wait(self, pid, kill_signal, kill_timeout=None):160 kill_result = self._kill_process(pid, kill_signal)161 if kill_result is False:162 return kill_result163 if self._process:164 try:165 self._process.wait(kill_timeout)166 except subprocess.TimeoutExpired:167 LOG.warning("Process %(pid)s [%(cmd)s] still running after "168 "%(timeout)d seconds. Sending %(signal)d to kill "169 "it.",170 {'pid': pid,171 'cmd': self.cmd,172 'timeout': kill_timeout,173 'signal': signal.SIGKILL})174 return self._kill_process(pid, signal.SIGKILL)175 return True176 def _kill_process(self, pid, kill_signal):177 try:178 # A process started by a root helper will be running as179 # root and need to be killed via the same helper.180 utils.kill_process(pid, kill_signal, self.run_as_root)181 except Exception:182 LOG.exception('An error occurred while killing [%s].',183 self.cmd)184 return False185 return True186 def _handle_process_error(self):187 """Kill the async process and respawn if necessary."""188 stdout = list(self.iter_stdout())189 stderr = list(self.iter_stderr())190 LOG.debug('Halting async process [%s] in response to an error. stdout:'191 ' [%s] - stderr: [%s]', self.cmd, stdout, stderr)192 self._kill(getattr(signal, 'SIGKILL', signal.SIGTERM))193 if self.respawn_interval is not None and self.respawn_interval >= 0:194 eventlet.sleep(self.respawn_interval)195 LOG.debug('Respawning async process [%s].', self.cmd)196 try:197 self.start()198 except AsyncProcessException:199 # Process was already respawned by someone else...200 pass201 def _watch_process(self, callback, kill_event):202 while not kill_event.ready():203 try:204 output = callback()205 if not output and output != "":206 break...

Full Screen

Full Screen

test_kill.py

Source:test_kill.py Github

copy

Full Screen

1#!/usr/bin/env python32'''Kill tests.3These tests run many scenarios in which jobs are killed (KILL_JOB).4'''5import json6import pandas as pd7import pytest8from helper import *9# The number of kills to do for each job.10KillCountMode = namedtuple('KillCountMode', ['name', 'kill_count_per_job'])11# The number of seconds between a job execution and its kill.12KillDelayMode = namedtuple('KillDelayMode', ['name', 'kill_delay'])13###################################################################14# Kill a job a given amount of time after starting its execution. #15###################################################################16def kill_after_delay(platform, workload, algorithm, redis_mode, nb_kills_per_job, delay_before_kill):17 test_name = f'kill-{delay_before_kill.name}-{nb_kills_per_job.name}-{algorithm.name}-{platform.name}-{workload.name}-{redis_mode.name}'18 output_dir, robin_filename, schedconf_filename = init_instance(test_name)19 if algorithm.sched_implem != 'batsched': raise Exception('This test only supports batsched for now')20 batparams = "--forward-profiles-on-submission"21 if redis_mode.enabled == True: batparams = batparams + " --enable-redis"22 batcmd = gen_batsim_cmd(platform.filename, workload.filename, output_dir, batparams)23 schedconf_content = {24 "delay_before_kill": delay_before_kill.kill_delay,25 "nb_kills_per_job": nb_kills_per_job.kill_count_per_job,26 }27 write_file(schedconf_filename, json.dumps(schedconf_content))28 instance = RobinInstance(output_dir=output_dir,29 batcmd=batcmd,30 schedcmd=f"batsched -v '{algorithm.sched_algo_name}' --variant_options_filepath '{schedconf_filename}'",31 simulation_timeout=30, ready_timeout=5,32 success_timeout=10, failure_timeout=033 )34 instance.to_file(robin_filename)35 ret = run_robin(robin_filename)36 if ret.returncode != 0: raise Exception(f'Bad robin return code ({ret.returncode})')37 # Analyze Batsim results38 batjobs_filename = f'{output_dir}/batres_jobs.csv'39 jobs = pd.read_csv(batjobs_filename)40 epsilon = 0.141 max_runtime = delay_before_kill.kill_delay + epsilon42 jobs_too_long = jobs.loc[jobs['execution_time'] > max_runtime]43 if jobs_too_long.empty:44 print(f'All jobs have been shorter than {max_runtime} s')45 else:46 print(f'Some jobs were longer than {max_runtime} s')47 print(jobs_too_long)48 raise Exception('Some were longer than f{max_runtime} s')49@pytest.mark.parametrize("nb_kills_per_job", [KillCountMode(f'{n}kills', n) for n in [1,2]])50@pytest.mark.parametrize("delay_before_kill", [KillDelayMode(f'after{n}', n) for n in [5,10,15]])51def test_kill_after_delay(small_platform, small_workload, killer_algorithm, redis_mode, nb_kills_per_job, delay_before_kill):52 kill_after_delay(small_platform, small_workload, killer_algorithm, redis_mode, nb_kills_per_job, delay_before_kill)53@pytest.mark.parametrize("nb_kills_per_job", [KillCountMode(f'{n}kills', n) for n in [1,2]])54@pytest.mark.parametrize("delay_before_kill", [KillDelayMode(f'after{n}', n) for n in [5,10,15]])55def test_kill_after_delay_sequences(small_platform, delaysequences_workload, killer_algorithm, redis_mode, nb_kills_per_job, delay_before_kill):56 kill_after_delay(small_platform, delaysequences_workload, killer_algorithm, redis_mode, nb_kills_per_job, delay_before_kill)57@pytest.mark.parametrize("nb_kills_per_job", [KillCountMode(f'{n}kills', n) for n in [1,2]])58@pytest.mark.parametrize("delay_before_kill", [KillDelayMode(f'after{n}', n) for n in [0]])59def test_kill_after_delay0(small_platform, small_workload, killer_algorithm, redis_mode, nb_kills_per_job, delay_before_kill):60 kill_after_delay(small_platform, small_workload, killer_algorithm, redis_mode, nb_kills_per_job, delay_before_kill)61@pytest.mark.parametrize("nb_kills_per_job", [KillCountMode(f'{n}kills', n) for n in [1]])62@pytest.mark.parametrize("delay_before_kill", [KillDelayMode(f'after{n}', n) for n in [1]])63def test_kill_after_delay_smpi(small_platform, smpi_workload, killer_algorithm, redis_mode, nb_kills_per_job, delay_before_kill):64 kill_after_delay(small_platform, smpi_workload, killer_algorithm, redis_mode, nb_kills_per_job, delay_before_kill)65#####################################################66# Kill the running job when a new one is submitted. #67#####################################################68def kill_on_new_submit(platform, workload, algorithm, redis_mode):69 test_name = f'kill-onnewsubmit-{algorithm.name}-{platform.name}-{workload.name}-{redis_mode.name}'70 output_dir, robin_filename, _ = init_instance(test_name)71 if algorithm.sched_implem != 'batsched': raise Exception('This test only supports batsched for now')72 batparams = "--forward-profiles-on-submission"73 if redis_mode.enabled == True: batparams = batparams + " --enable-redis"74 batcmd = gen_batsim_cmd(platform.filename, workload.filename, output_dir, batparams)75 instance = RobinInstance(output_dir=output_dir,76 batcmd=batcmd,77 schedcmd=f"batsched -v '{algorithm.sched_algo_name}'",78 simulation_timeout=30, ready_timeout=5,79 success_timeout=10, failure_timeout=080 )81 instance.to_file(robin_filename)82 ret = run_robin(robin_filename)83 if ret.returncode != 0: raise Exception(f'Bad robin return code ({ret.returncode})')84def test_kill_on_new_submit(small_platform, small_workload, killer2_algorithm, redis_mode):85 kill_on_new_submit(small_platform, small_workload, killer2_algorithm, redis_mode)86###############################################################################87# Kill jobs after a given delay, check that the given progress is consistent. #88###############################################################################89def kill_progress(platform, workload, algorithm, redis_mode, nb_kills_per_job, delay_before_kill):90 test_name = f'kill-{delay_before_kill.name}-{nb_kills_per_job.name}-{algorithm.name}-{platform.name}-{workload.name}-{redis_mode.name}'91 output_dir, robin_filename, schedconf_filename = init_instance(test_name)92 if algorithm.sched_implem != 'batsched': raise Exception('This test only supports batsched for now')93 batparams = "--forward-profiles-on-submission"94 if redis_mode.enabled == True: batparams = batparams + " --enable-redis"95 batcmd = gen_batsim_cmd(platform.filename, workload.filename, output_dir, batparams)96 schedconf_content = {97 "delay_before_kill": delay_before_kill.kill_delay,98 "nb_kills_per_job": nb_kills_per_job.kill_count_per_job,99 }100 write_file(schedconf_filename, json.dumps(schedconf_content))101 instance = RobinInstance(output_dir=output_dir,102 batcmd=batcmd,103 schedcmd=f"batsched -v '{algorithm.sched_algo_name}' --variant_options_filepath '{schedconf_filename}'",104 simulation_timeout=30, ready_timeout=5,105 success_timeout=10, failure_timeout=0106 )107 instance.to_file(robin_filename)108 ret = run_robin(robin_filename)109 if ret.returncode != 0: raise Exception(f'Bad robin return code ({ret.returncode})')110 # Read Batsim log file.111 batlog_filename = f'{output_dir}/log/batsim.log'112 batlog_content = open(batlog_filename, 'r').read()113 # Parse messages, then events.114 messages = parse_proto_messages_from_batsim(batlog_content)115 events = retrieve_proto_events(messages)116 # Filter JOB_KILLED events.117 kill_events = [e for e in events if e['type'] == 'JOB_KILLED']118 nb_err = 0119 for e in kill_events:120 job_data = e['data']121 if 'job_progress' not in job_data:122 print('Error: a job progress is missing!', job_data)123 nb_err = nb_err + 1124 #TODO test if this job is msg or delay of composed125 #and test the progress content type in regards126 if nb_err > 0:127 raise Exception('The progress of some killed jobs was missing.')128@pytest.mark.parametrize("nb_kills_per_job", [KillCountMode(f'{n}kills', n) for n in [1]])129@pytest.mark.parametrize("delay_before_kill", [KillDelayMode(f'after{n}', n) for n in [5]])130def test_kill_progress(small_platform, one_job_workload, killer_algorithm, redis_mode, nb_kills_per_job, delay_before_kill):...

Full Screen

Full Screen

restart-scenarios-test.py

Source:restart-scenarios-test.py Github

copy

Full Screen

1#!/usr/bin/env python32import testUtils3import argparse4import random5import signal6###############################################################7# Test for different nodes restart scenarios.8# Nodes can be producing or non-producing.9# -p <producing nodes count>10# -c <chain strategy[replay|resync|none]>11# -s <topology>12# -d <delay between nodes startup>13# -v <verbose logging>14# --kill-sig <kill signal [term|kill]>15# --kill-count <nodeos instances to kill>16# --dont-kill <Leave cluster running after test finishes>17# --dump-error-details <Upon error print etc/eosio/node_*/config.ini and var/lib/node_*/stderr.log to stdout>18# --keep-logs <Don't delete var/lib/node_* folders upon test completion>19###############################################################20Print=testUtils.Utils.Print21def errorExit(msg="", errorCode=1):22 Print("ERROR:", msg)23 exit(errorCode)24parser = argparse.ArgumentParser()25parser.add_argument("-p", type=int, help="producing nodes count", default=2)26parser.add_argument("-d", type=int, help="delay between nodes startup", default=1)27parser.add_argument("-s", type=str, help="topology", default="mesh")28parser.add_argument("-c", type=str, help="chain strategy[%s|%s|%s]" %29 (testUtils.Utils.SyncResyncTag, testUtils.Utils.SyncReplayTag, testUtils.Utils.SyncNoneTag),30 default=testUtils.Utils.SyncResyncTag)31parser.add_argument("--kill-sig", type=str, help="kill signal[%s|%s]" %32 (testUtils.Utils.SigKillTag, testUtils.Utils.SigTermTag), default=testUtils.Utils.SigKillTag)33parser.add_argument("--kill-count", type=int, help="nodeos instances to kill", default=-1)34parser.add_argument("-v", help="verbose logging", action='store_true')35parser.add_argument("--dont-kill", help="Leave cluster running after test finishes", action='store_true')36parser.add_argument("--dump-error-details",37 help="Upon error print etc/eosio/node_*/config.ini and var/lib/node_*/stderr.log to stdout",38 action='store_true')39parser.add_argument("--keep-logs", help="Don't delete var/lib/node_* folders upon test completion",40 action='store_true')41args = parser.parse_args()42pnodes=args.p43topo=args.s44delay=args.d45chainSyncStrategyStr=args.c46debug=args.v47total_nodes = pnodes48killCount=args.kill_count if args.kill_count > 0 else 149killSignal=args.kill_sig50killEosInstances= not args.dont_kill51dumpErrorDetails=args.dump_error_details52keepLogs=args.keep_logs53seed=154testUtils.Utils.Debug=debug55testSuccessful=False56random.seed(seed) # Use a fixed seed for repeatability.57cluster=testUtils.Cluster()58walletMgr=testUtils.WalletMgr(False)59try:60 cluster.setChainStrategy(chainSyncStrategyStr)61 cluster.setWalletMgr(walletMgr)62 cluster.killall()63 cluster.cleanup()64 Print ("producing nodes: %d, topology: %s, delay between nodes launch(seconds): %d, chain sync strategy: %s" % (65 pnodes, topo, delay, chainSyncStrategyStr))66 Print("Stand up cluster")67 if cluster.launch(pnodes, total_nodes, topo=topo, delay=delay) is False:68 errorExit("Failed to stand up eos cluster.")69 Print ("Wait for Cluster stabilization")70 # wait for cluster to start producing blocks71 if not cluster.waitOnClusterBlockNumSync(3):72 errorExit("Cluster never stabilized")73 accountsCount=total_nodes74 walletName="MyWallet"75 Print("Creating wallet %s if one doesn't already exist." % walletName)76 wallet=walletMgr.create(walletName)77 if wallet is None:78 errorExit("Failed to create wallet %s" % (walletName))79 Print ("Populate wallet with %d accounts." % (accountsCount))80 if not cluster.populateWallet(accountsCount, wallet):81 errorExit("Wallet initialization failed.")82 defproduceraAccount=cluster.defproduceraAccount83 Print("Importing keys for account %s into wallet %s." % (defproduceraAccount.name, wallet.name))84 if not walletMgr.importKey(defproduceraAccount, wallet):85 errorExit("Failed to import key for account %s" % (defproduceraAccount.name))86 Print("Create accounts.")87 #if not cluster.createAccounts(wallet):88 if not cluster.createAccounts(defproduceraAccount):89 errorExit("Accounts creation failed.")90 Print("Wait on cluster sync.")91 if not cluster.waitOnClusterSync():92 errorExit("Cluster sync wait failed.")93 # TBD: Known issue (Issue 2043) that 'get currency0000 balance' doesn't return balance.94 # Uncomment when functional95 # Print("Spread funds and validate")96 # if not cluster.spreadFundsAndValidate(10):97 # errorExit("Failed to spread and validate funds.")98 Print("Wait on cluster sync.")99 if not cluster.waitOnClusterSync():100 errorExit("Cluster sync wait failed.")101 Print("Kill %d cluster node instances." % (killCount))102 if cluster.killSomeEosInstances(killCount, killSignal) is False:103 errorExit("Failed to kill Eos instances")104 Print("nodeos instances killed.")105 # TBD: Known issue (Issue 2043) that 'get currency0000 balance' doesn't return balance.106 # Uncomment when functional107 # Print("Spread funds and validate")108 # if not cluster.spreadFundsAndValidate(10):109 # errorExit("Failed to spread and validate funds.")110 Print("Wait on cluster sync.")111 if not cluster.waitOnClusterSync():112 errorExit("Cluster sync wait failed.")113 Print ("Relaunch dead cluster nodes instances.")114 if cluster.relaunchEosInstances() is False:115 errorExit("Failed to relaunch Eos instances")116 Print("nodeos instances relaunched.")117 Print ("Resyncing cluster nodes.")118 if not cluster.waitOnClusterSync():119 errorExit("Cluster never synchronized")120 Print ("Cluster synched")121 # TBD: Known issue (Issue 2043) that 'get currency0000 balance' doesn't return balance.122 # Uncomment when functional123 # Print("Spread funds and validate")124 # if not cluster.spreadFundsAndValidate(10):125 # errorExit("Failed to spread and validate funds.")126 Print("Wait on cluster sync.")127 if not cluster.waitOnClusterSync():128 errorExit("Cluster sync wait failed.")129 testSuccessful=True130finally:131 if not testSuccessful and dumpErrorDetails:132 cluster.dumpErrorDetails()133 walletMgr.dumpErrorDetails()134 Print("== Errors see above ==")135 if killEosInstances:136 Print("Shut down the cluster%s" % (" and cleanup." if (testSuccessful and not keepLogs) else "."))137 cluster.killall()138 walletMgr.killall()139 if testSuccessful and not keepLogs:140 Print("Cleanup cluster and wallet data.")141 cluster.cleanup()142 walletMgr.cleanup()143 pass...

Full Screen

Full Screen

kill_ring.py

Source:kill_ring.py Github

copy

Full Screen

1import sublime_plugin, sublime2class KillRing:3 def __init__(self):4 self.limit = 165 self.buffer = [None for i in xrange(self.limit)]6 self.head = 07 self.len = 08 self.kill_points = []9 self.kill_id = 010 def top(self):11 return self.buffer[self.head]12 def seal(self):13 self.kill_points = []14 self.kill_id = 015 def push(self, text):16 self.head = (self.head + 1) % self.limit17 self.buffer[self.head] = text18 if self.len < self.limit:19 self.len += 120 def add(self, view_id, text, regions, forward):21 if view_id != self.kill_id:22 # view has changed, ensure the last kill ring entry will not be23 # appended to24 self.seal()25 begin_points = []26 end_points = []27 for r in regions:28 begin_points.append(r.begin())29 end_points.append(r.end())30 if forward:31 compare_points = begin_points32 else:33 compare_points = end_points34 if compare_points == self.kill_points:35 # Selection hasn't moved since the last kill, append/prepend the36 # text to the current entry37 if forward:38 self.buffer[self.head] = self.buffer[self.head] + text39 else:40 self.buffer[self.head] = text + self.buffer[self.head]41 else:42 # Create a new entry in the kill ring for this text43 self.push(text)44 self.kill_points = begin_points45 self.kill_id = view_id46 def get(self, index):47 return self.buffer[(self.head + index) % self.limit]48 def __len__(self):49 return self.len50kill_ring = KillRing()51class YankCommand(sublime_plugin.TextCommand):52 def run(self, edit):53 kill_ring.seal()54 text = kill_ring.top()55 lines = text.splitlines()56 regions = [r for r in self.view.sel()]57 regions.reverse()58 if len(regions) > 1 and len(regions) == len(lines):59 # insert one line from the top of the kill ring at each60 # corresponding selection61 for i in xrange(len(regions)):62 s = regions[i]63 line = lines[i]64 num = self.view.insert(edit, s.begin(), line)65 self.view.erase(edit, sublime.Region(s.begin() + num,66 s.end() + num))67 else:68 # insert the top of the kill ring at each selection69 for s in regions:70 num = self.view.insert(edit, s.begin(), text)71 self.view.erase(edit, sublime.Region(s.begin() + num,72 s.end() + num))73 def is_enabled(self):74 return len(kill_ring) > 075class AddToKillRingCommand(sublime_plugin.TextCommand):76 def run(self, edit, forward):77 delta = 178 if not forward:79 delta = -180 text = []81 regions = []82 for s in self.view.sel():83 if s.empty():84 s = sublime.Region(s.a, s.a + delta)85 text.append(self.view.substr(s))86 regions.append(s)...

Full Screen

Full Screen

test_mozprocess_kill.py

Source:test_mozprocess_kill.py Github

copy

Full Screen

...8here = os.path.dirname(os.path.abspath(__file__))9class ProcTestKill(proctest.ProcTest):10 """ Class to test various process tree killing scenatios """11 def test_kill_before_run(self):12 """Process is not started, and kill() is called"""13 p = processhandler.ProcessHandler([self.python, '-V'])14 self.assertRaises(RuntimeError, p.kill)15 def test_process_kill(self):16 """Process is started, we kill it"""17 p = processhandler.ProcessHandler([self.python, self.proclaunch, "process_normal_finish_python.ini"],18 cwd=here)19 p.run()20 p.kill()21 self.determine_status(p, expectedfail=('returncode',))22 def test_process_kill_deep(self):23 """Process is started, we kill it, we use a deep process tree"""24 p = processhandler.ProcessHandler([self.python, self.proclaunch, "process_normal_deep_python.ini"],25 cwd=here)26 p.run()27 p.kill()28 self.determine_status(p, expectedfail=('returncode',))29 def test_process_kill_deep_wait(self):30 """Process is started, we use a deep process tree, we let it spawn31 for a bit, we kill it"""32 p = processhandler.ProcessHandler([self.python, self.proclaunch, "process_normal_deep_python.ini"],33 cwd=here)34 p.run()35 # Let the tree spawn a bit, before attempting to kill36 time.sleep(3)37 p.kill()38 self.determine_status(p, expectedfail=('returncode',))39 def test_process_kill_broad(self):40 """Process is started, we kill it, we use a broad process tree"""41 p = processhandler.ProcessHandler([self.python, self.proclaunch, "process_normal_broad_python.ini"],42 cwd=here)43 p.run()44 p.kill()45 self.determine_status(p, expectedfail=('returncode',))46 @unittest.skipUnless(processhandler.isPosix, "posix only")47 def test_process_kill_with_sigterm(self):48 script = os.path.join(here, 'infinite_loop.py')49 p = processhandler.ProcessHandler([self.python, script])50 p.run()51 p.kill()52 self.assertEquals(p.proc.returncode, -signal.SIGTERM)53 @unittest.skipUnless(processhandler.isPosix, "posix only")54 def test_process_kill_with_sigint_if_needed(self):55 script = os.path.join(here, 'infinite_loop.py')56 p = processhandler.ProcessHandler([self.python, script, 'deadlock'])57 p.run()58 time.sleep(1)59 p.kill()60 self.assertEquals(p.proc.returncode, -signal.SIGKILL)61if __name__ == '__main__':...

Full Screen

Full Screen

test_kill_chain_phases.py

Source:test_kill_chain_phases.py Github

copy

Full Screen

1"""Tests for stix.ExternalReference"""2import pytest3import stix24LMCO_RECON = """{5 "kill_chain_name": "lockheed-martin-cyber-kill-chain",6 "phase_name": "reconnaissance"7}"""8def test_lockheed_martin_cyber_kill_chain():9 recon = stix2.KillChainPhase(10 kill_chain_name="lockheed-martin-cyber-kill-chain",11 phase_name="reconnaissance",12 )13 assert str(recon) == LMCO_RECON14FOO_PRE_ATTACK = """{15 "kill_chain_name": "foo",16 "phase_name": "pre-attack"17}"""18def test_kill_chain_example():19 preattack = stix2.KillChainPhase(20 kill_chain_name="foo",21 phase_name="pre-attack",22 )23 assert str(preattack) == FOO_PRE_ATTACK24def test_kill_chain_required_properties():25 with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:26 stix2.KillChainPhase()27 assert excinfo.value.cls == stix2.KillChainPhase28 assert excinfo.value.properties == ["kill_chain_name", "phase_name"]29def test_kill_chain_required_property_chain_name():30 with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:31 stix2.KillChainPhase(phase_name="weaponization")32 assert excinfo.value.cls == stix2.KillChainPhase33 assert excinfo.value.properties == ["kill_chain_name"]34def test_kill_chain_required_property_phase_name():35 with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:36 stix2.KillChainPhase(kill_chain_name="lockheed-martin-cyber-kill-chain")37 assert excinfo.value.cls == stix2.KillChainPhase...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.waitFor(5000);6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch({headless: false});11 const page = await browser.newPage();12 await page.waitFor(5000);13 await browser.close();14})();15const puppeteer = require('puppeteer');16(async () => {17 const browser = await puppeteer.launch({headless: false});18 const page = await browser.newPage();19 await page.waitFor(5000);20 await browser.close();21})();22const puppeteer = require('puppeteer');23(async () => {24 const browser = await puppeteer.launch({headless: false});25 const page = await browser.newPage();26 await page.waitFor(5000);27 await browser.close();28})();29const puppeteer = require('puppeteer');30(async () => {31 const browser = await puppeteer.launch({headless: false});32 const page = await browser.newPage();33 await page.waitFor(5000);34 await browser.close();35})();36const puppeteer = require('puppeteer');37(async () => {38 const browser = await puppeteer.launch({headless: false});39 const page = await browser.newPage();40 await page.waitFor(5000);41 await browser.close();42})();43const puppeteer = require('puppeteer');44(async () => {45 const browser = await puppeteer.launch({headless: false});

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.waitFor(5000);6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch({headless: false});11 const page = await browser.newPage();12 await page.waitFor(5000);13 await browser.close();14})();15const puppeteer = require('puppeteer');16(async () => {17 const browser = await puppeteer.launch({headless: false});18 const page = await browser.newPage();19 await page.waitFor(5000);20 await browser.close();21})();22const puppeteer = require('puppeteer');23(async () => {24 const browser = await puppeteer.launch({headless: false});25 const page = await browser.newPage();26 await page.waitFor(5000);27 await browser.close();28})();29const puppeteer = require('puppeteer');30(async () => {31 const browser = await puppeteer.launch({headless: false});32 const page = await browser.newPage();33 await page.waitFor(5000);34 await browser.close();35})();36const puppeteer = require('puppeteer');37(async () => {38 const browser = await puppeteer.launch({headless: false});39 const page = await browser.newPage();40 await page.waitFor(5000);41 await browser.close();42})();43const puppeteer = require('puppeteer');44(async () => {45 const browser = await puppeteer.launch({headless: false});46 const page = await browser.newPage();47 await page.waitFor(5000);48 await browser.close();49})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.waitFor(2000);6 await browser.close();7})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const page = await browser.newPage();6 await page.type('input[title="Search"]', 'puppeteer');7 await page.keyboard.press('Enter');8 await page.waitForNavigation();9 await page.screenshot({ path: 'example.png' });10 await browser.close();11})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.waitFor(5000);6 await browser.close();7})();8const puppeteer = require('puppeteer');9const PuppeteerCluster = require('puppeteer-cluster');10(async () => {11 const cluster = await PuppeteerCluster.launch({12 });13 cluster.on('taskerror', (err, data) => {14 console.log(`Error crawling ${data}: ${err.message}`);15 });16 await cluster.task(async ({ page, data: url }) => {17 await page.goto(url);18 await page.waitFor(5000);19 });20 await cluster.idle();21 await cluster.close();22})();23const puppeteer = require('puppeteer');24const PuppeteerPool = require('puppeteer-pool');25(async () => {26 const pool = new PuppeteerPool({27 puppeteerArgs: {28 },29 });30 await pool.use(async (browser) => {31 const page = await browser.newPage();32 await page.waitFor(5000);33 });34 await pool.drain();35 await pool.clear();36})();37const puppeteer = require('puppeteer');38const { PuppeteerCrawler } = require('apify');39(async () => {40 const crawler = new PuppeteerCrawler({41 handlePageFunction: async ({ request, page }) => {42 await page.goto(request.url);43 await page.waitFor(5000);44 },45 });46 await crawler.run();47})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3(async () => {4 const browser = await puppeteer.launch({5 });6 const page = await browser.newPage();7 await page.screenshot({path: 'google.png'});8 await browser.close();9})();10const { exec } = require('child_process');11exec('killall -9 node', (err, stdout, stderr) => {12 if (err) {13 console.error(err)14 } else {15 console.log(`stdout: ${stdout}`);16 console.log(`stderr: ${stderr}`);17 }18});19const { exec } = require('child_process');20exec('killall -9 node', (err, stdout, stderr) => {21 if (err) {22 console.error(err)23 } else {24 console.log(`stdout: ${stdout}`);25 console.log(`stderr: ${stderr}`);26 }27});28const { exec } = require('child_process');29exec('killall -9 node', (err, stdout, stderr) => {30 if (err) {31 console.error(err)32 } else {33 console.log(`stdout: ${stdout}`);34 console.log(`stderr: ${stderr}`);35 }36});37const { exec } = require('child_process');38exec('killall -9 node', (err, stdout, stderr) => {39 if (err) {40 console.error(err)41 } else {42 console.log(`stdout: ${stdout}`);43 console.log(`stderr: ${stderr}`);44 }45});46const { exec } = require('child_process');47exec('killall -9 node', (err, stdout, stderr) => {48 if (

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2async function main() {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await browser.close();6}7main();8const chromeLauncher = require('chrome-launcher');9async function main() {10 const chrome = await chromeLauncher.launch({11 });12 console.log(resp);13}14main();15const Chromeless = require('chromeless').Chromeless;16async function main() {17 const chromeless = new Chromeless();18 await chromeless.end();19}20main();21const Nightmare = require('nightmare');22const nightmare = Nightmare({ show: true });23 .end()24 .then(function(result) {25 console.log(result);26 })27 .catch(function(error) {28 console.error('Search failed:', error);29 });30const Zombie = require('zombie');31browser = new Zombie();32 browser.window.close();33});34var casper = require('casper').create();35 this.echo(this.getTitle());36});37casper.run(function() {38 this.exit();39});40var phantom = require('phantom');41phantom.create(function(ph) {42 ph.createPage(function(page) {43 console.log('opened site? ', status);44 ph.exit();45 });46 });47});48var page = require('webpage').create();49 console.log('opened site? ', status);50 phantom.exit();51});52var webdriver = require('selenium-webdriver');53var driver = new webdriver.Builder()54 .forBrowser('phantomjs')55 .build();

Full Screen

Using AI Code Generation

copy

Full Screen

1(async () => {2 const browser = await puppeteer.launch();3 const page = await browser.newPage();4 await page.waitFor(5000);5 await browser.close();6})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const browser = await puppeteer.launch({headless: false});3const page = await browser.newPage();4await page.screenshot({path: 'google.png'});5await browser.close();6const puppeteer = require('puppeteer');7const browser = await puppeteer.launch({headless: false});8const page = await browser.newPage();9await page.screenshot({path: 'google.png'});10await browser.close();11const puppeteer = require('puppeteer');12const browser = await puppeteer.launch({headless: false});13const page = await browser.newPage();14await page.screenshot({path: 'google.png'});15await browser.close();16const puppeteer = require('puppeteer');17const browser = await puppeteer.launch({headless: false});18const page = await browser.newPage();19await page.screenshot({path: 'google.png'});20await browser.close();21const puppeteer = require('puppeteer');22const browser = await puppeteer.launch({headless: false});23const page = await browser.newPage();24await page.screenshot({path: 'google.png'});25await browser.close();26const puppeteer = require('puppeteer');27const browser = await puppeteer.launch({headless: false});28const page = await browser.newPage();29await page.screenshot({path: 'google.png'});30await browser.close();31const puppeteer = require('puppeteer');32const browser = await puppeteer.launch({headless: false});33const page = await browser.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const process = require('process');3const os = require('os');4const platform = os.platform();5const { exec } = require('child_process');6const kill = async (platform, processName) => {7 switch (platform) {8 exec(`taskkill /F /IM ${processName}.exe`);9 break;10 exec(`pkill -f ${processName}`);11 break;12 exec(`pkill -f ${processName}`);13 break;14 break;15 }16};17(async () => {18 const browser = await puppeteer.launch({19 });20 const page = await browser.newPage();21 await page.waitFor(3000);22 await kill(platform, 'chrome');23})();24console.log('This message will be printed!');25const puppeteer = require('puppeteer');26const process = require('process');27const os = require('os');28const platform = os.platform();29const { exec } = require('child_process');30const kill = async (platform, processName) => {31 switch (platform) {32 exec(`taskkill /F /IM ${processName}.exe`);33 break;34 exec(`pkill -f ${processName}`);35 break;36 exec(`pkill -f ${processName}`);37 break;38 break;39 }40};41(async () => {42 const browser = await puppeteer.launch({43 });

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful