2015-12-27 162 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非常感谢! –