How to use get_docstring_directives_tags method in avocado

Best Python code snippet using avocado_python

safeloader.py

Source:safeloader.py Github

copy

Full Screen

...216 Checks if there's a given directive in a given docstring217 :rtype: bool218 """219 return directive in get_docstring_directives(docstring)220def get_docstring_directives_tags(docstring):221 """222 Returns the test categories based on a `:avocado: tags=category`223 docstring224 :rtype: dict225 """226 result = {}227 for item in get_docstring_directives(docstring):228 if item.startswith('tags='):229 _, comma_tags = item.split('tags=', 1)230 for tag in comma_tags.split(','):231 if not tag:232 continue233 if ':' in tag:234 key, val = tag.split(':', 1)235 if key in result:236 result[key].add(val)237 else:238 result[key] = set([val])239 else:240 result[tag] = None241 return result242def get_docstring_directives_requirements(docstring):243 """244 Returns the test requirements from docstring patterns like245 `:avocado: requirement={}`.246 :rtype: list247 """248 requirements = []249 for item in get_docstring_directives(docstring):250 if item.startswith('requirement='):251 _, requirement_str = item.split('requirement=', 1)252 try:253 requirements.append(json.loads(requirement_str))254 except json.decoder.JSONDecodeError:255 # ignore requirement in case of malformed dictionary256 continue257 return requirements258def find_class_and_methods(path, method_pattern=None, base_class=None):259 """260 Attempts to find methods names from a given Python source file261 :param path: path to a Python source code file262 :type path: str263 :param method_pattern: compiled regex to match against method name264 :param base_class: only consider classes that inherit from a given265 base class (or classes that inherit from any class266 if None is given)267 :type base_class: str or None268 :returns: an ordered dictionary with classes as keys and methods as values269 :rtype: collections.OrderedDict270 """271 def inherits_from_base_class(class_statement, base_class_name):272 base_ids = [base.id for base in class_statement.bases273 if hasattr(base, 'id')]274 return base_class_name in base_ids275 result = collections.OrderedDict()276 with open(path) as source_file:277 mod = ast.parse(source_file.read(), path)278 for statement in mod.body:279 if isinstance(statement, ast.ClassDef):280 if base_class is not None:281 if not inherits_from_base_class(statement,282 base_class):283 continue284 if method_pattern is None:285 methods = [st.name for st in statement.body if286 isinstance(st, ast.FunctionDef)]287 methods = data_structures.ordered_list_unique(methods)288 else:289 methods = [st.name for st in statement.body if290 isinstance(st, ast.FunctionDef) and291 method_pattern.match(st.name)]292 methods = data_structures.ordered_list_unique(methods)293 result[statement.name] = methods294 return result295def get_methods_info(statement_body, class_tags, class_requirements):296 """297 Returns information on an Avocado instrumented test method298 """299 methods_info = []300 for st in statement_body:301 if (isinstance(st, ast.FunctionDef) and302 st.name.startswith('test')):303 docstring = ast.get_docstring(st)304 mt_tags = get_docstring_directives_tags(docstring)305 mt_tags.update(class_tags)306 mt_requirements = get_docstring_directives_requirements(docstring)307 mt_requirements.extend(class_requirements)308 methods = [method for method, _, _ in methods_info]309 if st.name not in methods:310 methods_info.append((st.name, mt_tags, mt_requirements))311 return methods_info312def _determine_match_avocado(module, klass, docstring):313 """314 Implements the match check for Avocado Instrumented Tests315 """316 directives = get_docstring_directives(docstring)317 if 'disable' in directives:318 return True319 if 'enable' in directives:320 return True321 if 'recursive' in directives:322 return True323 # Still not decided, try inheritance324 return module.is_matching_klass(klass)325def _extend_test_list(current, new):326 for test in new:327 test_method_name = test[0]328 if test_method_name not in [_[0] for _ in current]:329 current.append(test)330def _examine_class(path, class_name, match, target_module, target_class,331 determine_match):332 """333 Examine a class from a given path334 :param path: path to a Python source code file335 :type path: str336 :param class_name: the specific class to be found337 :type path: str338 :param match: whether the inheritance from <target_module.target_class> has339 been determined or not340 :type match: bool341 :param target_module: the module name under which the target_class lives342 :type target_module: str343 :param target_class: the name of the class that class_name should344 ultimately inherit from345 :type target_class: str346 :param determine_match: a callable that will determine if a match has347 occurred or not348 :type determine_match: function349 :returns: tuple where first item is a list of test methods detected350 for given class; second item is set of class names which351 look like avocado tests but are force-disabled.352 :rtype: tuple353 """354 module = PythonModule(path, target_module, target_class)355 info = []356 disabled = set()357 for klass in module.iter_classes():358 if class_name != klass.name:359 continue360 docstring = ast.get_docstring(klass)361 if match is False:362 match = determine_match(module, klass, docstring)363 info = get_methods_info(klass.body,364 get_docstring_directives_tags(docstring),365 get_docstring_directives_requirements(366 docstring))367 # Getting the list of parents of the current class368 parents = klass.bases369 # From this point we use `_$variable` to name temporary returns370 # from method calls that are to-be-assigned/combined with the371 # existing `$variable`.372 # Searching the parents in the same module373 for parent in parents[:]:374 # Looking for a 'class FooTest(Parent)'375 if not isinstance(parent, ast.Name):376 # 'class FooTest(bar.Bar)' not supported withing377 # a module378 continue379 parent_class = parent.id380 _info, _disabled, _match = _examine_class(module.path, parent_class,381 match, target_module,382 target_class,383 determine_match)384 if _info:385 parents.remove(parent)386 _extend_test_list(info, _info)387 disabled.update(_disabled)388 if _match is not match:389 match = _match390 # If there are parents left to be discovered, they391 # might be in a different module.392 for parent in parents:393 if hasattr(parent, 'value'):394 if hasattr(parent.value, 'id'):395 # We know 'parent.Class' or 'asparent.Class' and need396 # to get path and original_module_name. Class is given397 # by parent definition.398 _parent = module.imported_objects.get(parent.value.id)399 if _parent is None:400 # We can't examine this parent (probably broken401 # module)402 continue403 parent_path = os.path.dirname(_parent)404 parent_module = os.path.basename(_parent)405 parent_class = parent.attr406 else:407 # We don't support multi-level 'parent.parent.Class'408 continue409 else:410 # We only know 'Class' or 'AsClass' and need to get411 # path, module and original class_name412 _parent = module.imported_objects.get(parent.id)413 if _parent is None:414 # We can't examine this parent (probably broken415 # module)416 continue417 parent_path, parent_module, parent_class = (418 _parent.rsplit(os.path.sep, 2))419 modules_paths = [parent_path,420 os.path.dirname(module.path)] + sys.path421 found_spec = PathFinder.find_spec(parent_module, modules_paths)422 if found_spec is not None:423 _info, _disabled, _match = _examine_class(found_spec.origin,424 parent_class,425 match,426 target_module,427 target_class,428 _determine_match_avocado)429 if _info:430 _extend_test_list(info, _info)431 disabled.update(_disabled)432 if _match is not match:433 match = _match434 return info, disabled, match435def find_python_tests(module_name, class_name, determine_match, path):436 """437 Attempts to find Python tests from source files438 A Python test in this context is a method within a specific type439 of class (or that inherits from a specific class).440 :param module_name: the name of the module from which a class should441 have come from442 :type module_name: str443 :param class_name: the name of the class that is considered to contain444 test methods445 :type class_name: str446 :type determine_match: a callable that will determine if a given module447 and class is contains valid Python tests448 :type determine_match: function449 :param path: path to a Python source code file450 :type path: str451 :returns: tuple where first item is dict with class name and additional452 info such as method names and tags; the second item is453 set of class names which look like Python tests but have been454 forcefully disabled.455 :rtype: tuple456 """457 module = PythonModule(path, module_name, class_name)458 # The resulting test classes459 result = collections.OrderedDict()460 disabled = set()461 for klass in module.iter_classes():462 docstring = ast.get_docstring(klass)463 # Looking for a class that has in the docstring either464 # ":avocado: enable" or ":avocado: disable465 if check_docstring_directive(docstring, 'disable'):466 disabled.add(klass.name)467 continue468 if check_docstring_directive(docstring, 'enable'):469 info = get_methods_info(klass.body,470 get_docstring_directives_tags(docstring),471 get_docstring_directives_requirements(472 docstring))473 result[klass.name] = info474 continue475 # From this point onwards we want to do recursive discovery, but476 # for now we don't know whether it is avocado.Test inherited477 # (Ifs are optimized for readability, not speed)478 # If "recursive" tag is specified, it is forced as test479 if check_docstring_directive(docstring, 'recursive'):480 is_valid_test = True481 else:482 is_valid_test = module.is_matching_klass(klass)483 info = get_methods_info(klass.body,484 get_docstring_directives_tags(docstring),485 get_docstring_directives_requirements(486 docstring))487 _disabled = set()488 # Getting the list of parents of the current class489 parents = klass.bases490 # Searching the parents in the same module491 for parent in parents[:]:492 # Looking for a 'class FooTest(Parent)'493 if not isinstance(parent, ast.Name):494 # 'class FooTest(bar.Bar)' not supported withing495 # a module496 continue497 parent_class = parent.id498 _info, _dis, _python_test = _examine_class(module.path,...

Full Screen

Full Screen

test_safeloader.py

Source:test_safeloader.py Github

copy

Full Screen

...166 self.assertFalse(safeloader.check_docstring_directive(":AVOCADO: DISABLE", 'disable'))167 self.assertFalse(safeloader.check_docstring_directive(":avocado: disabled", 'disable'))168 def test_get_tags_empty(self):169 for tag in self.NO_TAGS:170 self.assertEqual({}, safeloader.get_docstring_directives_tags(tag))171 def test_tag_single(self):172 raw = ":avocado: tags=fast"173 exp = {"fast": None}174 self.assertEqual(safeloader.get_docstring_directives_tags(raw), exp)175 def test_tag_double(self):176 raw = ":avocado: tags=fast,network"177 exp = {"fast": None, "network": None}178 self.assertEqual(safeloader.get_docstring_directives_tags(raw), exp)179 def test_tag_double_with_empty(self):180 raw = ":avocado: tags=fast,,network"181 exp = {"fast": None, "network": None}182 self.assertEqual(safeloader.get_docstring_directives_tags(raw), exp)183 def test_tag_lowercase_uppercase(self):184 raw = ":avocado: tags=slow,DISK"185 exp = {"slow": None, "DISK": None}186 self.assertEqual(safeloader.get_docstring_directives_tags(raw), exp)187 def test_tag_duplicate(self):188 raw = ":avocado: tags=SLOW,disk,disk"189 exp = {"SLOW": None, "disk": None}190 self.assertEqual(safeloader.get_docstring_directives_tags(raw), exp)191 def test_tag_tab_separator(self):192 raw = ":avocado:\ttags=FAST"193 exp = {"FAST": None}194 self.assertEqual(safeloader.get_docstring_directives_tags(raw), exp)195 def test_tag_empty(self):196 raw = ":avocado: tags="197 exp = {}198 self.assertEqual(safeloader.get_docstring_directives_tags(raw), exp)199 def test_tag_newline_before(self):200 raw = ":avocado: enable\n:avocado: tags=fast"201 exp = {"fast": None}202 self.assertEqual(safeloader.get_docstring_directives_tags(raw), exp)203 def test_tag_newline_after(self):204 raw = ":avocado: tags=fast,slow\n:avocado: enable"205 exp = {"fast": None, "slow": None}206 self.assertEqual(safeloader.get_docstring_directives_tags(raw), exp)207 def test_tag_keyval_single(self):208 raw = ":avocado: tags=fast,arch:x86_64"209 exp = {"fast": None, "arch": set(["x86_64"])}210 self.assertEqual(safeloader.get_docstring_directives_tags(raw), exp)211 def test_tag_keyval_double(self):212 raw = ":avocado: tags=fast,arch:x86_64,arch:ppc64"213 exp = {"fast": None, "arch": set(["x86_64", "ppc64"])}214 self.assertEqual(safeloader.get_docstring_directives_tags(raw), exp)215 def test_tag_keyval_duplicate(self):216 raw = ":avocado: tags=fast,arch:x86_64,arch:ppc64,arch:x86_64"217 exp = {"fast": None, "arch": set(["x86_64", "ppc64"])}218 self.assertEqual(safeloader.get_docstring_directives_tags(raw), exp)219 def test_get_requirement_empty(self):220 for req in self.NO_REQS:221 self.assertEqual([], safeloader.get_docstring_directives_requirements(req))222 def test_requirement_single(self):223 raw = ":avocado: requirement={\"foo\":\"bar\"}"224 exp = [{"foo": "bar"}]225 self.assertEqual(safeloader.get_docstring_directives_requirements(raw), exp)226 def test_requirement_double(self):227 raw = ":avocado: requirement={\"foo\":\"bar\"}\n:avocado: requirement={\"uri\":\"http://foo.bar\"}"228 exp = [{"foo": "bar"}, {"uri": "http://foo.bar"}]229 self.assertEqual(safeloader.get_docstring_directives_requirements(raw), exp)230 def test_directives_regex(self):231 """232 Tests the regular expressions that deal with docstring directives...

Full Screen

Full Screen

test_safeloader_docstring.py

Source:test_safeloader_docstring.py Github

copy

Full Screen

...84 self.assertFalse(check_docstring_directive(":AVOCADO: DISABLE", "disable"))85 self.assertFalse(check_docstring_directive(":avocado: disabled", "disable"))86 def test_get_tags_empty(self):87 for tag in self.NO_TAGS:88 self.assertEqual({}, get_docstring_directives_tags(tag))89 def test_tag_single(self):90 raw = ":avocado: tags=fast"91 exp = {"fast": None}92 self.assertEqual(get_docstring_directives_tags(raw), exp)93 def test_tag_double(self):94 raw = ":avocado: tags=fast,network"95 exp = {"fast": None, "network": None}96 self.assertEqual(get_docstring_directives_tags(raw), exp)97 def test_tag_double_with_empty(self):98 raw = ":avocado: tags=fast,,network"99 exp = {"fast": None, "network": None}100 self.assertEqual(get_docstring_directives_tags(raw), exp)101 def test_tag_lowercase_uppercase(self):102 raw = ":avocado: tags=slow,DISK"103 exp = {"slow": None, "DISK": None}104 self.assertEqual(get_docstring_directives_tags(raw), exp)105 def test_tag_duplicate(self):106 raw = ":avocado: tags=SLOW,disk,disk"107 exp = {"SLOW": None, "disk": None}108 self.assertEqual(get_docstring_directives_tags(raw), exp)109 def test_tag_tab_separator(self):110 raw = ":avocado:\ttags=FAST"111 exp = {"FAST": None}112 self.assertEqual(get_docstring_directives_tags(raw), exp)113 def test_tag_empty(self):114 raw = ":avocado: tags="115 exp = {}116 self.assertEqual(get_docstring_directives_tags(raw), exp)117 def test_tag_newline_before(self):118 raw = ":avocado: enable\n:avocado: tags=fast"119 exp = {"fast": None}120 self.assertEqual(get_docstring_directives_tags(raw), exp)121 def test_tag_newline_after(self):122 raw = ":avocado: tags=fast,slow\n:avocado: enable"123 exp = {"fast": None, "slow": None}124 self.assertEqual(get_docstring_directives_tags(raw), exp)125 def test_tag_keyval_single(self):126 raw = ":avocado: tags=fast,arch:x86_64"127 exp = {"fast": None, "arch": set(["x86_64"])}128 self.assertEqual(get_docstring_directives_tags(raw), exp)129 def test_tag_keyval_double(self):130 raw = ":avocado: tags=fast,arch:x86_64,arch:ppc64"131 exp = {"fast": None, "arch": set(["x86_64", "ppc64"])}132 self.assertEqual(get_docstring_directives_tags(raw), exp)133 def test_tag_keyval_duplicate(self):134 raw = ":avocado: tags=fast,arch:x86_64,arch:ppc64,arch:x86_64"135 exp = {"fast": None, "arch": set(["x86_64", "ppc64"])}136 self.assertEqual(get_docstring_directives_tags(raw), exp)137 def test_get_dependency_empty(self):138 for dep in self.NO_REQS:139 self.assertEqual([], get_docstring_directives_dependencies(dep))140 def test_dependency_single(self):141 raw = ':avocado: dependency={"foo":"bar"}'142 exp = [{"foo": "bar"}]143 self.assertEqual(get_docstring_directives_dependencies(raw), exp)144 def test_dependency_double(self):145 raw = ':avocado: dependency={"foo":"bar"}\n:avocado: dependency={"uri":"http://foo.bar"}'146 exp = [{"foo": "bar"}, {"uri": "http://foo.bar"}]147 self.assertEqual(get_docstring_directives_dependencies(raw), exp)148 def test_directives_regex(self):149 """150 Tests the regular expressions that deal with docstring directives...

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