How to use _call_test_function method in autotest

Best Python code snippet using autotest_python

test.py

Source:test.py Github

copy

Full Screen

...310 # Execute:311 os.chdir(self.outputdir)312 # call self.warmup cherry picking the arguments it accepts and313 # translate exceptions if needed314 _call_test_function(_cherry_pick_call, self.warmup,315 *args, **dargs)316 if hasattr(self, 'run_once'):317 p_args, p_dargs = _cherry_pick_args(self.run_once,318 args, dargs)319 # pull in any non-* and non-** args from self.execute320 for param in _get_nonstar_args(self.execute):321 if param in dargs:322 p_dargs[param] = dargs[param]323 else:324 p_args, p_dargs = _cherry_pick_args(self.execute,325 args, dargs)326 _call_test_function(self.execute, *p_args, **p_dargs)327 except Exception:328 try:329 logging.exception('Exception escaping from test:')330 except:331 pass # don't let logging exceptions here interfere332 # Save the exception while we run our cleanup() before333 # reraising it.334 exc_info = sys.exc_info()335 try:336 try:337 if run_cleanup:338 _cherry_pick_call(self.cleanup, *args, **dargs)339 except Exception:340 print 'Ignoring exception during cleanup() phase:'341 traceback.print_exc()342 print 'Now raising the earlier %s error' % exc_info[0]343 self.crash_handler_report()344 finally:345 self.job.logging.restore()346 try:347 raise exc_info[0], exc_info[1], exc_info[2]348 finally:349 # http://docs.python.org/library/sys.html#sys.exc_info350 # Be nice and prevent a circular reference.351 del exc_info352 else:353 try:354 if run_cleanup:355 _cherry_pick_call(self.cleanup, *args, **dargs)356 self.crash_handler_report()357 finally:358 self.job.logging.restore()359 except error.AutotestError:360 if self.network_destabilizing:361 self.job.enable_warnings("NETWORK")362 # Pass already-categorized errors on up.363 raise364 except Exception, e:365 if self.network_destabilizing:366 self.job.enable_warnings("NETWORK")367 # Anything else is an ERROR in our own code, not execute().368 raise error.UnhandledTestError(e)369 else:370 if self.network_destabilizing:371 self.job.enable_warnings("NETWORK")372def _get_nonstar_args(func):373 """Extract all the (normal) function parameter names.374 Given a function, returns a tuple of parameter names, specifically375 excluding the * and ** parameters, if the function accepts them.376 @param func: A callable that we want to chose arguments for.377 @return: A tuple of parameters accepted by the function.378 """379 return func.func_code.co_varnames[:func.func_code.co_argcount]380def _cherry_pick_args(func, args, dargs):381 """Sanitize positional and keyword arguments before calling a function.382 Given a callable (func), an argument tuple and a dictionary of keyword383 arguments, pick only those arguments which the function is prepared to384 accept and return a new argument tuple and keyword argument dictionary.385 Args:386 func: A callable that we want to choose arguments for.387 args: A tuple of positional arguments to consider passing to func.388 dargs: A dictionary of keyword arguments to consider passing to func.389 Returns:390 A tuple of: (args tuple, keyword arguments dictionary)391 """392 # Cherry pick args:393 if func.func_code.co_flags & 0x04:394 # func accepts *args, so return the entire args.395 p_args = args396 else:397 p_args = ()398 # Cherry pick dargs:399 if func.func_code.co_flags & 0x08:400 # func accepts **dargs, so return the entire dargs.401 p_dargs = dargs402 else:403 # Only return the keyword arguments that func accepts.404 p_dargs = {}405 for param in _get_nonstar_args(func):406 if param in dargs:407 p_dargs[param] = dargs[param]408 return p_args, p_dargs409def _cherry_pick_call(func, *args, **dargs):410 """Cherry picks arguments from args/dargs based on what "func" accepts411 and calls the function with the picked arguments."""412 p_args, p_dargs = _cherry_pick_args(func, args, dargs)413 return func(*p_args, **p_dargs)414def _validate_args(args, dargs, *funcs):415 """Verify that arguments are appropriate for at least one callable.416 Given a list of callables as additional parameters, verify that417 the proposed keyword arguments in dargs will each be accepted by at least418 one of the callables.419 NOTE: args is currently not supported and must be empty.420 Args:421 args: A tuple of proposed positional arguments.422 dargs: A dictionary of proposed keyword arguments.423 *funcs: Callables to be searched for acceptance of args and dargs.424 Raises:425 error.AutotestError: if an arg won't be accepted by any of *funcs.426 """427 all_co_flags = 0428 all_varnames = ()429 for func in funcs:430 all_co_flags |= func.func_code.co_flags431 all_varnames += func.func_code.co_varnames[:func.func_code.co_argcount]432 # Check if given args belongs to at least one of the methods below.433 if len(args) > 0:434 # Current implementation doesn't allow the use of args.435 raise error.TestError('Unnamed arguments not accepted. Please '436 'call job.run_test with named args only')437 # Check if given dargs belongs to at least one of the methods below.438 if len(dargs) > 0:439 if not all_co_flags & 0x08:440 # no func accepts *dargs, so:441 for param in dargs:442 if not param in all_varnames:443 raise error.AutotestError('Unknown parameter: %s' % param)444def _installtest(job, url):445 (group, name) = job.pkgmgr.get_package_name(url, 'test')446 # Bail if the test is already installed447 group_dir = os.path.join(job.testdir, "download", group)448 if os.path.exists(os.path.join(group_dir, name)):449 return (group, name)450 # If the group directory is missing create it and add451 # an empty __init__.py so that sub-directories are452 # considered for import.453 if not os.path.exists(group_dir):454 os.makedirs(group_dir)455 f = file(os.path.join(group_dir, '__init__.py'), 'w+')456 f.close()457 print name + ": installing test url=" + url458 tarball = os.path.basename(url)459 tarball_path = os.path.join(group_dir, tarball)460 test_dir = os.path.join(group_dir, name)461 job.pkgmgr.fetch_pkg(tarball, tarball_path,462 repo_url = os.path.dirname(url))463 # Create the directory for the test464 if not os.path.exists(test_dir):465 os.mkdir(os.path.join(group_dir, name))466 job.pkgmgr.untar_pkg(tarball_path, test_dir)467 os.remove(tarball_path)468 # For this 'sub-object' to be importable via the name469 # 'group.name' we need to provide an __init__.py,470 # so link the main entry point to this.471 os.symlink(name + '.py', os.path.join(group_dir, name,472 '__init__.py'))473 # The test is now installed.474 return (group, name)475def _call_test_function(func, *args, **dargs):476 """Calls a test function and translates exceptions so that errors477 inside test code are considered test failures."""478 try:479 return func(*args, **dargs)480 except error.AutotestError:481 # Pass already-categorized errors on up as is.482 raise483 except Exception, e:484 # Other exceptions must be treated as a FAIL when485 # raised during the test functions486 raise error.UnhandledTestFail(e)487def runtest(job, url, tag, args, dargs,488 local_namespace={}, global_namespace={},489 before_test_hook=None, after_test_hook=None,...

