首页 > 其他分享 >robotframework自动化测试框架实战教程:库文档工具(Libdoc)

robotframework自动化测试框架实战教程:库文档工具(Libdoc)

时间:2022-10-28 23:44:57浏览次数:80  
标签:log level self robotframework Libdoc 文档 message

Libdoc是Robot Framework内置的工具, 用来为测试库和资源文件生成关键字的文档. 文档分为HTML和XML格式, 前者供人阅读, 后者供RIDE和其它工具使用. 

文档文件被指定为库/资源名称或路径之后的第二个参数,默认情况下输出的格式将自动通过文件扩展名来判断, 也可以通过选项 --format 设置.如果测试库的导入需要参数, 这些参数必须跟在名字或路径的后面, 使用双冒号连接, 像 MyLibrary::arg1::arg2

class ExampleLibrary:
    """Library for demo purposes.

    This library is only used in an example and it doesn't do anything useful.
    """

    def my_keyword(self,s='a'):
        """Does nothing."""
        pass

    def your_keyword(self, arg):
        """Takes one argument and *does nothing* with it.

        Examples:
        | Your Keyword | xxx |
        | Your Keyword | yyy |
        """
        pass
libdoc ExampleLibrary::b ExampleLibrary.html

 

Libdoc还提供了几个特别的命令来在控制台显示库和资源的信息.

选项

-f, --format <html|xml|json|libspec>

指定是生成HTML/XML/JSON格式的robot可读规范文件,libspec格式表示文档转换为HTML的XML规范。如果不输入此选项默认格式是从输出文件扩展名获取的。

-s, --specdocformat <raw|html>

指定用于XML和JSON规范文件的文档格式。raw意味着保留原始文档格式,html意味着将doc字段值转换为html。当使用特殊的libspec格式时,默认值是原始的XML规范文件和html的JSON规范。

-F, --docformat <robot|html|text|rest>

类和方法描述的格式,默认就可

 -N, --name <newname>

设置文档库或资源的名称。

-P, --pythonpath <path>

类似于运行测试时的--pythonpath参数。

--quiet

不要将生成的输出文件的路径打印到控制台

-h, --help

帮助信息

 

之前生成的Libdoc XML或JSON规范文件也可以用作输入。使用*.xml,*.libspec或*.json:

libdoc Example.xml Example.html
libdoc Example.libspec Example.html
libdoc Example.json Example.html

 

四种类型文件

Libdoc HTML

HTML文档从一般的库介绍开始,接着是关于导入库时配置库的部分(如果适用),最后是指向所有关键字和关键字本身的快捷方式。

libdoc OperatingSystem OperatingSystem.html
libdoc --name MyLibrary Remote::http://10.0.0.42:8270 MyLibrary.html
libdoc -f HTML test/resource.robot doc/resource.htm
Libdoc XML

XML规范文件还包含库和关键字源信息,以便库和每个关键字可以具有源路径(source属性)和行号(lineno属性)。源路径为绝对路径。

libdoc OperatingSystem OperatingSystem.xml
libdoc test/resource.robot doc/resource.libspec
libdoc --format xml MyLibrary MyLibrary.spec
libdoc --format xml -s html MyLibrary MyLibrary.xml

测试2、4在浏览器中显示不出来,ide中乱码不好用

Libdoc JSON

Libdoc还可以生成JSON格式的文档,适用于编辑器或网页等外部工具。它包含与HTML格式相同的所有信息,但采用机器可读格式。

 与XML规范文件类似,JSON规范文件包含所有信息,也可以用作Libdoc的输入。从该格式可以创建任何其他输出格式。默认情况下,库文档字符串在JSON输出文件中转换为HTML格式(-s raw为原始格式)。

 

在控制台查看信息

Libdoc有3个特别的命令在控制台显示信息. 这些命令被用来取代输出文件的名字, 并且它们也可以带上额外的参数.

