home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / xampp / xampp-perl-addon-1.4.9-installer.exe / MockObject.pm < prev    next >
Encoding:
Perl POD Document  |  2003-02-06  |  16.9 KB  |  640 lines

  1. package Test::MockObject;
  2.  
  3. use strict;
  4.  
  5. use vars qw( $VERSION $AUTOLOAD );
  6. $VERSION = '0.12';
  7.  
  8. use Test::Builder;
  9. my $Test = Test::Builder->new();
  10. my (%calls, %subs);
  11.  
  12. sub new
  13. {
  14.     my ($class, $type) = @_;
  15.     $type ||= {};
  16.     bless $type, $class;
  17. }
  18.  
  19. sub mock
  20. {
  21.     my ($self, $name, $sub) = @_;
  22.     $sub ||= sub {};
  23.     _subs( $self )->{$name} = $sub;
  24.     $self;
  25. }
  26.  
  27. # deprecated and complicated as of 0.07
  28. sub add
  29. {
  30.     my $self = shift;
  31.     my $subs = _subs( $self );
  32.     return $subs->{add}->( $self, @_ )
  33.          if (exists $subs->{add} and !( UNIVERSAL::isa( $_[1], 'CODE' )));
  34.     $self->mock( @_ );
  35. }
  36.  
  37. sub set_always
  38. {
  39.     my ($self, $name, $value) = @_;
  40.     $self->mock( $name, sub { $value } );
  41. }
  42.  
  43. sub set_true
  44. {
  45.     my ($self, $name) = @_;
  46.     $self->mock( $name, sub { 1 } );
  47. }
  48.  
  49. sub set_false
  50. {
  51.     my ($self, $name) = @_;
  52.     $self->mock( $name, sub {} );
  53. }
  54.  
  55. sub set_list
  56. {
  57.     my ($self, $name, @list) = @_;
  58.     $self->mock( $name, sub { @{[ @list ]} } );
  59. }
  60.  
  61. sub set_series
  62. {
  63.     my ($self, $name, @list) = @_;
  64.     $self->mock( $name, sub { return unless @list; shift @list } );
  65. }
  66.  
  67. sub set_bound
  68. {
  69.     my ($self, $name, $ref) = @_;
  70.     my $code;
  71.     if (UNIVERSAL::isa( $ref, 'SCALAR' ))
  72.     {
  73.         $code = sub { $$ref };
  74.     }
  75.     elsif (UNIVERSAL::isa( $ref, 'ARRAY' ))
  76.     {
  77.         $code = sub { @$ref };
  78.     }
  79.     elsif (UNIVERSAL::isa( $ref, 'HASH' ))
  80.     {
  81.         $code = sub { %$ref };
  82.     }
  83.     $self->mock( $name, $code );
  84. }
  85.  
  86. sub can
  87. {
  88.     my ($self, $sub) = @_;
  89.  
  90.     # mockmethods are special cases, class methods are handled directly
  91.     my $subs = _subs( $self );
  92.     return $subs->{$sub} if (ref $self and exists $subs->{$sub});
  93.     return UNIVERSAL::can(@_);
  94. }
  95.  
  96. sub remove
  97. {
  98.     my ($self, $sub) = @_;
  99.     delete _subs( $self )->{$sub};
  100.     $self;
  101. }
  102.  
  103. sub called
  104. {
  105.     my ($self, $sub) = @_;
  106.     
  107.     for my $called (reverse @{ _calls( $self ) }) {
  108.         return 1 if $called->[0] eq $sub;
  109.     }
  110.  
  111.     return 0;
  112. }
  113.  
  114. sub clear
  115. {
  116.     my $self  = shift;
  117.     @{ _calls( $self ) } = ();
  118.     $self;
  119. }
  120.  
  121. sub call_pos
  122. {
  123.     $_[0]->_call($_[1], 0);
  124. }
  125.  
  126. sub call_args
  127. {
  128.     return @{ $_[0]->_call($_[1], 1) };
  129. }
  130.  
  131. sub _call
  132. {
  133.     my ($self, $pos, $type) = @_;
  134.     my $calls = _calls( $self );
  135.     return if abs($pos) > @$calls;
  136.     $pos-- if $pos > 0;
  137.     return $calls->[$pos][$type];
  138. }
  139.  
  140. sub call_args_string
  141. {
  142.     my $args = $_[0]->_call( $_[1], 1 ) or return;
  143.     return join($_[2] || '', @$args);
  144. }
  145.  
  146. sub call_args_pos
  147. {
  148.     my ($self, $subpos, $argpos) = @_;
  149.     my $args = $self->_call( $subpos, 1 ) or return;
  150.     $argpos-- if $argpos > 0;
  151.     return $args->[$argpos];
  152. }
  153.  
  154. sub next_call
  155. {
  156.     my ($self, $num) = @_;
  157.     $num ||= 1;
  158.  
  159.     my $calls = _calls( $self );
  160.     return unless @$calls >= $num;
  161.  
  162.     my ($call) = (splice(@$calls, 0, $num))[-1];
  163.     return wantarray() ? @$call : $call->[0];
  164. }
  165.  
  166. sub AUTOLOAD
  167. {
  168.     my $self = $_[0];
  169.     my $sub;
  170.     {
  171.         local $1;
  172.         ($sub) = $AUTOLOAD =~ /::(\w+)\z/;
  173.     }
  174.     return if $sub eq 'DESTROY';
  175.  
  176.     my $subs = _subs( $self );
  177.     if (exists $subs->{$sub})
  178.     {
  179.         push @{ _calls( $self ) }, [ $sub, [ @_ ] ];
  180.         goto &{ $subs->{$sub} };
  181.     }
  182.     else
  183.     {
  184.         require Carp;
  185.         Carp::carp("Un-mocked method '$sub()' called");
  186.     }
  187.     return;
  188. }
  189.  
  190. sub called_ok
  191. {
  192.     my ($self, $sub, $name) = @_;
  193.     $name ||= "object called '$sub'";
  194.     $Test->ok( $self->called($sub), $name );
  195. }
  196.  
  197. sub called_pos_ok
  198. {
  199.     my ($self, $pos, $sub, $name) = @_;
  200.     $name ||= "object called '$sub' at position $pos";
  201.     my $called = $self->call_pos($pos, $sub);
  202.     unless ($Test->ok( (defined $called and $called eq $sub), $name )) {
  203.         $called = 'undef' unless defined $called;
  204.         $Test->diag("Got:\n\t'$called'\nExpected:\n\t'$sub'\n");
  205.     }
  206. }
  207.  
  208. sub called_args_string_is
  209. {
  210.     my ($self, $pos, $sep, $expected, $name) = @_;
  211.     $name ||= "object sent expected args to sub at position $pos";
  212.     $Test->is_eq( $self->call_args_string( $pos, $sep ), $expected, $name );
  213. }
  214.  
  215. sub called_args_pos_is
  216. {
  217.     my ($self, $pos, $argpos, $arg, $name) = @_;
  218.     $name ||= "object sent expected arg '$arg' to sub at position $pos";
  219.     $Test->is_eq( $self->call_args_pos( $pos, $argpos ), $arg, $name );
  220. }
  221.  
  222. sub fake_module
  223. {
  224.     my ($class, $modname, %subs) = @_;
  225.     $modname =~ s!::!/!g;
  226.     $INC{ $modname . '.pm' } = 1;
  227.  
  228.     local $SIG{__WARN__} = sub { warn $_[0] unless $_[0] =~ /redefined/ };
  229.     no strict 'refs';
  230.     ${ $modname . '::' }{VERSION} ||= -1;
  231.     
  232.     foreach my $sub (keys %subs) {
  233.         unless (UNIVERSAL::isa( $subs{ $sub }, 'CODE')) {
  234.             require Carp;
  235.             Carp::carp("'$sub' is not a code reference" );
  236.             next;
  237.         }
  238.         *{ $_[1] . '::' . $sub } = $subs{ $sub };
  239.     }
  240. }
  241.  
  242. sub fake_new
  243. {
  244.     my ($self, $class) = @_;
  245.     $self->fake_module( $class, new => sub { $self } );
  246. }
  247.  
  248. {
  249.     my %calls;
  250.  
  251.     sub _calls
  252.     {
  253.         my $key = shift;
  254.         $calls{ $key } ||= [];
  255.     }
  256. }
  257.  
  258. {
  259.     my %subs;
  260.  
  261.     sub _subs
  262.     {
  263.         my $key = shift;
  264.         $subs{ $key } ||= {};
  265.     }
  266. }
  267.  
  268. 1;
  269.  
  270. __END__
  271.  
  272. =head1 NAME
  273.  
  274. Test::MockObject - Perl extension for emulating troublesome interfaces
  275.  
  276. =head1 SYNOPSIS
  277.  
  278.   use Test::MockObject;
  279.   my $mock = Test::MockObject->new();
  280.   $mock->set_true( 'somemethod' );
  281.   ok( $mock->somemethod() );
  282.  
  283.   $mock->set_true( 'veritas')
  284.          ->set_false( 'ficta' )
  285.        ->set_series( 'amicae', 'Sunny', 'Kylie', 'Bella' );
  286.  
  287. =head1 DESCRIPTION
  288.  
  289. It's a simple program that doesn't use any other modules, and those are easy to
  290. test.  More often, testing a program completely means faking up input to
  291. another module, trying to coax the right output from something you're not
  292. supposed to be testing anyway.
  293.  
  294. Testing is a lot easier when you can control the entire environment.  With
  295. Test::MockObject, you can get a lot closer.
  296.  
  297. Test::MockObject allows you to create objects that conform to particular
  298. interfaces with very little code.  You don't have to reimplement the behavior,
  299. just the input and the output.
  300.  
  301. =head2 IMPORTANT CAVEAT FOR TESTERS
  302.  
  303. Please note that it is possible to write highly detailed unit tests that pass
  304. even when your integration tests may fail.  Testing the pieces individually
  305. does not excuse you from testing the whole thing together.  I consider this to
  306. be a feature.
  307.  
  308. =head2 EXPORT
  309.  
  310. None by default.  Maybe the Test::Builder accessories, in a future version.
  311.  
  312. =head2 FUNCTIONS
  313.  
  314. The most important thing a Mock Object can do is to conform sufficiently to an
  315. interface.  For example, if you're testing something that relies on CGI.pm, you
  316. may find it easier to create a mock object that returns controllable results
  317. at given times than to fake query string input.
  318.  
  319. B<The Basics>
  320.  
  321. =over 4
  322.  
  323. =item * C<new>
  324.  
  325. Creates a new mock object.  By default, this is a blessed hash.  Pass a
  326. reference to bless that reference.
  327.  
  328.     my $mock_array  = Test::MockObject->new( [] );
  329.     my $mock_scalar = Test::MockObject->new( \( my $scalar ) );
  330.     my $mock_code   = Test::MockObject->new( sub {} );
  331.     my $mock_glob   = Test::MockObject->new( \*GLOB );
  332.  
  333. =back
  334.  
  335. B<Mocking>
  336.  
  337. Your mock object is nearly useless if you don't tell it what it's mocking.
  338. This is done by installing methods.  You control the output of these mocked
  339. methods.  In addition, any mocked method is tracked.  You can tell not only
  340. what was called, but which arguments were passed.  Please note that you cannot
  341. track non-mocked method calls.  They will still be allowed, though
  342. Test::MockObject will carp() about them.  This is considered a feature, though
  343. it may be possible to disable this in the future.
  344.  
  345. As implied in the example above, it's possible to chain these calls together.
  346. Thanks to a suggestion from the fabulous Piers Cawley (CPAN RT #1249), this
  347. feature came about in version 0.09.  Shorter testing code is nice!
  348.  
  349. =over 4
  350.  
  351. =item * C<mock(I<name>, I<coderef>)>
  352.  
  353. Adds a coderef to the object.  This allows the named method to be called on the
  354. object.  For example, this code:
  355.  
  356.     my $mock = Test::MockObject->new();
  357.     $mock->mock('fluorinate', 
  358.         sub { 'impurifying precious bodily fluids' });
  359.     print $mock->fluorinate;
  360.  
  361. will print a helpful warning message.  Please note that methods are only added
  362. to a single object at a time and not the class.  (There is no small similarity
  363. to the Self programming language, or the Class::Prototyped module.)
  364.  
  365. This method forms the basis for most of Test::MockObject's testing goodness.
  366.  
  367. B<Please Note:> this method used to be called C<add()>.  Due to its ambiguity,
  368. it is now spelled differently.  For backwards compatibility purposes, add() is
  369. available, though deprecated as of version 0.07.  It goes to some contortions
  370. to try to do what you mean, but I make few guarantees.
  371.  
  372. =item * C<fake_module(I<module name>), [ I<subname> => I<coderef>, ... ]
  373.  
  374. Lies to Perl that a named module has already been loaded.  This is handy when
  375. providing a mockup of a real module if you'd like to prevent the actual module
  376. from interfering with the nice fakery.  If you're mocking L<Regexp::English>,
  377. say:
  378.  
  379.     $mock->fake_module( 'Regexp::English' );
  380.  
  381. This can be invoked both as a class and as an object method.  Beware that this
  382. must take place before the actual module has a chance to load.  Either wrap it
  383. in a BEGIN block before a use or require, or place it before a C<use_ok()> or
  384. C<require_ok()> call.
  385.  
  386. You can optionally add functions to the mocked module by passing them as name
  387. => coderef pairs to C<fake_module()>.  This is handy if you want to test an
  388. import():
  389.  
  390.     my $import;
  391.     $mock->fake_module(
  392.         'Regexp::English',
  393.         import => sub { $import = caller }
  394.     );
  395.     use_ok( 'Regexp::Esperanto' );
  396.     is( $import, 'Regexp::Esperanto',
  397.         'Regexp::Esperanto should use() Regexp::English' );
  398.  
  399. =item * C<fake_new(I<module name>)>
  400.  
  401. Provides a fake constructor for the given module that returns the invoking mock
  402. object.  Used in conjunction with C<fake_module()>, you can force the tested
  403. unit to work with the mock object instead.
  404.  
  405.     $mock->fake_module( 'CGI' );
  406.     $mock->fake_new( 'CGI' );
  407.  
  408.     use_ok( 'Some::Module' );
  409.     my $s = Some::Module->new();
  410.     is( $s->{_cgi}, $mock,
  411.         'new() should create and store a new CGI object' );
  412.  
  413. =item * C<set_always(I<name>, I<value>)>
  414.  
  415. Adds a method of the specified name that always returns the specified value.
  416.  
  417. =item * C<set_true(I<name>)>
  418.  
  419. Adds a method of the specified name that always returns a true value.
  420.  
  421. =item * C<set_false(I<name>)>
  422.  
  423. Adds a method of the specified name that always returns a false value.  (Since
  424. it installs an empty subroutine, the value should be false in both scalar and
  425. list contexts.)
  426.  
  427. =item * C<set_list(I<name>, [ I<item1>, I<item2>, ... ]>
  428.  
  429. Adds a method that always returns a given list of values.  It takes some care
  430. to provide a list and not an array, if that's important to you.
  431.  
  432. =item * C<set_series(I<name>, [ I<item1>, I<item2>, ... ]>
  433.  
  434. Adds a method that will return the next item in a series on each call.  This
  435. can be an effective way to test error handling, by forcing a failure on the
  436. first method call and then subsequent successes.  Note that the series is
  437. (eventually) destroyed.
  438.  
  439. =item * C<set_bound(I<name>, I<reference>)>
  440.  
  441. Adds a method bound to a variable.  Pass in a reference to a variable in your
  442. test.  When you change the variable, the return value of the new method will
  443. change as well.  This is often handier than replacing mock methods.
  444.  
  445. =item * C<remove(I<name>)>
  446.  
  447. Removes a named method.
  448.  
  449. =back
  450.  
  451. B<Checking Your Mocks>
  452.  
  453. =over 4
  454.  
  455. =item * C<called(I<name>)>
  456.  
  457. Checks to see if a named method has been called on the object.  This returns a
  458. boolean value.  The current implementation does not scale especially well, so
  459. use this sparingly if you need to search through hundreds of calls.
  460.  
  461. =item * C<clear()>
  462.  
  463. Clears the internal record of all method calls on the object.  It's handy to do
  464. this every now and then.  Note that this does not affect the methods that have
  465. been mocked for the object -- only the log of all methods that have been called
  466. until this point.
  467.  
  468. It's handy to C<clear()> methods in between series of tests.  That makes it
  469. much easier to call C<next_method()> without having to skip over the calls from
  470. the last set of tests.
  471.  
  472. =item * C<next_call([ I<position> ])>
  473.  
  474. Returns the name and argument list of the next mocked method that was called on
  475. an object, in list context.  In scalar context, returns only the method name.
  476. There are two important things to know about this method.  First, it starts at
  477. the beginning of the call list.  If your code runs like this:
  478.  
  479.     $mock->set_true( 'foo' );
  480.     $mock->set_true( 'bar' );
  481.     $mock->set_true( 'baz' );
  482.  
  483.     $mock->foo();
  484.     $mock->bar( 3, 4 );
  485.     $mock->foo( 1, 2 );
  486.  
  487. Then you might get output of:
  488.  
  489.     my ($name, $args) = $mock->next_call();
  490.     print "$name (@$args)";
  491.  
  492.     # prints 'foo'
  493.  
  494.     $name = $mock->next_call();
  495.     print $name;
  496.  
  497.     # prints 'bar'
  498.  
  499.     ($name, $args) = $mock->next_call();
  500.     print "$name (@$args)";
  501.  
  502.     # prints 'foo 1 2'
  503.  
  504. If you provide an optional number as the I<position> argument, the method will
  505. skip that many calls, returning the data for the last one skipped.
  506.  
  507.     $mock->foo();
  508.     $mock->bar();
  509.     $mock->baz();
  510.  
  511.     $name = $mock->next_call();
  512.     print $name;
  513.  
  514.     # prints 'foo'
  515.  
  516.     $name = $mock->next_call( 2 );
  517.     print $name
  518.  
  519.     # prints 'baz'
  520.  
  521. When it reaches the end of the list, it returns undef.  This is probably the
  522. most convenient method in the whole module, but for the sake of completeness
  523. and backwards compatibility (it takes me a while to reach the truest state of
  524. laziness!), there are several other methods.
  525.  
  526. =item * C<call_pos(I<position>)>
  527.  
  528. Returns the name of the method called on the object at a specified position.
  529. This is handy if you need to test a certain order of calls.  For example:
  530.  
  531.     Some::Function( $mock );
  532.     is( $mock->call_pos(1),  'setup',
  533.         'Function() should first call setup()' );
  534.     is( $mock->call_pos(-1), 'end', 
  535.         '... and last call end()' );
  536.  
  537. Positions can be positive or negative.  Please note that the first position is,
  538. in fact, 1.  (This may change in the future.  I like it, but am willing to
  539. reconsider.)
  540.  
  541. =item * C<call_args(I<position>)>
  542.  
  543. Returns a list of the arguments provided to the method called at the appropriate
  544. position.  Following the test above, one might say:
  545.  
  546.     is( ($mock->call_args(1))[0], $mock,
  547.         '... passing the object to setup()' );
  548.     is( scalar $mock->call_args(-1), 0,
  549.         '... and no args to end()' );
  550.  
  551. =item * C<call_args_pos(I<call position>, I<argument position>)>
  552.  
  553. Returns the argument at the specified position for the method call at the
  554. specified position.  One might rewrite the first test of the last example as:
  555.  
  556.     is( $mock->call_args_pos(1, 1), $mock,
  557.         '... passing the object to setup()');
  558.  
  559. =item * C<call_args_string(I<position>, [ I<separator> ])>
  560.  
  561. Returns a stringified version of the arguments at the specified position.  If
  562. no separator is given, they will not be separated.  This can be used as:
  563.  
  564.     is( $mock->call_args_string(1), "$mock initialize",
  565.         '... passing object, initialize as arguments' );
  566.  
  567. =item * C<called_ok(I<method name>, [ I<test name> ])>
  568.  
  569. Tests to see whether a method of the specified name has been called on the
  570. object.  This and the following methods use Test::Builder, so they integrate
  571. nicely with a test suite built around Test::Simple, Test::More, or anything
  572. else compatible:
  573.  
  574.     $mock->foo();
  575.     $mock->called_ok( 'foo' );
  576.  
  577. A generic default test name is provided.
  578.  
  579. =item * C<called_pos_ok(I<position>, I<method name>, [ I<test name> ])>
  580.  
  581. Tests to see whether the named method was called at the specified position.  A
  582. default test name is provided.
  583.  
  584. =item * C<called_args_pos_is(I<method position>, I<argument position>, I<expected>, [ I<test name> ])>
  585.  
  586. Tests to see whether the argument at the appropriate position of the method in
  587. the specified position equals a specified value.  A default, rather
  588. non-descript test name is provided.
  589.  
  590. =item * C<called_args_string_is(I<method position>, I<separator>, I<expected>, [ I<test name> ])>
  591.  
  592. Joins together all of the arguments to a method at the appropriate position and
  593. matches against a specified string.  A generically bland test name is provided
  594. by default.  You can probably do much better.
  595.  
  596. =back
  597.  
  598. =head1 TODO
  599.  
  600. =over 4
  601.  
  602. =item * Add a factory method to avoid namespace collisions (soon)
  603.  
  604. =item * Handle C<isa()>
  605.  
  606. =item * Make C<fake_module()> and C<fake_new()> undoable
  607.  
  608. =item * Add more useful methods (catch C<import()>?)
  609.  
  610. =item * Move C<fake_module()> and C<fake_new()> into a Test::MockModule
  611.  
  612. =item * Allow certain methods to be mocked but not logged (Piers' suggestion)
  613.  
  614. =back
  615.  
  616. =head1 AUTHOR
  617.  
  618. chromatic, E<lt>chromatic@wgz.orgE<gt>
  619.  
  620. Thanks go to Curtis 'Ovid' Poe, as well as ONSITE! Technology, Inc., for
  621. finding several bugs and providing several constructive suggestions.
  622.  
  623. Jay Bonci also found a false positive in C<called_ok()>.  Thanks!
  624.  
  625. =head1 SEE ALSO
  626.  
  627. L<perl>, L<Test::Tutorial>, L<Test::More>,
  628. L<http:E<sol>E<sol>www.perl.comE<sol>pubE<sol>aE<sol>2001E<sol>12E<sol>04E<sol>testing.html>.
  629.  
  630. =head1 COPYRIGHT
  631.  
  632. Copyright 2002 - 2003 by chromatic E<lt>chromatic@wgz.orgE<gt>.
  633.  
  634. This program is free software; you can redistribute it and/or modify it under
  635. the same terms as Perl itself.
  636.  
  637. See http://www.perl.com/perl/misc/Artistic.html
  638.  
  639. =cut
  640.