forked from imbus/robotframework-debuglibrary
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDebugLibrary.py
More file actions
executable file
·877 lines (710 loc) · 28.2 KB
/
DebugLibrary.py
File metadata and controls
executable file
·877 lines (710 loc) · 28.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Xie Yanbo <xieyanbo@gmail.com>
# This software is licensed under the New BSD License. See the LICENSE
# file in the top distribution directory for the full license text.
"""A debug library and REPL for RobotFramework.
"""
from __future__ import print_function
import cmd
import os
import re
import sys
import tempfile
from functools import wraps
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.history import FileHistory
from prompt_toolkit.interface import AbortAction
from prompt_toolkit.shortcuts import print_tokens, prompt
from prompt_toolkit.styles import style_from_dict
from pygments.token import Token
from robot import run_cli
from robot.api import logger
from robot.errors import ExecutionFailed, HandlerExecutionFailed, ExecutionPassed, ExecutionFailures
from robot.libdocpkg.model import LibraryDoc
from robot.libdocpkg.robotbuilder import KeywordDocBuilder, LibraryDocBuilder
from robot.libraries import STDLIBS
from robot.libraries.BuiltIn import BuiltIn
from robot.running.namespace import IMPORTER
from robot.running.context import EXECUTION_CONTEXTS
from robot.running.signalhandler import STOP_SIGNAL_MONITOR
from robot.variables import is_var
import inspect
import math
from robot.running.model import TestCase, TestSuite, UserKeyword, Keyword, ResourceFile
__version__ = '1.1.4'
HISTORY_PATH = os.environ.get('RFDEBUG_HISTORY', '~/.rfdebug_history')
KEYWORD_SEP = re.compile(' +|\t')
def get_command_line_encoding():
"""Get encoding from shell environment, default utf-8"""
try:
encoding = sys.stdout.encoding
except AttributeError:
encoding = sys.__stdout__.encoding
return encoding or 'utf-8'
COMMAND_LINE_ENCODING = get_command_line_encoding()
class HelpMeta(type):
def __init__(cls, name, bases, attrs):
for key, value in attrs.items():
if key.startswith('do_') and hasattr(value, '__call__'):
def auto_help(self):
print(self.get_help_string(key))
attrs['help_' + key] = help # assign help method
type.__init__(cls, name, bases, attrs)
class BaseCmd(cmd.Cmd, object):
"""Basic REPL tool"""
__metaclass__ = HelpMeta
def emptyline(self):
"""By default Cmd runs last command if an empty line is entered.
Disable it."""
pass
def do_exit(self, arg):
"""Exit the interpreter. You can also use the Ctrl-D shortcut."""
return True
do_EOF = do_exit
def help_help(self):
"""Help of Help command"""
print('Show help message.')
def do_pdb(self, arg):
"""Enter the python debuger pdb. For development only."""
print('break into python debugger: pdb')
import pdb
pdb.set_trace()
def get_libs():
"""Get libraries robotframework imported"""
return sorted(IMPORTER._library_cache._items, key=lambda _: _.name)
def get_libs_as_dict():
"""Get libraries robotframework imported as a name -> lib dict"""
return {l.name: l for l in IMPORTER._library_cache._items}
def match_libs(name=''):
"""Find libraries by prefix of library name, default all"""
libs = [_.name for _ in get_libs()]
matched = [_ for _ in libs if _.lower().startswith(name.lower())]
return matched
def memoize(function):
"""Memoization decorator"""
memo = {}
@wraps(function)
def wrapper(*args):
if args in memo:
return memo[args]
else:
rv = function(*args)
memo[args] = rv
return rv
return wrapper
class ImportedLibraryDocBuilder(LibraryDocBuilder):
def build(self, lib):
libdoc = LibraryDoc(name=lib.name,
doc=self._get_doc(lib),
doc_format=lib.doc_format)
libdoc.inits = self._get_initializers(lib)
libdoc.keywords = KeywordDocBuilder().build_keywords(lib)
return libdoc
@memoize
def get_lib_keywords(library):
"""Get keywords of imported library"""
lib = ImportedLibraryDocBuilder().build(library)
keywords = []
for keyword in lib.keywords:
doc = keyword.doc.split('\n')[0]
keywords.append({'name': keyword.name,
'lib': library.name,
'doc': doc})
return keywords
def get_keywords():
"""Get all keywords of libraries"""
for lib in get_libs():
for keyword in get_lib_keywords(lib):
yield keyword
NORMAL_STYLE = style_from_dict({
Token.Head: '#00FF00',
Token.Message: '#CCCCCC',
})
ERROR_STYLE = style_from_dict({
Token.Head: '#FF0000',
Token.Message: '#FFFFFF',
})
def print_output(head, message, style=NORMAL_STYLE):
"""Print prompt-toolkit tokens to output"""
tokens = [
(Token.Head, head + ' '),
(Token.Message, message),
(Token, '\n'),
]
print_tokens(tokens, style=style)
def print_error(head, message, style=ERROR_STYLE):
"""Print to output with error style"""
print_output(head, message, style=style)
def parse_keyword(command):
unicode_command = ''
if sys.version_info > (3,):
unicode_command = command
else:
unicode_command = command.decode(COMMAND_LINE_ENCODING)
return KEYWORD_SEP.split(unicode_command)
def assign_variable(bi, variable_name, args):
variable_value = bi.run_keyword(*args)
bi._variables.__setitem__(variable_name, variable_value)
return variable_value
def run_keyword(bi, command):
"""Run a keyword in robotframewrk environment"""
if not command:
return
try:
keyword_args = parse_keyword(command)
keyword = keyword_args[0]
args = keyword_args[1:]
is_comment = keyword.strip().startswith('#')
if is_comment:
return
variable_name = keyword.rstrip('= ')
if is_var(variable_name):
variable_only = not args
if variable_only:
display_value = ['Log to console', keyword]
bi.run_keyword(*display_value)
else:
variable_value = assign_variable(bi,
variable_name,
args)
print_output('#',
'{} = {!r}'.format(variable_name,
variable_value))
else:
result = bi.run_keyword(keyword, *args)
if result:
print_output('<', repr(result))
except ExecutionFailed as exc:
print_error('! keyword:', command)
print_error('!', exc.message)
except HandlerExecutionFailed as exc:
print_error('! keyword:', command)
print_error('!', exc.full_message)
except Exception as exc:
print_error('! keyword:', command)
print_error('! FAILED:', repr(exc))
class CmdCompleter(Completer):
"""Completer for debug shell"""
def __init__(self, commands, cmd_repl=None):
self.names = []
self.displays = {}
self.display_metas = {}
for name, display, display_meta in commands:
self.names.append(name)
self.displays[name] = display
self.display_metas[name] = display_meta
self.cmd_repl = cmd_repl
def get_argument_completions(self, completer, document):
"""Using Cmd.py's completer to complete arguments"""
endidx = document.cursor_position_col
line = document.current_line
begidx = (line[:endidx].rfind(' ') + 1
if line[:endidx].rfind(' ') >= 0 else 0)
prefix = line[begidx:endidx]
completions = completer(prefix,
line,
begidx,
endidx)
for comp in completions:
yield Completion(comp, begidx - endidx, display=comp)
def get_completions(self, document, complete_event):
"""Compute suggestions"""
text = document.text_before_cursor.lower()
parts = KEYWORD_SEP.split(text)
if len(parts) >= 2:
cmd_name = parts[0].strip()
completer = getattr(self.cmd_repl, 'complete_' + cmd_name, None)
if completer:
for c in self.get_argument_completions(completer, document):
yield c
return
for name in self.names:
library_level = '.' in name and '.' in text
root_level = '.' not in name and '.' not in text
if not (root_level or library_level):
continue
if name.lower().strip().startswith(text.strip()):
display = self.displays.get(name, '')
display_meta = self.display_metas.get(name, '')
yield Completion(name,
-len(text),
display=display,
display_meta=display_meta)
class PtkCmd(BaseCmd):
"""CMD shell using prompt-toolkit"""
prompt = u'> '
get_prompt_tokens = None
prompt_style = None
intro = '''\
Only accepted plain text format keyword seperated with two or more spaces.
Type "help" for more information.\
'''
def __init__(self, completekey='tab', stdin=None, stdout=None):
BaseCmd.__init__(self, completekey, stdin, stdout)
self.history = FileHistory(os.path.expanduser(HISTORY_PATH))
def get_cmd_names(self):
"""Get all command names of CMD shell"""
pre = 'do_'
cut = len(pre)
return [_[cut:] for _ in self.get_names() if _.startswith(pre)]
def get_help_string(self, command_name):
"""Get help document of command"""
func = getattr(self, 'do_' + command_name, None)
if not func:
return ''
return func.__doc__
def get_helps(self):
"""Get all help documents of commands"""
return [(name, self.get_help_string(name) or name)
for name in self.get_cmd_names()]
def get_completer(self):
"""Get completer instance"""
commands = [(name, '', doc) for name, doc in self.get_helps()]
cmd_completer = CmdCompleter(commands, self)
return cmd_completer
def pre_loop(self):
pass
def cmdloop(self, intro=None):
"""Better command loop supported by prompt_toolkit
override default cmdloop method
"""
if intro is not None:
self.intro = intro
if self.intro:
self.stdout.write(str(self.intro) + '\n')
#self.do_look(None)
stop = None
while not stop:
self.pre_loop()
if self.cmdqueue:
line = self.cmdqueue.pop(0)
else:
kwargs = dict(history=self.history,
auto_suggest=AutoSuggestFromHistory(),
enable_history_search=True,
completer=self.get_completer(),
display_completions_in_columns=True,
on_abort=AbortAction.RETRY)
if self.get_prompt_tokens:
kwargs['get_prompt_tokens'] = self.get_prompt_tokens
kwargs['style'] = self.prompt_style
prompt_str = u''
else:
prompt_str = self.prompt
try:
line = prompt(prompt_str, **kwargs)
except EOFError:
line = 'EOF'
line = self.precmd(line)
stop = self.onecmd(line)
stop = self.postcmd(stop, line)
self.postloop()
def get_prompt_tokens(self, cli):
"""Print prompt-toolkit prompt"""
return [
(Token.Prompt, u'> '),
]
class DebugCmd(PtkCmd):
"""Interactive debug shell for robotframework"""
get_prompt_tokens = get_prompt_tokens
prompt_style = style_from_dict({Token.Prompt: '#0000FF'})
def __init__(self, completekey='tab', stdin=None, stdout=None, debug_inst=None):
PtkCmd.__init__(self, completekey, stdin, stdout)
self.rf_bi = BuiltIn()
self.debug_inst = debug_inst
def postcmd(self, stop, line):
"""Run after a command"""
return stop
def reset_robotframework_exception(self):
if STOP_SIGNAL_MONITOR._signal_count:
STOP_SIGNAL_MONITOR._signal_count = 0
STOP_SIGNAL_MONITOR._running_keyword = True
logger.info('Reset last exception by DebugLibrary')
def pre_loop(self):
self.reset_robotframework_exception()
def do_next(self, arg):
from robot.running.model import Keyword
new_kwd = Keyword(name='Debug')
self.debug_inst.most_recent_step_runner.steps.insert(1, new_kwd)
return True
# STUB
def do_step(self, arg):
current_steps = self.debug_inst.most_recent_step_runner.steps
next_step = current_steps[0]
from robot.running.model import Keyword
#new_kwd = Keyword(name='Debug')
# TODO: insert this keyword into the subsequent step, instead of after it.
# new_kwd needs to be inserted into next_step.
self.debug_inst.debug_trigger = True
return True
#logger.console("Step is not implemented yet.")
def do_look(self, depth=math.inf):
depth = int(depth) if depth else math.inf
stack = self.debug_inst.keyword_stack
# import pdb
# pdb.set_trace()
libs = get_libs_as_dict()
print_stack = []
source_of_next = None
for idx, (name, attributes, context, step_runner) in enumerate(stack):
source = source_of_next
namespace = context.namespace
runner = namespace.get_runner(name)
from robot.running.librarykeywordrunner import LibraryKeywordRunner
from robot.running.userkeywordrunner import UserKeywordRunner
if isinstance(runner, LibraryKeywordRunner):
source_of_next = runner.library.source
elif isinstance(runner, UserKeywordRunner):
user_keywords = namespace._kw_store.user_keywords
if name in user_keywords.handlers:
source_of_next = user_keywords.source
else:
potential_sources = []
resources = namespace._kw_store.resources.values()
for resource in resources:
if name in [handler.longname for handler in resource.handlers]:
potential_sources.append(resource.source)
if len(potential_sources) > 1:
raise NotImplementedError("Have not implemented dealing with multiple resources.")
source_of_next = potential_sources[0]
else:
raise Exception("Runner passed that is not dealt with.")
# Top level
# for step in step_runner.og_steps:
# print(step)
current_steps = step_runner.steps
parent_stack = []
parent_set = {step.parent for step in current_steps}
parent_set.discard(None)
if len(parent_set) > 1:
print('current_steps has multiple parents.')
for step in current_steps:
print(step, step.parent)
raise Exception('current_steps has multiple parents.')
elif len(parent_set) == 0:
print(parent_set)
raise Exception('current_steps has no parents somehow')
parent = next(iter(parent_set))
while parent is not None:
if isinstance(parent, TestCase):
parent_stack.append('Test Case: {}'.format(parent.name))
elif isinstance(parent, TestSuite):
parent_stack.append('Test Suite: {}, source: {}'.format(parent.name, parent.source))
elif isinstance(parent, UserKeyword):
parent_stack.append('Keyword: {}, source: {}'.format(parent.name, source))
else:
print('uncaught parent type')
print(parent)
raise Exception('Uncaught parent type')
if hasattr(parent, 'parent'):
parent = parent.parent
else:
parent = None
highlighted_idx = len(step_runner.og_steps) - len(step_runner.steps)
if idx != len(stack)-1:
highlighted_idx -= 1
steps_stack = []
for idx, step in enumerate(step_runner.og_steps):
if idx == highlighted_idx:
steps_stack.append(' {} <-----'.format(step))
else:
steps_stack.append(' {}'.format(step))
print_stack.append((source, steps_stack, parent_stack))
print('----------')
if depth < len(print_stack):
print_stack = print_stack[-depth:]
while len(print_stack) > 0:
source, steps_stack, parent_stack = print_stack.pop(0)
while len(parent_stack) > 0:
string = parent_stack.pop()
print(string)
for step in steps_stack:
print(step)
def do_help(self, arg):
"""Show help message."""
if not arg.strip():
print('''\
Input Robotframework keywords, or commands listed below.
Use "libs" or "l" to see available libraries,
use "keywords" or "k" see the list of library keywords,
use the TAB keyboard key to autocomplete keywords.\
''')
PtkCmd.do_help(self, arg)
def get_completer(self):
"""Get completer instance specified for robotframework"""
# commands
commands = [(cmd_name,
cmd_name,
'DEBUG command: {0}'.format(doc))
for cmd_name, doc in self.get_helps()]
# libraries
for lib in get_libs():
commands.append((lib.name,
lib.name,
'Library: {0} {1}'.format(lib.name, lib.version)))
# keywords
for keyword in get_keywords():
# name with library
name = keyword['lib'] + '.' + keyword['name']
commands.append((name,
keyword['name'],
u'Keyword: {0}'.format(keyword['doc'])))
# name without library
commands.append((keyword['name'],
keyword['name'],
u'Keyword[{0}.]: {1}'.format(keyword['lib'],
keyword['doc'])))
cmd_completer = CmdCompleter(commands, self)
return cmd_completer
def do_selenium(self, arg):
"""Start a selenium webdriver and open url in browser you expect.
s(elenium) [<url>] [<browser>]
default url is google.com, default browser is firefox.
"""
command = 'import library SeleniumLibrary'
print_output('#', command)
run_keyword(self.rf_bi, command)
# Set defaults, overriden if args set
url = 'http://www.google.com/'
browser = 'firefox'
if arg:
args = KEYWORD_SEP.split(arg)
if len(args) == 2:
url, browser = args
else:
url = arg
if '://' not in url:
url = 'http://' + url
command = 'open browser %s %s' % (url, browser)
print_output('#', command)
run_keyword(self.rf_bi, command)
do_s = do_selenium
def complete_selenium(self, text, line, begin_idx, end_idx):
"""complete selenium command"""
webdrivers = ['firefox',
'chrome',
'ie',
'opera',
'safari',
'phantomjs',
'remote']
if len(line.split()) == 3:
command, url, driver_name = line.lower().split()
return [d for d in webdrivers if d.startswith(driver_name)]
elif len(line.split()) == 2 and line.endswith(' '):
return webdrivers
return []
complete_s = complete_selenium
def default(self, line):
"""Run RobotFramework keywords"""
command = line.strip()
run_keyword(self.rf_bi, command)
def do_libs(self, args):
"""Print imported and builtin libraries, with source if `-s` specified.
l(ibs) [-s]
"""
print_output('<', 'Imported libraries:')
for lib in get_libs():
print_output(' {}'.format(lib.name), lib.version)
if lib.doc:
print(' {}'.format(lib.doc.split('\n')[0]))
if '-s' in args:
print(' {}'.format(lib.source))
print_output('<', 'Builtin libraries:')
for name in sorted(list(STDLIBS)):
print_output(' ' + name, '')
do_l = do_libs
def complete_libs(self, text, line, begin_idx, end_idx):
"""complete libs command"""
if len(line.split()) == 1 and line.endswith(' '):
return ['-s']
return []
complete_l = complete_libs
def do_keywords(self, args):
"""Print keywords of libraries, all or starts with <lib_name>
k(eywords) [<lib_name>]
"""
lib_name = args
matched = match_libs(lib_name)
if not matched:
print_error('< not found library', lib_name)
return
libs = get_libs_as_dict()
for name in matched:
lib = libs[name]
print_output('< Keywords of library', name)
for keyword in get_lib_keywords(lib):
print_output(' {}\t'.format(keyword['name']),
keyword['doc'])
do_k = do_keywords
def complete_keywords(self, text, line, begin_idx, end_idx):
"""complete keywords command"""
if len(line.split()) == 2:
command, lib_name = line.split()
return match_libs(lib_name)
elif len(line.split()) == 1 and line.endswith(' '):
return [_.name for _ in get_libs()]
return []
complete_k = complete_keywords
class DebugLibrary(object):
"""Debug Library for RobotFramework"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = __version__
ROBOT_LISTENER_API_VERSION = 2
keyword_stack = []
most_recent_step_runner = None
debug_trigger = False
def __init__(self, experimental=False):
logger.error('initializing debuglib')
if experimental:
StepRunner.run_steps = run_steps
self.ROBOT_LIBRARY_LISTENER = self
self.step_runner = None
self.debug_trigger = False
def start_test(self, name, results):
if len(self.keyword_stack) != 0:
raise Exception("Keyword stack not empty at test start")
def start_keyword(self, name, attributes):
context = EXECUTION_CONTEXTS.current
self.keyword_stack.append((name, attributes, context, self.most_recent_step_runner))
def end_keyword(self, name, attributes):
self.keyword_stack.pop()
def end_test(self, name, results):
if len(self.keyword_stack) != 0:
raise Exception("Keyword start not empty at test end.")
@staticmethod
def _get_closest_step_runner():
f = inspect.currentframe().f_back
while f is not None:
loc = f.f_locals
for v in loc.values():
if isinstance(v, StepRunner):
return v
f = f.f_back
raise Exception("No StepRunner found, this should never happen.")
# 0-indexed
@staticmethod
def _get_nth_closest_step_runner(n):
srs = set()
f = inspect.currentframe().f_back
while f is not None:
loc = f.f_locals
for v in loc.values():
if isinstance(v, StepRunner):
if len(srs) == n and v not in srs:
return v
elif v not in srs:
srs.add(v)
elif v in srs:
pass
f = f.f_back
raise Exception("No StepRunner found, this should never happen.")
def debug(self):
"""Open a interactive shell, run any RobotFramework keywords.
Keywords seperated by two space or one tab, and Ctrl-D to exit.
"""
# re-wire stdout so that we can use the cmd module and have readline
# support
self.debug_trigger = False
old_stdout = sys.stdout
sys.stdout = sys.__stdout__
print_output('\n>>>>>', 'Enter interactive shell')
debug_cmd = DebugCmd(debug_inst=self)
debug_cmd.cmdloop()
print_output('\n>>>>>', 'Exit shell.')
# put stdout back where it was
sys.stdout = old_stdout
def get_remote_url(self):
"""Get selenium URL for connecting to remote WebDriver."""
s = BuiltIn().get_library_instance('Selenium2Library')
url = s._current_browser().command_executor._url
return url
def get_session_id(self):
"""Get selenium browser session id."""
s = BuiltIn().get_library_instance('Selenium2Library')
job_id = s._current_browser().session_id
return job_id
def get_webdriver_remote(self):
"""Print the way connecting to remote selenium server."""
remote_url = self.get_remote_url()
session_id = self.get_session_id()
s = 'from selenium import webdriver;' \
'd=webdriver.Remote(command_executor="%s",' \
'desired_capabilities={});' \
'd.session_id="%s"' % (
remote_url,
session_id
)
logger.console('''
DEBUG FROM CONSOLE
# geckodriver user please check https://stackoverflow.com/a/37968826/150841
%s
''' % (s))
logger.info(s)
return s
TEST_SUITE = b'''*** Settings ***
Library DebugLibrary
** test case **
RFDEBUG REPL
debug
'''
def shell():
"""A standalone robotframework shell"""
with tempfile.NamedTemporaryFile(prefix='robot-debug-',
suffix='.txt',
delete=False) as test_file:
try:
test_file.write(TEST_SUITE)
test_file.flush()
default_no_logs = '-l None -x None -o None -L None -r None'
if len(sys.argv) > 1:
args = sys.argv[1:] + [test_file.name]
else:
args = default_no_logs.split() + [test_file.name]
rc = run_cli(args)
sys.exit(rc)
finally:
test_file.close()
# pybot will raise PermissionError on Windows NT or later
# if NamedTemporaryFile called with `delete=True`,
# deleting test file seperated will be OK.
if os.path.exists(test_file.name):
os.unlink(test_file.name)
if __name__ == '__main__':
shell()
from robot.running.steprunner import StepRunner
def run_steps(self, steps):
from robot.api import logger
logger.error('run_steps')
logger.error(steps)
debugLibrary = BuiltIn().get_library_instance('DebugLibrary')
debugLibrary.most_recent_step_runner = self
errors = []
self.steps = []
self.og_steps = steps
from robot.api import logger
logger.error('run steps before trigger check {}'.format(debugLibrary.debug_trigger))
if debugLibrary.debug_trigger:
logger.error('run steps debug trigger')
new_kwd = Keyword(name='Debug')
self.steps.append(new_kwd)
debugLibrary.debug_trigger = False
for step in steps:
self.steps.append(step)
while len(self.steps) > 0:
self.cur_step = self.steps.pop(0)
try:
self.run_step(self.cur_step)
except ExecutionPassed as exception:
exception.set_earlier_failures(errors)
raise exception
except ExecutionFailed as exception:
errors.extend(exception.get_errors())
if not exception.can_continue(self._context.in_teardown,
self._templated,
self._context.dry_run):
break
if errors:
raise ExecutionFailures(errors)