I'm doing some testing, and am trying to test each function in isolation, as much as is possible. In many cases, when testing a function that calls other, complex functions, I just want to call "stub functions" with known outputs. This simplifies my testing. I know that I can locally override the functions that I want (within the framework of a single test function), by using code like the following:
sub test_foo { my $temp; $temp = $^W; # save warning flag status $^W=0; # ignore "function is redefined" warning local *module::bar=\&stub_for_bar; $^W = $temp; # restore warnings # test code for module::foo() goes here }
I'd like to save myself some typing, and create a macro that overrides a given function with a given stub, local to the current scope. I see it looking something like this:
sub test_foo { override_with_stub_fn('module::bar',\&stub_for_bar); # test code for module::foo goes here }
I can't think of a way to do this in perl, however. If I try to move the code into a function, the local() command has the wrong scope. If there were a way to make it run in the parent's scope, (like TCL's uplevel() command), the problem would be solved, but I don't know of a way to do that. Is there some tricky caller/AUTOLOAD/goto trick I can do to accomplish this? I'd just as soon not use the -P (C-preprocessor) option if I can avoid it.

-- Ytrew


In reply to How do I localize a value to the calling function's scope? by Ytrew

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.