接上一篇 day1 run.py

发现build test suit还挺复杂的, 先从官网API找到了一些资料,可以看出这是robotframework进行组织

测试案例实现的重要步骤, 将传入的testCase解析并生成suite对象, 等待调用

https://robot-framework.readthedocs.io/en/v3.1/autodoc/robot.running.html

(一)官网 API 说明部分

robot.running package

Implements the core test execution logic.

The main public entry points of this package are of the following two classes:

  • TestSuiteBuilder for creating executable test suites based on existing test case files and directories.
  • TestSuiteBuilder 根据已有的测试文件和目录生成可执行的测试suites
  • TestSuite for creating an executable test suite structure programmatically.
  • TestSuite 根据传入参数生成可执行的测试suite
  • 两者区别是TestSuiteBuilder根据传入robotFramework的测试文件定义进行解析,然后生成可执行测试 suite
  • 而TestSuite是需要我们制定各种参数,生成可执行的测试 suite, TestSuiteBuilder解析之后回去调用TestSuite

It is recommended to import both of these classes via the robot.api package like in the examples below. Also TestCase and Keyword classes used internally by the TestSuite class are part of the public API. In those rare cases where these classes are needed directly, they can be imported from this package.

Examples

First, let’s assume we have the following test suite in file activate_skynet.robot:

 *** Settings ***
Library OperatingSystem *** Test Cases ***
Should Activate Skynet
[Tags] smoke
[Setup] Set Environment Variable SKYNET activated
Environment Variable Should Be Set SKYNET

We can easily parse and create an executable test suite based on the above file using the TestSuiteBuilder class as follows:

 from robot.api import TestSuiteBuilder

 suite = TestSuiteBuilder().build('path/to/activate_skynet.robot')

That was easy. Let’s next generate the same test suite from scratch using the TestSuite class:

from robot.api import TestSuite

suite = TestSuite('Activate Skynet')
suite.resource.imports.library('OperatingSystem')
test = suite.tests.create('Should Activate Skynet', tags=['smoke'])
test.keywords.create('Set Environment Variable', args=['SKYNET', 'activated'], type='setup')
test.keywords.create('Environment Variable Should Be Set', args=['SKYNET'])

Not that complicated either, especially considering the flexibility. Notice that the suite created based on the file could also be edited further using the same API.

Now that we have a test suite ready, let’s execute it and verify that the returned Result object contains correct information:

result = suite.run(critical='smoke', output='skynet.xml')

assert result.return_code == 0
assert result.suite.name == 'Activate Skynet'
test = result.suite.tests[0]
assert test.name == 'Should Activate Skynet'
assert test.passed and test.critical
stats = result.suite.statistics
assert stats.critical.total == 1 and stats.critical.failed == 0

Running the suite generates a normal output XML file, unless it is disabled by using output=None. Generating log, report, and xUnit files based on the results is possible using the ResultWriter class:

from robot.api import ResultWriter

# Report and xUnit files can be generated based on the result object.
ResultWriter(result).write_results(report='skynet.html', log=None)
# Generating log files requires processing the earlier generated output XML.
ResultWriter('skynet.xml').write_results()

(二)代码阅读部分

day1 的代码段,

suite = TestSuiteBuilder(settings['SuiteNames'], settings['WarnOnSkipped']).build(*datasources)

/robot/running/builder.py
from .model import ForLoop, Keyword, ResourceFile, TestSuite

def build(self, *paths):
"""
:param paths: Paths to test data files or directories.
:return: :class:`~robot.running.model.TestSuite` instance.
"""
if not paths:
raise DataError('One or more source paths required.')
if len(paths) == 1:
return self._parse_and_build(paths[0])
root = TestSuite()
for path in paths:
root.suites.append(self._parse_and_build(path))
return root

主要功能在TestSuite() 的构建上, 生成TestSuite()实例

*1*root = TestSuite()

实例化之后 解析path传入的文件

root.suites继承自父类 robot.model.testsuite.py, suites 返回TestSuites

suites.append 即 TestSuites.append, 而TestSuites又继承自(ItemList)

