python中的單元測試pyUnit


python中的單元測試pyUnit
 
在Python中進行單元測試時需要用到PyUnit模塊,Python 2.1及其以后的版本都將PyUnit作為一個標准模塊,但如果你使用的是較老版本的Python,那就要自已動手安裝了。在PyUnit的網站(http://sourceforge.net/projects/pyunit)上可以下載到PyUnit最新的源碼包,此處使用的是pyunit-1.4.1.tar.gz。
PyUnit跟Junit很相似,甚至連一些基本的函數名都一樣。例如測試類必須是TestCase的子類,且初始函數為setUp(self), 清理函數tearDown(self)。
 
將被測試的文件:widget.py
# 將要被測試的類
class Widget:
    def __init__(self, size = (40, 40)):
        self._size = size
    def getSize(self):
        return self._size
    def resize(self, width, height):
        if width < 0  or height < 0:
            raise ValueError, "illegal size"
        self._size = (width, height)
    def dispose(self):
        pass

測試文件:widgetTest.py

# 執行測試的類
from widget import Widget
import unittest
class WidgetTestCase(unittest.TestCase):
    def setUp(self):
        self.widget = Widget()
    def tearDown(self):
        self.widget.dispose()
        self.widget = None
    def testSize(self):
        self.assertEqual(self.widget.getSize(), (40, 40))
    def testResize(self):
        self.widget.resize(100, 100) 
        self.assertEqual(self.widget.getSize(), (100, 100)) 
    
# 測試
if __name__ == "__main__":
    # 構造測試集
    suite = unittest.TestSuite()
    suite.addTest(WidgetTestCase("testSize"))
    suite.addTest(WidgetTestCase("testResize"))
    # 執行測試
    runner = unittest.TextTestRunner()
    runner.run(suite)
    


執行測試代碼,測試完的結果:

C:\App\py_test\test>python diwgetTest.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

C:\App\py_test\test>


可以分幾步進行, 首先我們的測試類要繼承於unittest.TestCase. 如果采用動態測試的方法可以為每個需要測試的方法編寫測試方法,使用assertEqual( , ). 然后把我們的測試都放到unittest.TestSuite()容器中,最后使用 unittest.TextTestRunner().run(suite)方法自動測試。

參考:
http://www.ibm.com/developerworks/cn/linux/l-pyunit/index.html
http://www.cnblogs.com/ysisl/archive/2009/08/17/1548054.html 

================================================================================

python 單元測試 使用摘要
主要步驟:
1。編寫完備的單元測試用例
2。根據測試用例測試點編寫程序
3。每編寫完一個功能,執行測試用例,然后修改代碼,直到該點涉及用例全部通過
4。所有用例通過測試,停止編碼
5。發現新bug和開發新版本時,及時更新測試用例


編寫用例

使用方法
    python自帶unittest模塊,編寫的測試用例類繼承unittest.TestCase類,所有測試函數以test開頭,執行時,執行unittest.main(),所有測試類中以test開頭的函數自動執行
    保存文件:testproject.py,簡單例子如下:

import unittest
#import testproject
class mytestproject1(unittest.TestCase):
    def testcase1(self):
        #等於運算
        self.assertEquals(7/2,3)
    def testcase2(self):
        #等於運算
        self.assertEquals("".join(['a','b','c']),"abc")
            
class mytestproject2(unittest.TestCase):
    def testException(self):
        #出現異常
        self.assertRaises(ZeroDivisionError,lambda x:3/x,0)
    
    def testcase2(self):
        #不等於運算
        self.assertNotEqual("".join(['a','b','c']),"abcd")
                
if __name__ == '__main__':
    unittest.main()


執行后,會報告每個函數執行情況

測試用例的編寫
1。針對性
        每個用例,即test函數,必須只解決一個問題,這樣定位問題會很簡單
2。獨立性
        每個用例之間沒有影響,一個的輸出不會影響到另外一個的執行
3。完備性
        每個用例所挑選的例子應該有代表性,盡可能增加覆蓋度
4。順序
        對於每個功能點來說,可能涉及到不同的方面,這些用例最好用一個類組織起來,並按照一定的邏輯順序排列,這個對開發是有指導作用的
        
從測試對象來講,測試用例應該具備以下條件:
1。功能性用例
        做什么的問題
2。反面用例
        不能做什么的問題,對處理對象的限定
3。適應性,健壯性用例
        其他的輸入,達到安全性,可知性
        
unittest的接口:
主要用到unittest.TestCase中的接口,基本的是equal系列和raises系列。具體格式參見 help('unittest')

具體的assert的使用,可參看:python assert使用說明

unittest幫助文檔,可參看:unittest文檔翻譯 

=============================================================

Why unit test?

  • You're already doing it!

Speaker's notes:

You're probably already doing at least ad hoc testing at the interactive prompt. Why not get the most mileage out of that effort? Imagine if every little test that you already perform during development were somehow kept and could be rerun easily.

  • Testing helps you find errors in your code.

Speaker's notes:

Of course, you only find errors if you have written a test that exercises the particular functionality that's broken, but once you start writing unit tests, you may be surprised by how many errors you find. As you write test cases, you'll think, "Gee, I wonder whether I handle this case correctly," or, "Hm. I don't think that I handle this error correctly." When you're using a testing framework, you can simply add more test cases. The ease of adding new tests and running them encourages more thorough testing. Try it for a week, and you'll see what I mean. Many developers who have gotten in the habit of unit testing find programming without writing unit tests to be difficult and somewhat frightening. Programming is to driving like unit tests are to seat belts.

  • Testing helps you write better code.

Speaker's notes:

In addition to finding errors in your code, unit testing can help you during the initial development of your class or module's public interface. Unit tests force you to think about how another developer will want to use your code while you're writing that code. This shift in focus can help you present a smaller, cleaner interface to your classes and modules. This benefit is most often associated with test-driven development.

  • Writing test cases will save you time later.

Speaker's notes:

Imagine that you don't write test cases in code. You finish some module, and you start testing it at the interactive prompt. You realize that there's a tricky case your code doesn't handle correctly. A quick test reveals that you're right. You fix the module and move on. Later, you decide to rework the implementation of your module. Are you sure you didn't forget that tricky case? Can the new code handle it? If you had written test cases, you could just rerun the same set of tests (as long as the interface didn't change). As an added bonus, you can run your tests often so that you may find a bug after you've only written a few dozen lines of code. If a test suddenly fails, you know that it was introduced in the little bit of code you just changed. Not only is it easier to detect when you've introduced an error, but it is also easier to find the code that causes the error, reducing the time spent debugging.

  • Unit tests provide immediate feedback on your code.

