Bash完成脚本的单元测试 [英] Unit Test for Bash completion script

查看:46
本文介绍了Bash完成脚本的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为一个(相当复杂的)Bash完成脚本编写一个单元测试,最好使用Python-只是可以通过编程获取Bash完成值的东西.测试应如下所示:

I would like to write a Unit Test for a (rather complex) Bash completion script, preferrably with Python - just something that gets the values of a Bash completion programmatically. The test should look like this:

def test_completion():
  # trigger_completion should return what a user should get on triggering 
  # Bash completion like this: 'pbt createkvm<TAB>' 
  assert trigger_completion('pbt createkvm') == "module1 module2 module3" 

如何通过编程方式模拟Bash完成以检查工具的测试套件中的完成值?

How can I simulate Bash completion programmatically to check the completion values inside a testsuite for my tool?

推荐答案

假设您在名为 asdf-completion 的文件中有一个bash补全脚本,其中包含:

Say you have a bash-completion script in a file called asdf-completion, containing:

_asdf() {
COMPREPLY=()
local cur prev
cur=$(_get_cword)
COMPREPLY=( $( compgen -W "one two three four five six" -- "$cur") )
return 0
}    
complete -F _asdf asdf

这使用外壳函数 _asdf 提供虚构的 asdf 命令的完成内容.如果我们设置了正确的环境变量(来自bash手册页),那么我们可以获得相同的结果,即将潜在扩展放置到 COMPREPLY 变量中.这是在单元测试中执行此操作的示例:

This uses the shell function _asdf to provide completions for the fictional asdf command. If we set the right environment variables (from the bash man page), then we can get the same result, which is the placement of the potential expansions into the COMPREPLY variable. Here's an example of doing that in a unittest:

import subprocess
import unittest

class BashTestCase(unittest.TestCase):
    def test_complete(self):
        completion_file="asdf-completion"
        partial_word="f"
        cmd=["asdf", "other", "arguments", partial_word]
        cmdline = ' '.join(cmd)

        out = subprocess.Popen(['bash', '-i', '-c',
            r'source {compfile}; COMP_LINE="{cmdline}" COMP_WORDS=({cmdline}) COMP_CWORD={cword} COMP_POINT={cmdlen} $(complete -p {cmd} | sed "s/.*-F \\([^ ]*\\) .*/\\1/") && echo ${{COMPREPLY[*]}}'.format(
                compfile=completion_file, cmdline=cmdline, cmdlen=len(cmdline), cmd=cmd[0], cword=cmd.index(partial_word)
                )],
            stdout=subprocess.PIPE)
        stdout, stderr = out.communicate()
        self.assertEqual(stdout, "four five\n")

if (__name__=='__main__'):
    unittest.main()

这适用于使用 -F 的所有补全,但也可能适用于其他补全.

This should work for any completions that use -F, but may work for others as well.

je4d使用 expect 的注释是进行更完整测试的好方法.

je4d's comment to use expect is a good one for a more complete test.

这篇关于Bash完成脚本的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