How to use path_getrootdir method in Behave

Best Python code snippet using behave

runner_file.py

Source:runner_file.py Github

copy

Full Screen

...253 code = compile(f.read(), filename2, 'exec')254 exec(code, globals, locals)255 else:256 exec_file((filename, globals, locals))257def path_getrootdir(path):258 """259 Extract rootdir from path in a platform independent way.260 POSIX-PATH EXAMPLE:261 rootdir = path_getrootdir("/foo/bar/one.feature")262 assert rootdir == "/"263 WINDOWS-PATH EXAMPLE:264 rootdir = path_getrootdir("D:\\foo\\bar\\one.feature")265 assert rootdir == r"D:\"266 """267 drive, _ = os.path.splitdrive(path)268 if drive:269 # -- WINDOWS:270 return drive + os.path.sep271 # -- POSIX:272 return os.path.sep273class PathManager(object):274 """275 Context manager to add paths to sys.path (python search path) within a scope276 """277 def __init__(self, paths=None):278 self.initial_paths = paths or []279 self.paths = None280 def __enter__(self):281 self.paths = list(self.initial_paths)282 sys.path = self.paths + sys.path283 def __exit__(self, *crap):284 for path in self.paths:285 sys.path.remove(path)286 self.paths = None287 def add(self, path):288 if self.paths is None:289 # -- CALLED OUTSIDE OF CONTEXT:290 self.initial_paths.append(path)291 else:292 sys.path.insert(0, path)293 self.paths.append(path)294class Runner(object):295 '''296 Test runner for behave.297 .. attribute:: aborted298 This is set to true when the user aborts a test run299 (:exc:`KeyboardInterrupt` exception). Initially: False.300 Stored as derived attribute in :attr:`Context.aborted`.301 '''302 def __init__(self, config):303 self.config = config304 self.hooks = {}305 self.features = []306 self.undefined = []307 # -- XXX-JE-UNUSED:308 # self.passed = []309 # self.failed = []310 # self.skipped = []311 self.path_manager = PathManager()312 self.feature = None313 self.stdout_capture = None314 self.stderr_capture = None315 self.log_capture = None316 self.old_stdout = None317 self.old_stderr = None318 self.base_dir = None319 self.context = None320 self.formatters = None321 # @property322 def _get_aborted(self):323 """324 Indicates that a test run was aborted by the user325 (:exc:`KeyboardInterrupt` exception).326 Stored in :attr:`Context.aborted` attribute (as root attribute).327 :return: Current aborted state, initially false.328 :rtype: bool329 """330 value = False331 if self.context:332 value = self.context.aborted333 return value334 # @aborted.setter335 def _set_aborted(self, value):336 """337 Set the aborted value.338 :param value: New aborted value (as bool).339 """340 assert self.context341 self.context._set_root_attribute('aborted', bool(value))342 aborted = property(_get_aborted, _set_aborted,343 doc="Indicates that test run is aborted by the user.")344 def setup_paths(self):345 if self.config.paths:346 if self.config.verbose:347 print348 'Supplied path:', \349 ', '.join('"%s"' % path for path in self.config.paths)350 first_path = self.config.paths[0]351 if hasattr(first_path, "filename"):352 # -- BETTER: isinstance(first_path, FileLocation):353 first_path = first_path.filename354 base_dir = first_path355 if base_dir.startswith('@'):356 # -- USE: behave @features.txt357 base_dir = base_dir[1:]358 file_locations = self.feature_locations()359 if file_locations:360 base_dir = os.path.dirname(file_locations[0].filename)361 base_dir = os.path.abspath(base_dir)362 # supplied path might be to a feature file363 if os.path.isfile(base_dir):364 if self.config.verbose:365 print366 'Primary path is to a file so using its directory'367 base_dir = os.path.dirname(base_dir)368 else:369 if self.config.verbose:370 print371 'Using default path "./features"'372 base_dir = os.path.abspath('features')373 # Get the root. This is not guaranteed to be '/' because Windows.374 root_dir = path_getrootdir(base_dir)375 new_base_dir = base_dir376 while True:377 if self.config.verbose:378 print379 'Trying base directory:', new_base_dir380 if os.path.isdir(os.path.join(new_base_dir, 'steps')):381 break382 if os.path.isfile(os.path.join(new_base_dir, 'environment.py')):383 break384 if new_base_dir == root_dir:385 break386 new_base_dir = os.path.dirname(new_base_dir)387 if new_base_dir == root_dir:388 if self.config.verbose:...

Full Screen

Full Screen

runner.py

Source:runner.py Github

copy

Full Screen

