TestCase.pm


NAME

TestCase - the 'test bone' for Communiware testing.


SYNOPSIS

 use lib './t';
 require Communiware::TestCase;
 my $t = Communiware::TestCase->typical();
 $t->begin(8);
 my ($server, $user) = $t->get_identity;
 my $dbh = $t->dbh;
 $t->skip('Test name');
 $t->ok_sql('Test name', 
            "non-select SQL statement", 
            $number_of_rows_affected);
 $t->ok_select('Test name', 
               "SQL select statement", 
               @wanted_row);
 $t->ok_select_table('Test name', 
                     "SQL select statement", 
                     [@wanted_row1], 
                     [@wanted_row2],...);
 $t->ok_perl('Message for log', 
             sub{some perl code...}, 
             @wanted);
 $t->ok_put_file(
   'Message for log', 
        $item_id,
        $fname,
        'file contents'
        $wanted size
 );
 $t->do_redirect(1);
 $t->restart_server();
 $t->ok_http_request('Test name',
                     'POST',
                     'http://www.anyhost.com', 
                     [Content_Type=>'multipart/form-data'],
                     'name=qwerty&value=qazwsx',
                     200,
                     'OK',
                     [Content_Type=>'text/html'],
                     '<html>Content</html>',
                     $debug
 );
 $t->exists_cookie("Check cookie",
        {'key' => 'AUTHOR_ID',
                'val' => 'vasya'},
                1
 );
 $t->reset_cookie;
 $t->ok_parse(... see below ...);
 $t->ok_expression("Subtest name",
                   $expr_source,
                   \%context_attrs,
                   $wanted_value_or_error,
                   $wanted_is_const);
 $t->ok_compile_template("Check template compiling",
                         {LANG => 'en', ITEM_ID => 'some_tpl'},
                         '<:Cond><:Case 1:><:EndCase:><:EndCond:>',
                         'sub {...}, sub {...}'
                        );


DESCRIPTION

This module extend Communiware::TBone (from CPAN) functionallity for specific Communiware necessiies. It must be placed into communiware/t/Extutil directory as well as TBone module itself. The module saves structure of testing provided by TBone, so see TBone manpage for details.


HELPER FUNCTIONS

typical

  my $t = Communiware::TestCase->typical(12);

Constructor of Communiware::TestCase class. The only argument - number of subtests in script.

skip

  $t->skip('Test name', 'reason');

This method does nothing except writes on stdout and into logfile string 'Test skipped: reason'. Where reason is why it was skipped.

cfg

  my $cfg = $t->cfg;

Method returns reference to hash, which contains of .config file - Comminiware install time congiguration.

testnum

  my $test_object_id = 'objecttype_' . $t->testnum;

Return string suitable for use as part of item_id for items created during test script. This string for each test sctipt because based on name of test script.

dbh

  $dbh = $t->dbh;

Method returns value of $Communiware::dbh - database connection.

agent

  $ua = $t->agent;

Method returns object of HTTP::UserAgent type, which is used into ok_http_request method.

get_identity

  ($server, $user) = $t->get_identity;

Method returns two-members list, values of communiware server and communiware user suitable for communiware identity. The values are taken from table 'item', first by 'written' order.

set_identity

  ($server, $user) = $t->set_identity;
  ($server, $user) = $t->set_identity($server, $user);
  ($server, $user) = $t->set_identity($server, undef);
  ($server, $user) = $t->set_identity(undef, $user);

Method accepts to arguments communiware server & communiware user suitable for communiware identity. Both values can be undefined. Returns two-members list, values of communiware server and communiware user suitable for communiware identity. The values are taken by get_identity method.

delete_test_items

        delete_test_items();

This functions deletes test servers enumerated in @test_servers array that is normally filled by create_test_item() when creating test server. It is also installed as die handler, to safely delete test data if test script has errors that lead to die. If servers deleted successfully it checks existence of other test items. And warns if any still exists.

create_test_item

        $new_id = $t->create_test_item({'TYPE_ID'=>'SERVER',...});
        $new_id = $t->create_test_item( 'TYPE_ID'=>'SERVER',... );

This function creates test item choosing ID if not specified. After successful creating of server it calls Communiware::cache_servers() and identity() for newly created server, and also adds it to @test_servers for automatic deletion.

Returns new ID.


TESTING FUNCTIONS

Next functions are 'simple tests'. All of them work like 'ok' or 'ok_eq' from TBone package (see). Log of these methods execution is written into 'testout/TEST_NAME.tlog' file. First argument of all these methods is message prepended to test log into logfile.

ok_select

        $t->ok_select($message, $query, @patt);

