stefanbirkner / system-lambda

System Lambda is a collection of functions for testing code that uses java.lang.System
MIT License
211 stars 14 forks source link

[Feature Request] Provide facility to change the current working directory #22

Open christianhujer opened 3 years ago

christianhujer commented 3 years ago

It would be great if system-lambda would also provide a facility to change the current working directory. As far as I am aware, this requires two things at the same time: a) setting the System property user.dir. b) Making a native call to chdir() or fchdir()

The JRuby folks seem to have done something like this.

See also: https://stackoverflow.com/a/8204584/3554264

CAVEAT: The working directory is a process attribute, not a thread attribute. Changing it may have undesired results when running tests in parallel should these tests directly or indirectly rely on the current working directory in any way.

I would expect code to work like this:

@Test
void chDirExample() {
    withCwd(Path.of(".").parent, () -> System.out.println(Pathof(".")));
}
stefanbirkner commented 3 years ago

Hi Christian, thank you for this nice idea for a feature. I cannot promise anything because System Lambda is a free-time project of mine and my time is currently very limited. If you're using JUnit Lambda you can also talk to the team of @junit-pioneer whether they are interested in implementing this feature into their library.

christianhujer commented 3 years ago

I actually worked on a prototype of this, and it doesn't look good. Path.of() uses a defaultFileSystem which effectively cashes the result of System.getProperty("user.dir"), which means that at least for Path.of(), a withCwd() would work only once per ClassLoader. I have to dig deeper to see if ClassLoader isolation can help, and even then there are open questions.

A solution that would work only half of the times (works for new File(".") but not for Path.of("") would be confusing.

I'll keep you posted.