Best Python code snippet using robotframework
completer.py
Source:completer.py
...118 """119 if self._doc_cache is None:120 self._doc_cache = {}121 for lib in ["BuiltIn"]:122 self._load_libdoc(lib)123 self._update_imports(history)124 docs = dict(**self._doc_cache, **self._history_docs(history))125 return docs126 def _load_libdoc(self, name, source=None, use_cache=True):127 """ Try to load a libdoc, either by name, or named source. Tries to use128 the cache.129 """130 strategies = [name]131 if source is not None and source.endswith(".robot"):132 try:133 strategies += [find_file(source)]134 except Exception:135 pass136 for strategy in strategies:137 if use_cache and strategy in self._doc_cache:138 return self._doc_cache[strategy]139 try:140 libdoc = LibraryDocumentation(strategy)141 self._doc_cache[strategy] = self._doc_cache[name] = libdoc142 return libdoc143 except Exception as err:144 pass145 self.log.debug("Could not load libdoc for %s: %s", strategy, err)146 def _lib_html(self, libname: str, history: List[str]) -> str:147 """ Return documentation for a library (or keyword)148 TODO: keywords, variables149 """150 found = None151 for name, libdoc in self.docs(history).items():152 if libname.lower().strip() == name.lower().strip():153 found = libdoc154 break155 found = found or self._load_libdoc(libname)156 if found is None:157 return158 formatter = DocFormatter(found.keywords, found.doc, found.doc_format)159 libdoc_json = JsonConverter(formatter).convert(found)160 return LIB_TEMPLATE.render(libdoc=libdoc_json, **DOC_CONTEXT)161 def _keyword_html(self, tokens, code, line, line_cursor, offset, history):162 for name, libdoc in self.docs(history).items():163 for kw in libdoc.keywords:164 for token in filter(str, tokens):165 if kw.name.lower() == token.lower():166 formatter = DocFormatter([kw], libdoc.doc, libdoc.doc_format)167 libdoc_json = JsonConverter(formatter).convert(libdoc)168 libdoc_json["keywords"] = [169 libkw170 for libkw in libdoc_json["keywords"]171 if libkw["name"] == kw.name172 ]173 return KW_TEMPLATE.render(libdoc=libdoc_json, **DOC_CONTEXT)174 def _update_imports(self, history=[]):175 for impname, imp in (self.imports or {}).items():176 if impname not in SKIP_LIBS:177 source = imp.get("source")178 if source is not None and source.endswith(".robot"):179 try:180 source = find_file(source)181 except Exception:182 pass183 self._load_libdoc(impname, source=source)184 for match in re.findall(RE_IMPORT, "\n".join(history), flags=re.I | re.M):185 self._load_libdoc(match[2])186 def _history_docs(self, history: List[str] = None) -> dict:187 hist_with_keywords = self._history_with_keywords(history)188 if not hist_with_keywords:189 return {}190 hist_libdoc = self._history_libdoc(hist_with_keywords)191 if hist_libdoc is None:192 return {}193 return {"__main__": hist_libdoc}194 def _history_libdoc(self, history: List[str]):195 libdoc = None196 keywords = {}197 with TemporaryDirectory() as td:198 tdp = Path(td)199 for i, hist in enumerate(history):200 tmp_lib = tdp / f"{i}.robot"201 tmp_lib.write_text(hist)202 libdoc = self._load_libdoc(str(tmp_lib), use_cache=False)203 if libdoc is None:204 continue205 for kw in getattr(libdoc, "keywords", []):206 keywords[kw.name] = kw207 if libdoc is None or not keywords:208 return None209 libdoc.keywords = keywords.values()210 return libdoc211 def _history_with_keywords(self, history: List[str] = None) -> List[str]:212 for hist in history or []:213 if re.match(r"^\*+\s*keywords", hist, flags=re.I):214 yield hist215 def _history_with_imports(self, history: List[str] = None) -> List[str]:216 for hist in history or []:...
libdoc.py
Source:libdoc.py
...148 from robot.libdoc import libdoc_cli149 libdoc_cli(['--version', '1.0', 'MyLibrary.py', 'MyLibraryDoc.html'])150 """151 LibDoc().execute_cli(arguments)152def libdoc(library_or_resource, outfile, name='', version='', format=None):153 """Executes libdoc.154 Arguments have same semantics as Libdoc command line options with155 same names.156 Example::157 from robot.libdoc import libdoc158 libdoc('MyLibrary.py', 'MyLibraryDoc.html', version='1.0')159 """160 LibDoc().execute(library_or_resource, outfile, name=name, version=version,161 format=format)162if __name__ == '__main__':...
htmlwriter.py
Source:htmlwriter.py
1# Copyright 2008-2012 Nokia Siemens Networks Oyj2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14import os15import re16from robot.errors import DataError17from robot.htmldata import HtmlFileWriter, ModelWriter, JsonWriter, LIBDOC18from robot import utils19class LibdocHtmlWriter(object):20 def write(self, libdoc, output):21 model_writer = LibdocModelWriter(output, libdoc)22 HtmlFileWriter(output, model_writer).write(LIBDOC)23class LibdocModelWriter(ModelWriter):24 def __init__(self, output, libdoc):25 self._output = output26 self._libdoc = libdoc27 def write(self, line):28 self._output.write('<script type="text/javascript">' + os.linesep)29 self.write_data()30 self._output.write('</script>' + os.linesep)31 def write_data(self):32 formatter = DocFormatter(self._libdoc.keywords, self._libdoc.doc,33 self._libdoc.doc_format)34 libdoc = JsonConverter(formatter).convert(self._libdoc)35 JsonWriter(self._output).write_json('libdoc = ', libdoc)36class JsonConverter(object):37 def __init__(self, doc_formatter):38 self._doc_formatter = doc_formatter39 def convert(self, libdoc):40 return {41 'name': libdoc.name,42 'doc': self._doc_formatter.html(libdoc.doc, intro=True),43 'version': libdoc.version,44 'named_args': libdoc.named_args,45 'scope': libdoc.scope,46 'generated': utils.get_timestamp(daysep='-', millissep=None),47 'inits': self._get_keywords(libdoc.inits),48 'keywords': self._get_keywords(libdoc.keywords)49 }50 def _get_keywords(self, keywords):51 return [self._convert_keyword(kw) for kw in keywords]52 def _convert_keyword(self, kw):53 return {54 'name': kw.name,55 'args': ', '.join(kw.args),56 'doc': self._doc_formatter.html(kw.doc),57 'shortdoc': kw.shortdoc58 }59class DocFormatter(object):60 _header_regexp = re.compile(r'<h2>(.+?)</h2>')61 _name_regexp = re.compile('`(.+?)`')62 def __init__(self, keywords, introduction, doc_format='ROBOT'):63 self._doc_to_html = DocToHtml(doc_format)64 self._targets = self._get_targets(keywords, introduction,65 doc_format == 'ROBOT')66 def _get_targets(self, keywords, introduction, robot_format):67 targets = utils.NormalizedDict({68 'introduction': 'introduction',69 'library introduction': 'introduction',70 'importing': 'importing',71 'library importing': 'importing',72 'shortcuts': 'shortcuts',73 'keywords': 'keywords'74 })75 for kw in keywords:76 targets[kw.name] = kw.name77 if robot_format:78 for header in self._yield_header_targets(introduction):79 targets[header] = header80 return targets81 def _yield_header_targets(self, introduction):82 for line in introduction.splitlines():83 line = line.strip()84 if line.startswith('= ') and line.endswith(' ='):85 yield line[1:-1].strip()86 def html(self, doc, intro=False):87 doc = self._doc_to_html(doc)88 if intro:89 doc = self._header_regexp.sub(r'<h2 id="\1">\1</h2>', doc)90 return self._name_regexp.sub(self._link_keywords, doc)91 def _link_keywords(self, match):92 name = match.group(1)93 if name in self._targets:94 return '<a href="#%s" class="name">%s</a>' % (self._targets[name], name)95 return '<span class="name">%s</span>' % name96class DocToHtml(object):97 def __init__(self, format):98 self._formatter = self._get_formatter(format)99 def _get_formatter(self, format):100 try:101 return {'ROBOT': utils.html_format,102 'TEXT': self._format_text,103 'HTML': self._format_html,104 'REST': self._format_rest}[format]105 except KeyError:106 raise DataError("Invalid documentation format '%s'." % format)107 def _format_text(self, doc):108 return '<p style="white-space: pre-wrap">%s</p>' % utils.html_escape(doc)109 def _format_html(self, doc):110 return '<div style="margin: 0">%s</div>' % doc111 def _format_rest(self, doc):112 try:113 from docutils.core import publish_parts114 except ImportError:115 raise DataError("reST format requires 'docutils' module to be installed.")116 parts = publish_parts(doc, writer_name='html')117 return self._format_html(parts['html_body'])118 def __call__(self, doc):...
doc_template.py
Source:doc_template.py
1# Copyright (c) 2018 Georgia Tech Research Corporation2# Distributed under the terms of the BSD-3-Clause License3import re4from jinja2 import Template5def anchorify(text):6 """ robot uses the id hack, but lab strips it out. rebuild anchors.7 """8 return re.sub(9 r"(<h\d\s*[^>]*>)\s*(.*?)\s*(</h\d>)", r"""<a name="\2"></a>\1\2\3""", text10 )11def dollarify(text):12 """ robot uses lots of dollars, but they usually aren't LaTeX. Escape.13 """14 return re.sub(r"\$", "<span>$</span>", text)15def with_twenty(match):16 """ Do some stuff with escaped whitespace17 """18 return f"""<a href="{match.group(2).replace("%20", " ")}" """.replace("%23", "#")19def twentify(text):20 """ some of the libraries escape spaces in hrefs. Don't.21 """22 return re.sub(r"""(<a href=")([^"]+)(")""", with_twenty, text)23# extra context for jinja24DOC_CONTEXT = {"dollarify": dollarify, "anchorify": anchorify}25# HTML fragment for keywords26KW_FRAG = """27<a name="{{ kw.name }}"></a>28<div class="jp-Robot-Docs-keyword">29 <div class="jp-Robot-Docs-spec">30 <table><tr><td>31 <h3>{%- if is_init -%}32 Library {{ libdoc.name }}33 {%- else -%}34 {%- if show_libname %}<em>{{ libdoc.name }}.</em>{% endif -%}35 <strong>{{ kw.name }}</strong>36 {%- endif -%}37 38 {%- for arg in kw.args -%}39 <code> 40 {%- if "=" in arg or "*" in arg -%}41 <em>{{ arg }}</em>42 {%- else -%}43 {{ arg }}44 {%- endif -%}45 </code>46 {% endfor %}47 </h3>48 </td></tr></table>49 </div>50 <div class="jp-Robot-Docs-html">51 <blockquote>{{ dollarify(kw.doc) }}</blockquote>52 </div>53</div>54"""55# HTML template for library docs56LIB_TEMPLATE = Template(57 "".join(58 [59 """60{% set show_libname = False %}61{% set is_init = False %}62<div class="jp-Robot-Docs">63 <div class="jp-Robot-Docs-header">64 <table>65 <thead>66 <tr>67 <th>version</th>68 <th>scope</th>69 <th>named<br/>arguments</th>70 <th>tags</th>71 <th>inits</th>72 <th>keywords</th>73 </tr>74 </thead>75 <tbody>76 <tr>77 <td>{{ libdoc.version }}</td>78 <td>{{ libdoc.scope }}</td>79 <td>{% if named_args %}yes{% else %}no{% endif %}</td>80 <td>81 {% for tag in libdoc.tags %}82 <code>{{ tag }}</code>83 {% else %}84 -85 {% endfor %}86 </td>87 <td>88 {% if libdoc.inits %}89 <a href="#Importing">{{ libdoc.inits | count }}</a>90 {% else %}91 no92 {% endif %}93 </td>94 <td>95 {% if libdoc.keywords %}96 <a href="#Keywords">{{ libdoc.keywords | count }}</a>97 {% else %}98 no99 {% endif %}100 </td>101 </tr>102 </tbody>103 </table>104 </div>105 <h1>{{ libdoc.name }}</h1>106 <div class="jp-Robot-Docs-html">107 <blockquote>{{ dollarify(anchorify(libdoc.doc)) }}</blockquote>108 </div>109 {% if libdoc.inits %}110 {% set is_init = True %}111 <a name="Importing"></a><h1>Importing</h1>112 {% for kw in libdoc.inits %}113 """,114 KW_FRAG,115 """116 {% endfor %}117 {% endif %}118 {% set is_init = False %}119 <a name="Keywords"></a><h1>Keywords</h1>120 {% for kw in libdoc.keywords %}121 """,122 KW_FRAG,123 """124 {% endfor %}125</div>126""",127 ]128 )129)130# template for keywords131KW_TEMPLATE = Template(132 "".join(133 [134 """135{% set show_libname = True %}136{% set is_init = False %}137<div class="jp-Robot-Docs">138 {% set kw = libdoc.keywords[0] %}139""",140 KW_FRAG,141 """142</div>143""",144 ]145 )...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!