...241 # except Exception as e:242 # e_text = _text(e)243 # print("Exception %s: %s" % (e.__class__.__name__, e_text))244 # raise245def path_getrootdir(path):246 """247 Extract rootdir from path in a platform independent way.248 POSIX-PATH EXAMPLE:249 rootdir = path_getrootdir("/foo/bar/one.feature")250 assert rootdir == "/"251 WINDOWS-PATH EXAMPLE:252 rootdir = path_getrootdir("D:\\foo\\bar\\one.feature")253 assert rootdir == r"D:\"254 """255 drive, _ = os.path.splitdrive(path)256 if drive:257 # -- WINDOWS:258 return drive + os.path.sep259 # -- POSIX:260 return os.path.sep261class PathManager(object):262 """263 Context manager to add paths to sys.path (python search path) within a scope264 """265 def __init__(self, paths=None):266 self.initial_paths = paths or []267 self.paths = None268 def __enter__(self):269 self.paths = list(self.initial_paths)270 sys.path = self.paths + sys.path271 def __exit__(self, *crap):272 for path in self.paths:273 sys.path.remove(path)274 self.paths = None275 def add(self, path):276 if self.paths is None:277 # -- CALLED OUTSIDE OF CONTEXT:278 self.initial_paths.append(path)279 else:280 sys.path.insert(0, path)281 self.paths.append(path)282class ModelRunner(object):283 """284 Test runner for a behave model (features).285 Provides the core functionality of a test runner and286 the functional API needed by model elements.287 .. attribute:: aborted288 This is set to true when the user aborts a test run289 (:exc:`KeyboardInterrupt` exception). Initially: False.290 Stored as derived attribute in :attr:`Context.aborted`.291 """292 def __init__(self, config, features=None):293 self.config = config294 self.features = features or []295 self.hooks = {}296 self.formatters = []297 self.undefined_steps = []298 self.context = None299 self.feature = None300 self.stdout_capture = None301 self.stderr_capture = None302 self.log_capture = None303 self.old_stdout = None304 self.old_stderr = None305 # @property306 def _get_aborted(self):307 value = False308 if self.context:309 value = self.context.aborted310 return value311 # @aborted.setter312 def _set_aborted(self, value):313 assert self.context314 self.context._set_root_attribute('aborted', bool(value))315 aborted = property(_get_aborted, _set_aborted,316 doc="Indicates that test run is aborted by the user.")317 def run_hook(self, name, context, *args):318 if not self.config.dry_run and (name in self.hooks):319 # try:320 with context.user_mode():321 self.hooks[name](context, *args)322 # except KeyboardInterrupt:323 # self.aborted = True324 # if name not in ("before_all", "after_all"):325 # raise326 def setup_capture(self):327 if not self.context:328 self.context = Context(self)329 if self.config.stdout_capture:330 self.stdout_capture = StringIO()331 self.context.stdout_capture = self.stdout_capture332 if self.config.stderr_capture:333 self.stderr_capture = StringIO()334 self.context.stderr_capture = self.stderr_capture335 if self.config.log_capture:336 self.log_capture = LoggingCapture(self.config)337 self.log_capture.inveigle()338 self.context.log_capture = self.log_capture339 def start_capture(self):340 if self.config.stdout_capture:341 # -- REPLACE ONLY: In non-capturing mode.342 if not self.old_stdout:343 self.old_stdout = sys.stdout344 sys.stdout = self.stdout_capture345 assert sys.stdout is self.stdout_capture346 if self.config.stderr_capture:347 # -- REPLACE ONLY: In non-capturing mode.348 if not self.old_stderr:349 self.old_stderr = sys.stderr350 sys.stderr = self.stderr_capture351 assert sys.stderr is self.stderr_capture352 def stop_capture(self):353 if self.config.stdout_capture:354 # -- RESTORE ONLY: In capturing mode.355 if self.old_stdout:356 sys.stdout = self.old_stdout357 self.old_stdout = None358 assert sys.stdout is not self.stdout_capture359 if self.config.stderr_capture:360 # -- RESTORE ONLY: In capturing mode.361 if self.old_stderr:362 sys.stderr = self.old_stderr363 self.old_stderr = None364 assert sys.stderr is not self.stderr_capture365 def teardown_capture(self):366 if self.config.log_capture:367 self.log_capture.abandon()368 def run_model(self, features=None):369 if not self.context:370 self.context = Context(self)371 if features is None:372 features = self.features373 # -- ENSURE: context.execute_steps() works in weird cases (hooks, ...)374 context = self.context375 self.setup_capture()376 self.run_hook('before_all', context)377 run_feature = not self.aborted378 failed_count = 0379 undefined_steps_initial_size = len(self.undefined_steps)380 for feature in features:381 if run_feature:382 try:383 self.feature = feature384 for formatter in self.formatters:385 formatter.uri(feature.filename)386 failed = feature.run(self)387 if failed:388 failed_count += 1389 if self.config.stop or self.aborted:390 # -- FAIL-EARLY: After first failure.391 run_feature = False392 except KeyboardInterrupt:393 self.aborted = True394 failed_count += 1395 run_feature = False396 # -- ALWAYS: Report run/not-run feature to reporters.397 # REQUIRED-FOR: Summary to keep track of untested features.398 for reporter in self.config.reporters:399 reporter.feature(feature)400 # -- AFTER-ALL:401 if self.aborted:402 print("\nABORTED: By user.")403 for formatter in self.formatters:404 formatter.close()405 self.run_hook('after_all', self.context)406 for reporter in self.config.reporters:407 reporter.end()408 # if self.aborted:409 # print("\nABORTED: By user.")410 failed = ((failed_count > 0) or self.aborted or411 (len(self.undefined_steps) > undefined_steps_initial_size))412 return failed413 def run(self):414 """415 Implements the run method by running the model.416 """417 self.context = Context(self)418 return self.run_model()419class Runner(ModelRunner):420 """421 Standard test runner for behave:422 * setup paths423 * loads environment hooks424 * loads step definitions425 * select feature files, parses them and creates model (elements)426 """427 def __init__(self, config):428 super(Runner, self).__init__(config)429 self.path_manager = PathManager()430 self.base_dir = None431 def setup_paths(self):432 if self.config.paths:433 if self.config.verbose:434 print('Supplied path:', \435 ', '.join('"%s"' % path for path in self.config.paths))436 first_path = self.config.paths[0]437 if hasattr(first_path, "filename"):438 # -- BETTER: isinstance(first_path, FileLocation):439 first_path = first_path.filename440 base_dir = first_path441 if base_dir.startswith('@'):442 # -- USE: behave @features.txt443 base_dir = base_dir[1:]444 file_locations = self.feature_locations()445 if file_locations:446 base_dir = os.path.dirname(file_locations[0].filename)447 base_dir = os.path.abspath(base_dir)448 # supplied path might be to a feature file449 if os.path.isfile(base_dir):450 if self.config.verbose:451 print('Primary path is to a file so using its directory')452 base_dir = os.path.dirname(base_dir)453 else:454 if self.config.verbose:455 print('Using default path "./features"')456 base_dir = os.path.abspath('features')457 # Get the root. This is not guaranteed to be '/' because Windows.458 root_dir = path_getrootdir(base_dir)459 new_base_dir = base_dir460 steps_dir = self.config.steps_dir461 environment_file = self.config.environment_file462 while True:463 if self.config.verbose:464 print('Trying base directory:', new_base_dir)465 if os.path.isdir(os.path.join(new_base_dir, steps_dir)):466 break467 if os.path.isfile(os.path.join(new_base_dir, environment_file)):468 break469 if new_base_dir == root_dir:470 break471 new_base_dir = os.path.dirname(new_base_dir)472 if new_base_dir == root_dir:...

