How to use fixture_decorator method in Testify

Best Python code snippet using Testify_python

test_fixtures.py

Source:test_fixtures.py Github

copy

Full Screen

...239 inspect.isroutine(obj)):240 # if this is an old setUp/tearDown/etc, tag it as a fixture241 fixture_type = DEPRECATED_FIXTURE_TYPE_MAP[name]242 fixture_decorator = globals()[fixture_type]243 fixture_method = fixture_decorator(obj)244 else:245 continue246 depth = reverse_mro_index[defining_class]247 fixture_method._defining_class_depth = depth248 # We grabbed this from the class and need to bind it to the test249 # case250 # http://stackoverflow.com/q/4364565251 instance_method = fixture_method.__get__(test_case, test_class)252 all_fixtures[instance_method._fixture_type].append(instance_method)253 class_level = ['class_setup', 'class_teardown', 'class_setup_teardown']254 inst_level = ['setup', 'teardown', 'setup_teardown']255 return cls(256 class_fixtures=list(itertools.chain(*[all_fixtures[typ] for typ in class_level])),257 instance_fixtures=list(itertools.chain(*[all_fixtures[typ] for typ in inst_level])),258 )259def suite(*args, **kwargs):260 """Decorator to conditionally assign suites to individual test methods.261 This decorator takes a variable number of positional suite arguments and two optional kwargs:262 - conditional: if provided and does not evaluate to True, the suite will not be applied.263 - reason: if provided, will be attached to the method for logging later.264 Can be called multiple times on one method to assign individual conditions or reasons.265 """266 def mark_test_with_suites(function):267 conditions = kwargs.get('conditions')268 reason = kwargs.get('reason')269 if not hasattr(function, '_suites'):270 function._suites = set()271 if args and (conditions is None or bool(conditions) is True):272 function._suites = set(function._suites) | set(args)273 if reason:274 if not hasattr(function, '_suite_reasons'):275 function._suite_reasons = []276 function._suite_reasons.append(reason)277 return function278 return mark_test_with_suites279# unique id for fixtures280_fixture_id = [0]281def __fixture_decorator_factory(fixture_type):282 """Decorator generator for the fixture decorators.283 Tagging a class/instancemethod as 'setup', etc, will mark the method with a284 _fixture_id. Smaller fixture ids correspond to functions higher on the285 class hierarchy, since base classes (and their methods!) are created before286 their children.287 When our test cases are instantiated, they use this _fixture_id to sort288 methods into the appropriate _fixture_methods bucket. Note that this289 sorting cannot be done here, because this decorator does not recieve290 instancemethods -- which would be aware of their class -- because the class291 they belong to has not yet been created.292 **NOTE**: This means fixtures of the same type on a class will be executed293 in the order that they are defined, before/after fixtures execute on the294 parent class execute setups/teardowns, respectively.295 """296 def fixture_decorator(callable_):297 # Decorators act on *functions*, so we need to take care when dynamically298 # decorating class attributes (which are (un)bound methods).299 function = inspection.get_function(callable_)300 # record the fixture type and id for this function301 function._fixture_type = fixture_type302 if function.__name__ in DEPRECATED_FIXTURE_TYPE_MAP:303 # we push deprecated setUps/tearDowns to the beginning or end of304 # our fixture lists, respectively. this is the best we can do,305 # because these methods are generated in the order their classes306 # are created, so we can't assign a fair fixture_id to them.307 function._fixture_id = 0 if fixture_type.endswith('setup') else float('inf')308 else:309 # however, if we've tagged a fixture with our decorators then we310 # effectively register their place on the class hierarchy by this...

Full Screen

Full Screen

fixtures.py

Source:fixtures.py Github

copy

Full Screen