$query is any SQL-select statement. It executes into DB and first (!) row of answer compares with @patt - column by column. Test is 'OK' if all the columns are equal. For non-numeric fields is used 'ne' operation, but for numeric - '!='. So '1.0000' and '1' are equal.

If @arg omitted test is successful.

ok_select_table

  $t->ok_select_table($msg, $query, @patt);

This method is like to 'ok_select', but it checks not only one row from sql-answer but several ones. @patt argument is list of array-references, each of them corresponds to one row in sql-answer. If @patt arg is omitted test is reputed as success.

ok_sql

  $t->ok_sql($msg, $query, $rv);

Method executes non-select $query (such as 'insert', 'update',...) and compares result of $dbh->do statement with $rv if present.

ok_perl

  $t->ok_perl($msg, $code, @patt);

Method executes $code - reference to perl subroutine and compares it result with @patt.

ok_perl

  $t->ok_put_file($msg, $item_id, $file_name, $file_contents, $wanted_size);

Method puts file $file_name with $file_contents to existing item $item_id. And compares real file size with wanted.

do_redirect

  $t->do_redirect(1);

This method sets one of two modes of ok_http_request: do or do not autoredirection. 'LWP::UserAgent->request' or 'simple_request' methods are called depends of this parameter. Default value - do redirect.

ok_http_request

  $t->ok_http_request($msg,
                      $method, $url, $reqhdr, $reqcont,
                      $wantcode, $wantmsg, $whdr, $wantcont,
                      $debug);
  $t->ok_http_request($msg,
                      $req,
                      $wantcode, $wantmsg, $whdr, $wantcont,
                      $debug);

The metod send http-request via network to http-server, receives response from server and compares it with wanted one. Method has two possibilites to set request data: explicit use request parameters or use HTTP::Request object.

Argument are:

$method
HTTP-method, such as 'GET', 'PUT', 'POST', 'HEAD'.

$url
'Path' part of full url. HTTP host name is taken from .config file (DEFAULTHOST parameter). So if value of $url is 'default/myitem' this method requests really to 'http://hostname.from.config/default/myitem'.

$reqhdr
Array reference contains headers of request. May be 'undef'. It is possible to use underscore instead of minus sign in header names. Names are _not_ case-sensetive. See also manpage of HTTP::Headers. I.E. [content_type=>'text/html'] is valid.

$reqcont
Content of request, may be undef.