Full Screen

Full Screen

runner.pyi

Source:runner.pyi Github

copy

Full Screen

...23@contextlib.contextmanager24def use_context_with_mode(context: Context, mode: Mode) -> Iterator[None]: ...25@contextlib.contextmanager26def scoped_context_layer(context: Context, layer_name: str|None = None) -> Iterator[Context]: ...27def path_getrootdir(path: str)-> str: ...28class CleanupError(RuntimeError): ...29class ContextMaskWarning(UserWarning): ...30class Context(Protocol):31 def __getattr__(self, name: str) -> Any: ...32 def __setattr__(self, name: str, value: Any) -> None: ...33 def __contains__(self, name: str) -> bool: ...34 def add_cleanup(self, cleanup_func: Callable[..., None], *a: Any, **k: Any) -> None: ...35 @property36 def config(self) -> Configuration: ...37 @property38 def aborted(self) -> bool: ...39 @property40 def failed(self) -> bool: ...41 @property...

Full Screen

Full Screen

behave.py

Source:behave.py Github

copy

Full Screen

...9 import behave.runner10 class GGRCRunner(behave.runner.Runner):11 def find_steps_paths_from_path(self, path):12 steps_dirs = []13 root_dir = behave.runner.path_getrootdir(path)14 while True:15 if os.path.isdir(os.path.join(path, 'steps')):16 steps_dirs.append(os.path.join(path, 'steps'))17 if path == root_dir:18 break19 path = os.path.dirname(path)20 return steps_dirs21 def find_steps_paths_from_paths(self, paths):22 steps_dirs = []23 # `self.config.paths` contains all paths passed on the command line24 for path in self.config.paths:25 # We use 'abspath' to normalize trailing '/' and avoid duplicates26 path = os.path.abspath(path)27 steps_dirs.extend(self.find_steps_paths_from_path(path))...

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