Advanced Python's source code analysis: how to become more of a class method method?

The previous article "How to achieve Python parametric test? "I mentioned several libraries implement parametric testing in Python and leave a question:

> How do they become a way to put more methods, and each method with the corresponding parameters bind it?

We then refine it, is tantamount to the original problem: in a class, how to use a decorator to a class way into more than one class method (or a similar effect)?

# 带有一个方法的测试类
class TestClass:
    def test_func(self): pass # 使用装饰器,生成多个类方法 class TestClass: def test_func1(self): pass def test_func2(self): pass def test_func3(self): pass 

In essence Python decorator is deceitful, with a new alternative approach to be decorated. In the process of implementing parameterized, we introduced several libraries in the end by what means / secret weapons?

1, how ddt realize parameter?

First look at the last article written ddt library:

import unittest
from ddt import ddt,data,unpack
@ddt
class MyTest(unittest.TestCase):  @data((3, 1), (-1, 0), (1.2, 1.0))  @unpack def test(self, first, second): pass 

ddt provides four decorator: @ddt applied on a category, there are three methods applied to the class @ data, @ unpack and @file_data (not mentioned earlier).

Take a look at the role of class methods applied to the three decorators:

# ddt 版本(win):1.2.1
def data(*values): global index_len index_len = len(str(len(values))) return idata(values) def idata(iterable): def wrapper(func): setattr(func, DATA_ATTR, iterable) return func return wrapper def unpack(func): setattr(func, UNPACK_ATTR, True) return func def file_data(value): def wrapper(func): setattr(func, FILE_ATTR, value) return func return wrapper 

Their interaction is setattr () to add the class attribute in the method. As these properties to use at what time? Let's look at the class plus the @ddt decorator Source:

A first layer for loop through all of the class methods, and then if / elif two branches, respectively DATA_ATTR / FILE_ATTR, i.e., the corresponding parameters of two sources: data (@data) and files (@file_data).

elif branch logical parse the file, after processing the data with similar, so we skipped it, mainly to see if the previous branch. This part of the logic is very clear, the main tasks are as follows:

  • Traversing the class key parameter of the method
  • Yes, create a new method based on the original method name and parameters
  • Obtaining the documentation string of original method
  • Tuples and lists of types of parameters for unpacking
  • Add a new test method in the test class, and bind parameters with the document string

Source code analysis, it can be seen, @ data, @ unpack and decorator @file_data three main parameter passing and setting properties, and is the core of the decorator @ddt processing logic.

Such decorative dispersed (plus in each class and class methods), and then combining scheme used, very elegant. Why can not unite to use it? Later we will analyze it too awkward, first refrain, take a look at other implementations of what?

2、parameterized 如何实现参数化?

先回顾一下上篇文章中 parameterized 库的写法:

import unittest
from parameterized import parameterized
class MyTest(unittest.TestCase):  @parameterized.expand([(3,1), (-1,0), (1.5,1.0)]) def test_values(self, first, second): self.assertTrue(first > second) 

它提供了一个装饰器类 @parameterized,源码如下(版本 0.7.1),主要做了一些初始的校验和参数解析,并非我们关注的重点,略过。

我们主要关注这个装饰器类的 expand() 方法,它的文档注释中写到:

> A "brute force" method of parameterizing test cases. Creates new test cases and injects them into the namespace that the wrapped function is being defined in. Useful for parameterizing tests in subclasses of 'UnitTest', where Nose test generators don't work.

关键的两个动作是:“creates new test cases(创建新的测试单元)”和“inject them into the namespace…(注入到原方法的命名空间)”。

关于第一点,它跟 ddt 是相似的,只是一些命名风格上的差异,以及参数的解析及绑定不同,不值得太关注。

最不同的则是,怎么令新的测试方法生效?

parameterized 使用的是一种“注入”的方式:

inspect 是个功能强大的标准库,在此用于获取程序调用栈的信息。前三句代码的目的是取出 f_locals,它的含义是“local namespace seen by this frame”,此处 f_locals 指的就是类的局部命名空间。

说到局部命名空间,你可能会想到 locals(),但是,我们之前有文章提到过“locals() 与 globals() 的读写问题”,locals() 是可读不可写的,所以这段代码才用了 f_locals。

3、pytest 如何实现参数化?

按惯例先看看上篇文章中的写法:

import pytest
@pytest.mark.parametrize("first,second", [(3,1), (-1,0), (1.5,1.0)])
def test_values(first, second): assert(first > second) 

首先看到“mark”,pytest 里内置了一些标签,例如 parametrize、timeout、skipif、xfail、tryfirst、trylast 等,还支持用户自定义的标签,可以设置执行条件、分组筛选执行,以及修改原测试行为等等。

用法也是非常简单的,然而,其源码可复杂多了。我们这里只关注 parametrize,先看看核心的一段代码:

根据传入的参数对,它复制了原测试方法的调用信息,存入待调用的列表里。跟前面分析的两个库不同,它并没有在此创建新的测试方法,而是复用了已有的方法。在 parametrize() 所属的 Metafunc 类往上查找,可以追踪到 _calls 列表的使用位置:

最终是在 Function 类中执行:

好玩的是,在这里我们可以看到几行神注释……

阅读(粗浅涉猎) pytest 的源码,真的是自讨苦吃……不过,依稀大致可以看出,它在实现参数化时,使用的是生成器的方案,遍历一个参数则调用一次测试方法,而前面的 ddt 和 parameterized 则是一次性把所有参数解析完,生成 n 个新的测试方法,再交给测试框架去调度。

对比一下,前两个库的思路很清晰,而且由于其设计单纯是为了实现参数化,不像 pytest 有什么标记和过多的抽象设计,所以更易读易懂。前两个库发挥了 Python 的动态特性,设置类属性或者注入局部命名空间,而 pytest 倒像是从什么静态语言中借鉴的思路,略显笨拙。

4、最后小结

回到标题中的问题“如何将一个方法变为多个方法?”除了在参数化测试中,不知还有哪些场景会有此诉求?欢迎留言讨论。

本文分析了三个测试库的装饰器实现思路,通过阅读源码,我们可以发现它们各有千秋,这个发现本身还挺有意思。在使用装饰器时,表面看它们差异不大,但是真功夫的细节都隐藏在底下。

源码分析的意义在于探究其所以然,在这次探究之旅中,读者们可有什么收获啊?一起来聊聊吧!

来源:长春网站优化

Guess you like

Origin www.cnblogs.com/1994jinnan/p/12080453.html