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"
How can I simulate Bash completion programmatically to check the completion values inside a testsuite for my tool?
bonsaiviking's solution almost worked for me. I had to change the bash string script. I added an extra ';' separator to the executed bash script otherwise the execution wouldn't work on Mac OS X. Not really sure why.
I also generalized the initialization of the various COMP_ arguments a bit to handle the various cases I ended up with.
The final solution is a helper class to test bash completion from python so that the above test would be written as:
The completion lib is located under https://github.com/lacostej/unity3d-bash-completion/blob/master/lib/completion.py
Say you have a bash-completion script in a file called
asdf-completion
, containing:This uses the shell function
_asdf
to provide completions for the fictionalasdf
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 theCOMPREPLY
variable. Here's an example of doing that in a unittest:This should work for any completions that use
-F
, but may work for others as well.je4d's comment to use
expect
is a good one for a more complete test.