Speaker's notes:

When you're writing code deep in a library or in a server side module for a user interface, a unit test gives you feedback as you work. You don't have to wait until after code in a separate part of the application is written before you can test and know whether your code works. Those little "throw-away" programs you may be writing to test your code become reusable unit tests attached to a consistent testing framework.

  • Test cases document intent.

Speaker's notes:

Test cases provide minimal documentation about what you think your code should do. Tests don't necessarily explain why your code should behave the way shown, but they can explain how it should behave. In fact, some developers write their tests before they write their code. The tests define how the unit should behave. In this case, tests always fail at first. The programmer writes code until all of the tests are passing again. This style of programming called test-first programming or test-driven programming. Test-driven development also ensures that you have unit tests for all of your code since all of the code was developed to satisfy a test.

 

Why unit test?

  • You're already doing it!

Speaker's notes:

You're probably already doing at least ad hoc testing at the interactive prompt. Why not get the most mileage out of that effort? Imagine if every little test that you already perform during development were somehow kept and could be rerun easily.

  • Testing helps you find errors in your code.

Speaker's notes:

Of course, you only find errors if you have written a test that exercises the particular functionality that's broken, but once you start writing unit tests, you may be surprised by how many errors you find. As you write test cases, you'll think, "Gee, I wonder whether I handle this case correctly," or, "Hm. I don't think that I handle this error correctly." When you're using a testing framework, you can simply add more test cases. The ease of adding new tests and running them encourages more thorough testing. Try it for a week, and you'll see what I mean. Many developers who have gotten in the habit of unit testing find programming without writing unit tests to be difficult and somewhat frightening. Programming is to driving like unit tests are to seat belts.

  • Testing helps you write better code.