所以调用TtemList.append

robot.model.testsuite.py

*2*root.suites.append(self._parse_and_build(path))
--->
    @setter
    def suites(self, suites):
    """Child suites as a :class:`~.TestSuites` object."""
    return TestSuites(self.__class__, self, suites)     class TestSuites(ItemList):
     __slots__ = []     def __init__(self, suite_class=TestSuite, parent=None, suites=None):
    ItemList.__init__(self, suite_class, {'parent': parent}, suites) #初始化父类
@py2to3
class ItemList(object):
__slots__ = ['_item_class', '_common_attrs', '_items'] def __init__(self, item_class, common_attrs=None, items=None):
self._item_class = item_class
self._common_attrs = common_attrs
self._items = ()
if items:
self.extend(items) def create(self, *args, **kwargs):
return self.append(self._item_class(*args, **kwargs)) def append(self, item):
self._check_type_and_set_attrs(item)
self._items += (item,)
return item

_build_suite
构建文件中的每个suite, 然后填入list中待执行, 详细见_build_suite这块代码解析
下面三个函数进行了suite的具体构建, setup/teardown/test, 每个suite的三元素进行了构建
_build_setup
(suite, data.setting_table.suite_setup)
_build_teardown(suite, data.setting_table.suite_teardown)
_build_test(suite, test_data, defaults)
*3*self._parse_and_build(path)

    def _parse_and_build(self, path):
    suite = self._build_suite(self._parse(path))
    suite.remove_empty_suites()
    return suite

from robot.parsing import TestData, ResourceFile as ResourceData    

def _parse(self, path):
try:
return TestData(source=abspath(path),
include_suites=self.include_suites,
warn_on_skipped=self.warn_on_skipped)
except DataError as err:
raise DataError("Parsing '%s' failed: %s" % (path, err.message))
    def _build_suite(self, data, parent_defaults=None):
     #根据传入的data进行 test suite 构建

defaults = TestDefaults(data.setting_table, parent_defaults)
suite = TestSuite(name=data.name, # 传入data.name ... 下同
source=data.source,
doc=unic(data.setting_table.doc),
metadata=
self._get_metadata(data.setting_table))
self._build_setup(suite, data.setting_table.suite_setup)
self._build_teardown(suite, data.setting_table.suite_teardown)
for test_data in data.testcase_table.tests:
self._build_test(suite, test_data, defaults)
for child in data.children:
suite.suites.append(self._build_suite(child, defaults))
ResourceFileBuilder().build(data, target=suite.resource)
return suite
 

running 中的 TestSuite 继承自 robot.model.TestSuite

class TestSuite(model.TestSuite):
"""Represents a single executable test suite. See the base class for documentation of attributes not documented here.
"""
__slots__ = ['resource']
test_class = TestCase #: Internal usage only.
keyword_class = Keyword #: Internal usage only. def __init__(self, name='', doc='', metadata=None, source=None):
model.TestSuite.__init__(self, name, doc, metadata, source)
#: :class:`ResourceFile` instance containing imports, variables and
#: keywords the suite owns. When data is parsed from the file system,
#: this data comes from the same test case file that creates the suite.
self.resource = ResourceFile(source=source)

脑瓜疼, 看不下去了, 休息一会儿 。。。 。。。

