in reply to mocking or trapping system calls

I just want to clarify: You want to test code that you don't control, right? If it were your own code, you could just change it to do something other than system() and backticks.

Can you tell us more about the job this code is doing? Even if we can't figure out how to bamboozle system(), backticks, etc, we might be able to come up with an alternative approach.

--Pileofrogs

Replies are listed 'Best First'.
Re^2: mocking or trapping system calls
by wu-lee (Beadle) on May 10, 2008 at 23:44 UTC
    The script runs a handful of root-owned commands and parses the output to gather information into a reporting system.

    For my own sake I'd like to add some basic automated tests which make it simple to run this and other scripts as a non-root user, both for development purposes, and to have some regression tests in place.

    It's code I currently control, so refactoring is an option, but I'd rather avoid refactoring something which works into something that imposes what may be perceived as pointless complexity on future custodians.

    So, I was hoping for was a module someone had already written, or a simple trick, which could do this fairly transparently and effortlessly.

    By the way, thanks for the suggestions so far, it's always educational to ask for help. I quite like the PATH idea, and overriding readpipe is in fact doable in the same way as it is for system, but a quick experiment suggests that it's not that easy to change the behaviour of backticks:

    $ perl -le 'BEGIN { *CORE::GLOBAL::readpipe = sub { print "hello $_[0 +]" } } readpipe "foo"; `bar` ' hello foo

      Trapping all exits from perl may indeed make your code too complex.

      I like pc88mxer's idea above of controlling your test environment with a VM or chroot solution. This way you can "mock" the expected, root owned external commands as you see fit w/o touching your perl code.