我正在使用Python创建文件下载程序API。 API将能够使用FTP或SFTP从主机下载文件(我已经为两者实现了单独的类),并且还应该以CSV文件,数据库表或Excel文件的形式跟踪已下载的文件(我已实现为所有人分开的课程。我已经做了一些基本的实现,现在我想对我的所有方法进行单元测试(因为我不想实际从真正的主机上下载文件并保存在我的机器上,但只是想确保它按预期的方式运行工作)。我很难找到一个良好的单元测试起点,特别是单元测试文件处理部分和FTP,SFTP下载器方法。我的完整代码可以在这里找到 https://ghostbin.com/paste/o8jxk
任何帮助或有用的学习资源将不胜感激。
文件读写类的代码
class CSVManager(DownloadManager):
def __init__(self, file_path, csv_file):
self.path = os.path.join(file_path, csv_file)
def register_download(self, file_name):
files = file_name
with open(self.path, "wb") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for file in files:
writer.writerow(file)
def downloaded(self):
downloaded_files = []
with open(self.path, "rb") as csv_file:
reader = csv.reader(csv_file)
for file in reader:
downloaded_files.append(file)
return downloaded_files
答案 0 :(得分:0)
你肯定需要研究{3}这是Python 3+中标准Python库的一部分。 mock对于模拟包括读写内容的文件特别有用,Python文档有很多有用的例子。
即使您使用的是Python 2.7,也可以向后兼容,因此您应该可以使用pip install mock
答案 1 :(得分:0)
我使用测试夹具https://pythonhosted.org/testfixtures/files.html对其进行了测试。这是我的代码:
def test_CSVManager_register_download_and_downloaded_methods(self):
with TempDirectory() as d:
myList = ['test', 'test1', 'test2']
d.write('test.csv', 'test')
csvManager = CSVManager(d.path, 'test.csv')
csvManager.register_download(myList)
print(csvManager.downloaded())
print(d.read('test.csv'))