Create a context manager for changing current working directory
Hello,
I have a use-case which doesn't quite work in testinfra as it stands.
host.run() on a local host eventually calls subprocess.run(). That's great, but I noticed it doesn't pass **kwargs. The fix is trivial, but I've no idea:
- if this implementation of the fix is acceptable
- what it breaks outside my use case.
I added a test, which fails in docker (see below). I haven't started digging in yet because I thought I'd check first if this whole idea was a non-starter?
test/test_modules.py::test_command_execution_in_chdir[docker://debian_stretch]
[gw1] [ 93%] FAILED test/test_modules.py::test_command_execution_in_chdir[docker://debian_stretch]
def test_command_execution_in_chdir(host):
> assert host.run("pwd", cwd='/tmp').stdout.strip() == '/tmp'
E AssertionError: assert '/' == '/tmp'
E - /
E + /tmp
Hi, thanks for contributing !
I'm not sure all arguments of subprocess are useful here, but cwd definitively is. But the way you've implemented it only works with "local" backend. What about adding a new context manager cwd for this, which could enable it for all modules ? For instance:
with host.cwd('/opt/local/app'):
assert host.file('./myapp').mode == 755
assert host.run('./myapp --version') == '1.2.3'
Under the hood, all remote commands would change directory before running the command.
I think this code will be similar to host.sudo() context manager.
What do you think ?
@philpep
That sounds reasonable. I'll change the title to reflect that and take a look at an implementation.
This is the file you're suggesting as a model, yes? testinfra/modules/sudo.py