2015-12-27 214 views
1

我是新來的Python測試我試圖讓我的頭一輪的嘲弄嘲弄內地理位置對象。我是一個從地理位置對象獲取地址緯度和經度的類,我之前在類中設置了這個地理對象。我試圖嘲笑這個地理定位對象及其方法來測試它。這裏是我的課:的Python - 單元測試類

from geopy.geocoders import Nominatim 
from geopy.exc import GeocoderTimedOut 

class GeolocationFinder(): 
    def __init__(self): 
     self.location_cache = {} 
     self.geolocator = Nominatim() 
     self.geolocation = None 

    def get_location(self, location): 
     if location is None: 
      return None, None, None 
     elif location in self.location_cache: 
      # Check cache for location 
      self.set_geolocation_from_cache(location) 
      address, latitude, longitude = self.get_addr_lat_long 
      return address, latitude, longitude 
     else: 
      # Location not cached so fetch from geolocator 
      self.set_geolocation_from_geolocator(location) 
      if self.geolocation is not None: 
       address, latitude, longitude = self.get_addr_lat_long() 
       return address, latitude, longitude 
      return 'None', 'None', 'None' 

    def set_geolocation_from_cache(self, location): 
     self.geolocation = self.location_cache[location] 

    def set_geolocation_from_geolocator(self, location): 
     try: 
      self.geolocation = self.geolocator.geocode(location, timeout=None) 
      if self.geolocation is not None: 
       self.location_cache[location] = self.geolocation 
       return self.geolocation 
     except GeocoderTimedOut as e: 
      print('error Geolocator timed out') 
      self.geolocation = None 

    def get_addr_lat_long(self): 
     address = self.geolocation.address 
     latitude = self.geolocation.latitude 
     longitude = self.geolocation.longitude 
     self.geolocation = None 
     return address, latitude, longitude 

我在測試__get_addr_lat_long的函數,它將做出了嘗試需要我嘲笑一個地理位置的類:

class GeolocationFinderTests(unittest.TestCase): 
    def setUp(self): 
     self.test_geolocation_finder = GeolocationFinder() 
     attrs = {'address.return_value': 'test_address', 'latitude.return_value': '0000', 'longitude.return_value': '0000'} 
     self.mock_geolocation = Mock(**attrs) 
     self.test_geolocation_finder.geolocation = self.mock_geolocation 

    def test_get_addr_lat_long(self): 
     address, lat, long = self.test_geolocation_finder.get_addr_lat_long() 

     self.assertEqual(address, 'test_address') 

if __name__ == '__main__': 
    unittest.main() 

這個測試結果失敗: Asse田:模擬名稱= 'mock.address' ID = '140481378030816'= 'test_address'

任何幫助將不勝感激!

回答

0

return_value用於可調用例如如果你在嘲笑對象方法。對於對象屬性,您只需使用名稱,在這種情況下:

attrs = {'address': 'test_address', 'latitude': '0000', 'longitude': '0000'} 
+1

非常感謝!發揮了魅力。 @John Keyes非常感謝! –