...37 else:38 is_yield = is_pytest_yield_fixture(fixture_decorator)39 if is_yield:40 self.error_from_node(DeprecatedYieldFixture, fixture_decorator)41 def _check_fixture_decorator(42 self,43 fixture_decorator: Union[ast.Call, ast.Attribute],44 fixture_func: AnyFunctionDef,45 ) -> None:46 """Checks for PT001, PT002, PT003."""47 if not isinstance(fixture_decorator, ast.Call):48 if self.config.fixture_parentheses:49 self.error_from_node(50 IncorrectFixtureParenthesesStyle,51 fixture_decorator,52 expected_parens='()',53 actual_parens='',54 )55 return56 if (57 not self.config.fixture_parentheses58 and not fixture_decorator.args59 and not fixture_decorator.keywords60 ):61 self.error_from_node(62 IncorrectFixtureParenthesesStyle,63 fixture_decorator,64 expected_parens='',65 actual_parens='()',66 )67 if fixture_decorator.args:68 self.error_from_node(69 FixturePositionalArgs, fixture_decorator, name=fixture_func.name70 )71 for keyword in fixture_decorator.keywords:72 if (73 keyword.arg == 'scope'74 and isinstance(keyword.value, ast.Str)75 and keyword.value.s == 'function'76 ):77 self.error_from_node(78 ExtraneousScopeFunction, fixture_decorator, name=fixture_func.name79 )80 def _check_fixture_returns(self, node: AnyFunctionDef) -> None:81 """Checks for PT004, PT005, PT022."""82 # skip these checks for abstract fixtures83 if is_abstract_method(node):84 return85 has_return_with_value = False86 has_yield_from = False87 yield_statements = []88 for child in walk_without_nested_functions(node):89 if isinstance(child, ast.Yield):90 yield_statements.append(child)91 if isinstance(child, (ast.Return, ast.Yield)) and child.value is not None:92 has_return_with_value = True93 if isinstance(child, ast.YieldFrom):94 has_yield_from = True95 if has_return_with_value and node.name.startswith('_'):96 self.error_from_node(IncorrectFixtureNameUnderscore, node, name=node.name)97 elif (98 not has_return_with_value99 and not has_yield_from100 and not node.name.startswith('_')101 ):102 # we shouldn't fire PT004 if we found a `yield from` because103 # there is no adequate way to determine whether a value is actually yielded104 self.error_from_node(MissingFixtureNameUnderscore, node, name=node.name)105 last_statement_is_yield = isinstance(node.body[-1], ast.Expr) and isinstance(106 node.body[-1].value, ast.Yield107 )108 if last_statement_is_yield and len(yield_statements) == 1:109 self.error_from_node(UselessYieldFixture, node, name=node.name)110 def _check_fixture_addfinalizer(self, node: AnyFunctionDef) -> None:111 """Checks for PT021."""112 if 'request' not in get_all_argument_names(node.args):113 return114 for child in walk_without_nested_functions(node): # pragma: no branch115 if (116 isinstance(child, ast.Call)117 and get_qualname(child.func) == 'request.addfinalizer'118 ):119 self.error_from_node(FixtureFinalizerCallback, child)120 return121 def _check_fixture_marks(self, node: AnyFunctionDef) -> None:122 """Checks for PT024, PT025."""123 reported_errors = set()124 marks = get_mark_decorators(node)125 for mark in marks:126 mark_name = get_mark_name(mark)127 if (128 mark_name == 'asyncio'129 and UnnecessaryAsyncioMarkOnFixture not in reported_errors130 ):131 self.error_from_node(UnnecessaryAsyncioMarkOnFixture, mark)132 reported_errors.add(UnnecessaryAsyncioMarkOnFixture)133 if (134 mark_name == 'usefixtures'135 and ErroneousUseFixturesOnFixture not in reported_errors136 ):137 self.error_from_node(ErroneousUseFixturesOnFixture, mark)138 reported_errors.add(ErroneousUseFixturesOnFixture)139 def _check_test_function_args(self, node: AnyFunctionDef) -> None:140 """Checks for PT019."""141 # intentionally not looking at posonlyargs because pytest passes everything142 # as kwargs, so declaring fixture args as positional-only will fail anyway143 for arg in node.args.args + node.args.kwonlyargs:144 if arg.arg.startswith('_'):145 self.error_from_node(FixtureParamWithoutValue, node, name=arg.arg)146 def visit_FunctionDef(self, node: AnyFunctionDef) -> None:147 fixture_decorator = get_fixture_decorator(node)148 if fixture_decorator:149 self._check_fixture_decorator_name(fixture_decorator)150 self._check_fixture_decorator(fixture_decorator, node)151 self._check_fixture_returns(node)152 self._check_fixture_addfinalizer(node)153 self._check_fixture_marks(node)154 if is_test_function(node):155 self._check_test_function_args(node)156 self.generic_visit(node)...

Full Screen

Full Screen

context.py

Source:context.py Github

copy

Full Screen

1import asyncio2from pathlib import Path3from typing import List, Tuple4from starkware.cairo.lang.cairo_constants import DEFAULT_PRIME5from starkware.cairo.lang.compiler.cairo_compile import (6 compile_cairo_ex, get_codes, get_module_reader,7)8from starkware.cairo.lang.compiler.program import Program9from starkware.starknet.compiler.compile import get_entry_points_by_type10from starkware.starknet.compiler.starknet_pass_manager import (11 starknet_pass_manager,12)13from starkware.starknet.compiler.starknet_preprocessor import (14 SUPPORTED_DECORATORS, StarknetPreprocessedProgram,15)16from starkware.starknet.services.api.contract_definition import (17 ContractDefinition, EntryPointType,18)19from starkware.starknet.testing.starknet import Starknet20from pytest_cairo.contract import TestContract21from pytest_cairo.fixture import FIXTURE_DECORATOR22from pytest_cairo.info_collector import ContractFunctionInfoCollector23SUPPORTED_DECORATORS.add(FIXTURE_DECORATOR)24class Context:25 def __init__(self, cairo_path: List[str] = []) -> None:26 self.cairo_path = cairo_path27 self.starknet = asyncio.run(Starknet.empty())28 def deploy_contract(self, source: str) -> TestContract:29 assert Path(source).is_file()30 contract_def, preprocessed = self.compile_contracts(31 files=[source],32 cairo_path=self.cairo_path,33 )34 contract_def.entry_points_by_type[EntryPointType.CONSTRUCTOR] = []35 contract = asyncio.run(self.starknet.deploy(36 contract_def=contract_def,37 ))38 return TestContract(contract, contract_def, preprocessed)39 @staticmethod40 def compile_contracts(41 files: List[str],42 cairo_path: List[str] = [],43 debug_info: bool = True,44 ) -> Tuple[ContractDefinition, StarknetPreprocessedProgram]:45 pass_manager = starknet_pass_manager(46 prime=DEFAULT_PRIME,47 read_module=get_module_reader(cairo_path=cairo_path).read,48 disable_hint_validation=True,49 )50 for name, stage in pass_manager.stages:51 if name == 'preprocessor':52 stage.auxiliary_info_cls = ContractFunctionInfoCollector53 program, preprocessed = compile_cairo_ex(54 code=get_codes(files),55 debug_info=debug_info,56 pass_manager=pass_manager,57 )58 program = Program.load(data=program.dump())59 assert isinstance(preprocessed, StarknetPreprocessedProgram)60 return (61 ContractDefinition(62 program=program,63 entry_points_by_type=get_entry_points_by_type(program=program),64 abi=preprocessed.abi,65 ),66 preprocessed,...

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