xiuc001
V2EX  ›  问与答

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

  •  
  •   xiuc001 · Dec 27, 2016 · 2399 views
    This topic created in 3440 days ago, the information mentioned may be changed or developed.
        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 replies    2016-12-28 17:30:37 +08:00
    xiuc001
        1
    xiuc001  
    OP
       Dec 27, 2016
    ```
    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  
       Dec 28, 2016 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  
       Dec 28, 2016 via iPhone
    试试 mock
    xiuc001
        4
    xiuc001  
    OP
       Dec 28, 2016
    @zjuhwc 谢谢,我这边没有使用 os.system,我拼好命令使用 subprocess 来执行的,是不是用 os.system 的话可能会拼接多个命令,导致安全问题?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2888 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 08:56 · PVG 16:56 · LAX 01:56 · JFK 04:56
    ♥ Do have faith in what you're doing.