How to use LibraryScope method in Robotframework

Best Python code snippet using robotframework

test_testlibrary.py

Source:test_testlibrary.py Github

copy

Full Screen

1import os.path2import re3import sys4import unittest5from robot.running.testlibraries import (TestLibrary, _ClassLibrary,6 _ModuleLibrary, _DynamicLibrary)7from robot.utils.asserts import (assert_equal, assert_false, assert_none,8 assert_not_equal, assert_not_none, assert_true,9 assert_raises, assert_raises_with_msg)10from robot.utils import normalize11from robot.errors import DataError12from classes import (NameLibrary, DocLibrary, ArgInfoLibrary, GetattrLibrary,13 SynonymLibrary, __file__ as classes_source)14# Valid keyword names and arguments for some libraries15default_keywords = [ ( "no operation", () ),16 ( "log", ("msg",) ),17 ( "L O G", ("msg","warning") ),18 ( "fail", () ),19 ( " f a i l ", ("msg",) ) ]20example_keywords = [ ( "Log", ("msg",) ),21 ( "log many", () ),22 ( "logmany", ("msg",) ),23 ( "L O G M A N Y", ("m1","m2","m3","m4","m5") ),24 ( "equals", ("1","1") ),25 ( "equals", ("1","2","failed") ), ]26class TestLibraryTypes(unittest.TestCase):27 def test_python_library(self):28 lib = TestLibrary("BuiltIn")29 assert_equal(lib.__class__, _ClassLibrary)30 assert_equal(lib.positional_args, [])31 def test_python_library_with_args(self):32 lib = TestLibrary("ParameterLibrary", ['my_host', '8080'])33 assert_equal(lib.__class__, _ClassLibrary)34 assert_equal(lib.positional_args, ['my_host', '8080'])35 def test_module_library(self):36 lib = TestLibrary("module_library")37 assert_equal(lib.__class__, _ModuleLibrary)38 def test_module_library_with_args(self):39 assert_raises(DataError, TestLibrary, "module_library", ['arg'] )40 def test_dynamic_python_library(self):41 lib = TestLibrary("RunKeywordLibrary")42 assert_equal(lib.__class__, _DynamicLibrary)43class TestImports(unittest.TestCase):44 def test_import_python_class(self):45 lib = TestLibrary("BuiltIn")46 self._verify_lib(lib, "BuiltIn", default_keywords)47 def test_import_python_class_from_module(self):48 lib = TestLibrary("robot.libraries.BuiltIn.BuiltIn")49 self._verify_lib(lib, "robot.libraries.BuiltIn.BuiltIn", default_keywords)50 def test_import_python_module(self):51 lib = TestLibrary("module_library")52 kws = ["passing", "two arguments from class", "lambdakeyword", "argument"]53 self._verify_lib(lib, "module_library", [(kw, None) for kw in kws])54 def test_import_python_module_from_module(self):55 lib = TestLibrary("pythonmodule.library")56 self._verify_lib(lib, "pythonmodule.library",57 [("keyword from submodule", None)])58 def test_import_non_existing_module(self):59 msg = ("Importing library '{libname}' failed: "60 "ModuleNotFoundError: No module named '{modname}'")61 for name in 'nonexisting', 'nonexi.sting':62 error = assert_raises(DataError, TestLibrary, name)63 expected = msg.format(libname=name, modname=name.split('.')[0])64 assert_equal(str(error).splitlines()[0], expected)65 def test_import_non_existing_class_from_existing_module(self):66 assert_raises_with_msg(DataError,67 "Importing library 'pythonmodule.NonExisting' failed: "68 "Module 'pythonmodule' does not contain 'NonExisting'.",69 TestLibrary, 'pythonmodule.NonExisting')70 def test_import_invalid_type(self):71 msg = "Importing library '%s' failed: Expected class or module, got %s."72 assert_raises_with_msg(DataError,73 msg % ('pythonmodule.some_string', 'string'),74 TestLibrary, 'pythonmodule.some_string')75 assert_raises_with_msg(DataError,76 msg % ('pythonmodule.some_object', 'SomeObject'),77 TestLibrary, 'pythonmodule.some_object')78 def test_import_with_unicode_name(self):79 self._verify_lib(TestLibrary(u"BuiltIn"), "BuiltIn", default_keywords)80 self._verify_lib(TestLibrary(u"robot.libraries.BuiltIn.BuiltIn"),81 "robot.libraries.BuiltIn.BuiltIn", default_keywords)82 self._verify_lib(TestLibrary(u"pythonmodule.library"), "pythonmodule.library",83 [("keyword from submodule", None)])84 def test_global_scope(self):85 self._verify_scope(TestLibrary('libraryscope.Global'), 'GLOBAL')86 def _verify_scope(self, lib, expected):87 assert_equal(str(lib.scope), expected)88 def test_suite_scope(self):89 self._verify_scope(TestLibrary('libraryscope.Suite'), 'SUITE')90 self._verify_scope(TestLibrary('libraryscope.TestSuite'), 'SUITE')91 def test_test_scope(self):92 self._verify_scope(TestLibrary('libraryscope.Test'), 'TEST')93 self._verify_scope(TestLibrary('libraryscope.TestCase'), 'TEST')94 def test_task_scope_is_mapped_to_test_scope(self):95 self._verify_scope(TestLibrary('libraryscope.Task'), 'TEST')96 def test_invalid_scope_is_mapped_to_test_scope(self):97 for libname in ['libraryscope.InvalidValue',98 'libraryscope.InvalidEmpty',99 'libraryscope.InvalidMethod',100 'libraryscope.InvalidNone']:101 self._verify_scope(TestLibrary(libname), 'TEST')102 def _verify_lib(self, lib, libname, keywords):103 assert_equal(libname, lib.name)104 for name, _ in keywords:105 handler = lib.handlers[name]106 exp = "%s.%s" % (libname, name)107 assert_equal(normalize(handler.longname), normalize(exp))108class TestLibraryInit(unittest.TestCase):109 def test_python_library_without_init(self):110 self._test_init_handler('ExampleLibrary')111 def test_python_library_with_init(self):112 self._test_init_handler('ParameterLibrary', ['foo'], 0, 2)113 def test_new_style_class_without_init(self):114 self._test_init_handler('newstyleclasses.NewStyleClassLibrary')115 def test_new_style_class_with_init(self):116 lib = self._test_init_handler('newstyleclasses.NewStyleClassArgsLibrary', ['value'], 1, 1)117 assert_equal(len(lib.handlers), 1)118 def test_library_with_metaclass(self):119 self._test_init_handler('newstyleclasses.MetaClassLibrary')120 def test_library_with_zero_len(self):121 self._test_init_handler('LenLibrary')122 def _test_init_handler(self, libname, args=None, min=0, max=0):123 lib = TestLibrary(libname, args)124 assert_equal(lib.init.arguments.minargs, min)125 assert_equal(lib.init.arguments.maxargs, max)126 return lib127class TestVersion(unittest.TestCase):128 def test_no_version(self):129 self._verify_version('classes.NameLibrary', '')130 def test_version_in_class_library(self):131 self._verify_version('classes.VersionLibrary', '0.1')132 self._verify_version('classes.VersionObjectLibrary', 'ver')133 def test_version_in_module_library(self):134 self._verify_version('module_library', 'test')135 def _verify_version(self, name, version):136 assert_equal(TestLibrary(name).version, version)137class TestDocFormat(unittest.TestCase):138 def test_no_doc_format(self):139 self._verify_doc_format('classes.NameLibrary', '')140 def test_doc_format_in_python_libarary(self):141 self._verify_doc_format('classes.VersionLibrary', 'HTML')142 def _verify_doc_format(self, name, doc_format):143 assert_equal(TestLibrary(name).doc_format, doc_format)144class _TestScopes(unittest.TestCase):145 def _get_lib_and_instance(self, name):146 lib = TestLibrary(name)147 if lib.scope.is_global:148 assert_not_none(lib._libinst)149 else:150 assert_none(lib._libinst)151 return lib, lib._libinst152 def _start_new_suite(self):153 self.lib.start_suite()154 assert_none(self.lib._libinst)155 inst = self.lib.get_instance()156 assert_not_none(inst)157 return inst158 def _verify_end_suite_restores_previous_instance(self, prev_inst):159 self.lib.end_suite()160 assert_true(self.lib._libinst is prev_inst)161 if prev_inst is not None:162 assert_true(self.lib.get_instance() is prev_inst)163class GlobalScope(_TestScopes):164 def test_global_scope(self):165 lib, instance = self._get_lib_and_instance('BuiltIn')166 for mname in ['start_suite', 'start_suite', 'start_test', 'end_test',167 'start_test', 'end_test', 'end_suite', 'start_suite',168 'start_test', 'end_test', 'end_suite', 'end_suite']:169 getattr(lib, mname)()170 assert_true(instance is lib._libinst)171class TestSuiteScope(_TestScopes):172 def setUp(self):173 self.lib, self.instance = self._get_lib_and_instance("libraryscope.Suite")174 self.lib.start_suite()175 def test_start_suite_flushes_instance(self):176 assert_none(self.lib._libinst)177 inst = self.lib.get_instance()178 assert_not_none(inst)179 assert_false(inst is self.instance)180 def test_start_test_or_end_test_do_not_flush_instance(self):181 inst = self.lib.get_instance()182 for _ in range(10):183 self.lib.start_test()184 assert_true(inst is self.lib._libinst)185 assert_true(inst is self.lib.get_instance())186 self.lib.end_test()187 assert_true(inst is self.lib._libinst)188 def test_end_suite_restores_previous_instance_with_one_suite(self):189 self.lib.start_test()190 self.lib.get_instance()191 self.lib.end_test()192 self.lib.get_instance()193 self.lib.end_suite()194 assert_none(self.lib._libinst)195 def test_intance_caching(self):196 inst1 = self.lib.get_instance()197 inst2 = self._start_new_suite()198 assert_false(inst1 is inst2)199 self._run_tests(inst2)200 self._verify_end_suite_restores_previous_instance(inst1)201 inst3 = self._start_new_suite()202 inst4 = self._start_new_suite()203 self._run_tests(inst4, 10)204 self._verify_end_suite_restores_previous_instance(inst3)205 self._verify_end_suite_restores_previous_instance(inst1)206 self._verify_end_suite_restores_previous_instance(None)207 def _run_tests(self, exp_inst, count=3):208 for _ in range(count):209 self.lib.start_test()210 assert_true(self.lib.get_instance() is exp_inst)211 self.lib.end_test()212 assert_true(self.lib.get_instance() is exp_inst)213class TestCaseScope(_TestScopes):214 def setUp(self):215 self.lib, self.instance = self._get_lib_and_instance("libraryscope.Test")216 self.lib.start_suite()217 def test_different_instances_for_all_tests(self):218 self._run_tests(None)219 inst = self.lib.get_instance()220 self._run_tests(inst, 5)221 self.lib.end_suite()222 assert_none(self.lib._libinst)223 def test_nested_suites(self):224 top_inst = self.lib.get_instance()225 self._run_tests(top_inst, 4)226 self.lib.start_suite()227 self._run_tests(None, 3)228 self.lib.start_suite()229 self._run_tests(self.lib.get_instance(), 3)230 self.lib.end_suite()231 self.lib.end_suite()232 assert_true(self.lib._libinst is top_inst)233 def _run_tests(self, suite_inst, count=3):234 old_insts = [suite_inst]235 for _ in range(count):236 self.lib.start_test()237 assert_none(self.lib._libinst)238 inst = self.lib.get_instance()239 assert_false(inst in old_insts)240 old_insts.append(inst)241 self.lib.end_test()242 assert_true(self.lib._libinst is suite_inst)243class TestHandlers(unittest.TestCase):244 def test_get_handlers(self):245 for lib in [NameLibrary, DocLibrary, ArgInfoLibrary, GetattrLibrary, SynonymLibrary]:246 handlers = TestLibrary('classes.%s' % lib.__name__).handlers247 assert_equal(lib.handler_count, len(handlers), lib.__name__)248 for handler in handlers:249 assert_false(handler._handler_name.startswith('_'))250 assert_true('skip' not in handler._handler_name)251 def test_non_global_dynamic_handlers(self):252 lib = TestLibrary("RunKeywordLibrary")253 assert_equal(len(lib.handlers), 2)254 assert_true('Run Keyword That Passes' in lib.handlers)255 assert_true('Run Keyword That Fails' in lib.handlers)256 assert_none(lib.handlers['Run Keyword That Passes']._method)257 assert_none(lib.handlers['Run Keyword That Fails']._method)258 def test_global_dynamic_handlers(self):259 lib = TestLibrary("RunKeywordLibrary.GlobalRunKeywordLibrary")260 assert_equal(len(lib.handlers), 2)261 for name in 'Run Keyword That Passes', 'Run Keyword That Fails':262 handler = lib.handlers[name]263 assert_not_none(handler._method)264 assert_not_equal(handler._method, lib._libinst.run_keyword)265 assert_equal(handler._method.__name__, 'handler')266 def test_synonym_handlers(self):267 testlib = TestLibrary('classes.SynonymLibrary')268 names = ['handler', 'synonym_handler', 'another_synonym']269 for handler in testlib.handlers:270 # test 'handler_name' -- raises ValueError if it isn't in 'names'271 names.remove(handler._handler_name)272 assert_equal(len(names), 0, 'handlers %s not created' % names, False)273 def test_global_handlers_are_created_only_once(self):274 lib = TestLibrary('classes.RecordingLibrary')275 assert_true(lib.scope.is_global)276 instance = lib._libinst277 assert_true(instance is not None)278 assert_equal(instance.kw_accessed, 1)279 assert_equal(instance.kw_called, 0)280 for _ in range(5):281 lib.handlers.create_runner('kw')._run(_FakeContext(), [])282 assert_true(lib._libinst is instance)283 assert_equal(instance.kw_accessed, 1)284 assert_equal(instance.kw_called, 5)285class TestDynamicLibrary(unittest.TestCase):286 def test_get_keyword_doc_is_used_if_present(self):287 lib = TestLibrary('classes.ArgDocDynamicLibrary')288 assert_equal(lib.handlers['No Arg'].doc,289 'Keyword documentation for No Arg')290 assert_equal(lib.handlers['Multiline'].doc,291 'Multiline\nshort doc!\n\nBody\nhere.')292 def test_get_keyword_doc_and_args_are_ignored_if_not_callable(self):293 lib = TestLibrary('classes.InvalidAttributeDynamicLibrary')294 assert_equal(len(lib.handlers), 7)295 assert_equal(lib.handlers['No Arg'].doc, '')296 assert_handler_args(lib.handlers['No Arg'], 0, sys.maxsize)297 def test_handler_is_not_created_if_get_keyword_doc_fails(self):298 lib = TestLibrary('classes.InvalidGetDocDynamicLibrary')299 assert_equal(len(lib.handlers), 0)300 def test_handler_is_not_created_if_get_keyword_args_fails(self):301 lib = TestLibrary('classes.InvalidGetArgsDynamicLibrary')302 assert_equal(len(lib.handlers), 0)303 def test_arguments_without_kwargs(self):304 lib = TestLibrary('classes.ArgDocDynamicLibrary')305 for name, (mina, maxa) in [('No Arg', (0, 0)),306 ('One Arg', (1, 1)),307 ('One or Two Args', (1, 2)),308 ('Many Args', (0, sys.maxsize)),309 ('No Arg Spec', (0, sys.maxsize))]:310 assert_handler_args(lib.handlers[name], mina, maxa)311 def test_arguments_with_kwargs(self):312 lib = TestLibrary('classes.ArgDocDynamicLibraryWithKwargsSupport')313 for name, (mina, maxa) in [('No Arg', (0, 0)),314 ('One Arg', (1, 1)),315 ('One or Two Args', (1, 2)),316 ('Many Args', (0, sys.maxsize))]:317 assert_handler_args(lib.handlers[name], mina, maxa, kwargs=False)318 for name, (mina, maxa) in [('Kwargs', (0, 0)),319 ('Varargs and Kwargs', (0, sys.maxsize)),320 ('No Arg Spec', (0, sys.maxsize))]:321 assert_handler_args(lib.handlers[name], mina, maxa, kwargs=True)322def assert_handler_args(handler, minargs=0, maxargs=0, kwargs=False):323 assert_equal(handler.arguments.minargs, minargs)324 assert_equal(handler.arguments.maxargs, maxargs)325 assert_equal(bool(handler.arguments.var_named), kwargs)326class TestDynamicLibraryIntroDocumentation(unittest.TestCase):327 def test_doc_from_class_definition(self):328 self._assert_intro_doc('dynlibs.StaticDocsLib',329 'This is lib intro.')330 def test_doc_from_dynamic_method(self):331 self._assert_intro_doc('dynlibs.DynamicDocsLib',332 'Dynamic intro doc.')333 def test_dynamic_doc_overrides_class_doc(self):334 self._assert_intro_doc('dynlibs.StaticAndDynamicDocsLib',335 'dynamic override')336 def test_failure_in_dynamic_resolving_of_doc(self):337 lib = TestLibrary('dynlibs.FailingDynamicDocLib')338 assert_raises(DataError, getattr, lib, 'doc')339 def _assert_intro_doc(self, library_name, expected_doc):340 assert_equal(TestLibrary(library_name).doc, expected_doc)341class TestDynamicLibraryInitDocumentation(unittest.TestCase):342 def test_doc_from_class_init(self):343 self._assert_init_doc('dynlibs.StaticDocsLib', 'Init doc.')344 def test_doc_from_dynamic_method(self):345 self._assert_init_doc('dynlibs.DynamicDocsLib', 'Dynamic init doc.')346 def test_dynamic_doc_overrides_method_doc(self):347 self._assert_init_doc('dynlibs.StaticAndDynamicDocsLib',348 'dynamic override')349 def test_failure_in_dynamic_resolving_of_doc(self):350 init = TestLibrary('dynlibs.FailingDynamicDocLib').init351 assert_raises(DataError, getattr, init, 'doc')352 def _assert_init_doc(self, library_name, expected_doc):353 assert_equal(TestLibrary(library_name).init.doc, expected_doc)354class TestSourceAndLineno(unittest.TestCase):355 def test_class(self):356 lib = TestLibrary('classes.NameLibrary')357 self._verify(lib, classes_source, 10)358 def test_class_in_package(self):359 from robot.variables.variables import __file__ as source360 lib = TestLibrary('robot.variables.Variables')361 self._verify(lib, source, 24)362 def test_dynamic(self):363 lib = TestLibrary('classes.ArgDocDynamicLibrary')364 self._verify(lib, classes_source, 215)365 def test_module(self):366 from module_library import __file__ as source367 lib = TestLibrary('module_library')368 self._verify(lib, source, 1)369 def test_package(self):370 from robot.variables import __file__ as source371 lib = TestLibrary('robot.variables')372 self._verify(lib, source, 1)373 def test_decorated(self):374 lib = TestLibrary('classes.Decorated')375 self._verify(lib, classes_source, 317)376 def test_no_class_statement(self):377 lib = TestLibrary('classes.NoClassDefinition')378 self._verify(lib, classes_source, -1)379 def _verify(self, lib, source, lineno):380 if source:381 source = re.sub(r'(\.pyc|\$py\.class)$', '.py', source)382 source = os.path.normpath(source)383 assert_equal(lib.source, source)384 assert_equal(lib.lineno, lineno)385class _FakeNamespace:386 def __init__(self):387 self.variables = _FakeVariableScope()388 self.uk_handlers = []389 self.test = None390class _FakeVariableScope:391 def __init__(self):392 self.variables = {}393 def replace_scalar(self, variable):394 return variable395 def replace_list(self, args, replace_until=None):396 return []397 def replace_string(self, variable):398 try:399 number = variable.replace('$', '').replace('{', '').replace('}', '')400 return int(number)401 except ValueError:402 pass403 try:404 return self.variables[variable]405 except KeyError:406 raise DataError("Non-existing variable '%s'" % variable)407 def __setitem__(self, key, value):408 self.variables.__setitem__(key, value)409 def __getitem__(self, key):410 return self.variables.get(key)411class _FakeOutput:412 def trace(self, str):413 pass414 def log_output(self, output):415 pass416class _FakeContext:417 def __init__(self):418 self.output = _FakeOutput()419 self.namespace = _FakeNamespace()420 self.dry_run = False421 self.in_teardown = False422 self.variables = _FakeVariableScope()423 self.timeouts = set()424 self.test = None425if __name__ == '__main__':...

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