星期二, 十一月 13, 2007

python distutils 调整目录结构后

在项目自动化中谈到对整个目录结构进行调整以利于测试和项目自动化构建,则相应的,distutils 的 setup.py 也需要相应的进行调整。

现在以完成部分的目录结构是这样的:
trunk/
ChangeLog
lib/
tree.py
LICENSE
MANIFEST.in
README
setup.py
test/
caxes/
__init__.py
support.py
test_support.py
test_tree.py
test_tree_complex.py
test_tree.bk
则调整后的 setup.py 为:
#!/usr/bin/python
# -*- encoding: utf-8 -*-

__author__ = "Roc Zhou #周鹏"
__date__ = "13 November 2007"
__version__ = "0.2"
__license__ = "GPL v2.0"

from distutils.core import setup
from distutils import sysconfig

lib_prefix = sysconfig.get_python_lib()

setup(
name = 'caxes',
version = '0.2',
description = """
Some new Python data types such as Tree,
and configuration sharing mechanism implementation.
""",
long_description = """
Some new Python data structure,
can be afforded as APIs for new ways of configuration,
and configuration sharing mechanism implementation.

It's a subproject of uLFS.

uLFS means "Your Manageable, Automatable and Templated Reusable Linux From Scratch",
it's a set of tools to build your own customed Linux distribution with
more managability than raw LFS(Linux From Scratch). Include source package
manager, file system backup and realtime mirror apps, and some assistant data
structure such as Tree writen in Python, etc...
""",
author = "Roc Zhou",
author_email = 'chowroc.z@gmail.com',
platforms = "Platform Independent",
license = "GPL v2.0",
url = "http://crablfs.sourceforge.net",
download_url = "http://sourceforge.net/projects/crablfs",
classifiers = [
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: GNU General Public License (GPL)",
"Natural Language :: English",
"Natural Language :: Chinese (Simplified)",
"Operating System :: POSIX",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules"
],
py_modules = ["tree"],
package_dir = {"" : "lib", "caxes" : "lib/caxes"},
# data_files = [("%s/test" % lib_prefix, ["test/test_tree*.py", "test/support.py"])],
# data_files = [("%s/test" % lib_prefix, ["test/*.py"]), ("%s/test/caxes" % lib_prefix, ["test/caxes/*.py"])],
data_files = [("%s/test" % lib_prefix, ["test/*.py", "test/caxes"])],
# packages = ['caxes']
)
这里先说明一下 py_modules 和 package_dir 的调整。

之前的定义为:
py_modules = ["tree"]
package_dir = {"caxes" : "lib"}
因为目录结构为:
trunk/
tree.py
lib/
...
但当目录结构调整后,会提示找不到模块 tree 的文件 tree.py,因为这个文件已经不再 trunk 的根目录下了,而是移到了 lib/,此时应该调整 package_dir,增加 "" : "lib"。而原来的 lib/ 变成了 lib/caxes,所以 package_dir 也应该相应变动。

