zoukankan      html  css  js  c++  java
  • Python3+RobotFramewok 用户自定义库的开发(四)

      在介绍这个之前,可以先看下python的目录PythonLibsite-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=(',', ': '))
  • 相关阅读:
    ISP整体流程介绍
    Demosiac 去马赛克 (CIP)
    ISP-CMOS图像传感器内部结构及工作原理
    数字图像显示原理
    浅析图像到视频
    摄像机gamma校正
    理解 Pix Binning
    人工智能"眼睛"——摄像头
    CMOS 摄像头的Skipping 和 Binning 模式
    android 向服务器发送json数据,以及发送头信息的三种方式
  • 原文地址:https://www.cnblogs.com/andrew209/p/10940670.html
Copyright © 2011-2022 走看看