Best Python code snippet using unittest-xml-reporting_python
executor.py
Source:executor.py  
1import klib.math2import klib.environment3from klib.bytecode import opcodes4from .stack   import stack5from klib.io import stdout6import klib.interpreter.kl_exception7import klib.exception8from klib.interpreter.kl_exception import kl_exception, kl_return9from klib.environment.environment import unknown_cell10class executor_context:11  def __init__(self, program, environment):12    self.program          = program13    self.environment      = environment14    self.current_index    = 015    self.stack            = stack()16    self.exceptions_stack = stack()17class exception_context:18  def __init__(self, index):19    self.index = index20class executor:21  opmaps = {}22  def __init__(self):23    self.current_context = None24    self.execution_stack = stack()25    if(len(executor.opmaps) == 0):26      # Stack27      executor.opmaps[opcodes.PUSH] = executor.execute_push28      executor.opmaps[opcodes.POP] = executor.execute_pop29      executor.opmaps[opcodes.DUP] = executor.execute_dup30      executor.opmaps[opcodes.SWAP] = executor.execute_swap31      executor.opmaps[opcodes.PUSH_ENV] = executor.execute_push_env32      executor.opmaps[opcodes.NEW_ENV] = executor.execute_new_env33      executor.opmaps[opcodes.DROP_ENV] = executor.execute_drop_env34      executor.opmaps[opcodes.MAKE_REF] = executor.execute_make_ref35      executor.opmaps[opcodes.STORE] = executor.execute_store36      executor.opmaps[opcodes.DCL_CELL] = executor.execute_dcl_cell37      executor.opmaps[opcodes.DEF_VALUE] = executor.execute_def_value38      executor.opmaps[opcodes.CLEAR] = executor.execute_clear39      executor.opmaps[opcodes.PUSH_CALL_TRACE] = executor.execute_push_call_trace40      executor.opmaps[opcodes.JMP] = executor.execute_jmp41      executor.opmaps[opcodes.IFJMP] = executor.execute_ifjmp42      executor.opmaps[opcodes.UNLESSJMP] = executor.execute_unlessjmp43      executor.opmaps[opcodes.RET] = executor.execute_ret44      executor.opmaps[opcodes.NATIVE_CALL] = executor.execute_native_call45      executor.opmaps[opcodes.CALL] = executor.execute_call46      executor.opmaps[opcodes.TRY_PUSH] = executor.execute_try_push47      executor.opmaps[opcodes.TRY_POP] = executor.execute_try_pop48      executor.opmaps[opcodes.THROW] = executor.execute_throw49      executor.opmaps[opcodes.MAKE_FUNC] = executor.execute_make_func50      executor.opmaps[opcodes.ADD] = executor.execute_add51      executor.opmaps[opcodes.SUB] = executor.execute_sub52      executor.opmaps[opcodes.DIV] = executor.execute_div53      executor.opmaps[opcodes.MUL] = executor.execute_mul54      executor.opmaps[opcodes.MOD] = executor.execute_mod55      executor.opmaps[opcodes.LEFT_SHIFT] = executor.execute_left_shift56      executor.opmaps[opcodes.RIGHT_SHIFT] = executor.execute_right_shift57      executor.opmaps[opcodes.UNSIGNED_RIGHT_SHIFT] = executor.execute_unsigned_right_shift58      executor.opmaps[opcodes.GREATER] = executor.execute_greater59      executor.opmaps[opcodes.GREATER_EQUAL] = executor.execute_greater_equal60      executor.opmaps[opcodes.LESS] = executor.execute_less61      executor.opmaps[opcodes.LESS_EQUAL] = executor.execute_less_equal62      executor.opmaps[opcodes.EQUAL] = executor.execute_equal63      executor.opmaps[opcodes.DIFFERENT] = executor.execute_different64      executor.opmaps[opcodes.AND] = executor.execute_and65      executor.opmaps[opcodes.OR] = executor.execute_or66      executor.opmaps[opcodes.NEG] = executor.execute_neg67      executor.opmaps[opcodes.TILDE] = executor.execute_tilde68      executor.opmaps[opcodes.NOT] = executor.execute_not69  def __pop_value(self):70    value = self.current_context.stack.pop()71    while isinstance(value, klib.environment.reference):72      value = value.environment.get(value.name)73    while isinstance(value, klib.environment.cell.cell) or isinstance(value, klib.environment.value.value):74      value = value.get_value()75    return value76  def execute(self, program, environment = klib.environment.environment(), caller_metadata = None, verbose = False, return_stack = False):77    self.current_context = executor_context(program, environment)78    self.caller_metadata = caller_metadata79    if verbose:80      program.print()81    while(self.current_context.current_index < len(self.current_context.program.instructions)):82      inst = self.current_context.program.instructions[self.current_context.current_index]83      if verbose:84        stdout.writeln("===== In context level: {}", len(self.execution_stack))85        stdout.write("{}: {} ({})", self.current_context.current_index, inst.opcode.name, inst.opcode.index)86        for k in inst.params:87          stdout.write(" {}={}", k, inst.params[k])88        stdout.writeln("")89        self.current_context.stack.print()90      #print(inst.opcode.name)91      f = executor.opmaps[inst.opcode]92      r = f(self, **inst.params)93      self.current_context.current_index += 194    if(len(self.execution_stack) != 0):95      raise Exception("execution stack is not empty")96    if return_stack:97      return self.current_context.stack.stack98    if(len(self.current_context.stack) > 0):99      return self.__pop_value()100  def execute_push(self, value):101    self.current_context.stack.push(value)102  def execute_dup(self):103    self.current_context.stack.dup()104  def execute_swap(self):105    self.current_context.stack.swap()106  def execute_pop(self, count = 1):107    for i in range(0, count):108      self.current_context.stack.pop()109     # reference.enviroment = self.current_context.enviroment110     #111  def execute_push_env(self):112    self.current_context.stack.push(self.current_context.environment)113  def execute_new_env(self):114    self.current_context.environment = klib.environment.environment(self.current_context.environment)115  def execute_drop_env(self):116    self.current_context.environment = self.current_context.environment.parent117  def execute_make_ref(self, name=None):118    if name == None:119      name = self.current_context.stack.pop()120    #  Pusha en ny reference till stacken, dens environment blir det längst upp på den nuvarande stacken.121    self.current_context.stack.push(klib.environment.reference(self.current_context.stack.pop(), name))122  def execute_store(self, name=None):123    value = self.current_context.stack.pop()124    # Hämta environmentet vi ska hantera, antingen från en referens ifall name = None, annars det som finns längst upp på stacken.125    environment = None126    if name == None:127      reference = self.current_context.stack.pop()128      environment = reference.environment129      name = reference.name130    else:131      environment = self.current_context.stack.pop()132    # Ifall value är en referense måste vi avreferera det och hämta dens riktiga värde.133    while isinstance(value, klib.environment.reference):134      value = value.environment.get(value.name)135    # Ifall value är en cell måste vi hämta dens numreriska värde.136    while isinstance(value, klib.environment.cell.cell):137      value = value.get_value()138    # Uppdatera värdet på cellen om den finns annars definiera en ny.139    try:140      cell = environment.get(name)141      cell.set_value(value)142    except unknown_cell as e:143      environment.define_cell(name, value)144    # Pusha det refererade värdet till stacken.145    self.execute_push(value)146  def execute_dcl_cell(self, name):147    #self.current_context.environment.define_cell(name, self.current_context.stack.pop())148    self.current_context.stack.pop().define_cell(name)149  def execute_def_value(self, name):150    value = self.current_context.stack.pop()151    env = self.current_context.stack.pop()152    env.define_value(name, value)153  def execute_clear(self, name=None):154    # Ifall vi inte gett ett namn cleara referencens namn i referencens environment.155    if name == None:156      ref = self.current_context.stack.pop()157      name = ref.name158      env = ref.environment159    else:160      env = self.current_context.stack.pop()161    env.clear(name)162    self.execute_push(None)163  def execute_push_call_trace(self):164    metadata = klib.parser.metadata(self.current_context.current_index, 0, None, None, self.current_context.environment.parent)165    self.execute_push([metadata])166  def execute_jmp(self, index):167    self.current_context.current_index = index-1168  def execute_ifjmp(self, index):169    if self.current_context.stack.pop():170      self.execute_jmp(index)171  def execute_unlessjmp(self, index):172    if not self.current_context.stack.pop():173      self.execute_jmp(index)174  def execute_ret(self):175    # Sätt current_index till slutet av programmet så inget mer exekveras.176    self.current_context.current_index = len(self.current_context.program.instructions)177  def execute_native_call(self, native_function, count):178    args = []179    for i in range(count):180      args.append(self.current_context.stack.pop())181    self.execute_push(native_function(*args))182  def execute_call(self, count):183    func = self.current_context.stack.pop()184    args = []185    for i in range(count):186      args.append(self.current_context.stack.pop())187    env, program = func.prepare_call(args)188    self.execute_push(*self.execute(program, env))189  def execute_try_push(self, index):190    self.current_context.exceptions_stack.push(index)191  def execute_try_pop(self):192    self.current_context.exceptions_stack.pop()193  def execute_throw(self):194    # Hoppa till första indexet i exceoptions_stack ifall det finns, annars throw kl_exception195    index = None196    try:197      index = self.current_context.exceptions_stack.stack[0]198      self.execute_jmp(index)199    except IndexError as e:200      raise kl_exception("No jmp index on the exception stack")201  def execute_make_func(self, body, argument_names, modifiers):202    self.execute_push(klib.environment.function(argument_names, body, self.current_context.environment))203  def execute_add(self):204    self.execute_push(self.current_context.stack.pop() + self.current_context.stack.pop())205  def execute_sub(self):206    v2 = self.current_context.stack.pop()207    v1 = self.current_context.stack.pop()208    self.execute_push(v1 - v2)209  def execute_div(self):210    v2 = self.current_context.stack.pop()211    v1 = self.current_context.stack.pop()212    self.execute_push(v1 / v2)213  def execute_mul(self):214    self.execute_push(self.current_context.stack.pop() * self.current_context.stack.pop())215  def execute_mod(self):216    v2 = self.current_context.stack.pop()217    v1 = self.current_context.stack.pop()218    self.execute_push(v1 % v2)219  def execute_left_shift(self):220    v2 = self.current_context.stack.pop()221    v1 = self.current_context.stack.pop()222    # v1 << v2 = v1 * pow(2,v2)223    self.execute_push(int(v1 * (2 ** v2)))224  def execute_right_shift(self):225    v2 = self.current_context.stack.pop()226    v1 = self.current_context.stack.pop()227    # v1 >> v2 = v1 / pow(2,v2)228    self.execute_push(int(v1 / (2 ** v2)))229  def execute_unsigned_right_shift(self):230    v2 = self.current_context.stack.pop()231    v1 = self.current_context.stack.pop()232    # Unsigned right shift = push 0 to the left of the binary representation of the number.233    self.execute_push(int(v1 % 0x100000000) >> int(v2))234  def execute_greater(self):235    v2 = self.current_context.stack.pop()236    v1 = self.current_context.stack.pop()237    self.execute_push(v1 > v2)238  def execute_greater_equal(self):239    v2 = self.current_context.stack.pop()240    v1 = self.current_context.stack.pop()241    self.execute_push(v1 >= v2)242  def execute_less(self):243    v2 = self.current_context.stack.pop()244    v1 = self.current_context.stack.pop()245    self.execute_push(v1 < v2)246  def execute_less_equal(self):247    v2 = self.current_context.stack.pop()248    v1 = self.current_context.stack.pop()249    self.execute_push(v1 <= v2)250  def execute_equal(self):251    self.execute_push(self.current_context.stack.pop() == self.current_context.stack.pop())252  def execute_different(self):253    self.execute_push(self.current_context.stack.pop() != self.current_context.stack.pop())254  def execute_and(self):255    v2 = self.current_context.stack.pop()256    v1 = self.current_context.stack.pop()257    self.execute_push(v2 and v1)258  def execute_or(self):259    v2 = self.current_context.stack.pop()260    v1 = self.current_context.stack.pop()261    self.execute_push(v2 or v1)262  def execute_neg(self):263    self.execute_push(self.current_context.stack.pop() * -1)264  def execute_tilde(self):265    self.execute_push(~int(self.current_context.stack.pop()))266  def execute_not(self):...usage_metadata_logger_test.py
Source:usage_metadata_logger_test.py  
1#!/usr/bin/env python32#3#   Copyright 2020 - The Android Open Source Project4#5#   Licensed under the Apache License, Version 2.0 (the "License");6#   you may not use this file except in compliance with the License.7#   You may obtain a copy of the License at8#9#       http://www.apache.org/licenses/LICENSE-2.010#11#   Unless required by applicable law or agreed to in writing, software12#   distributed under the License is distributed on an "AS IS" BASIS,13#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14#   See the License for the specific language governing permissions and15#   limitations under the License.16import unittest17from unittest import TestCase18from acts.context import TestCaseContext, TestClassContext, RootContext19from acts.libs.proto.proto_utils import parse_proto_to_ascii20from acts.metrics.loggers import usage_metadata_logger21from acts.metrics.loggers.protos.gen import acts_usage_metadata_pb222from acts.metrics.loggers.usage_metadata_logger import UsageMetadataKey23from acts.metrics.loggers.usage_metadata_logger import UsageMetadataPublisher24from acts.metrics.loggers.usage_metadata_logger import _usage_map25from acts.metrics.loggers.usage_metadata_logger import log_usage26from acts.metrics.core import ProtoMetric27from mock import Mock28from mock import patch29CURRENT_CONTEXT = 'acts.context.get_current_context'30class UsageMetadataLoggerTest(TestCase):31    def setUp(self):32        usage_metadata_logger._reset()33    @patch(CURRENT_CONTEXT)34    def test_log_usage_context_change(self, current_context):35        class HurloWorld:36            """Just for testing"""37        class YerAHarryWizard:38            """Just for testing"""39        test_case = 'make toast'40        current_context.side_effect = [41            TestCaseContext(HurloWorld(), test_case),42            TestClassContext(YerAHarryWizard()),43            TestClassContext(YerAHarryWizard())44        ]45        module_name = 'com.android.google'46        func_name = 'test_func'47        joined_name = '.'.join([module_name, func_name])48        log_usage(module_name, func_name) # TestCaseContext49        log_usage(module_name, func_name) # TestClassContext50        log_usage(module_name, func_name) # TestClassContext51        case_key = UsageMetadataKey(joined_name,52                                    '%s.%s' % (HurloWorld.__name__, test_case))53        class_key = UsageMetadataKey(joined_name, YerAHarryWizard.__name__)54        self.assertIn(case_key, _usage_map)55        self.assertIn(class_key, _usage_map)56        case_value = _usage_map[case_key]57        class_value = _usage_map[class_key]58        self.assertEqual(case_value, 1)59        self.assertEqual(class_value, 2)60    @patch(CURRENT_CONTEXT)61    def test_log_usage_test_case_context(self, current_context):62        class HurlowWorld:63            """Just for testing"""64        test_case = 'made toast'65        current_context.return_value = TestCaseContext(HurlowWorld(),66                                                       test_case)67        module_name = 'com.android.google'68        func_name = 'test_func'69        joined_name = '.'.join([module_name, func_name])70        log_usage(module_name, func_name)71        key = UsageMetadataKey(joined_name,72                               '%s.%s' %(HurlowWorld.__name__, test_case))73        self.assertIn(key, _usage_map)74        value = _usage_map[key]75        self.assertEqual(value, 1)76    @patch(CURRENT_CONTEXT)77    def test_log_usage_test_class_context(self, current_context):78        class YerAHarryWizard:79            """Just for testing"""80        current_context.return_value = TestClassContext(YerAHarryWizard())81        module_name = 'com.android.google'82        func_name = 'test_func'83        joined_name = '.'.join([module_name, func_name])84        log_usage(module_name, func_name)85        key = UsageMetadataKey(joined_name, YerAHarryWizard.__name__)86        self.assertIn(key, _usage_map)87        value = usage_metadata_logger._usage_map[key]88        self.assertEqual(value, 1)89class UsageMetadataPublisherTest(TestCase):90    def setUp(self):91        usage_metadata_logger._reset()92    @patch(CURRENT_CONTEXT)93    def test_init(self, current_context):94        publisher = UsageMetadataPublisher()95        self.assertEqual(publisher.context.__class__, RootContext)96    @patch(CURRENT_CONTEXT)97    def test_usage_map_to_proto_metric(self, current_context):98        context = TestCaseContext('a', 'b')99        current_context.return_value = context100        publisher = UsageMetadataPublisher()101        umk1 = UsageMetadataKey('a.b', 'c.d')102        umk2 = UsageMetadataKey('e.f', 'h.i')103        _usage_map[umk1] = 51104        _usage_map[umk2] = 5105        usage_metadata_proto = acts_usage_metadata_pb2.ActsTestRunMetadata()106        method_invocation = usage_metadata_proto.usage.add()107        method_invocation.method_identifier = 'a.b'108        method_invocation.test_context = 'c.d'109        method_invocation.count = 51110        method_invocation = usage_metadata_proto.usage.add()111        method_invocation.method_identifier = 'e.f'112        method_invocation.test_context = 'h.i'113        method_invocation.count = 5114        expected = ProtoMetric(name='acts_usage_metadata',115                               data=usage_metadata_proto)116        actual = publisher._usage_map_to_proto_metric()117        self.assertEqual(expected.name, actual.name)118        self.assertEqual(parse_proto_to_ascii(expected.data),119                         parse_proto_to_ascii(actual.data))120    @patch(CURRENT_CONTEXT)121    def test_publish(self, current_context):122        context = Mock()123        current_context.return_value = context124        publisher = UsageMetadataPublisher()125        publisher._publish_single = Mock()126        publisher.publish()127        publisher._publish_single.assert_called_once()128if __name__ == '__main__':...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!!