Speaker's notes:

In addition to finding errors in your code, unit testing can help you during the initial development of your class or module's public interface. Unit tests force you to think about how another developer will want to use your code while you're writing that code. This shift in focus can help you present a smaller, cleaner interface to your classes and modules. This benefit is most often associated with test-driven development.

  • Writing test cases will save you time later.

Speaker's notes:

Imagine that you don't write test cases in code. You finish some module, and you start testing it at the interactive prompt. You realize that there's a tricky case your code doesn't handle correctly. A quick test reveals that you're right. You fix the module and move on. Later, you decide to rework the implementation of your module. Are you sure you didn't forget that tricky case? Can the new code handle it? If you had written test cases, you could just rerun the same set of tests (as long as the interface didn't change). As an added bonus, you can run your tests often so that you may find a bug after you've only written a few dozen lines of code. If a test suddenly fails, you know that it was introduced in the little bit of code you just changed. Not only is it easier to detect when you've introduced an error, but it is also easier to find the code that causes the error, reducing the time spent debugging.

  • Unit tests provide immediate feedback on your code.

Speaker's notes:

When you're writing code deep in a library or in a server side module for a user interface, a unit test gives you feedback as you work. You don't have to wait until after code in a separate part of the application is written before you can test and know whether your code works. Those little "throw-away" programs you may be writing to test your code become reusable unit tests attached to a consistent testing framework.

  • Test cases document intent.

Speaker's notes:

Test cases provide minimal documentation about what you think your code should do. Tests don't necessarily explain why your code should behave the way shown, but they can explain how it should behave. In fact, some developers write their tests before they write their code. The tests define how the unit should behave. In this case, tests always fail at first. The programmer writes code until all of the tests are passing again. This style of programming called test-first programming or test-driven programming. Test-driven development also ensures that you have unit tests for all of your code since all of the code was developed to satisfy a test.

Why unit test? (cont'd)

  • Test cases provide a sample use of your code. That is, programmers who want to use your code can read your unit tests to see how you expect client code to use it.

Speaker's notes:

If you are distributing Free Software or Open Source code, you can ship your unit tests to show others how to use your classes and modules. Even with code written for "internal use," unit tests provide simple examples of how you expect clients to interact with a unit. That way, you may be able to avoid writing separate sample programs for other programmers who need to use your code. They can just read the unit tests.

  • In a very dynamic language like Python, unit tests provide added safety. Unit tests make up for some of the compile time checks that you lose.

Speaker's notes:

For those who have never programmed in a less dynamic language, such as C++ or Java, you may not realize how important some developers feel compile-time checks are. In these languages, code is written to push as much error detection as possible to compile time so that errors won't be discovered by QA or customers at run time. In the absence of compile time checks, thorough unit testing is even more important because it can catch many simple bugs (NameErrors and such) that may only be detectable at runtime in Python.

We need a unit testing framework!

  • Testing without a framework is difficult to reproduce

Speaker's notes:

Testing without a framework is often ad hoc. The tests may not be expressed in code at all. If they are, they are often not written in a way that they can be run again in the future. If they are, the way they are written and reproduced may be different for each unit. If they are consistent, then congratulations, you've written your own framework. :-)

  • Reproducible tests that don't use a standard framework may be more difficult for other developers to understand.

Speaker's notes:

For example, the unittest (PyUnit) module implements a unit testing framework that is already implemented and used in many other programming languages. Even if a developer hasn't used the Python version of this framework, he may be familiar with it from another programming language.

  • A unit testing framework provides
    • A mechanism to organize and group multiple tests
    • A simple way to invoke tests
    • Clear indication of which tests passed/failed
    • A standard way to write tests and specify expected results.

Speaker's notes:

Of course, we still have to write the test code and specify the expected results. Even with a framework, that task can be challenging. Thus, you probably don't want to combine the challenge of writing tests with the difficulty of creating your own testing framework.

 

出處:http://www.cnblogs.com/dkblog/archive/2011/07/10/2102610.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM