Python3+RobotFramewok 用户自定义库的开发(四)

  在介绍这个之前,可以先看下python的目录Python\Lib\site-packages下面的文件夹,你会发现这个目录下面有DatabaseLibrary、RequestsLibrary、Selenium2Library等等这些我们熟悉的名称,没错,就是在RIDE编辑框里面import的包名,所以有时候为什么会import失败(导入后显示红色),就是因为这个目录没有你要导入的包。因此,我们如果要开发自定义关键字库,就可以在这个目录新建一个类似的文件夹即可,具体结构是怎么样的,可以先看看RequestsLibrary是怎么写的,依葫芦画瓢即可。

  点开RequestsLibrary目录之后,我们发现有这么几个py文件

首先看__init__.py,学了python的同学都知道这个很眼熟,类的初始化时经常用到,这里的作用基本类似,打开看下

from .RequestsKeywords import RequestsKeywords
from .version import VERSION

_version_ = VERSION


class RequestsLibrary(RequestsKeywords):
    """ RequestsLibrary is a HTTP client keyword library that uses
    the requests module from Kenneth Reitz
    https://github.com/kennethreitz/requests


        Examples:
        | Create Session | google | http://www.google.com |
        | Create Session | github  | http://github.com/api/v2/json |
        | ${resp} | Get  google  |  / |
        | Should Be Equal As Strings |  ${resp.status_code} | 200 |
        | ${resp} | Get  github  | /user/search/bulkan |
        | Should Be Equal As Strings  |  ${resp.status_code} | 200 |
        | ${jsondata}  | To Json |  ${resp.content} |
        | Dictionary Should Contain Value | ${jsondata['users'][0]} | Bulkan Savun Evcimen |

    """
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'

这里就知道另外一个文件version.py是干啥用的了,这个笔者认为可有可无,只是一个版本号,直接在__init__.py定义也一样。类名RequestsLibrary就是我们在RIDE导入的名称,继承的这个RequestsKeywords,就是文件RequestsKeywords.py里面的一个关键字实现类,最后一行ROBOT_LIBRARY_SCOPE = 'GLOBAL',必须要加,自定义时照着写即可,RF框架会自动识别;最后一个文件compat.py点开阅读源码后发现,其实是在判断是否为python3,主要为了兼容python2和python3而import依赖包,也不是必要文件。因此我们可以知道,实际生效有作用的文件主要就是__init__.py和RequestsKeywords.py了。

接下来笔者不详细举案例了,简单分析一下RequestsKeywords.py里面的一个关键字实现

  def create_session(self, alias, url, headers={}, cookies=None,
                       auth=None, timeout=None, proxies=None,
                       verify=False, debug=0, max_retries=3, backoff_factor=0.10, disable_warnings=0):
        """ Create Session: create a HTTP session to a server

        ``url`` Base url of the server

        ``alias`` Robot Framework alias to identify the session

        ``headers`` Dictionary of default headers

        ``auth`` List of username & password for HTTP Basic Auth

        ``timeout`` Connection timeout

        ``proxies`` Dictionary that contains proxy urls for HTTP and HTTPS communication

        ``verify`` Whether the SSL cert will be verified. A CA_BUNDLE path can also be provided.
                 Defaults to False.

        ``debug`` Enable http verbosity option more information
                https://docs.python.org/2/library/httplib.html#httplib.HTTPConnection.set_debuglevel

        ``max_retries`` The maximum number of retries each connection should attempt.

        ``backoff_factor`` The pause between for each retry

        ``disable_warnings`` Disable requests warning useful when you have large number of testcases
        """
        auth = requests.auth.HTTPBasicAuth(*auth) if auth else None

        logger.info('Creating Session using : alias=%s, url=%s, headers=%s, \
                    cookies=%s, auth=%s, timeout=%s, proxies=%s, verify=%s, \
                    debug=%s ' % (alias, url, headers, cookies, auth, timeout,
                                  proxies, verify, debug))

        return self._create_session(
            alias,
            url,
            headers,
            cookies,
            auth,
            timeout,
            max_retries,
            backoff_factor,
            proxies,
            verify,
            debug,
            disable_warnings)

create_session这个关键字是不是很熟悉,在RF中使用的时候,直接输入Create Session即可使用,按F5查看帮助信息,跟上面源码注释部分一样。

好了,弄明白这个原理,接下来就可以依葫芦画瓢愉快的手撕python代码实现自己想要的关键字了,哈哈~~

扩展:如果按照上述的方法,确实可以完成用户自定义库的开发,但是有时候这样会给项目维护带来一定的困难,因为你写的关键字不是跟项目的测试用例放在一起维护的,还需要单独去维护用户自定义库的工程。所以推荐另外一种方式完成自定义关键字库的开发和维护,这里举一个例子,在关键字的文件夹下面直接创建一个py文件,采用函数式编程的方式,使用的关键字之前,直接导入Library,选择你写好的py文件。注意:路径不对或者py文件语法写的有问题导入都会报错,显示红色。

示例代码,mykey.py:

import json
import types
import sys

from robot.api import logger
from robot.libraries.BuiltIn import BuiltIn


builtin = BuiltIn()
PY3 = sys.version_info > (3,)

def mykey_to_json(content, pretty_print=False):
    """ Convert a string to a JSON object

    ``content`` String content to convert into JSON

    ``pretty_print`` If defined, will output JSON is pretty print format
    """
    if PY3:
        if isinstance(content, bytes):
            content = content.decode(encoding='utf-8')
    if pretty_print:
        json_ = _json_pretty_print(content)
    else:
        json_ = json.loads(content)
    logger.info('To JSON using : content=%s ' % (content))
    logger.info('To JSON using : pretty_print=%s ' % (pretty_print))

    return json_

def _json_pretty_print(content):
    """
    Pretty print a JSON object

    ``content``  JSON object to pretty print
    """
    temp = json.loads(content)
    return json.dumps(temp, sort_keys=True, indent=4, separators=(',', ': '))

 

转载于:https://www.cnblogs.com/andrew209/p/10940670.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值