Python測試函數和類 笨方法學習Python

1. 測試類python

笨方法學習Python中ex47中,按照書中的代碼進行測試,總是出現下述錯誤:app

Traceback (most recent call last):
  File "C:\Users\zqm\Desktop\ex47\tests\ex47_test.py", line 3, in <module>
    from game import Room
ImportError: No module named game函數

追蹤緣由就是 game.py路徑未加到python搜索路徑中學習

3 import nose
4 import sys
5 sys.path.append("../ex47")
測試

32 if __name__ == "__main__"
33     nose.runmodule()
spa

因此對代碼進行了修改。ex47的文檔結構以下:ex47/ex47/game.py   ex47/tests/test_game.pycode

測試對象game.py 代碼以下 對象

1 class Room(object):
2     def __init__(self, name, description):
3         self.name = name
4         self.description = description
5         self.paths = {}
6     def go(self, direction):
7         return self.paths.get(direction, None)
8     def add_paths(self, paths):
9         self.paths.update(paths)

測試函數test_game.py代碼以下blog

 1 from nose.tools import *
 2 
 3 import nose
 4 import sys
 5 sys.path.append("../ex47")
 6 
 7 from game import Room
 8 
 9 def test_room():
10     gold = Room("GoldRoom", """This room has gold in it you can grab. There's a
11             door to the north.""")
12     assert_equal(gold.name, "GoldRoom")
13     assert_equal(gold.paths, {})
14 def test_room_paths():
15     center = Room("Center", "Test room in the center.")
16     north = Room("North", "Test room in the north.")
17     south = Room("South", "Test room in the south.")
18     center.add_paths({'north': north, 'south': south})
19     assert_equal(center.go('north'), north)
20     assert_equal(center.go('south'), south)
21 def test_map():
22     start = Room("Start", "You can go west and down a hole.")
23     west = Room("Trees", "There are trees here, you can go east.")
24     down = Room("Dungeon", "It's dark down here, you can go up.")
25     start.add_paths({'west': west, 'down': down})
26     west.add_paths({'east': start})
27     down.add_paths({'up': start})
28     assert_equal(start.go('west'), west)
29     assert_equal(start.go('west').go('east'), start)
30     assert_equal(start.go('down').go('up'), start)
31 
32 if __name__ == "__main__":  
33     nose.runmodule() 


2.測試函數ip

測試對象temperature.py

1 def to_celsius (t):
2     return round ( (t-32.0)*5.0/9.0 )
3 
4 def above_freezing (t):
5     return t>0


測試函數test_temperature.py

 1 import nose  
 2 from temperature import to_celsius  
 3 from temperature import above_freezing  
 4   
 5 def test_above_freezing ():  
 6     '''''Test above_freezing '''  
 7     assert above_freezing(89.4), 'A temperature above freezing'  
 8     assert not above_freezing(-42), 'A temperature below freezing'  
 9     assert not above_freezing(0), 'A temperature at freezing'  
10   
11 def test_boiling ():  
12     '''''Test boiling point'''  
13     assert to_celsius(212) == 100 
14   
15 def test_roundoff ():  
16     '''''Test that roundoff works'''  
17     assert to_celsius(100) == 38, 'Returning an unrounded result'   #not 37.77...   
18   
19 if __name__ == "__main__":  
20     nose.runmodule()  
相關文章
相關標籤/搜索