$req
An object of HTTP::Reques class may be used instead of previous for parameters. This way may be convinient together with using HTTP::Request::Common package for making requests with multipart/form-data content type. See <HTTP::Request::Common> for details. An example:
 $t->ok_http_request(
   "Upload picture",
    POST(
         'http://somewhere.com',
         Content_Type => 'form-data',
         Content => [
                     'picfiledata' => [picname('a.gif')],
                    ],
   )
   ...

$wantcode
Wanted status code, such as 200 (RC_OK), 404 (RC_NOT_FOUND) etc. It is possible to use HTTP::Status module for mnemonic constants for this value. This, and following three parameters, are checking only if they are defined.

This parameter can be reference to perl code. If so this code calls with only argument - received code. Undefined return is sign of success, otherwise return value must be error message.

$wantmsg
Wanted status message from response.

$whdr
Wanted response headers. Argument is like $reqhdr - array reference. The only present headers are checked. Unlike $reqhdr values of headers may be either strings or perl subroutine references. In last case this subroutine calls with only parameter - received from server value of header. It must return true - on 'found' header or 'false' othervise.

Header can be specified with prefix CMWCount. It means we'll check that count of headers is equal to specified.

Example of this parameter:

  [
    Connection=>'close',
    Set-Cookie=>sub{$_[0] =~ /AUTHOR_ID=something; path=\/;/},
                CMWCountSet-Cookie=>1
  ]

$wantcont
Wanted content of response, optional parameter. This argument can be either string or reference to perl subroutine. In last case this subroutine calls with only parameter - received content. It must return error message or 'undef' on success.

$debug
If this parameter has 'true' value both request and response are printed to STDOUT. This feature is useful for test debug.

reset_cookie

Method reset internal cookie object, so it becomes empty.

set_cookie

set_cookie ($name, $val, [$domain, $maxage])

$name is a name of a cookie $val is a value of a cookie

if $domain is specified, cookie is set to specified domain To $Communiware::config{'DEFAULTHOST'} otherwise

$maxage specifies lifetime of a cookie (86400 seconds if omitted). If $maxage is negative, cookie is deleted

exists_cookie

        Checks for existence of specified cookie
        Scans all cookies 
                $msg - description of test
                $data - hash with keys specified in HTTP::Cookies. key and val must exist.
                $wanted - 0 if specified cookie must be absent, 1 otherwise

ok_parse

        $t->ok_parse("Subtest name",
                $template_fragment_text,
                $current_context,
                $document_item_context,
                $expected_error_stage,
                $expected_document_fragment_or_error_regex,
                $expected_context,
                $expected_headers,
                $expected_status);

Tests expansion of piece of template in the given context (i.e handler method).

Parameter notes:

$template_fragment_text
analyzed template fragment. It is parsed, compiled and executed

$current_context
the context in which $template_fragment_text is executed

$document_item_context
the document item's context for execution. It may be not the same context as $current_context.

$expected_error_stage
expected stage when an error should occur. If it is empty, success is expected. Other possible values are 'parse', 'compile', 'eval', 'exec'. Throwing an Communiware::Exception::HTTP is not considered an error if $expected_status is defined

$expected_document_fragment_or_error_regex
expected output, if success expected, or error message regex, if error expected.

$expected_context
hash reference to interesting expected context attribures, if any (as reported by $current_context->get).

$expected_headers
expected list of interesting headers as string with one header per line, if any.

$expected_status
expected code of Communiware::Exception::HTTP. For example this parameter must have value 302 if executed template forces redirection.

=back

If expected output is not HTML-equivalent to resulting output, HTML::Element's dumps of both expected and resulting output is saved in testout/N.wanted and testout/N.got respectively in order to make it easier to find difference (with diff, wdiff, vimdiff or another appropriate tool.

ok_lister

 $t->ok_lister("Lister test", '<:Include tpl @TITLE:>',
                  {ITEM_ID => $server}, qw(TITLE LANG));

This method checks if the list of used attributes (lister) is equal with wanted one.

Parameters are:

$name
Name of the test.

$code
Source code of template.

$context
Hash contains name-value pairs of attributes in used context.

@wanted_attrs
Non-sorted list of wanted attributes names.

different_textes

 $t->different_textes($message, $first_long_text, $second_long_text)

This method compares two given text argument. It assumes that first is 'wanted' and second is 'got' version of some, possible long, data. If argumens are not equal the method writes them into two files (for future comparsation with 'diff' programm) and returns message containing names od these files and $message argument. If arguments are equal the method does nothing and returns an empty string.

ok_compile_template

 $t->ok_compile_template("Check template compiling",
                         {LANG => 'en', ITEM_ID => 'some_tpl'},
                         '<:Cond><:Case 1:><:EndCase:><:EndCond:>',
                         'sub {...}, sub {...}',
                         undef
                        )

This method is intended for checking template to perl code compiling. Arguments are:

  • Test name

  • Reference to hash with attributes for creation new template via Communiware::Template::new

  • Source text of template

  • Wanted after translation perl code, linefeeds and indentation does not matter. If undef no generated code comparsation performed, checks on errors only.

  • Wanted error message or undef if no errors wanted.

ok_expression

        $t->ok_expression("Subtest name",
                                        $expr_source,
                                        $current_context,
                                        $wanted_error_stage,
                                        $wanted_value_or_error,
                                        $wanted_type,
                                        $wanted_is_const);

This method takes source text of template language expression, compiles it and evaluates in a given context. After this it compares resulting value against wanted.

$wanted_error_stage is interpreted as

'' or any other false value
we expect a success

'parse'
we expect a parsing error

'compile'
we expect a compilation error

'eval'
we expect an evaluation error

If we expect a success, $wanted_value_or_error is a wanted value.

If we expect an error, $wanted_value_or_error is a regular expression that should be matched by the real error for the ok_expression to be successful.

If not all expression is 'eaten' by compiler is is a compilation error.

If wanted value is either 'true' or 'false' then expression counted as condition and its value is interpreted as perl boolean.

ok_filter_has_data

        $t->ok_filter_has_data('Subtest name', $current_context, $filter, $debug_print, @data);

ok_filter_has_rows

    $t->ok_filter_has_rows(
        name   => 'Subtest name',
        ctx    => $current_context,
        filter => $filter,
        debug  => 1,
        rows   => @data
    );

Main difference with ok_function_has_row - it allows not constant set of keys in returned rows.

Also introduce named arguments in test method.

restart_server

$t->restart_server(); Executes server soft reconfig

set_special_contexts

        ($gc, $sc, $dc, $uc, $tc) =
          set_special_contexts($gc_src, $sc_src, $dc_src, $uc_src, $tc_src, $is_auth_strong);

Sets global contexts to given contexts. *_src may be:

undef
Skip this context setting.

item ID
Create item context for this item and set it as a special context (for item contexts). Specifying a '' for $uc_src creates anonymous context.

CGI object
Create global context for this CGI object and sets it as a special context (for global context only).

context object
Sets this object as a corresponding special context.

If parameter $is_auth_strong is true and user's context is set, authentication will be strong.

Returns created contexts (undef for untouched).

16 октябрь 2007 13:45