Robot Framework 源码阅读 day2 TestSuitBuilder的更多相关文章

  1. Robot Framework 源码阅读 day1 run.py

    robot里面run起来的接口主要有两类 run_cli def run_cli(arguments): """Command line execution entry ...

  2. Robot Framework 源码阅读 day1 __main__.py

    robot文件夹下的__main__.py函数 是使用module运行时的入口函数: import sys # Allows running as a script. __name__ check n ...

  3. Robot Framework 源码解析(1) - java入口点

    一直很好奇Robot Framework 是如何通过关键字驱动进行测试的,好奇它是如何支持那么多库的,好奇它是如何完成截图的.所以就打算研究一下它的源码. 这是官方给出的Robot framework ...

  4. Robot Framework源码解析(2) - 执行测试的入口点

    我们再来看 src/robot/run.py 的工作原理.摘录部分代码: from robot.conf import RobotSettings from robot.model import Mo ...

  5. Android源码阅读 – Zygote

    @Dlive 本文档: 使用的Android源码版本为:Android-4.4.3_r1 kitkat (源码下载: http://source.android.com/source/index.ht ...

  6. Spring源码阅读笔记

    前言 作为一个Java开发者,工作了几年后,越发觉力有点不从心了,技术的世界实在是太过于辽阔了,接触的东西越多,越感到前所未有的恐慌. 每天捣鼓这个捣鼓那个,结果回过头来,才发现这个也不通,那个也不精 ...

  7. jdk源码阅读笔记-LinkedHashMap

    Map是Java collection framework 中重要的组成部分,特别是HashMap是在我们在日常的开发的过程中使用的最多的一个集合.但是遗憾的是,存放在HashMap中元素都是无序的, ...

  8. Apollo源码阅读笔记(二)

    Apollo源码阅读笔记(二) 前面 分析了apollo配置设置到Spring的environment的过程,此文继续PropertySourcesProcessor.postProcessBeanF ...

  9. SpringMVC源码阅读系列汇总

    1.前言 1.1 导入 SpringMVC是基于Servlet和Spring框架设计的Web框架,做JavaWeb的同学应该都知道 本文基于Spring4.3.7源码分析,(不要被图片欺骗了,手动滑稽 ...

随机推荐

  1. luogu 4004 Hello world! 分块 + 并查集 + 乱搞

    其实呢,我也不理解这道题咋做,等以后有时间再研究研究 #include <bits/stdc++.h> #define ll long long #define maxn 100002 u ...

  2. 最大流 && 最小费用最大流模板

    模板从  这里   搬运,链接博客还有很多网络流题集题解参考. 最大流模板 ( 可处理重边 ) ; const int INF = 0x3f3f3f3f; struct Edge { int from ...

  3. 一本通例题埃及分数—题解&&深搜的剪枝技巧总结

    一.简述: 众所周知,深搜(深度优先搜索)的时间复杂度在不加任何优化的情况下是非常慢的,一般都是指数级别的时间复杂度,在题目严格的时间限制下难以通过.所以大多数搜索算法都需要优化.形象地看,搜索的优化 ...

  4. 给字体和元素加阴影text-shadow和box-shadow

    1.语法:  对象选择器 {text-shadow:X轴偏移量 Y轴偏移量 阴影模糊半径 阴影颜色} 注:text-shadow可以使用一个或多个投影,如果使用多个投影时必须需要用逗号“,”分开. 2 ...

  5. CentOS yum 安装历史版本 java

    1.以1.6为例,找到对应版本 $ yum --showduplicate list java* |grep 1.6 java--openjdk.x86_64 :1.6.0.41-1.13.13.1. ...

  6. codeforces 704B - Ant Man [想法题]

    题目链接:http://codeforces.com/problemset/problem/704/B ------------------------------------------------ ...

  7. 【SVN】 一次SVN 修复笔记

    同事乱提交了一个版本之后,SVN上最新版本出现了问题. 原本按照网上其他人的说法,可以手动到服务器端干掉最新版的存档,并修改版本记录到前一个版本号即可,但是这应该是个坑. 掉进这个坑后,需要解决,又不 ...

  8. 2019 Nanchang Onsite

    D.Interesting Series F(n)实际上是一个等比数列的和,将它从递推式转变为通项公式(a^n-1)/(a-1),这里只需要确定n就可以. 题目要求选取k大小的所有子集的答案求和,可以 ...

  9. 阶段1 语言基础+高级_1-2 -面向对象和封装_16this关键字的作用

    this主要是在重名的情况下 ,起到区分的效果 新建demo04的包,里面新建类Person 通过this.进行区分 this关键字可以解决重名 分不开的问题 这里的person调用的sayHello ...

  10. 百度人脸识别python调用例子

    # 首先pip install baidu-aip # SDK文档链接http://ai.baidu.com/docs#/Face-Python-SDK/top import base64 from ...