Best Python code snippet using autotest_python
test_ir.py
Source:test_ir.py
...16TIMEOUT = 1517class IRkernelTests(jkt.KernelTests):18 kernel_name = 'testir'19 language_name = 'R'20 def _execute_code(self, code, tests=True, silent=False, store_history=True):21 self.flush_channels()22 reply, output_msgs = self.execute_helper(code, silent=silent, store_history=store_history)23 self.assertEqual(reply['content']['status'], 'ok', '{0}: {0}'.format(reply['content'].get('ename'), reply['content'].get('evalue')))24 if tests:25 self.assertGreaterEqual(len(output_msgs), 1)26 # the irkernel only sends display_data, not execute_results27 self.assertEqual(output_msgs[0]['msg_type'], 'display_data')28 return reply, output_msgs29 code_hello_world = 'print("hello, world")'30 completion_samples = [31 {32 'text': 'zi',33 'matches': {'zip'},34 },35 ]36 complete_code_samples = ['1', 'print("hello, world")', 'f <- function(x) {\n x*2\n}']37 incomplete_code_samples = ['print("hello', 'f <- function(x) {\n x*2']38 code_display_data = [39 {'code': '"a"', 'mime': 'text/plain'},40 {'code': '"a"', 'mime': 'text/html'},41 {'code': '"a"', 'mime': 'text/latex'},42 {'code': '1:3', 'mime': 'text/plain'},43 {'code': '1:3', 'mime': 'text/html'},44 {'code': '1:3', 'mime': 'text/latex'},45 {'code': without_rich_display.format('"a"'), 'mime': 'text/plain'},46 {'code': without_rich_display.format('1:3'), 'mime': 'text/plain'},47 ]48 def test_display_vector(self):49 """display of vectors"""50 code = '1:3'51 reply, output_msgs = self._execute_code(code)52 53 # we currently send those formats: text/plain, text/html, text/latex, and text/markdown54 data = output_msgs[0]['content']['data']55 self.assertEqual(len(data), 4, data.keys())56 self.assertEqual(data['text/plain'], '[1] 1 2 3')57 self.assertIn('text/html', data)58 59 # this should not be a test of the repr functionality...60 self.assertIn('</li>', output_msgs[0]['content']['data']['text/html'])61 self.assertIn('text/latex', output_msgs[0]['content']['data'])62 self.assertIn('text/markdown', output_msgs[0]['content']['data'])63 def test_display_vector_only_plaintext(self):64 """display of plain text vectors"""65 code = without_rich_display.format('1:3')66 reply, output_msgs = self._execute_code(code)67 data = output_msgs[0]['content']['data']68 self.assertEqual(len(data), 1, data.keys())69 self.assertEqual(data['text/plain'], '[1] 1 2 3')70 def test_irkernel_plots(self):71 """plotting"""72 code = 'plot(1:3)'73 reply, output_msgs = self._execute_code(code)74 75 # we currently send two formats: png, and text/plain76 data = output_msgs[0]['content']['data']77 self.assertEqual(len(data), 2, data.keys())78 self.assertEqual(data['text/plain'], 'plot without title')79 self.assertIn('image/png', data)80 81 # we isolate only svg plots, which are not included in the default types82 metadata = output_msgs[0]['content']['metadata']83 self.assertEqual(len(metadata), 0, metadata.keys())84 def test_irkernel_plots_only_PNG(self):85 """plotting PNG"""86 # the reset needs to happen in another execute because plots are sent after either87 # the next plot is opened or everything is executed, not at the time when plot88 # command is actually happening.89 # (we have a similar problem with width/... but we worked around it by setting the90 # appropriate options to the recorderdplot object)91 code = '''\92 old_options <- options(jupyter.plot_mimetypes = c('image/png'))93 plot(1:3)94 '''95 reply, output_msgs = self._execute_code(code)96 97 # Only png, no svg or plain/text98 data = output_msgs[0]['content']['data']99 self.assertEqual(len(data), 1, data.keys())100 self.assertIn('image/png', data)101 # nothing in metadata102 metadata = output_msgs[0]['content']['metadata']103 self.assertEqual(len(metadata), 0, metadata.keys())104 # And reset105 code = 'options(old_options)'106 reply, output_msgs = self._execute_code(code, tests=False)107 def test_irkernel_plots_only_SVG(self):108 # again the reset dance (see PNG)109 code = '''\110 old_options <- options(jupyter.plot_mimetypes = c('image/svg+xml'))111 plot(1:3)112 '''113 reply, output_msgs = self._execute_code(code)114 # Only svg, no png or plain/text115 data = output_msgs[0]['content']['data']116 self.assertEqual(len(data), 1, data.keys())117 self.assertIn('image/svg+xml', data)118 119 # svg output is currently isolated120 metadata = output_msgs[0]['content']['metadata']121 self.assertEqual(len(metadata), 1, metadata.keys())122 self.assertEqual(len(metadata['image/svg+xml']), 1)123 self.assertEqual(metadata['image/svg+xml']['isolated'], True)124 # And reset125 code = 'options(old_options)'126 reply, output_msgs = self._execute_code(code, tests=False)127 def test_irkernel_plots_without_rich_display(self):128 code = '''\129 options(jupyter.rich_display = FALSE)130 plot(1:3)131 '''132 reply, output_msgs = self._execute_code(code)133 # Even with rich output as false, we send plots134 data = output_msgs[0]['content']['data']135 self.assertEqual(len(data), 2, data.keys())136 self.assertEqual(data['text/plain'], 'plot without title')137 self.assertIn('image/png', data)138 # And reset139 code = 'options(jupyter.rich_display = TRUE)'140 reply, output_msgs = self._execute_code(code, tests=False)141 def test_irkernel_df_default_rich_output(self):142 """data.frame rich representation"""143 code = 'data.frame(x = 1:3)'144 reply, output_msgs = self._execute_code(code)145 146 # we currently send three formats: text/plain, html, and latex147 data = output_msgs[0]['content']['data']148 self.assertEqual(len(data), 4, data.keys())149 def test_irkernel_df_no_rich_output(self):150 """data.frame plain representation"""151 code = '''152 options(jupyter.rich_display = FALSE)153 data.frame(x = 1:3)154 options(jupyter.rich_display = TRUE)155 '''156 reply, output_msgs = self._execute_code(code)157 158 # only text/plain159 data = output_msgs[0]['content']['data']160 self.assertEqual(len(data), 1, data.keys())161 def test_html_isolated(self):162 """HTML isolation"""163 code = '''164 repr_html.full_page <- function(obj) sprintf('<html><body>%s</body></html>', obj)165 structure(0, class = 'full_page')166 '''167 reply, output_msgs = self._execute_code(code)168 169 data = output_msgs[0]['content']['data']170 self.assertEqual(len(data), 2, data.keys())171 self.assertEqual(data['text/html'], '<html><body>0</body></html>')172 173 metadata = output_msgs[0]['content']['metadata']174 self.assertEqual(len(metadata), 1, metadata.keys())175 self.assertEqual(len(metadata['text/html']), 1, metadata['text/html'].keys())176 self.assertEqual(metadata['text/html']['isolated'], True)177 def test_in_kernel_set(self):178 """jupyter.in_kernel option"""179 reply, output_msgs = self._execute_code('getOption("jupyter.in_kernel")')180 data = output_msgs[0]['content']['data']181 self.assertGreaterEqual(len(data), 1, data.keys())182 self.assertEqual(data['text/plain'], '[1] TRUE', data.keys())183 184 def test_warning_message(self):185 self.flush_channels()186 reply, output_msgs = self.execute_helper('warning(simpleWarning("wmsg"))')187 self.assertEqual(output_msgs[0]['msg_type'], 'stream')188 self.assertEqual(output_msgs[0]['content']['name'], 'stderr')189 self.assertEqual(output_msgs[0]['content']['text'], 'Warning message:\nâwmsgâ')190 191 self.flush_channels()192 reply, output_msgs = self.execute_helper('f <- function() warning("wmsg"); f()')193 self.assertEqual(output_msgs[0]['msg_type'], 'stream')194 self.assertEqual(output_msgs[0]['content']['name'], 'stderr')195 self.assertEqual(output_msgs[0]['content']['text'], 'Warning message in f():\nâwmsgâ')196 def test_should_increment_history(self):197 """properly increments execution history"""198 code = 'data.frame(x = 1:3)'199 reply, output_msgs = self._execute_code(code)200 reply2, output_msgs2 = self._execute_code(code)201 execution_count_1 = reply['content']['execution_count']202 execution_count_2 = reply2['content']['execution_count']203 self.assertEqual(execution_count_1 + 1, execution_count_2)204 def test_should_not_increment_history(self):205 """Does not increment history if silent is true or store_history is false"""206 code = 'data.frame(x = 1:3)'207 reply, output_msgs = self._execute_code(code, store_history=False)208 reply2, output_msgs2 = self._execute_code(code, store_history=False)209 reply3, output_msgs3 = self._execute_code(code, tests=False, silent=True)210 execution_count_1 = reply['content']['execution_count']211 execution_count_2 = reply2['content']['execution_count']212 execution_count_3 = reply3['content']['execution_count']213 self.assertEqual(execution_count_1, execution_count_2)214 self.assertEqual(execution_count_1, execution_count_3)215 def test_irkernel_inspects(self):216 """Test if object inspection works."""217 self.flush_channels()218 def test_token_is_ok(token, preprocess=None, postprocess=None):219 """Check if inspect_request for the `token` returns a reply.220 Run code in `preprocess` before requesting if it's given,221 and `proprocess` after requesting.222 Currently just test if the kernel replys without an error223 and not care about its content.224 Because the contents of inspections are still so arguable.225 When the requirements for the contents are decided,226 fix the tests beow and check the contents.227 """228 if preprocess:229 self._execute_code(preprocess, tests=False)230 msg_id = self.kc.inspect(token)231 reply = self.kc.get_shell_msg(timeout=TIMEOUT)232 validate_message(reply, 'inspect_reply', msg_id)233 self.assertEqual(reply['content']['status'], 'ok')234 self.assertTrue(reply['content']['found'])235 self.assertGreaterEqual(len(reply['content']['data']), 1)236 if postprocess:237 self._execute_code(postprocess, tests=False)238 # Numeric constant239 test_token_is_ok('1')240 # Reserved word241 test_token_is_ok('NULL')242 # Dataset with a help document243 test_token_is_ok('iris')244 # Function with a help document245 test_token_is_ok('c')246 # Function name with namespace247 test_token_is_ok('base::c')248 # Function not exported from namespace249 test_token_is_ok('tools:::.Rd2pdf')250 # User-defined variable251 test_token_is_ok(...
handeld.py
Source:handeld.py
1from typing import List, Tuple2def _execute_code(code: List[str]) -> Tuple[int, int]:3 accu, register, current_index = 0, list(), 04 while current_index < len(code):5 instr, val = code[current_index].split(' ')6 val = int(val)7 if current_index in register:8 return accu, False9 register.append(current_index)10 current_index += val if instr == 'jmp' else 111 accu += val if instr == 'acc' else 012 return accu, True13def compute_accumulator_value(filename: str) -> int:14 with open(filename, 'r') as f:15 instructions = f.readlines()16 return _execute_code(instructions)[0]17def compute_final_value_debugged_code(filename: str) -> int:18 with open(filename, 'r') as f:19 instructions = f.readlines()20 candidates = [(i, v) for i, v in enumerate(instructions) if 'nop' in v or 'jmp' in v]21 accu, ok = _execute_code(instructions)22 for c, v in candidates:23 inst, _ = v.split(' ')24 cinst = instructions.copy()25 if inst == 'jmp':26 cinst[c] = v.replace('jmp', 'nop')27 else:28 cinst[c] = v.replace('nop', 'jmp')29 accu, ok = _execute_code(cinst)30 if ok:31 break...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!