如何mock Paramiko的SFTP文件属性以编写单元测试?
解决方案
你只需要构造一个带st_mtime属性的Mock对象即可,不需要完整模拟整个SFTPClient的文件对象,因为你的函数逻辑仅用到了这个属性。
依赖说明
直接使用Python标准库自带的unittest.mock就能实现,不需要安装额外第三方依赖。
完整单元测试示例
import unittest from datetime import datetime as dt from unittest.mock import Mock # 请将下方导入替换为你自己的模块路径 from your_module import is_recently_modified_file_sftp class TestSFTPModifiedTimeCheck(unittest.TestCase): def test_modified_time_later_than_threshold_return_true(self): # 设定对比阈值时间为2024-01-01 00:00:00 threshold_time = dt(2024, 1, 1) # 模拟SFTP文件对象,仅需给st_mtime赋值对应时间戳即可 # 此处赋值为2024-01-02 00:00:00对应的时间戳 mock_sftp_file = Mock() mock_sftp_file.st_mtime = 1704124800 result = is_recently_modified_file_sftp(mock_sftp_file, threshold_time) self.assertTrue(result) def test_modified_time_earlier_than_threshold_return_false(self): threshold_time = dt(2024, 1, 1) # 赋值为2023-12-31 00:00:00对应的时间戳 mock_sftp_file = Mock() mock_sftp_file.st_mtime = 1703952000 result = is_recently_modified_file_sftp(mock_sftp_file, threshold_time) self.assertFalse(result) def test_modified_time_equal_to_threshold_return_true(self): # 边界场景:修改时间和阈值完全相等 threshold_time = dt(2024, 1, 1) # 赋值为2024-01-01 00:00:00对应的时间戳 mock_sftp_file = Mock() mock_sftp_file.st_mtime = 1704038400 result = is_recently_modified_file_sftp(mock_sftp_file, threshold_time) self.assertTrue(result) if __name__ == '__main__': unittest.main()
补充说明
因为你的函数没有用到SFTP文件对象的其他方法或属性,所以无需引入Paramiko相关的复杂Mock逻辑,也不需要真实建立SFTP连接,仅需模拟用到的st_mtime属性就能完成所有场景的测试。上面的用例已经覆盖了早于、等于、晚于阈值的三种核心情况,覆盖所有边界逻辑。
内容的提问来源于stack exchange,提问作者banana_99
相关产品推荐
相关产品推荐

