V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
xiuc001
V2EX  ›  问与答

用 python 写了一个调用系统命令的方法,怎么使用 unittest 测试这个方法

  •  
  •   xiuc001 · 2016-12-27 17:40:46 +08:00 · 1706 次点击
    这是一个创建于 2648 天前的主题,其中的信息可能已经有所发展或是发生改变。
        def move_file(self, source, dest, sync=True):
            """
            move file from source to dest
            :param source:
            :param dest:
            :param sync:    if sync=Ture, block util move command is over
            :return:
            """
            if os.path.exists(dest):
                os.remove(dest)
            if sync:
                command = 'mv ' + source + ' ' + dest
                self.__sync_exec_command(command)
            else:
                shutil.move(source, dest)
                
    

    比如以上这个方法,我想用 unittest 对他进行测试,需要怎么做呢?

    4 条回复    2016-12-28 17:30:37 +08:00
    xiuc001
        1
    xiuc001  
    OP
       2016-12-27 17:48:30 +08:00
    ```
    def test_move_file(self):
    supervisord = DummySupervisor()
    interface = self.makeOne(supervisord)

    curdir = os.path.abspath(os.curdir)
    os.system('touch ' + curdir + '/test.log')
    interface.move_file(curdir + '/test.log', curdir + '/test1.log')
    self.assertEqual(True, os.path.exists(curdir + '/test1.log'))
    ```

    我现在是这么测试的,不知道符不符合规范
    zjuhwc
        2
    zjuhwc  
       2016-12-28 00:19:31 +08:00 via iPhone   ❤️ 1
    1. 测试文件可以用临时目录, python 应该有个方法可以判断系统临时目录,搜下
    2. unittest 有 assertTrue 方法,不需要 assertEqual
    3. 如果要测多个场景,可以用单元测试的 setup 函数做初始化,还有个对应的函数做数据清理(比如删掉你生成的临时文件),避免副作用
    4. 直接使用 os.system ,字符串拼接命令有风险,可以用 subprocess : https://docs.python.org/2/library/subprocess.html
    fzleee
        3
    fzleee  
       2016-12-28 08:34:56 +08:00 via iPhone
    试试 mock
    xiuc001
        4
    xiuc001  
    OP
       2016-12-28 17:30:37 +08:00
    @zjuhwc 谢谢,我这边没有使用 os.system,我拼好命令使用 subprocess 来执行的,是不是用 os.system 的话可能会拼接多个命令,导致安全问题?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1799 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 16:29 · PVG 00:29 · LAX 09:29 · JFK 12:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.