list
列出测试库或资源文件所包含的关键字列表. 可以传递表示模式的参数来过滤展示结果, 只有那些名字包含了给定模式的关键字才会列出来.
show
显示测试库或资源文件的文档. 也可以传递表示名字的参数(可以是多个). 名字匹配上的关键字才会展示. 特殊参数值 intro 可用来只显示测试库的介绍(introduction)和导入章节.
version
显示测试的版本.

list 和 show 命令支持的可选名字模式都是大小写和空格无关的, 并且都支持使用 * 和 ? 作为通配符.

python -m robot.libdoc BuiltIn show Log
python -m robot.libdoc BuiltIn show "Log*"
python -m robot.libdoc BuiltIn show intro

 

Robot Framework文档语法

robot格式

下面的例子展示了一些最重要的格式化功能. 注意, 由于这是默认的格式, 所以没有必要设置 ROBOT_LIBRARY_DOC_FORMAT 属性, 也无需在命令行指定格式.

"""Example library in Robot Framework format.

- Formatting with *bold* and _italic_.
- URLs like http://example.com are turned to links.
- Custom links like [http://robotframework.org|Robot Framework] are supported.
- Linking to `My Keyword` works.
"""

def my_keyword():
    """Nothing more to see here."""

当使用Robot Framework文档格式时,可以通过将一个特殊的%TOC%标记单独添加到一行中来自动完成。目录是根据引言中使用的顶级章节标题(例如= Section title =)创建的。

""Example library demonstrating TOC generation.

The %TOC% marker only creates the actual table of contents and possible
header or other explanation needs to be added separately like done below.

== Table of contents ==

%TOC%

= Section title =

The top-level section titles are automatically added to the TOC.

= Second section =

== Sub section ==

Sub section titles are not added to the TOC.
"""

def my_keyword():
    """Nothing more to see here."""

 

纯文本格式

当使用纯文本格式时,Libdoc按原样使用文档。除缩进和HTML特殊字符(<>&)转义外,保留换行符和其他空白。唯一完成的格式化是将URL转换为可点击链接

"""Example library in plain text format.

- Formatting is not supported.
- URLs like http://example.com are turned to links.
- Custom links are not supported.
- Linking to `My Keyword` works.
"""
ROBOT_LIBRARY_DOC_FORMAT = 'text'

def my_keyword():
    """Nothing more to see here."""

 

reStructuredText格式

reStructuredText是一种简单而强大的标记语法,广泛用于Python项目(包括本用户指南)和其他地方。主要限制是您需要安装docutils模块才能使用它生成文档。

reStructured支持的一个很好的特性是能够标记语法突出显示的代码块。语法突出显示需要额外的Pygments模块,并支持Pygment支持的所有语言。

"""Example library in reStructuredText format.

