如何配置Tox在运行测试命令前source文件?解决InvocationError报错
Got it, let's figure out how to fix this source error in Tox first—here's the root cause: source isn't a standalone executable, it's a built-in command that only works within a shell session. Tox's default way of running commands doesn't launch a shell, so it can't find source at all.
Luckily, you don't have to copy your setup.bash content into tox.ini to make this work. Here are four practical solutions, ordered from simplest to most scalable:
1. Wrap the source + test command in a bash invocation
This is the quickest fix: tell Tox to launch a bash shell and execute both the source command and your test command in one go. The shell will handle the built-in source command, and your tests will run with the environment from setup.bash.
Add this to your tox.ini:
[testenv] commands = bash -c "source ./setup.bash && pytest" # Replace pytest with your actual test command
2. Enable shell mode for the testenv
You can configure Tox to run all commands in a shell session by setting shell = true in your testenv. This lets you use shell built-ins like source directly in the commands list—just make sure to chain source and your test command in a single line (each line runs in a separate shell, so environment variables won't carry over otherwise).
Example tox.ini:
[testenv] shell = true commands = source ./setup.bash && pytest
3. Use a pre-command shell wrapper (if you want separation)
If you prefer to keep the environment setup and test commands visually separate, you can use Tox's commands_pre option—but you still need to wrap the source call in a shell to make it work. Note: This only works if your test command inherits the shell environment, so wrapping both in a single command is still more reliable, but here's how you'd do it with commands_pre:
[testenv] commands_pre = bash -c "source ./setup.bash" commands = bash -c "pytest" # Must also run test in same shell context
4. Create a wrapper script (best for complex setups)
If your setup.bash has a lot of logic, or you want to keep tox.ini clean, create a simple bash script that handles the environment setup and test execution:
- Create a
run_tests.shfile:
#!/bin/bash # Source the setup file first source ./setup.bash # Execute the test command, passing any arguments exec pytest "$@"
- Make the script executable:
chmod +x run_tests.sh
- Update your
tox.inito call the script:
[testenv] commands = ./run_tests.sh
This way, any changes to your environment setup only need to happen in setup.bash or the wrapper script—no edits to tox.ini required.
内容的提问来源于stack exchange,提问作者Cerin

