Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Perl: Системное программирование > тестирование Модуля perl


Автор: mishnik 24.4.2011, 00:10
Уважаемый гуры перла, Христос Воскресе!!!
http://www.togotutor.com/learn-perl/pm-perl.php 
очень хорошо описывается как создать модуль с помощью команды
Код

h2xs -b 5.6.1 -AX Utils
Writing Utils/lib/Utils.pm
Writing Utils/Makefile.PL
Writing Utils/README
Writing Utils/t/Utils.t
Writing Utils/Changes
Writing Utils/MANIFEST

все супер, но далее,если 
я запустил так
Код

h2xs -b 5.6.1 -AX Trade::Index
получилась следующая структура папок
tree /F Trade-Index
C:\USERS\MISHNIK\DOCUMENTS\PERL\INDEX\TRADE-INDEX
│   Changes
│   Makefile.PL
│   MANIFEST
│   README
│
├───lib
│   └───Trade
│           Index.pm
│
└───t
        Trade-Index.t



добавляем код 
Код

package Trade::Index;

use 5.006001;
use strict;
use warnings;

require Exporter;

our @ISA = qw(Exporter);

# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.

# This allows declaration    use Trade::Index ':all';
# If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
# will save memory.
our %EXPORT_TAGS = ( 'all' => [ qw(
    _strip trim
) ] );

our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );

our @EXPORT = qw(
    
);

our $VERSION = '0.01';


# Preloaded methods go here.
=head1 FUNCTIONS

Разные прикладные функции

=over

=item _strip(ARG)

=item trim(ARG)

Функции по обрезанию пробелов,
интересно понять какая из них быстрее работает
=cut

 
sub _strip {
    my $string = shift;

    return defined $string ? ($string =~ /^\s*(.*?)\s*$/s)[0] : $string;
}
sub trim {
   my ($string) = @_;
   $string =~ s/\n//sm;
   $string =~ s/\r//sm;
   $string =~ s/^\s+//sm;
   $string =~ s/\s+$//sm;
   return $string;
}

1;
__END__
# Below is stub documentation for your module. You'd better edit it!

=head1 NAME

Trade::Index - Perl extension for blah blah blah

=head1 SYNOPSIS

  use Trade::Index;
  blah blah blah

=head1 DESCRIPTION

Stub documentation for Trade::Index, created by h2xs. It looks like the
author of the extension was negligent enough to leave the stub
unedited.

Blah blah blah.

=head2 EXPORT

None by default.



=head1 SEE ALSO

Mention other useful documentation such as the documentation of
related modules or operating system documentation (such as man pages
in UNIX), or any relevant external documentation such as RFCs or
standards.

mishin.narod.ru

=head1 AUTHOR

Nikolay Mishin (Mishnik) <[email protected]>

=head1 COPYRIGHT


Copyright (C) 2011 Nikolay Mishin (Mishnik) <[email protected]>

=head1 LICENSE

This module is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

=cut

1;



пытаемся добавить код в тестовый модуль
Код

# Before `make install' is performed this script should be runnable with
# `make test'. After `make install' it should work as `perl Trade-Index.t'

#########################

# change 'tests => 1' to 'tests => last_test_to_print';
#BEGIN {
#    unshift @INC, '../lib/Trade::Index';# './lib', '../t',  './t';#отлично модуль, который мне нужно тестировать - виден!
#    use Trade::Index;
#
#} 
use Test::More;   # see done_testing()
use strict;
use warnings;

BEGIN { 
    unshift @INC, '../lib';# './lib', '../t',  './t';#отлично модуль, который мне нужно тестировать - виден!        
        #use_ok( 'Trade::Index' );
         }
  require_ok( 'Trade::Index' );
  

use Test;
BEGIN { plan tests => 3 };
use IO::File ();
ok(1); # If we made it this far, we're ok.
require_ok( 'Trade::Index' );
my $data=<<END;
        please me

END
is(_strip($data),'please me',' _strip($data) is = Got root');
is(trim($data),'please me','Got root');
 
