def read(self, ipynbfile, rawdata):
            notebook = nbformat.read(ipynbfile, 4)
            data = []

            for cell in notebook.cells:
                # Skip non-code cells
                if not cell.cell_type == "code":
                    continue

                # Execute %%python module magics
                match = re.match("^%%python module ([a-zA-Z_]+)", cell.source)
                if match is not None:
                    module = match.groups()[0]
                    cursor = len("%%python module {0:s}".format(module))
                    exec_code_into_module(cell.source[cursor:], module)
                    continue

                # Add the rest into robot test suite
                data.append(cell.source)

            data = "\n\n".join(data)

            if HAS_RF32_PARSER:
                return data
            else:
                robotfile = BytesIO(data.encode("UTF-8"))
                return RobotReader().read(robotfile, rawdata, ipynbfile.name)
def complete_settings(
    completer: Completer,
    line: str,
    code: str,
    cursor_pos: int,
    line_cursor: int,
    offset: int,
    history: List[str],
) -> Tuple[List[str], List[dict]]:
    """ Complete settings
    """
    matches = []

    row = DataRow(RobotReader.split_row(line[:line_cursor]))
    tokens = row.data

    current_table = find_current_table(code, cursor_pos)

    if current_table is None:
        return matches, []

    bracket = False
    settings = None
    if "etting" in current_table:
        settings = SUITE_SETTINGS
    elif "test case" in current_table or "task" in current_table:
        settings, bracket = CASE_SETTINGS, True
    elif "keyword" in current_table:
        settings, bracket = KEYWORD_SETTINGS, True

    if not settings:
        return matches, []

    matches = complete_table_settings(completer, settings, tokens[-1], bracket)

    post = ""

    if bracket and not line.strip()[-1] == "]":
        post = "]"
        post += " | " if line.startswith("|") else "  "
    elif not bracket:
        post += " | " if line.startswith("|") else "  "

    matches = [
        f"{line[:line_cursor - (len(tokens[-1]))]}{match}{post}" for match in matches
    ]

    return (
        matches,
        [
            {
                "start": cursor_pos,
                "end": offset + len(line),
                "type": "setting",
                "text": m,
            }
            for m in matches
        ],
    )
Beispiel #3
0
 def populate(self, source):
     """ Populate from the string
     """
     LOGGER.info("Parsing string '%s'." % source)
     try:
         RobotReader().read(BytesIO(source.encode("utf-8")), self)
     except Exception:
         raise DataError(get_error_message())
def complete_keywords(
    completer: Completer,
    line: str,
    code: str,
    cursor_pos: int,
    line_cursor: int,
    offset: int,
    history: List[str],
) -> Tuple[List[str], List[dict]]:
    """ Complete keywords from all imported libraries
    """
    matches = []

    row = DataRow(RobotReader.split_row(line))
    tokens = row.data

    if len(tokens) < 2:
        return matches, []

    if len(tokens) == 2 and not tokens[0].strip():
        kw_token = tokens[1]
    elif re.match(RE_PRE_KEYWORD_SUITE, tokens[0], flags=re.I) is not None:
        kw_token = tokens[1]
    elif re.match(RE_PRE_KEYWORD_BRACKET, tokens[1], flags=re.I) is not None:
        kw_token = tokens[2]
    else:
        return matches, []

    bdd = None
    orig_kw_token = kw_token
    bdd_token = re.match(r"^(given|when|then|and|but)?\b *(.*)", kw_token, flags=re.I)

    if bdd_token is not None:
        bdd, kw_token = bdd_token.groups()

    for doc in completer.docs(history).values():
        for keyword in getattr(doc, "keywords", []):
            if kw_token.lower() in keyword.name.lower():
                suggest_token = f"{bdd} {keyword.name}" if bdd else keyword.name
                pre = line.split(orig_kw_token)[0]
                if line.strip()[0] == "|":
                    matches.append(f"""{pre}{suggest_token} | """)
                else:
                    matches.append(f"""{pre}{suggest_token}  """)
    return (
        matches,
        [
            {
                "start": cursor_pos,
                "end": offset + len(line),
                "type": "keyword",
                "text": m,
            }
            for m in matches
        ],
    )
def complete_libraries(
    completer: Completer,
    line: str,
    code: str,
    cursor_pos: int,
    line_cursor: int,
    offset: int,
    history: List[str],
) -> Tuple[List[str], List[dict]]:
    """ Complete library names

        This could do better with sub-modules.
    """
    matches = []

    row = DataRow(RobotReader.split_row(line))
    tokens = row.data

    if not re.findall(r"\* *settings", code.lower(), flags=re.I):
        return matches, []

    if not tokens or tokens[0].lower() != "library":
        return matches, []

    for lib in list(STDLIBS) + list(get_root_modules()):
        if tokens[1].lower() in lib.lower():
            pre = line.split(tokens[1])[0]
            if line.startswith("|"):
                matches += [f"""{pre}{lib} | """]
            else:
                matches += [f"""{pre}{lib}  """]

    return (
        matches,
        [
            {
                "start": cursor_pos,
                "end": offset + len(line),
                "type": "library",
                "text": m,
            }
            for m in matches
        ],
    )
Beispiel #6
0
    def do_inspect(self, code: str, cursor_pos: int, detail_level: int,
                   history: List[str]) -> dict:
        """ Handle inspect payload and return a message spec with some docs
            set of completions
        """
        doc = None

        line, line_cursor, offset = find_line(code, cursor_pos)
        tokens = DataRow(RobotReader.split_row(line)).data

        self.docs(history + [code])

        if len(tokens) > 1:
            if tokens[0].lower() in ["library"]:
                doc = self._lib_html(tokens[1], history)
            elif tokens[0].lower() in ["resource"]:
                source = None
                try:
                    source = find_file(tokens[1])
                except Exception:
                    pass

                if source is not None:
                    doc = self._lib_html(source, history)

        if not doc:
            doc = self._keyword_html(tokens, code, line, line_cursor, offset,
                                     history)

        if doc is not None:
            return {
                "status": "ok",
                "data": {
                    "text/html": doc
                },
                "metadata": {},
                "found": True,
            }
        else:
            return {"status": "ok", "data": {}, "metadata": {}, "found": False}
Beispiel #7
0
        def read(self, ipynbfile, rawdata):
            notebook = nbformat.read(ipynbfile, 4)
            data = []

            for cell in notebook.cells:
                # Skip non-code cells
                if not cell.cell_type == 'code':
                    continue

                # Execute %%python module magics
                match = re.match('^%%python module ([a-zA-Z_]+)', cell.source)
                if match is not None:
                    module = match.groups()[0]
                    cursor = len('%%python module {0:s}'.format(module))
                    exec_code_into_module(cell.source[cursor:], module)
                    continue

                # Add the rest into robot test suite
                data.append(cell.source)

            data = '\n\n'.join(data)
            robotfile = BytesIO(data.encode('UTF-8'))
            return RobotReader().read(robotfile, rawdata, ipynbfile.name)