Full Screen

Full Screen

unitspec.py

Source:unitspec.py Github

copy

Full Screen

...22 @wraps(func)23 def run_spec(*args, **kwargs):24 self = next(iter(args or []), None)25 context = Context()26 _call_test_function(func, context, *args, **kwargs)27 test_func = _get_original_func(func) # we need to get to the test function to find spec step methods28 steps = get_spec_steps(test_func, self)29 if len(steps) == 0:30 return31 _output_step("* SPEC: ", test_func)32 try:33 for name, section in steps.items():34 if name.startswith("given"):35 _output_step(" ", section)36 section(context)37 if name.startswith("when"):38 _output_step(" ", section)39 section(context)40 if name.startswith("it_should"):41 _output_step(" > ", section)42 section(context)43 finally:44 cleanups = _get_all_named_like(steps, "cleanup")45 for cleanup in cleanups:46 _output_step(" ", cleanup)47 cleanup(context)48 return run_spec49class MetaSpec(type):50 def __new__(mcs, clsname, bases, attrs):51 decorated_attrs = {}52 for name, val in attrs.items():53 if name.startswith("test_") and inspect.isroutine(val):54 decorated_attrs[name.replace("_", " ")] = spec(val)55 else:56 decorated_attrs[name] = val57 return super(MetaSpec, mcs).__new__(mcs, clsname, bases, decorated_attrs)58 def __getattr__(self, name):59 return _get_spaced_test(self, name)60def with_metaclass(meta, *bases):61 """Create a base class with a metaclass."""62 class Metaclass(meta):63 def __new__(cls, name, this_bases, d):64 return meta(name, bases, d)65 return type.__new__(Metaclass, 'temporary_class', (), {})66class SpecTestCase(with_metaclass(MetaSpec, unittest.TestCase)):67 def __getattr__(self, name):68 return _get_spaced_test(self, name)69def _is_step_name(name):70 return name.startswith("given")\71 or name.startswith("when")\72 or name.startswith("it_should")\73 or name.startswith("cleanup")74def _get_original_func(func):75 if isinstance(func, (classmethod, staticmethod)):76 return func.__func__77 # get original func from decorators (only for those who follow standard update_wrapper/wraps pattern)78 while hasattr(func, "__wrapped__"):79 func = func.__wrapped__80 return func81def _call_test_function(func, context, *args, **kwargs):82 args_names = inspect.getargspec(_get_original_func(func))[0]83 if "ctx" in args_names:84 kwargs["ctx"] = context85 if isinstance(func, (classmethod, staticmethod)):86 self = args[0]87 args = args[1:]88 func = func.__get__(self, type(self)) # we need to call underlying static or class function89 func(*args, **kwargs)90def _get_all_named_like(dict_, name):91 return [v for k, v in dict_.items() if k.startswith(name)]92def _output_step(message, func):93 func_name = func.__name__.replace("_", " ")94 print(message + func_name)95def _get_spaced_test(self, name):...

Full Screen

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 autotest 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