#########################

# Insert your test code below, the Test::More module is use()ed here so read
# its man page ( perldoc Test::More ) for help writing this test script.




А теперь 2 вопроса:
1. Без добавления строки
Код

unshift @INC, '../lib';# './lib', '../t',  './t';#отлично модуль, который мне нужно тестировать - виден!        

скрипт не найдет нужного модуля
Код

Error:  Can't locate Trade/Index.pm in @INC (@INC contains: C:/strawberry/perl/lib C:/strawberry/perl/site/lib C:\strawberry\perl\vendor\lib .) at (eval 9) line 2.

странно, почему это не сделано по умолчанию?
2. Ошибка
Код

Undefined subroutine &main::_strip

хотя в модуле эта процедура указана в модуле
Код

our %EXPORT_TAGS = ( 'all' => [ qw(
    _strip trim
) ] );


чтобы все заработало надо эти фукнции явно указать при вызове модуля
Код

use Trade::Index qw/_strip trim/;

Почему они и так не видяться?

Спасибо..
В общем все заработало, но хотелось бы знать что вы об этом думаете?

Добавлено через 4 минуты и 13 секунд
Работающий вариант (с perltidy) модуля и теста
Код

package Trade::Index;

use 5.006001;
use strict;
use warnings;

require Exporter;

our @ISA = qw(Exporter);

# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.

# This allows declaration    use Trade::Index ':all';
# If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
# will save memory.
our %EXPORT_TAGS = (
    'all' => [
        qw(
          _strip trim
          )
    ]
);

our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );

our @EXPORT = qw(

);

our $VERSION = '0.01';

# Preloaded methods go here.

=head1 FUNCTIONS

Разные прикладные функции

=over

=item _strip(ARG)

=item trim(ARG)

Функции по обрезанию пробелов,
интересно понять какая из них быстрее работает
=cut

sub _strip {
    my $string = shift;

    return defined $string ? ( $string =~ /^\s*(.*?)\s*$/s )[0] : $string;
}

sub trim {
    my ($string) = @_;
    $string =~ s/\n//sm;
    $string =~ s/\r//sm;
    $string =~ s/^\s+//sm;
    $string =~ s/\s+$//sm;
    return $string;
}

1;
__END__
# Below is stub documentation for your module. You'd better edit it!

=head1 NAME

Trade::Index - Perl extension for blah blah blah

=head1 SYNOPSIS

  use Trade::Index;
  blah blah blah

=head1 DESCRIPTION

Stub documentation for Trade::Index, created by h2xs. It looks like the
author of the extension was negligent enough to leave the stub
unedited.

Blah blah blah.

=head2 EXPORT

None by default.

=head1 SEE ALSO

Mention other useful documentation such as the documentation of
related modules or operating system documentation (such as man pages
in UNIX), or any relevant external documentation such as RFCs or
standards.

mishin.narod.ru

=head1 AUTHOR

Nikolay Mishin (Mishnik) <[email protected]>

=head1 COPYRIGHT

Copyright (C) 2011 Nikolay Mishin (Mishnik) <[email protected]>

=head1 LICENSE

This module is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

=cut

1;


и
Код

# Before `make install' is performed this script should be runnable with
# `make test'. After `make install' it should work as `perl Trade-Index.t'

#########################

use Test::More tests => 4;    # see done_testing()
use strict;
use warnings;

BEGIN {
    unshift @INC, '../lib';
}
require_ok('Trade::Index');

#use Trade::Index qw/_strip trim/;
use Trade::Index ':all';

ok(1);                        # If we made it this far, we're ok.
my $data = <<END;
        please me

END
my $t = _strip($data);
is( $t, 'please me', " [$t]=[please me] - OK" );
my $t1 = trim($data);
is( $t1, 'please me', " [$t1]=[please me] - OK" );

#########################

# Insert your test code below, the Test::More module is use()ed here so read
# its man page ( perldoc Test::More ) for help writing this test script.





