2020年9月12日 / 132次阅读 / Last Modified 2021年2月2日
unittest,开源项目
代码写多了,就会有一个感觉,不同项目之间,其实有一些基础功能函数是可以共用的。于是,我把自己的这部分共用函数,做成了common库。
common这个项目很简单,就是把自己在各个不同项目中可以共用的基础函数汇总起来,形成一个独立的项目库,并对每个函数配上单元测试!
$ python3 -m pydoc common
$ python3 test.py test_common_py
我把主流的内部排序函数都写了一遍,所有函数都是线程安全的,可重入的,并且在执行失败时,输入的int array保持原样。这部分函数的单元测试使用Python,用python的unittest框架测试.so中的C函数接口。
$ python3 test.py test_common_c test_sort_c
用python的timeit模块测试各个排序函数的执行时间,使用相同的数据。同时一并将python和numpy的排序函数一并测试了:
$ python3 test_sort_time.py
如下是我在自己的i3电脑上的测试结果:
$ python3 test_sort_time.py
# test sort time (cpu) with same data:
sizeof(int) = 4
sizeof(size_t) = 8
Data1: 200000 integers in random from -500 to 500 (many duplicated)
algo name time(s)
1 count 0.0004098210
2 radix 0.0078493200
3 btree 0.0103174390
4 merge_r 0.0118437550
5 merge 0.0126967190
6 qsort(glibc) 0.0164184000
7 shell 0.0168394210
8 np.sort(numpy) 0.0193520060
9 quick 0.0204938350
10 heapify 0.0206660650
11 shell2 0.0211150230
12 list.sort(python) 0.0245994310
13 sorted(python) 0.0283234870
14 binsert2 1.3200866190
15 binsert 1.3212886200
16 insert2 4.3334431380
17 insert 4.4169052290
18 selects 9.8839823420
19 bubble 57.5378292150
Data2: 200000 integers in random from -2147483648 to 2147483647
algo name time(s)
1 merge_r 0.0149472760
2 merge 0.0154368890
3 quick 0.0170181770
4 qsort(glibc) 0.0188416350
5 shell 0.0199692830
6 heapify 0.0214382860
7 np.sort(numpy) 0.0234466090
8 shell2 0.0247646730
9 radix 0.0257750700
10 btree 0.0553454840
11 list.sort(python) 0.0607240240
12 sorted(python) 0.0658427440
13 binsert2 1.3145383520
14 binsert 1.3212747060
15 insert2 4.3275937470
16 insert 4.3964931220
17 selects 9.8862850800
18 bubble 57.4958768850
19 count E:3
我在这个项目上,已经尽心写了docstring。而且,从这个项目开始使用flake8!因此,tox.ini文件对我而言,也是各项目通用。从这个项目开始,Python与C的混合编程测试,全部用python做单元测试。
单元测试很重要,如下是我对单元测试的一点思考:
Remember:
1, unit test could not kill all bugs, but you will come across more bugs if there is not unit test.
2, unit test is the key to practice TDD and give you confidence of your code.
3, unit test can help you thinking and designing code in a more layered way.
4, If you find the code is hard to do unit test, maybe there is a chance to refactor it.
5, Coding while testing is my best practice, why not keep the test code decently! You will find them useful all the time.
2021年1月9日:V0.06
2020年12月30日:V0.05
2020年11月26日:V0.04
2020年10月25日:V0.03
2020年10月9日:V0.02
2020年9月13日:V0.01
-- EOF --
本文链接:https://www.pynote.net/archives/2481
《common:个人基础函数库》有2条留言
前一篇:python动态导入模块
后一篇:hashlib模块的使用
Ctrl+D 收藏本页
©Copyright 麦新杰 Since 2019 Python笔记
lint + unittest,有助于提升代码质量 [ ]
写单元测试之所以能提高代码质量,是因为如果不是高内聚低耦合的代码,你会发现单元测试非常难写。 比如,你只想测一下方法A,但是发现里面的依赖错综复杂,好吧,都stub掉。最后发现测一个方法写了几十个stub,这种操作我亲眼看到过……。这就是前面提到的「内容耦合」过多了。 所以,能轻松地写出单元测试,并且将其养成一种习惯,你的代码质量必然不会差。 [ ]