- Formatting with **bold** and *italic*.
- URLs like http://example.com are turned to links.
- Custom links like reStructuredText__ are supported.
- Linking to \`My Keyword\` works but requires backtics to be escaped.

__ http://docutils.sourceforge.net

.. code:: robotframework

    *** Test Cases ***
    Example
        My keyword    # How cool is this!!?!!?!1!!
"""
ROBOT_LIBRARY_DOC_FORMAT = 'reST'

def my_keyword():
    """Nothing more to see here."""

 

内部链接

Libdoc支持在文档的不同部分生成关键字的内部链接. 使用反引号将目标的名字括起来即可, 例如 `target`. 目标名字是大小写无关的, 支持哪些目标将在下面的章节介绍.

如果要链接的目标没有找到, Libdoc也不会报错或警告, 只是将文字设为斜体. 早期的时候, 曾经推荐使用这种方式来引用关键字的参数, 但是这有可能导致无意中创建了内部链接. 现在则推荐使用双反引号来标示参数, 例如 ``argument``. 使用单反引号而没有找到的链接目标的情况在未来的版本中有可能会以报错处理.

链接到关键字

测试库中所有的关键字都会自动创建链接目标, 可通过诸如 `Keyword Name` 的语法链接到. 下面的例子展示了两个关键字之间互相链接.

def keyword(log_level="INFO"):
    """Does something and logs the output using the given level.

    Valid values for log level` are "INFO" (default) "DEBUG" and "TRACE".

    See also `Another Keyword`.
    """
    # ...

def another_keyword(argument, log_level="INFO"):
    """Does something with the given argument else and logs the output.

    See `Keyword` for information about valid log levels.
    """
    # ...

链接到段落

所有这些段落都是可作为链接目标的, 目标名字参见下表. 如何使用参见下一节的示例.

SectionTarget
Introduction 库doc
Importing __init__()方法
Keywords 方法名

支持自定义 section titles, 其中的标题自动创建为链接目标.

 

 表示参数

测试库中方法的参数和资源文件中用户关键字的参数, 将这些参数单独一列展示. 用户关键字的参数将去除 ${} 或 @{}, 以使得这些参数不管是来自哪里看起来都一个样. 示例代码
[Arguments]     ${a}=1      ${b}=${2}       ${c}=True       @{d}        &{e}
def log_two_messages(self, message0 ,message1:int=42, message2:str='qq', message3:bool=False, level=None,*args, **kwargs):
    ...

 

完整案例

下面的例子比较完整的展示了如何使用 `文档格式化`中最有用的功能, 内部链接 等等.点击 这里 查看生成的文档是什么样

class LoggingLibrary:
    """Library for logging messages.

    = Table of contents =

    %TOC%

    = Usage =

    This library has several keyword, for example `Log Message`, for logging
    messages. In reality the library is used only for _Libdoc_ demonstration
    purposes.

    = Valid log levels =

    Valid log levels are ``INFO``, ``DEBUG``, and ``TRACE``. The default log
    level can be set during `importing`.

    = Examples =

    Notice how keywords are linked from examples.

    | `Log Message`      | My message    |                |               |
    | `Log Two Messages` | My message    | Second message | level=DEBUG   |
    | `Log Messages`     | First message | Second message | Third message |
    """
    ROBOT_LIBRARY_VERSION = '0.1'

    def __init__(self, default_level='INFO'):
        """The default log level can be given at library import time.

        See `Valid log levels` section for information about available log
        levels.

        Examples:

        | =Setting= |     =Value=    | =Value= |          =Comment=         |
        | Library   | LoggingLibrary |         | # Use default level (INFO) |
        | Library   | LoggingLibrary | DEBUG   | # Use the given level      |
        """
        self.default_level = self._verify_level(default_level)

    def _verify_level(self, level):
        level = level.upper()
        if level not in ['INFO', 'DEBUG', 'TRACE']:
            raise RuntimeError("Invalid log level'%s'. Valid levels are "
                               "'INFO', 'DEBUG', and 'TRACE'")
        return level

    def log_message(self, message='a', level=None):
        """Writes given message to the log file using the specified log level.

        The message to log and the log level to use are defined using
        ``message`` and ``level`` arguments, respectively.

        If no log level is given, the default level given during `library
        importing` is used.
        """
        level = self._verify_level(level) if level else self.default_level
        print("*%s* %s" % (level, message))

    def log_two_messages(self, message0 ,message1:int=42, message2:str='qq', message3:bool=False, level=None,*args, **kwargs):
        """Writes given messages to the log file using the specified log level.

        See `Log Message` keyword for more information.
        """
        self.log_message(message1, level)
        self.log_message(message2, level)

    def log_messages(self, *messages, **kwargs):
        """Logs given messages using the log level set during `importing`.

        See also `Log Message` and `Log Two Messages`.
        """
        for msg in messages:
            self.log_message(msg)

所有标准库都有由Libdoc生成的文档,它们的文档(和源代码)可以作为更实际的示例。

标签:log,level,self,robotframework,Libdoc,文档,message
From: https://www.cnblogs.com/zerotest/p/16837608.html

相关文章