Вопросы остаются в силе, все-таки могли сделать так, что тестовый скрипт по умолчанию будет уже видеть модуль, который он призван тестировать без предварительной магии.

Автор: Pfailed 24.4.2011, 07:13
Не нужно никаких unshift. Что у вас в Makefile.PL? Как вы пытаетесь запустить тест?
Обычно для запуска тестов делают
Код

perl Makefile.PL
make
make test


Смотрите модули с cpan, благо примеров хватает.

Автор: Pfailed 24.4.2011, 07:40
Цитата(mishnik @  24.4.2011,  00:10 Найти цитируемый пост)
чтобы все заработало надо эти фукнции явно указать при вызове модуля

Потому что @EXPORT_OK это то что нужно явно указывать. Из @EXPORT импортируются автоматически, но только при использовании use, но не require. Соответственно в тесте нужно заменить require_ok на use_ok.

Автор: mishnik 25.4.2011, 00:50
Цитата(Pfailed @ 24.4.2011,  07:13)
Не нужно никаких unshift. Что у вас в Makefile.PL? Как вы пытаетесь запустить тест?
Обычно для запуска тестов делают
Код

perl Makefile.PL
make
make test


Смотрите модули с cpan, благо примеров хватает.

спасибо, так работает, но я думал запустить тест просто открыв его в Padre и нажав F5 (run)

Добавлено через 13 минут и 27 секунд
Цитата(Pfailed @ 24.4.2011,  07:40)
Цитата(mishnik @  24.4.2011,  00:10 Найти цитируемый пост)
чтобы все заработало надо эти фукнции явно указать при вызове модуля

Потому что @EXPORT_OK это то что нужно явно указывать. Из @EXPORT импортируются автоматически, но только при использовании use, но не require. Соответственно в тесте нужно заменить require_ok на use_ok.

фантастика , добавил
Код

our @EXPORT = qw(
          _strip _trim
);
и
use_ok('Trade::Index');

и все заработало (
то есть строки
Код

use Trade::Index ':all';

уже можно не ставить
) - божественно, спасибо

Автор: mishnik 17.5.2011, 10:28
закрываю тему, чтобы показать пример, что темы , если они исчерпаны - надо закрывать

Автор: Pfailed 17.5.2011, 11:12
Кстати, именно тесты удобнее запускать утилитой prove, которая входит в поставку perl.
Если структура диреторий следующая
Цитата

t
lib

то
prove -l  - запуск всех тестов из t/
prove -l -v - с подробным выводом
prove -l /t/smth.t  - запуск отдельного теста

В общем смотрите документацию.

Автор: mishnik 26.5.2011, 17:37
и на последок, правильнее модуль создавать так 
Код

module-starter --module=Trade --author="[Nikolay Mishin]" --email=[[email protected]] --builder=Module::Install


Добавлено через 1 минуту и 49 секунд
Pfailed, спасибо, очень полезно

Автор: mishin 30.8.2011, 21:18
Цитата(Pfailed @ 17.5.2011,  11:12)
prove -l  - запуск всех тестов из t/
prove -l -v - с подробным выводом
prove -l /t/smth.t  - запуск отдельного теста

спасибо, полезно, а еще для 

еще можно тестировать так
Код

 perl Build.PL
  ./Build
  ./Build test



Автор: mishin 7.9.2011, 18:04
a если в 
Код

cat ~/.module-starter/config
author: Nikolay Mishin
email:  [email protected]

есть настройки, то код 
Код

module-starter --module=MyTools --mb
создает модуль
Added to MANIFEST: Build.PL
Added to MANIFEST: Changes
Added to MANIFEST: ignore.txt
Added to MANIFEST: lib/MyTools.pm
Added to MANIFEST: MANIFEST
Added to MANIFEST: README
Added to MANIFEST: t/00-load.t
Added to MANIFEST: t/boilerplate.t
Added to MANIFEST: t/manifest.t
Added to MANIFEST: t/pod-coverage.t
Added to MANIFEST: t/pod.t
Created starter directories and files


Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)