減少重複的測試程式碼的一些方法

Post on 02-Jul-2015

162 views 3 download

description

如何避免重複測試程式碼的一些方法

Transcript of 減少重複的測試程式碼的一些方法

減少重複的測試程式碼的一些方法

果凍

簡介

● 任職於迎廣科技o python

o openstack

● c++, java, scala

● http://about.me/ya790206

● http://blog.blackwhite.tw

/

● https://github.com/ya790

206/call_seq

不重要的聲明

● 我用 unittest 的 libraray,不代表是 unittest

code 。● 故事純屬虛構。如有雷同,純屬巧合。

前情提要

● 有個 web service。● 使用者只有一種。● 要登入才能進行動作

一段測試碼

時間不斷的前進

● 有一天● 就是有一天● 使用者分成兩種!

o 假設分成兩種。 admin 和 user。o user 能使用的功能是 admin 的功能的子集合。

測試碼UserAdmin

重複的程式碼出現了

How to slove it?

● inherited

● composition今日重點

For admin

For user

我不想讓 base

class 被測試,因此跳過它。

● So far so good.

● But …

● If we have many test case, we need to add

`setUpClass` to every class.

● WTF !

redundancy

How to solve it ?

● decorator

● meta classSee it first.

decorator

Test Code

在多都不怕一行就搞定

● Decorator is good.

● Does it end?

● Not yet. If you have custom `setUpClass`,

how to make it?

Now we can custom setUpClass

● Does it end?

● Not yet. We have another redundancy code.

Test Code

redundancy(If

you don’t think

so, that’s ok.

How to slove it if you think it is

redundancy

● Multiple Inheritance

Login class go

first, so it can

call login

correctly.

How does it work?

● mro (Method Resolution Order )

Is it possible to make it shorter?

Maybe it’s

not useful.

Another way to solve redundancy.

● decorator

● meta class See it now.

Meta class

Meta class

Meta class

● 不算是一個好的作法● meta class 是為了建立 class 前,先作一些事

情。可是這個例子沒有。這個例子是事後才作些事情。

● 因為是事後才作些事情,因此可用 decorator

代替。

結論

● 懶得寫重複的程式碼是種美德:o 可以讓你維護更少的程式碼o 可以讓你寫更少的程式碼o 可以讓你讀更少的程式碼

● python 很好用,可以讓你懶惰。