Question

I need to extend a python code which has plenty of hard coded path
In order not to mess everything, I want to create unit-tests for the code before my modifications: it will serve as non-regression tests with my new code (that will not have hard-coded paths)

But because of hard coded system path, I shall run my test inside a chroot tree (I don't want to pollute my system dir)
My problem is that I want to set up the chroot only for test, and this can be done with os.chroot only with root privileges (and I don't want to run the test scripts as root)

In fact, I just need a fake tree diretory so that when the code that open('/etc/resolv.conf) retrieves a fake resolv.conf and not my system one

I obviously don't want to replace myself the hard coded path in the code because it would not be real regression test

Do you have any idea how to achieve this?

Thanks

Note that all the path accessed are readable with a user accout

Was it helpful?

Solution

In your test set-up you could override the built-in open in the module that you are testing with your own version that reads from your "fake" directory structure:

import mymod
import os.path

def chroot_open(filename,*args):
    filename = os.path.join("/home/you/fakeroot",filename)
    return open(filename,*args)

mymod.open = chroot_open

OTHER TIPS

You could use a helper application that is setuid root to run the chroot; that would avoid the need to run the tests as root. Of course, that would probably still open up a local root exploit, so should only be done with appropriate precautions (e.g. in a VM image).

At any rate, any solution with chroot is inherently platform-dependent, so it's rather awkward. I actually like the idea of Dave Webb (override open) better, I must admit...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top