在下面定义 data_files,保证 test/test_tree*.py 被安装到 /usr/lib/python2.4/site-packages/test/,而 test/caxes/ 被拷贝成 /usr/lib/python2.4/site-packages/caxes/,忽略掉 *.bk 文件。此时必须记住要调整 trunk/ 下的 MANIFEST.in 文件:
include *.py
include test/*.py
recursive-include test/caxes *
include README
include ChangeLog
include LICENSE
注意 recursive-include 一行,否真 test/caxes 目录不会被拷贝。

有一点比较奇怪的是,当我使用:
data_files = [("%s/test" % lib_prefix, ["test/test_tree*.py", "test/caxes"])]
却提示找不到文件 test/test_tree*.py。这是为什么呢?

__package__ = "caxes"
__revision__ = [258:259]

星期六, 十一月 10, 2007

python unittest TestSuite 框架实践和几个问题

之前的 python Tree 实现中单元测试做的不好,在"Progmatic Unit Testing", 心得和自省中说过这一点。现在要重写单元测试。

为了保证所有测试的独立性和正交性,编写测试 setattr() 操作正确性的代码如下:
#!/usr/bin/env python
# -*- encoding: utf-8 -*-

__author__ = "Roc Zhou #周鹏"
__date__ = "09 November 2007"
__version__ = "0.2"
__license__ = "GPL v2.0"

"""Unittest for tree.Tree"""

from gettext import gettext as _

import os
import unittest
import inspect

import tree
from tree import Tree,TreeExc,TreeTypeExc,TreePathConvExc

# def _setAll(self):
# names = []
# for member in inspect.getmembers(self, inspect.ismethod):
# method_name = member[0]
# if method_name.startswith("_set"):
# names.append(method_name)
# names.remove("_setAll")
# for name in names:
# method = getattr(self, name)
# method()

# def testPreviousAll(self):
# # """The previous Tree nodes should not be affected by the latter operations"""
# self._setToggle = 0
# names = []
# for test_name in inspect.getmembers(self, inspect.ismethod):
# if test_name.startswith("test"):
# names.append(test_name)
# names.remove("testPreviousAll")
# # #1:
# suite = unittest.TestSuite(map(self.__class__, test_names))
# suite.run()
# # #2:
# # for name in names:
# # test_method = getattr(self, name)
# # test_method()

class TestTree(unittest.TestCase):
def setUp(self):
self._setToggle = 1
### self._setAll = _setAll
### self.testPreviousAll = testPreviousAll
### Why can't ??????

def tearDown(self):
self.root = None

def assertNodeSet(self, node, value):
self.failUnless(isinstance(node, Tree))
self.failUnlessEqual(node._Tree__node_value, value)

def assertNodeValue(self, node, value):
self.failUnless(isinstance(node, Tree))
self.failUnlessEqual(node(), value)

def assertNodeIndex(self, node, key, value):
self.failUnless(node._Tree__node_items.has_key(key))
self.failUnless(isinstance(node[key], Tree))
self.failUnlessEqual(node[key]._Tree__node_value, value)

def assertNotNodeIndex(self, node, key):
self.failIf(node._Tree__node_items.has_key(key))

def assertNodeIndexValue(self, node, key, value):
self.failUnless(node.has_key(key))
self.assertNodeValue(node[key], value)

def _setBaseCase(self):
self.root = Tree("root", data="root.data", extra="extra")

def testBaseCase(self):
# """The simplest assignment should create a Tree instance with several valid sub nodes"""
if self._setToggle:
self._setBaseCase()
self.assertNodeSet(self.root, "root")
self.assertNodeSet(self.root.data, "root.data")
self.assertNodeSet(self.root.extra, "extra")

def _setAll(self):
names = []
for member in inspect.getmembers(self, inspect.ismethod):
method_name = member[0]
if method_name.startswith("_set"):
names.append(method_name)
names.remove("_setAll")
for name in names:
method = getattr(self, name)
method()

def testPreviousAll(self):
# """The previous Tree nodes should not be affected by the latter operations"""
self._setToggle = 0
# self.tearDown()
# self.setUp()
self._setAll()
names = []
for member in inspect.getmembers(self, inspect.ismethod):
test_name = member[0]
if test_name.startswith("test"):
names.append(test_name)
names.remove("testPreviousAll")
# #1:
# suite = unittest.TestSuite(map(self.__class__, names))
# suite.run(suite)
# #2:
for name in names:
test_method = getattr(self, name)
test_method()

class TestSetAttr(TestTree):
def setUp(self):
TestTree.setUp(self)
self._setBaseCase()

def testNameReserved(self):
# """Assign to reserved names should be avoided"""
__used_names = object.__dict__.copy().keys() + [
'_Tree__path_stack', '_Tree__id_visited', '_Tree__used_names',
'_Tree__node_value', '_Tree__node_items',
'__path_stack', '__id_visited', '__used_names', '__node_value', '__node_items',
'__getattr__', '__setitem__', '__getitem__', '__call__',
'__add__', '__iadd__', '__cmp__',
'_one_node_set', '__traverse__', '__update__', '__copy__', '__search__'
]
for used_name in __used_names:
try:
setattr(self.root, used_name, 1)
self.fail(_("A reserved name '%s' should can not be reassignable" % used_name))
except TreeExc:
pass
except TypeError:
pass

def _setCreateNew(self):
self.root.trunk = 1
self.root.branch = Tree(None, data='branch/data', extra=('branch', 'extra'))

def testCreateNew(self):
# """If the sub node does not exist, assign it directly"""
if self._setToggle:
self._setCreateNew()
self.assertNodeSet(self.root.trunk, 1)
self.assertNodeSet(self.root.branch, None)
self.assertNodeSet(self.root.branch.data, "branch/data")
self.assertNodeSet(self.root.branch.extra, ('branch', 'extra'))

def _setAssignNonTreeToExisted(self):
self.root.nt_ex_simple = 1
self.root.nt_ex_complex = Tree(1, data="nt_ex_complex/data", extra="nt_ex_complex/extra")
# Create new first
self.root.nt_ex_simple = "one"
self.root.nt_ex_complex = "ONE"

def testAssignNonTreeToExisted(self):
# """If attribute is an existed Tree, and target is not a Tree, only the node value should be replaced"""
if self._setToggle:
self._setAssignNonTreeToExisted()
self.assertNodeSet(self.root.nt_ex_simple, "one")
self.assertNodeSet(self.root.nt_ex_complex, "ONE")
# If the node has childs, only value replacement:
self.assertNodeSet(self.root.nt_ex_complex.data, "nt_ex_complex/data")
self.assertNodeSet(self.root.nt_ex_complex.extra, "nt_ex_complex/extra")

def _setAssignTreeToExisted(self):
self.root.tr_ex_simple = 2
self.root.tr_ex_complex = Tree(2, data="tr_ex_complex/data")
self.root.tr_ex_simple_branch = '2'
self.root.tr_ex_complex_branch = Tree(2, data="tr_ex_complex_branch/data")
# Create first
self.root.tr_ex_simple = Tree("two")
self.root.tr_ex_complex = Tree("TWO")
self.root.tr_ex_simple_branch = Tree("_two", data="tr_ex_simple_branch/data")
self.root.tr_ex_complex_branch = Tree("_TWO", extra="tr_ex_complex_branch/extra")

def testAssignTreeToExisted(self):
# """If attribute is an existed Tree, and target is a Tree too, the node itself should be replaced"""
if self._setToggle:
self._setAssignTreeToExisted()
# (1) target Tree instance does not have attributes, and original Tree does not have sub nodes:
self.assertNodeSet(self.root.tr_ex_simple, "two")
# (2) target Tree instance does not have attributes, and original Tree have sub nodes:
self.assertNodeSet(self.root.tr_ex_complex, "TWO")
self.failIf(hasattr(self.root.tr_ex_complex, "data"))
# (3) target Tree instance has attributes, and original Tree does not have sub nodes:
self.assertNodeSet(self.root.tr_ex_simple_branch, "_two")
self.assertNodeSet(self.root.tr_ex_simple_branch.data, "tr_ex_simple_branch/data")
# (4) target Tree instance has attributes, and original Tree have sub nodes too:
self.assertNodeSet(self.root.tr_ex_complex_branch, "_TWO")
self.failIf(hasattr(self.root.tr_ex_complex_branch, "data"))
self.assertNodeSet(self.root.tr_ex_complex_branch.extra, "tr_ex_complex_branch/extra")

def _setReserveSomeAttrWhenReplaceNode(self):
self.root.replace_but_reserve_1 = ["Replace", "But", "Reserve", "Method", 1]
self.root.replace_but_reserve_1.br1 = 1
subtree = self.root.replace_but_reserve_1.br1
self.root.replace_but_reserve_1 = Tree("replaced_by_method_1", data="another_1")
self.root.replace_but_reserve_1.br1 = subtree

self.root.replace_but_reserve_2 = ["Replace", "But", "Reserve", "Method", 2]
self.root.replace_but_reserve_2.br2 = 2
self.root.replace_but_reserve_2 = Tree("replaced_by_method_2", br2=self.root.replace_but_reserve_2.br2, data="another_2")

def testReserveSomeAttrWhenReplaceNode(self):
if self._setToggle:
self._setReserveSomeAttrWhenReplaceNode()
self.assertNodeSet(self.root.replace_but_reserve_1, "replaced_by_method_1")
self.assertNodeSet(self.root.replace_but_reserve_1.br1, 1)
self.assertNodeSet(self.root.replace_but_reserve_1.data, "another_1")
self.assertNodeSet(self.root.replace_but_reserve_2, "replaced_by_method_2")
self.assertNodeSet(self.root.replace_but_reserve_2.br2, 2)
self.assertNodeSet(self.root.replace_but_reserve_2.data, "another_2")

......
这里首先从 TestCase 继承一个 TestTree 基类,并自定义一些 assert 测试方法来做一些基本的测试。这样测试 setattr() 的类 TestSetAttr 可以从 TestTree 继承并直接调用这些 assert 来完成更复杂的测试,这样也就提高了复用性。

每一个 test* 方法基本上和一个 _set* 方法对应,并只进行很简单很专门的测试,这样就可以将方法名定义得更具有可读性,而且方便其他测试方法来调用,test* 和 _set* 分开也是为了这个目的。

比如,上面在 TestTree 中定义的 testPreviousAll() 方法,就是为了测试之前所有的操作是否互相影响,比如对一个节点的子节点进行操作之后,它本身的值、它的兄弟节点和其他子节点都不应该受到影响,它会利用 inspect 模块提供的功能寻找所有自己这个测试类中的 test* 方法(排除自身),并逐一调用,以确保这一点。因为 TestSetAttr 是从 TestTree 继承的,所以它也会有这个 testPreviousAll() 方法。

要逐一调用这些方法方法,有两种想法,其一是利用 getattr() 得到这个方法的实例,并直接调用;另一种思路是利用 TestSuite 的构造方法得到一个 test suite,并调用 suite.run() 直接运行。

除了利用 testPreviousAll() 方法来做这件事外,我一开始的另一个思路是在后面调用 TextTestRunner().run(suite) 的时候调用对 TestSetAttr 前后调用两次,而不用使用 testPreviousAll() 方法。

无论使用那种方法,前后两次调用 test* 方法都需要分别设定 _setToggle 标志,保证第二次调用的时候,test* 方法不会去调用 _set* 重复设定各个节点,这样才能得到正确的测试结果。

但是这几种思路都有问题。逐一来讨论。

首先,更深入的了解一下 unittest 的框架。TestCase 为一个基本单元,由若干 TestCase 组成一个 TestSuite,是可以运行的单元,TestSuite 也可以包含 TestSuite。但必须通过调用 TestRunner 的实例来运行 TestSuite 的实例。例如:
suite = unittest.TestSuite()
suite.addTest(...)
...
unittest.TextTestRunner(verbosity=2).run(suite)
在 Python 的官方手册中,提到一个 test fixture,这个 fixture 事实上并没有相应的 class,只不过是一种概念,即可以将若干包含 TestSuite 的 TestSuite 看作一个 fixture,因为其环境比较复杂了。如何对这样一个 fixture 设置 setUp() 和 tearDown() 环境这里不讨论。

为了运行所有这些测试,最简单的办法是直接调用 unittest.main() 函数:
if __name__ == "__main__":
unittest.main()
它会自动去寻找当前模块里所有的 tests 组成 TestSuite 并运行之。因此这段代码的等效代码可以看作是:
if __name__ == "__main__":
import __main__
suite = unittest.TestLoader().loadTestsFromModule(__main__)
unittest.TextTestRunner(verbosity=2).run(suite)
所以问题的关键是如何得到这些 TestSuite 并将 tests 加入其中。

除了调用 unittest.main() 以外,显式地创建 test suite 有很多方法,除了上面的 TestLoader 之外,还可以逐个加入:
suite = unittest.TestSuite()
suite.addTest(TestSetAttr("testNameReserved"))
suite.addTest(TestSetAttr("testCreateNew"))
...
unittest.TextTestRunner(verbosity=2).run(suite)
通过阅读 unittest 的源代码可以知道,addTest() 的参数即为一个 test,也就是一个 TestCase 的 instance,并且这个 instance 的 testMothod() 方法指向传递给构造函数的方法名所表示的方法。

TestSuite.addTests() 的参数是 tuple list of tests。

另一种方法是:
test_names = [
"testNameReserved",
"testCreateNew",
"testAssignNonTreeToExisted",
"testAssignTreeToExisted",
"testReserveSomeAttrWhenReplaceNode",
"testPreviousAll" ]
suite = unittest.TestSuite(map(TestSetAttr, test_names))
因为 TestSetAttr 是 callable,所以 map(function, seq1, [seq2, ...]) 会将它作为一个函数调用,并将 test_names 依次作为其调用时的参数。这样就会依次构建所有的 tests instance。

回到这个测试的具体案例上来。如果采用 unittest.main() 或 unittest.TestLoader().loadTestsFromModules(__main__) 的做法,有一个问题就是 tests 不会按照你定义他们的时候的上下顺序来运行(而且即使按照定义的顺序来运行也没有用,下面谈到),但是在定义测试的时候,如最开始所描述的,必须要考虑到对 Previous 条件进行测试的需要。如果我不做 testPreviousAll(),那么这样运行没有什么问题,但问题就在于做 testPreviousAll() 是有必要的。

一开始,使用 unittest.main() 或 unittest.TestLoader().loadTestsFromModules(__main__) 这种方法,在 TestTree 这个基类中定义的方法如下:
def _setAll(self):
names = []
for member in inspect.getmembers(self, inspect.ismethod):
method_name = member[0]
if method_name.startswith("_set"):
names.append(method_name)
names.remove("_setAll")
for name in names:
method = getattr(self, name)
method()

def testPreviousAll(self):
self._setToggle = 0
self._setAll()
names = []
for member in inspect.getmembers(self, inspect.ismethod):
test_name = member[0]
if test_name.startswith("test"):
names.append(test_name)
names.remove("testPreviousAll")
# #1:
suite = unittest.TestSuite(map(self.__class__, names))
suite.run(suite)
# unittest.TextTestRunner(verbosity=2).run(suite)
# #2:
# for name in names:
# test_method = getattr(self, name)
# test_method()
然后运行:
 python test_tree.bk
testBaseCase (__main__.TestKeyIndex) ... ok
testDeepIndexedNodes (__main__.TestKeyIndex) ... ok
testIndexedParentReplacement (__main__.TestKeyIndex) ... ok
testInexistentNode (__main__.TestKeyIndex) ... ok
testNodeReplacement (__main__.TestKeyIndex) ... ok
testNodeWithKeys (__main__.TestKeyIndex) ... ok
testNodeWithoutKey (__main__.TestKeyIndex) ... ok
testOnlyValueReplacement (__main__.TestKeyIndex) ... ok
testPreviousAll (__main__.TestKeyIndex) ... ERROR
testUnhashable (__main__.TestKeyIndex) ... ok
testAssignNonTreeToExisted (__main__.TestSetAttr) ... ok
testAssignTreeToExisted (__main__.TestSetAttr) ... ok
testBaseCase (__main__.TestSetAttr) ... ok
testCreateNew (__main__.TestSetAttr) ... ok
testNameReserved (__main__.TestSetAttr) ... ok
testPreviousAll (__main__.TestSetAttr) ... ERROR
testReserveSomeAttrWhenReplaceNode (__main__.TestSetAttr) ... ok
testBaseCase (__main__.TestTree) ... ok
testPreviousAll (__main__.TestTree) ... ERROR

======================================================================
ERROR: testPreviousAll (__main__.TestKeyIndex)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_tree.bk", line 113, in testPreviousAll
suite.run(suite)
File "/usr/lib/python2.4/unittest.py", line 422, in run
if result.shouldStop:
AttributeError: 'TestSuite' object has no attribute 'shouldStop'

======================================================================
ERROR: testPreviousAll (__main__.TestSetAttr)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_tree.bk", line 113, in testPreviousAll
suite.run(suite)
File "/usr/lib/python2.4/unittest.py", line 422, in run
if result.shouldStop:
AttributeError: 'TestSuite' object has no attribute 'shouldStop'

======================================================================
ERROR: testPreviousAll (__main__.TestTree)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_tree.bk", line 113, in testPreviousAll
suite.run(suite)
File "/usr/lib/python2.4/unittest.py", line 422, in run
if result.shouldStop:
AttributeError: 'TestSuite' object has no attribute 'shouldStop'

----------------------------------------------------------------------
Ran 19 tests in 0.462s

FAILED (errors=3)
显然,你不能向 suite.run() 传递 suite 作为参数,你只能向 suite.run() 传递 TestResult 的 instance 作为参数,或者将 suite 作为参数传递给 TestRunner 的 instance,亦即在上面的定义中使用的另外一种方法:unittest.TextTestRunner(verbosity=2).run(suite)。但这样运行会导致你的输出很不规整,你可能会得到类似这样的结果:
sh# python test_tree.bk
testBaseCase (__main__.TestKeyIndex) ... ok
testDeepIndexedNodes (__main__.TestKeyIndex) ... ok
testIndexedParentReplacement (__main__.TestKeyIndex) ... ok
testInexistentNode (__main__.TestKeyIndex) ... ok
testNodeReplacement (__main__.TestKeyIndex) ... ok
testNodeWithKeys (__main__.TestKeyIndex) ... ok
testNodeWithoutKey (__main__.TestKeyIndex) ... ok
testOnlyValueReplacement (__main__.TestKeyIndex) ... ok
testPreviousAll (__main__.TestKeyIndex) ... testBaseCase (__main__.TestKeyIndex) ... ok
testDeepIndexedNodes (__main__.TestKeyIndex) ... ok
testIndexedParentReplacement (__main__.TestKeyIndex) ... ok
testInexistentNode (__main__.TestKeyIndex) ... ok
testNodeReplacement (__main__.TestKeyIndex) ... ok
testNodeWithKeys (__main__.TestKeyIndex) ... ok
testNodeWithoutKey (__main__.TestKeyIndex) ... ok
testOnlyValueReplacement (__main__.TestKeyIndex) ... ok
testUnhashable (__main__.TestKeyIndex) ... ok

----------------------------------------------------------------------
Ran 9 tests in 0.157s

OK
ok
testUnhashable (__main__.TestKeyIndex) ... ok
testAssignNonTreeToExisted (__main__.TestSetAttr) ... ok
testAssignTreeToExisted (__main__.TestSetAttr) ... ok
testBaseCase (__main__.TestSetAttr) ... ok
testCreateNew (__main__.TestSetAttr) ... ok
testNameReserved (__main__.TestSetAttr) ... ok
testPreviousAll (__main__.TestSetAttr) ... testAssignNonTreeToExisted (__main__.TestSetAttr) ... ok
testAssignTreeToExisted (__main__.TestSetAttr) ... ok
testBaseCase (__main__.TestSetAttr) ... ok
testCreateNew (__main__.TestSetAttr) ... ok
testNameReserved (__main__.TestSetAttr) ... ok
testReserveSomeAttrWhenReplaceNode (__main__.TestSetAttr) ... ok

----------------------------------------------------------------------
Ran 6 tests in 0.124s

OK
ok
testReserveSomeAttrWhenReplaceNode (__main__.TestSetAttr) ... ok
testBaseCase (__main__.TestTree) ... ok
testPreviousAll (__main__.TestTree) ... testBaseCase (__main__.TestTree) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.006s

OK
ok

----------------------------------------------------------------------
Ran 19 tests in 0.759s
这样显然是不利于测试的组织和代码的排错的。所以改用在上面的定义中的 #2 所指明的办法。

在上面 testPreviousAll() 的定义中调用了 self._setAll(),这看上去会降低正交性,但是不再其中定义却不行,你会得到这样的错误:

# python test_tree.bk
testBaseCase (__main__.TestKeyIndex) ... ok
testDeepIndexedNodes (__main__.TestKeyIndex) ... ok
testIndexedParentReplacement (__main__.TestKeyIndex) ... ok
testInexistentNode (__main__.TestKeyIndex) ... ok
testNodeReplacement (__main__.TestKeyIndex) ... ok
testNodeWithKeys (__main__.TestKeyIndex) ... ok
testNodeWithoutKey (__main__.TestKeyIndex) ... ok
testOnlyValueReplacement (__main__.TestKeyIndex) ... ok
testPreviousAll (__main__.TestKeyIndex) ... ERROR
testUnhashable (__main__.TestKeyIndex) ... ok
testAssignNonTreeToExisted (__main__.TestSetAttr) ... ok
testAssignTreeToExisted (__main__.TestSetAttr) ... ok
testBaseCase (__main__.TestSetAttr) ... ok
testCreateNew (__main__.TestSetAttr) ... ok
testNameReserved (__main__.TestSetAttr) ... ok
testPreviousAll (__main__.TestSetAttr) ... ERROR
testReserveSomeAttrWhenReplaceNode (__main__.TestSetAttr) ... ok
testBaseCase (__main__.TestTree) ... ok
testPreviousAll (__main__.TestTree) ... ERROR

======================================================================
ERROR: testPreviousAll (__main__.TestKeyIndex)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_tree.bk", line 118, in testPreviousAll
test_method()
File "test_tree.bk", line 360, in testDeepIndexedNodes
self.assertNodeSet(self.root.deep, "deep_indexed_prefix")
AttributeError: Tree instance has no attribute 'deep'

======================================================================
ERROR: testPreviousAll (__main__.TestSetAttr)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_tree.bk", line 118, in testPreviousAll
test_method()
File "test_tree.bk", line 168, in testAssignNonTreeToExisted
self.assertNodeSet(self.root.nt_ex_simple, "one")
AttributeError: Tree instance has no attribute 'nt_ex_simple'

======================================================================
ERROR: testPreviousAll (__main__.TestTree)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_tree.bk", line 118, in testPreviousAll
test_method()
File "test_tree.bk", line 84, in testBaseCase
self.assertNodeSet(self.root, "root")
AttributeError: 'TestTree' object has no attribute 'root'

----------------------------------------------------------------------
Ran 19 tests in 0.304s

FAILED (errors=3)
因为通过构造 TestSuite 的方法可以看出,每一次传递给它的构造函数的都是一个全新的 TestCase instance,并且每一个这样的 instance 中在运行的时候只有其中的一个 test* 方法被运行,就是 testMothod 所指向的那个方法。所以如果不先调用这个方法,那么任何节点都不会设置。

如果使用方法 #1,则似乎不会出现这个问题,所有测试都 OK 通过,但其实是不对的。因为在检查 PreviousAll 的时候,我必须避免对要检查的节点重复设置,所以在 test* 方法中使用了 _setToggle 标志来实现这一点。但因为使用 TestSuite() 创建了新的 tests,而这些 tests 的 _setToggle 必然是重新设置为 1 的,所以所有节点都会被重复设置,因此测出的结果是不正确的。如果将 _setToggle 定义为 class 的 static 变量呢?似乎可行,但显然会降低正交性,并且如前所述,测试的结果输出很不规范。

这也就是前面提到,即使按照顺序来调用这些 tests 也没有用的原因。如果要按照顺序来调用,可以这样:
fixture = unittest.TestSuite()
test_names = ["testBaseCase"]
suite = unittest.TestSuite(map(TestTree, test_names))
fixture.addTest(suite)
test_names = [
"testNameReserved",
"testCreateNew",
"testAssignNonTreeToExisted",
"testAssignTreeToExisted",
"testReserveSomeAttrWhenReplaceNode",
"testPreviousAll" ]
suite = unittest.TestSuite(map(TestSetAttr, test_names))
fixture.addTest(suite)
test_names = [
"testNodeWithoutKey",
"testNodeWithKeys",
"testInexistentNode",
"testOnlyValueReplacement",
"testNodeReplacement",
"testIndexedParentReplacement",
"testUnhashable",
"testDeepIndexedNodes",
"testPreviousAll" ]
suite = unittest.TestSuite(map(TestKeyIndex, test_names))
fixture.addTest(suite)
unittest.TextTestRunner(verbosity=3).run(fixture)
当然这样意义不大,而且显然增加了重复性。

即使是在 testPreviousAll() 中调用了 _setAll() 也仍然是有问题的,因为
for member in inspect.getmembers(self, inspect.ismethod)
这段代码也不会按照你定义的顺序去 inspect member methods,所以 _setBaseCase() 可能会在中间运行再次被运行(setUp() 里面运行过第一次,否则没有根节点,我这里实际上就在中间重新运行的),因此导致 root 节点被重新设置,结果是已经设置的其他节点被冲掉了,因此后面必然会抛出 AttributeError 异常。当然结果是不确定的,可能会出现这样的问题,也可能会巧合的按照定义顺序进行。

显然第一种思路是行不通了。那么第二种思路呢?
fixture = unittest.TestSuite()
suite = unittest.TestLoader().loadTestsFromTestCase(TestTree)
fixture.addTest(suite)
suite = unittest.TestLoader().loadTestsFromTestCase(TestSetAttr)
fixture.addTest(suite)
TestSetAttr._setToggle = 0
suite = unittest.TestLoader().loadTestsFromTestCase(TestSetAttr)
fixture.addTest(suite)
suite = unittest.TestLoader().loadTestsFromTestCase(TestKeyIndex)
fixture.addTest(suite)
TestKeyIndex._setToggle = 0
suite = unittest.TestLoader().loadTestsFromTestCase(TestKeyIndex)
fixture.addTest(suite)
unittest.TextTestRunner(verbosity=2).run(fixture)
这时候,不定义 testPrevious() 和 _setAll() 方法,并且 _setToggle 定义为类的 static 变量。结果当然仍然是不行,可以推想,因为所有的 tests 都是全新的 TestCase instance,相互之间没有关联,因此第二次产生的 suite 并不会使用第一次产生的 suite 的结果。在将 TestSetAttr._setToggle 设置为 0 后,调用 unittest.TestLoader().loadTestsFromTestCase(TestSetAttr) 产生的 tests,其 test* 将不再设置 _set* 方法,因此所有的节点都不会被设置,必然会抛出 AttributeError。实际运行的结果也是如此。

那么如何解决这个正交性和测试独立性的问题呢?

因为同时必须要考虑到顺序的问题,但同时因为各个测试方法之间都是互相独立的,所以我接下来的一个思路就是在每一个 test* 方法中调用定义的前一个 test* 和 _set*。代码大概是这样(此时不再需要定义 testPreviousAll() 和 _setAll()):
class TestTree(unittest.TestCase):
...
def _testPrevious(self, test_name):
self._setToggle = 0
test_method = getattr(self, test_name)
test_method()
self._setToggle = 1

class TestSetAttr(TestTree):
def setUp(self):
TestTree.setUp(self)
self._setBaseCase()
...
def _setCreateNew(self):
self._setBaseCase()
self.root.trunk = 1
self.root.branch = Tree(None, data='branch/data', extra=('branch', 'extra'))

def testCreateNew(self):
# """If the sub node does not exist, assign it directly"""
if self._setToggle:
self._setCreateNew()
self.assertNodeSet(self.root.trunk, 1)
self.assertNodeSet(self.root.branch, None)
self.assertNodeSet(self.root.branch.data, "branch/data")
self.assertNodeSet(self.root.branch.extra, ('branch', 'extra'))
self._testPrevious("testBaseCase")
这样在运行 testCreateNew() 的时候,会接着运行 testBaseCase() 以确保前面设置的节点没有受到 CreateNew 操作的影响,并且因为关闭了 _setToggle,不会导致重复设置。

但如果把这个问题扩展一下呢?就是说,如果我按照任意的顺序去调用 _set* 方法,那么能否始终保证后面的操作不会对前面的已有结果造成破坏呢?

另外还有一个问题。在:
python assemble methods at runtime?
和
python unzip
中,曾提到运行时装配方法的技巧。但在这里似乎行不通,因为这时候这个 testPreviousAll() 方法好像根本就没有被检测到(使用 loadTestsFromModules(__main__)):
sh# python test_tree.bk
testBaseCase (__main__.TestKeyIndex) ... ok
testDeepIndexedNodes (__main__.TestKeyIndex) ... ok
testIndexedParentReplacement (__main__.TestKeyIndex) ... ok
testInexistentNode (__main__.TestKeyIndex) ... ok
testNodeReplacement (__main__.TestKeyIndex) ... ok
testNodeWithKeys (__main__.TestKeyIndex) ... ok
testNodeWithoutKey (__main__.TestKeyIndex) ... ok
testOnlyValueReplacement (__main__.TestKeyIndex) ... ok
testUnhashable (__main__.TestKeyIndex) ... ok
testAssignNonTreeToExisted (__main__.TestSetAttr) ... ok
testAssignTreeToExisted (__main__.TestSetAttr) ... ok
testBaseCase (__main__.TestSetAttr) ... ok
testCreateNew (__main__.TestSetAttr) ... ok
testNameReserved (__main__.TestSetAttr) ... ok
testReserveSomeAttrWhenReplaceNode (__main__.TestSetAttr) ... ok
testBaseCase (__main__.TestTree) ... ok

----------------------------------------------------------------------
Ran 16 tests in 0.280s

OK
看一下 unittest 的源代码,其调用关系是这样的:
loadTestsFromModules()
\--> loadTestsFromTestCase() # TestSetAttr
\--> getTestCaseNames(self, testCaseClass)

class TestLoader:
......
def loadTestsFromTestCase(self, testCaseClass):
"""Return a suite of all tests cases contained in testCaseClass"""
if issubclass(testCaseClass, TestSuite):
raise TypeError("Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?")
testCaseNames = self.getTestCaseNames(testCaseClass)
if not testCaseNames and hasattr(testCaseClass, 'runTest'):
testCaseNames = ['runTest']
return self.suiteClass(map(testCaseClass, testCaseNames))

def loadTestsFromModule(self, module):
"""Return a suite of all tests cases contained in the given module"""
tests = []
for name in dir(module):
obj = getattr(module, name)
if (isinstance(obj, (type, types.ClassType)) and
issubclass(obj, TestCase)):
tests.append(self.loadTestsFromTestCase(obj))
return self.suiteClass(tests)

def getTestCaseNames(self, testCaseClass):
"""Return a sorted sequence of method names found within testCaseClass
"""
def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
return attrname.startswith(prefix) and callable(getattr(testCaseClass, attrname))
testFnNames = filter(isTestMethod, dir(testCaseClass))
for baseclass in testCaseClass.__bases__:
for testFnName in self.getTestCaseNames(baseclass):
if testFnName not in testFnNames: # handle overridden methods
testFnNames.append(testFnName)
if self.sortTestMethodsUsing:
testFnNames.sort(self.sortTestMethodsUsing)
return testFnNames
filter 是 builtin 函数,显然在使用 dir(testCaseClass) 的时候是不会包含 testPreviousAll() 的,因为 testPreviousAll()只会在 TestCase instance 中存在。

所以应该不是在 setUp() 方法里面设置,而是应该定义 TestTree.testPreviousAll = testPreviousAll。

包含这些问题的代码在 caxes/trunk/test/test_tree.bk 中:
__package__ = "caxes"
__revision__ = [257:259]

星期三, 十一月 07, 2007

sourceforge vhost

绑定 VirtualHost。在 Project -> Admin -> Shell/DB/Web -> "Manage VHOSTs" 下,添加一个 vhost(Add New Virtual Host -> New Virtual Host),例如我原来的项目站点为 crablfs.sourceforge.net,这时增加一个 www.yourlfs.net。

然后设置 DNS。注册一个域名 yourlfs.net(¥50/年),并进行如下设置:
yourlfs.net      IN    A        66.35.250.210
www.yourlfs.net IN CNAME vhost.sourceforge.net.
svn.yourlfs.net IN CNAME crablfs.svn.sourceforge.net.

dig DNS 迭代查询以及双线 view 问题

默认情况下,DNS 都会使用递归查询。通过迭代查询,可以获得查询的路径,即对域名是如何被解析的得到一个直观印象。可以通过运行
sh$ dig +trace www.example.com (@server)
来进行查询。

我在 "变态"DNS中曾经讨论过为双线设置 DNS 的方法。但最近发现老是会被解析到网通的服务器,即使是电信的 DNS 服务器,也会得到网通的结果。用 dig +trace 也看不出所以然来。

后来发现网通的 slave DNS 的两个域文件(电信 .zone 和 网通 .cnc_zone)的内容完全一样。原来从服务器同步的时候,因为地址是网通的,所以主服务器只会返回网通的结果。这样看来,从主服务器之间也是通过 53 端口传递数据并且也受 acl view 规则的影响。

要解决这个问题,复杂一点的办法是从服务器绑定两个 IP 地址,主服务器的两个 view 设置不同的 allow-transfer {},从服务器的两个 view 设置两个 transfer-source $ipaddr,可参考:
http://www.chinalinuxpub.com/read.php?wid=1452

简单点的办法就是把两个都设置成主的 DNS 并手工同步。

python setup.py classifiers for pypi

通过编写 setup.py 中的 classfiers,以及相应的 url/download_url 和 description,可以直接从命令行上运行 python setup.py register 将包直接上传到 pypi,从而避免每次发布新版本的时候都要登录到 web 页面填写表单这样的重复劳动。例子如下:
#!/usr/bin/python
# -*- encoding: utf-8 -*-

# Author: Roc Zhou
# Date: 2007-11-07
# Email: chowroc.z@gmail.com

from distutils.core import setup
from distutils import sysconfig

lib_prefix = sysconfig.get_python_lib()

setup(
name = 'caxes',
version = '0.1.4'
description = """
Some new Python data structure,
can be afforded as APIs for new ways of configuration.

It's a subproject of uLFS.

uLFS means "Your Manageable, Automatable and Templated Reusable Linux From Scratch",
it's a set of tools to build your own customed Linux distribution with
more managability than raw LFS(Linux From Scratch). Include source package
manager, file system backup and realtime mirror apps, and some assistant data
structure such as Tree writen in Python, etc...
""",
author = "Roc Zhou",
author_email = 'chowroc.z@gmail.com',
platforms = "Platform Independent",
license = "GPL v2.0",
url = "http://crablfs.sourceforge.net",
download_url = "http://sourceforge.net/projects/crablfs",
classifiers = [
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: GNU General Public License (GPL)",
"Natural Language :: English",
"Natural Language :: Chinese (Simplified)",
"Operating System :: POSIX",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules"
],
py_modules = ['tree'],
# data_files = [('test', ['tree_ut.py'])],
data_files = [("%s/test" % lib_prefix, ['test_tree.py'])],
# package_dir = {'caxes' : 'lib'},
# packages = ['caxes']
)
不过不知道为什么 description 却和 web 页面中的 Description 不一样,却显示在了 Summary 下面。结果 Summary 信息很长。

星期日, 十一月 04, 2007

python distutils data_files lib_prefix

使用 distutils 的 setup() 的 data_files 参数,本来期望文件被拷贝到 /usr/lib/python2.4/site-packages/test 下面,结果却被拷贝到了 /usr/test(如果使用 upm 安装则没有权限),因为 prefix 为 /usr。

那么我希望改变这个设置。因为 /usr/lib/python2.4/site-packages 应该是在安装时的 LIB 目录设定下的,所以找到 lib_prefix 即可:
from distutils import sysconfig

lib_prefix = sysconfig.get_python_lib()

setup(
...
data_files = [("%s/test" % lib_prefix, ['tree_ut.py'])],
...

星期五, 十一月 02, 2007

SNMP access 的一个问题

SNMP Agent 的配置文件:
sh$ egrep -v '(^#|^$)' snmpd.conf
syslocation Unknown (edit /etc/snmp/snmpd.conf)
syscontact Root (configure /etc/snmp/snmp.local.conf)
pass .1.3.6.1.4.1.4413.4.1 /usr/bin/ucd5820stat
syscontact monitor@zovatech.com
disk / 36G
com2sec mynet 192.168.0.0/24 public
com2sec mynet 222.66.231.106 public
group mynet v1 mynet
group mynet v2c mynet
view system included .1
access mynet "" any noauth exact system none none
exec .1.3.6.1.4.1.2021.54 hdNum /usr/local/bin/snmpdiskio hdNum
exec .1.3.6.1.4.1.2021.55 hdIndex /usr/local/bin/snmpdiskio hdIndex
exec .1.3.6.1.4.1.2021.56 hdDescr /usr/local/bin/snmpdiskio hdDescr
exec .1.3.6.1.4.1.2021.57 hdInBlocks /usr/local/bin/snmpdiskio hdInBlocks
exec .1.3.6.1.4.1.2021.58 hdOutBlocks /usr/local/bin/snmpdiskio hdOutBlocks
本来没有设置 com2sec mynet 222.66.231.106 的。因为 SNMP client 这台主机有两个 IP,一个是内网的 192.168.0.1,还有一个是外网的 202.66.231.106,而 SNMP Agent 所在主机为 192.168.0.197。则在配置 SNMP access 的候,一个很直接的想法就是只要允许了所有内网的主机就应该可以了呀,但是在这里却不行,对于 192.168.0.1 这台主机,必须要使用外网(eth1)的那个 IP 来指定。

不知道原因是什么?

星期四, 十一月 01, 2007

项目自动化

《Pragmatic Project Automation》主要是针对 Java 项目的自动化建构和部署以及监控。我目前主要使用 Python,接着需要重新再学习 C,那么我需要考虑一些不同的情况。

首先,我不大可能使用象 Ant 和 CruiseControl 这样的工具,不过我想应该可以直接利用 Python 的 distutils 工具基本上也可以做这些。

首先,为了使测试能够自动化,并且编写单元测试的时候能够更加一致,也许应该调整一下目录结构。以 caxes 项目为例,目前的目录结构是:
ulfs/
caxes/
tree.py
test_tree.py
lib/
ctemplates.py
edconfig.py
sctmd.py
test/
test_ctemplates.py
test_edconfig.py
test_sctmd.py
......
但对于单元测试文件的存放就不一致了。另一个问题是,test_ctemplates.py 要 import ctemplates.py,在 sandbox 中和安装后的包路径会不一致,因为安装后显然只能是 caxes 包(或其他名字如 libcaxes,但不可能是 lib),虽然可以象这样:
try:
pwd = os.getcwd()
MODULE_PATH = os.path.dirname(pwd)
sys.path.insert(0, MODULE_PATH)
import mirrord,fs_info
sys.path.pop(0)
except ImportError:
from cutils import mirrord,fs_info
但这会导致重复增加。所以我想这样的目录结构也许更合理:
ulfs/
caxes/
lib/
tree.py
caxes/
ctemplates.py
edconfig.py
sctmd.py
test/
test_tree.py
caxes/
test_ctemplates.py
test_edconfig.py
test_sctmd.py
......
然后做一个构建脚本,在其中首先设置 PYTHONPATH,并调用 setup.py build --build-base=build/,并进入 build/ 目录自动运行所有的测试即可。例如:
#!/bin/sh
cd /opt/automated/
svn co http://crablfs.svn.sourceforge.net/svnroot/crablfs ulfs/
cd ulfs/caxes/
python setup.py build --build-base=build/
cd build/
export PYTHONPATH=`pwd`/lib
python test/test_ctemplates.py
python test/test_edconfig.py
python test/test_sctmd.py
...
当然应该能够写的更好?不过我不知道有没有 Python 下对应的工具?

另一个问题是如果将定时构建脚本的输出重定向到邮件、短信或信号灯,这应该属于监控的问题了。

另外,书中写到在安装和部署时使用诊断测试排除故障的技巧是比较有价值。

星期三, 十月 31, 2007

Linux 内存寻址 1GB(896MB) 限制问题

《Understanding the LINUX KERNEL》(《深入理解LINUX内核》)一书,P51 提到:
In theory, up to 4GB of RAM could be installed on such systems; in practice, due to the linear address space requirements of User Mode processes, the kernel cannot directly address more than 1GB of RAM, as we will see in the later secion "Paging in Linux."


然后,在 P70 中(Paging in Linux -> Kernel Page Tables)中首先说明的是"Final kernel Page Table when RAM size is less than 896MB"。这个 896MB 根据后面的说明,是 1GB - 128MB = 896MB,128MB 有别的用处。但这个 1GB 是怎么来的呢?

参考 P47 关于 "Regular Paging" 的说明,可以看到,实际上每个进程(Process)都有它自己的 Linear Address 空间,默认会分配一个 Page Directory 和 Page Table(因此最小内存占用量为 8KB),而在 "Paging in Linux" 中讲到,系统被分为 User Mode 和 Kernel Mode,如果将 kernel 看作一个进程(init),那么系统最多为它预留的内存只能是 1GB,否则它将不得不使用 User Mode 的内存作为内核之用。因为 User Mode 无法获得直接获得 Kernel Mode 的内容,而 Kernel Mode 则可以从 User Mode 中存取数据,所以以最通常的情况 4GB 最大寻址空间为例,则 3GB 作为 User Mode 使用,1GB 给 Kernel Mode 使用,而 Kernel Mode 的线性地址空间为:0xc0000000 到 0xffffffff。

这个 4GB 的最大寻址空间是指 32 位使用最简单的线性地址表示方法时可以映射的最大寻址空间,也就是只有一个 Page Directory 和 1024 个 Page Table 的情况,此时是一个两级的目录状态。为了支持 Intel 处理器的 PAE(Physical Address Extension)功能以支持超过 4GB 的物理内存,Linux 可以在 PD(称为 Page Gloabl Directory, PGD) 和 PT 之间增加 Page Upper Directory 和 Page Middle Directory,显然这增加了目录级数,也就意味着增加了寻址时间。所以如果不使用那么大的内存,Linux 会将 PUD 和 PMD 的长度设定为 0 并直接映射为 PGD 的一个条目。

但这个 Kernel Mode 和 Low Memory/High Memory 有联系吗?

"Permission Denied" when load php module (SELinux)

Cannot load /usr/local/apache2/modules/libphp4.so into server: /usr/local/apache2/modules/libphp4.so : cannot restore segment prot after reloc: Permission Denied
这个错误是因为打开了 RedHat 的 SELinux,关闭就可以了。

另外,在编译 php 时使用了 --enable-gd-native-ttf 和 --with-gd=/usr/local 参数,待同样报告类似的错误:
/usr/local/lib/libgd.so.2: cannot restore segment prot after reloc: Permission Denied
,同样也是 SELinux 造成的。

星期六, 十月 27, 2007

"Progmatic Unit Testing", 心得和自省

昨天花了一天时间,把《Progmatic Unit Testing》这本书基本上过了一遍。写的很不错,结合之前做项目时写单元测试的经验,有一些心得,也必须做一些反省。

最主要的一个方面是关于测试代码本身的质量。测试代码应该与产品代码有同样的质量,因此要遵循 DRY 和正交性、低耦合的设计原则,而这一点在我之前的测试中做的很不好,以 Python Tree 来说,本来我想测试应该保证逻辑上的尽可能简单,因此为了保证测试覆盖面足够,结果包含了很多重复的语句,尤其是有时侯需要对一个变量(Tree Node)的几个方面做检查的时候,这些检查语句都要反复写,这就很不好。

在书中提到,最好从 TestCase 继承一个类,然后所有的其他所有的测试类都从这个继承基类再继承,这样可以在这个基类里面做 setUp() 和 tearDown(),并且可以自定义 assert/fail 函数。例如,对 Python Tree,我大可以这样定义:
class TestTree(unittest.TestCase):
def assertValidTreeNode(node, value):
self.failUnlessEqual(node(), value)
...

class TestSetAttr(TestTree):
def testNotExisted():
self.root.branch = 1
self.assertValidTreeNode(self.root.branch, 1)
...
在 cutils 的 mirrord/fs_mirror 项目中也存在这个问题。这样导致我在单元测试上花费了太多的时间,特别是如果对产品代码做出改动,在单元测试中就需要改很多地方,也就是说,复用性不好!不够专业。

另一个重要的问题是”独立性“不好。这一点在做 cutils 的 mirrord/fs_mirror 的时候尤其明显。一个方面是对于环境的依赖,在 mirrord/fs_mirror 中,因为并发非常重要,所以在 test_mirrord 中需要测试这种不同的并发情况会产生的不同的结果,之前的做法就是调度一个实际的实例,然后进行一些 sleep/wait 来等待并发的状态变化。但因为并发状态会如何变化是不受控制的,在不同的主机上结果也可能完全不同,所以只能等的更久来保证状态一定会变化(实际上有时侯也难以完全保证),结果就是运行的时间很长。另外,这也导致了在编写的时候更难保持 DRY 和正交性、低耦合的原则,对进度很不利。

我当时还在找多线程/并发的单元测试方法,好像对于 Java 还有专门的这样的软件。但现在看来,其实并不需要,只要利用 Mock 对象,模拟出相同的接口,然后在里面可控的设置并发状态,这个问题应该很好解决。

在 caxes Tree 的顺序问题也反映了独立性不够,主要是必须保证以前的节点不会因为后面的操作而受到影响,之前的做法就是逐一检查,当然也就导致了重复,而且后面的操作受前面的影响,没有前面的操作,后面就无从谈起,但完全可以利用 fixture 做多个 TestSuite,每次使用 fixture 和 test case 的 setUp() 重建就好了,然后利用 fixture 和 test suites 重新调用前面的测试就可以了。

在 test_mirrord 也有顺序问题,因为并发状态不同,可能结果不同,那么测试 server thread 的时候和测试 monitor 的时候结果可能不同!我之前的做法显然是错误的,只是因为想不到好的办法,就将前面测试 monitor 的结果记录到文件中,在 测试 server thread 的时候调出来比较,这显然不正确,只不过一般机器的运行调度结果在一般情况下会一样,所以基本上不会出现 fail 而已。

关于测试的“彻底性”和"自动化"方面,应该做得还可以,不过因为复用性不好,比较烦琐。当然,书中提到的对测试覆盖和边界条件的检查的原则还是相当有价值的,我之前也很难说做的很好。

另外,使用数据文件的技巧也很有意思。

要重写了! '')