我正在尝试为一个函数编写单元测试,该函数将FTP会话作为输入参数以及一些其他参数。这是功能:
def get_listing_photos_ftp(session, source_system_id, mls_system, mls_num, photo_type, max_photos, skip_first=False,
photo_file_name=None):
"""Get Photo from FTP
session_type = 'FTP' (TREB_DLA)
Refer to info on FTP photo file names here: http://trebdata.trebnet.com/photos.htm
"""
del source_system_id, mls_system, photo_type, skip_first
photos = []
for photo_num in range(1, max_photos):
filename = photo_file_name(photo_num, mls_num)
try:
"""Gets a file (StringIO binary file contents object) from the FTP server. Will raise error if
file not found.
"""
photo = session.get_file(filename)
except socket.error as e:
raise Exception("FTP server socket error. Error details: " + str(e))
# Append photo tuple (filename.extension, photo content) - photo may be None if listing has less than 21
if photo is not None:
photos.append(photo_tuple(photo_num, photo.getvalue()))
return photos
我尝试模拟所有可以返回指定值进行测试的函数调用。有人可以指导我更好的计划来解决这种模拟测试。
def test_get_listing_photos_ftp():
filename = Mock(return_value='\mlsphotos\2\478\N4054478_2.jpg')
session = Mock(return_value='<common.ftp.FTP object at 0x112092150>')
#throws an error as I am calling 'session' is a string
session.get_file = Mock(return_value='00100001 01010000 10101011 10001011 11010111 11001101')
getvalue = Mock(return_value='asdsadadsdadasd')
assert photos_helper.get_listing_photos_ftp('session', 'N4067078', 'treb', 'N4067078', 'jpg', 4, False, filename) == []
答案 0 :(得分:0)
这里模拟FTP会话的一个例子如下:
def test_get_listing():
content = 'First line.\n'
output = StringIO.StringIO()
output.write(content)
session = Mock()
session.get_file = Mock(return_value=output)
def photo_file_name(x, y):
return "123.jpg"
result = get_listing_photos_ftp(session, None, None, 2, None, 3, photo_file_name=photo_file_name)
assert result == [(1, content), (2, content)]
看看Mock()对象以及它如何具有我们希望生成session.get_file()方法调用的return_value。以类似的方式,您可以测试其他方案,例如返回值为无等等。