File Coverage

blib/lib/WWW/Search/Test.pm
Criterion Covered Total %
statement 82 364 22.5
branch 4 156 2.5
condition 2 53 3.7
subroutine 22 45 48.8
pod 22 22 100.0
total 132 640 20.6


line stmt bran cond sub pod time code
1             # $rcs = ' $Id: Test.pm,v 2.293 2015-06-06 20:55:31 Martin Exp $ ' ;
2              
3             package WWW::Search::Test;
4              
5 3     3   77091 use strict;
  3         17  
  3         87  
6 3     3   21 use warnings;
  3         10  
  3         135  
7              
8             our
9             $VERSION = 2.294;
10              
11             =head1 NAME
12              
13             WWW::Search::Test - utilities to aid in testing WWW::Search backends
14              
15             =head1 SYNOPSIS
16              
17             $oTest = new WWW::Search::Test('HotBot,Yahoo,Excite');
18             $oTest->test('HotBot', 'Kingpin', 'one', $sQuery, $TEST_RANGE, 1, 10);
19              
20             =head1 DESCRIPTION
21              
22             See file test.pl in the WWW-Search-HotBot distribution for a detailed
23             "real-world" example.
24              
25             =head1 METHODS AND FUNCTIONS
26              
27             =cut
28              
29 3     3   1385 use Bit::Vector;
  3         3003  
  3         152  
30 3     3   21 use Carp;
  3         6  
  3         173  
31 3     3   18 use Config;
  3         5  
  3         137  
32 3     3   17 use Cwd;
  3         6  
  3         171  
33 3     3   1938 use Data::Dumper; # for debugging only
  3         20327  
  3         178  
34 3     3   1230 use Date::Manip;
  3         441511  
  3         459  
35 3     3   28 use base 'Exporter';
  3         7  
  3         406  
36 3     3   22 use File::Path;
  3         10  
  3         195  
37 3     3   1687 use File::Slurp;
  3         41334  
  3         217  
38 3     3   22 use File::Spec::Functions qw( :ALL );
  3         8  
  3         526  
39 3     3   22 use Test::More;
  3         6  
  3         57  
40 3     3   1555 use WWW::Search;
  3         8  
  3         139  
41              
42 3     3   18 use vars qw( $MODE_DUMMY $MODE_INTERNAL $MODE_EXTERNAL $MODE_UPDATE );
  3         7  
  3         227  
43 3     3   33 use vars qw( $TEST_DUMMY $TEST_EXACTLY $TEST_BY_COUNTING $TEST_GREATER_THAN $TEST_RANGE );
  3         13  
  3         207  
44 3     3   20 use vars qw( $iTest $oSearch $sEngine );
  3         7  
  3         159  
45             # If set, will be used as a filename to save HTML when a test fails:
46 3     3   19 use vars qw( $sSaveOnError );
  3         6  
  3         114  
47              
48 3     3   16 use vars qw( @EXPORT );
  3         6  
  3         200  
49             @EXPORT = qw( eval_test test
50             no_test not_working not_working_with_tests not_working_and_abandoned
51             $MODE_DUMMY $MODE_INTERNAL $MODE_EXTERNAL $MODE_UPDATE
52             $TEST_DUMMY $TEST_EXACTLY $TEST_BY_COUNTING $TEST_GREATER_THAN $TEST_RANGE
53             new_engine run_test run_gui_test skip_test count_results
54             tm_new_engine tm_run_test tm_run_test_no_approx
55             );
56              
57 3     3   20 use vars qw( $bogus_query $websearch );
  3         14  
  3         290  
58              
59             $bogus_query = "Bogus" . $$ . "NoSuchWord" . time;
60              
61             ($MODE_DUMMY, $MODE_INTERNAL, $MODE_EXTERNAL, $MODE_UPDATE) = qw(dummy internal external update);
62             ($TEST_DUMMY, $TEST_EXACTLY, $TEST_BY_COUNTING, $TEST_GREATER_THAN, $TEST_RANGE) = (1..10);
63              
64 3     3   22 use constant DEBUG => 0;
  3         5  
  3         12403  
65              
66             =head2 find_websearch
67              
68             Returns the full path of an executable WebSearch program,
69             or undef if none can be found.
70              
71             =cut
72              
73             sub find_websearch
74             {
75 2 100   2 1 1247 unless ($websearch)
76             {
77             # Try to find a working WebSearch:
78 1         3 my $sProg = 'WebSearch';
79 1         4 my @asTry = ( $sProg );
80             # Try local directory, in case . is not in the path:
81 1         6 push @asTry, catfile(curdir, $sProg);
82 1         6 push @asTry, catfile(qw( blib script ), $sProg);
83             # See if WebSearch.BAT has been created/installed, and try it with
84             # explicit 'perl' in front:
85 1         3 push @asTry, map { ("$_.bat", "$Config{perlpath} $_") } @asTry;
  3         110  
86 1         13 DEBUG && print STDERR Dumper(\@asTry);
87             WEBSEARCH_TRY:
88 1         3 foreach my $sTry (@asTry)
89             {
90 1         3 my $sCmd = "$sTry --VERSION";
91 1         2 DEBUG && print STDERR " + W::S::T::find_websearch() cmd ==$sCmd==\n";
92             # Turn off warnings:
93 1         4 local $^W = 0;
94             # Wrap it in an eval so we don't die if it fails:
95 1         2 my @as = split(/\s/, eval{`$sCmd`});
  1         170028  
96 1   50     65 $websearch = shift(@as) || undef;
97 1 50       52 last WEBSEARCH_TRY if $websearch;
98             } # foreach
99             # Prevent undef warning:
100 1   50     24 $websearch ||= '';
101 1 50       42 undef $websearch unless ($websearch =~ m/WebSearch/);
102             # print STDERR "in WWW::Search::Test, websearch is $websearch\n";
103             } # unless
104 2         36 return $websearch;
105             } # find_websearch
106              
107              
108             =head2 new
109              
110             Create a new WWW::Search::Test object.
111             All arguments are strings, names of backends that this object will be able to test.
112             If no arguments are given, will be able to test all backends.
113              
114             =cut
115              
116             sub new
117             {
118 0     0 1   my $class = shift;
119 0           my $sEngines = join(',', '', @_, '');
120              
121 0           return bless {
122             debug => 0,
123             engines => $sEngines,
124             error_count => 0,
125             mode => $MODE_DUMMY,
126             verbose => 0,
127             # websearch => $websearch, # why do we need this?
128             }, $class;
129             } # new
130              
131              
132             =head2 mode
133              
134             Set / get the test mode of this object.
135             If an argument is given, sets the mode to that value.
136             Returns the current (or newly set) value.
137              
138             There are three test modes available. They are:
139              
140             $MODE_INTERNAL: parse URLs out of saved pages (as a sanity check or regression test);
141             $MODE_EXTERNAL: send the query to the search engine "live", parse the results, and compare them to the previously saved results;
142             and
143             $MODE_UPDATE: send the query to the search engine "live", parse the results, and save them for future testing.
144              
145             =cut
146              
147             sub mode
148             {
149 0     0 1   my $self = shift;
150 0           my $new_mode = shift;
151 0 0         if ($new_mode)
152             {
153 0           $self->{'mode'} = $new_mode;
154             }
155 0           return $self->{'mode'};
156             } # mode
157              
158             =head2 relevant_test
159              
160             Given the name of a backend,
161             returns true if this Test object is able to test that backend.
162              
163             =cut
164              
165             sub relevant_test
166             {
167 0     0 1   my $self = shift;
168 0 0         return 1 if ($self->{engines} eq ',,');
169 0           my $e = ','.shift().',';
170             # print STDERR " + relevant_test($e|", $self->{engines}, ")\n";
171 0           return ($self->{engines} =~ m/$e/);
172             } # relevant_test
173              
174              
175             =head2 eval_test
176              
177             Given the name of a backend,
178             grabs the $TEST_CASES variable from that backend and evaluates it.
179              
180             =cut
181              
182             sub eval_test
183             {
184 0     0 1   my $self = shift;
185 0           my $sSE = shift;
186 0 0         return unless $self->relevant_test($sSE);
187 0           my $o = new WWW::Search($sSE);
188 0           my $iVersion = $o->version;
189 0           my $code = $o->test_cases;
190 0   0       $code ||= '';
191 0 0         unless ($code ne '')
192             {
193 0           print " $sSE version $iVersion contains no TEST_CASES\n";
194 0           $self->{error_count}++;
195             }
196             # print STDERR " BEFORE SUBST: $code\n";
197 0           $code =~ s!&test\(!\$self->test\(!g;
198 0           $code =~ s/&no_test\(/\$self->no_test\(/g;
199 0           $code =~ s/¬_working\(/\$self->not_working\(/g;
200 0           $code =~ s/¬_working_and_abandoned\(/\$self->not_working_and_abandoned\(/g;
201 0           $code =~ s/¬_working_with_tests\(/\$self->not_working_with_tests\(/g;
202             # print STDERR " AFTER SUBST: $code\n";
203 0           print "\n"; # put a little space between each engine's results
204 0           eval $code;
205 0 0         warn $@ if $@;
206             } # eval_test
207              
208              
209             =head2 test
210              
211             Run test(s) for a backend.
212             Arguments are, in order:
213             name of a backend to test (string, required);
214             name of backend maintainer (string, if undef $backend::MAINTAINER will be used);
215             filename for results storage/comparison (string, required);
216             query to be sent to backend (string, required);
217             test method (required, one of the following).
218              
219             Several test methods are possible:
220              
221             $TEST_EXACTLY: list of URLs must match exactly (line for line, in order);
222             $TEST_BY_COUNTING: test passes if number of resulting URLs is equal;
223             $TEST_GREATER_THAN: test passes if we get more than N result URLs;
224             and
225             $TEST_RANGE: like $TEST_GREATER_THAN but constrained on both ends.
226              
227             =cut
228              
229             sub test
230             {
231 0     0 1   my $self = shift;
232 0           my $sSE = shift;
233 0           my $sM = shift;
234 0           my $file = shift;
235 0           my $query = shift;
236 0           my $test_method = shift;
237 0 0         print STDERR " + test($sSE,$sM,$file,$query,$test_method)\n" if $self->{debug};
238 0           my ($low_end, $high_end) = @_;
239 0   0       $low_end ||= 0;
240 0   0       $high_end ||= 0;
241 0           my $sExpected = $low_end;
242 0 0         if ($test_method == $TEST_GREATER_THAN)
243             {
244 0           $low_end++;
245 0           $sExpected = "$low_end..";
246             }
247 0 0         if (0 < $high_end)
248             {
249 0           $sExpected = "$low_end..$high_end";
250             }
251 0 0         return if (!$self->relevant_test($sSE));
252 0           print " trial $file (", $self->{'mode'}, ")\n";
253 0 0 0       if (($self->{'mode'} eq $MODE_INTERNAL) && ($query =~ m/$bogus_query/))
254             {
255 0           print " skipping test on this platform.\n";
256 0           return;
257             } # if
258              
259 0           my $pwd = curdir();
260 0           my @asSE = split(/::/, $sSE);
261 0           my $path = catdir($pwd, 'Test-Pages', @asSE);
262 0           mkpath $path;
263 0 0         if ($self->{'mode'} eq $MODE_UPDATE)
264             {
265             # Delete all existing test result files for this Engine:
266 0           opendir DIR, $path;
267 0           foreach my $afile (readdir DIR)
268             {
269 0 0         unlink catfile($path, $afile) if $afile =~ m/^$file/;
270             } # foreach
271 0           closedir DIR;
272             } # if MODE_UPDATE
273             # Look at the filename argument we got:
274 0           my ($v,$d,$f) = splitpath($file);
275             # If it contains no path element (file name only):
276 0 0         if ($d eq '')
277             {
278             # Prepend path onto file:
279 0           $file = catfile($path, $file);
280             } # if
281 0           my $o = new WWW::Search($sSE);
282 0           my $version = $o->version;
283 0           print " ($sSE $version, $sM)\n";
284 0 0         print STDERR " expect to find results in $file\n" if $self->{debug};
285 0           my %src = (
286             $MODE_INTERNAL => "--option search_from_file=$file",
287             $MODE_EXTERNAL => '',
288             $MODE_UPDATE => "--option search_to_file=$file",
289             );
290             # --max 209 added by Martin Thurn 1999-09-27. We never want to
291             # fetch more than three pages, if we can at all help it (or do we?)
292 0           my $websearch = &find_websearch;
293 0   0       $websearch ||= catfile($pwd, 'blib', 'script', 'WebSearch');
294 0           my $cmd = $Config{'perlpath'} . " -MExtUtils::testlib $websearch ";
295 0 0         $cmd .= $self->{debug} ? '--debug '.$self->{debug} : '';
296 0           $cmd .= " --max 209 --engine $sSE ". $src{$self->{'mode'}} ." -- $query";
297 0 0 0       print " $cmd\n" if ($self->{verbose} || $self->{debug});
298 0 0         open(TRIALSTREAM, "$cmd|") || die "$0: cannot run test ($!)\n";
299 0 0         open(TRIALFILE, ">$file.trial") || die "$0: cannot open $file.trial for writing ($!)\n";
300 0 0 0       open(OUTFILE, ">$file.out") || die "$0: cannot open $file.out for writing ($!)\n" if ($self->{'mode'} eq $MODE_UPDATE);
301 0           my $iActual = 0;
302 0           while ()
303             {
304 0           print TRIALFILE $_;
305 0           $iActual++;
306 0 0         print OUTFILE $_ if ($self->{'mode'} eq $MODE_UPDATE);
307             }
308 0           close TRIALSTREAM;
309 0           close TRIALFILE;
310 0 0         if ($self->{'mode'} eq $MODE_UPDATE)
311             {
312 0           close OUTFILE;
313 0 0         if (open TS, ">$file.README")
314             {
315 0           print TS "This set of test-result pages was created on ", scalar(localtime(time)), "\n";
316 0           close TS;
317             } # if
318 0           my $iPageCount = &wc_l($file);
319 0           my $iURLCount = &wc_l("$file.out");
320 0           print " $query --> $iURLCount urls (should be $sExpected) on $iPageCount pages\n";
321 0           return;
322             } # if
323              
324 0 0         if (-f "$file.out")
325             {
326 0           my ($e, $sMsg) = (0, '');
327 0 0         if ($test_method == $TEST_GREATER_THAN)
    0          
    0          
    0          
328             {
329 0 0         if ($iActual <= $low_end)
330             {
331 0           $sMsg .= "expected more than $low_end, but got $iActual; ";
332 0           $e = 1;
333             }
334             } # TEST_GREATER_THAN
335             elsif ($test_method == $TEST_RANGE)
336             {
337 0 0         $sMsg .= "INTERNAL ERROR, low_end has no value; " unless defined($low_end);
338 0 0         $sMsg .= "INTERNAL ERROR, high_end has no value; " unless defined($high_end);
339 0 0         $sMsg .= "INTERNAL ERROR, high_end is zero; " unless 0 < $high_end;
340 0 0         if ($iActual < $low_end)
341             {
342 0           $sMsg .= "expected $low_end..$high_end, but got $iActual; ";
343 0           $e = 1;
344             }
345 0 0         if ($high_end < $iActual)
346             {
347 0           $sMsg .= "expected $low_end..$high_end, but got $iActual; ";
348 0           $e = 1;
349             }
350             } # TEST_RANGE
351             elsif ($test_method == $TEST_EXACTLY)
352             {
353 0 0         $e = &diff("$file.out", "$file.trial") ? 1 : 0;
354             } # TEST_EXACTLY
355             elsif ($test_method == $TEST_BY_COUNTING)
356             {
357 0           my $iExpected = shift;
358 0           my $iActual = &wc_l("$file.trial");
359 0 0         if ($iActual != $iExpected)
360             {
361 0           $sMsg .= "expected $iExpected, but got $iActual; ";
362 0           $e = 1;
363             }
364             }
365             else
366             {
367 0           $e = 0;
368 0           $sMsg = "INTERNAL ERROR, unknown test method $test_method; ";
369             }
370              
371 0 0         if ($e == 0)
    0          
372             {
373 0           print " ok.\n";
374 0           unlink("$file.trial"); # clean up
375             }
376             elsif ($e == 1)
377             {
378 0           print "DIFFERENCE DETECTED: $query --> $sMsg\n";
379 0           $self->{error_count}++;
380             }
381             else
382             {
383 0           print "INTERNAL ERROR $query --> e is $e.\n";
384 0           $self->{error_count}++;
385             }
386             }
387             else
388             {
389 0           print "NO SAVED OUTPUT, can not evaluate test results.\n";
390 0           $self->{error_count}++;
391             }
392             } # test
393              
394             =head2 no_test
395              
396             Prints a message stating that this backend does not have a test suite.
397             Takes two arguments, the backend name and the name of the maintainer.
398              
399             =cut
400              
401             sub no_test
402             {
403 0     0 1   my $self = shift;
404 0           my ($engine, $maint) = @_;
405 0 0         return unless ($self->relevant_test($engine));
406 0           print <<"NONE";
407             trial none ($engine)
408             This search engine does not have any tests,
409             but report problems with it to $maint.
410             NONE
411             } # no_test
412              
413              
414             =head2 not_working
415              
416             Prints a message stating that this backend is known to be broken.
417             Takes two arguments, the backend name and the name of the maintainer.
418              
419             =cut
420              
421             sub not_working
422             {
423 0     0 1   my $self = shift;
424 0           my ($engine, $maint) = @_;
425 0 0         return unless ($self->relevant_test($engine));
426 0           print <<"BROKEN";
427             trial none ($engine)
428             This search engine is known to be non-functional.
429             You are encouraged to investigate the problem and email its maintainer,
430             $maint.
431             BROKEN
432             } # not_working
433              
434              
435             =head2 not_working_with_tests
436              
437             Prints a message stating that this backend is known to be broken
438             even though it has a test suite.
439             Takes two arguments, the backend name and the name of the maintainer.
440              
441             =cut
442              
443             sub not_working_with_tests
444             {
445 0     0 1   my $self = shift;
446 0           my ($engine, $maint) = @_;
447 0 0         return if (!$self->relevant_test($engine));
448 0           print <<"KNOWNFAILURE";
449             trial none ($engine)
450             Test cases for this search engine are known to fail.
451             You are encouraged to investigate the problem and email its maintainer,
452             $maint.
453             KNOWNFAILURE
454             } # not_working_with_tests
455              
456              
457             =head2 not_working_and_abandoned
458              
459             Prints a message stating that this backend is known to be broken
460             and is not being actively maintained.
461             Takes two arguments, the backend name and the name of the maintainer.
462              
463             =cut
464              
465             sub not_working_and_abandoned
466             {
467 0     0 1   my $self = shift;
468 0           my ($engine, $maint) = @_;
469 0 0         return if (!$self->relevant_test($engine));
470 0           print <<"ADOPT";
471             trial none ($engine)
472             This search engine is known to be non-functional.
473             You are encouraged to adopt it from its last known maintainer,
474             $maint.
475             ADOPT
476             } # not_working_and_abandoned
477              
478              
479             =head2 reset_error_count
480              
481             Reset the counter of errors to zero.
482             You probably want to call this before each call to test() or eval_test().
483              
484             =cut
485              
486             sub reset_error_count
487             {
488 0     0 1   my $self = shift;
489 0           $self->{error_count} = 0;
490             } # reset_error_count
491              
492              
493             =head2 wc_l (private, not a method)
494              
495             Given a filename, count the number of lines of text contained
496             within the file.
497             (I.e. simulate running UNIX command C on a file)
498              
499             =cut
500              
501             sub wc_l
502             {
503             # SPECIAL CASE: If first line is "Nothing found.", report 0 lines.
504 0 0   0 1   open WC, shift or return 0;
505 0           $/ = "\n";
506 0           my $i = 0;
507 0           while ()
508             {
509 0 0         last if /Nothing found./;
510 0           $i++;
511             } # while
512 0           return $i;
513             } # wc_l
514              
515              
516             =head2 diff (private, not a method)
517              
518             Given two files, returns TRUE if contents are line-by-line
519             different, or FALSE if contents are line-by-line same.
520             (I.e. like the UNIX command diff, but just reports true or false)
521              
522             =cut
523              
524             sub diff
525             {
526 0 0   0 1   open DIFF1, shift or return 91;
527 0 0         open DIFF2, shift or return 92;
528 0           my $iResult = 0;
529 0           $/ = "\n";
530 0   0       while ((defined(my $s1 = )) &&
531             ($iResult ne 1))
532             {
533 0           my $s2 = ;
534 0 0         unless (defined($s2))
535             {
536 0           $iResult = 1;
537 0           last;
538             }
539 0           chomp $s1;
540 0           chomp $s2;
541 0 0         if ($s1 ne $s2)
542             {
543 0           $iResult = 1;
544 0           last;
545             }
546             } # while
547 0           close DIFF1;
548 0           close DIFF2;
549 0           return $iResult;
550             } # diff
551              
552              
553             =head2 Shortcuts for running backend tests
554              
555             WWW::Search::Test keeps its own count of test numbers,
556             so if you want to mix-and-match these functions with your own tests,
557             use the $WWW::Search::Test::iTest counter.
558              
559             =head2 new_engine
560              
561             One argument: the name of a backend suitable to be passed to WWW::Search::new().
562             Prints 'ok' or 'not ok' and the test number.
563             Creates a WWW::Search object internally,
564             to be used for all subsequent calls to run_test and run_gui_test (see below).
565              
566             =cut
567              
568             sub new_engine
569             {
570 0     0 1   $iTest++;
571 0           $sEngine = shift;
572 0           $oSearch = new WWW::Search($sEngine);
573 0 0         print ref($oSearch) ? '' : 'not ';
574 0           print "ok $iTest\n";
575 0           $oSearch->env_proxy('yes');
576             } # new_engine
577              
578             =head2 tm_new_engine
579              
580             Same as new_engine(), but uses Test::More instead of just printing 'ok'.
581              
582             =cut
583              
584             sub tm_new_engine
585             {
586 0     0 1   my $sEngine = shift;
587 0           $oSearch = new WWW::Search($sEngine);
588 0           Test::More::ok(ref($oSearch), "instantiate WWW::Search::$sEngine object");
589 0           $oSearch->env_proxy('yes');
590             } # tm_new_engine
591              
592             =head2 run_test
593              
594             Three arguments: a query string, NOT escaped;
595             a minimum number of expected results; and
596             a maximum number of expected results.
597             Optional fourth argument: integer value to be used as the search_debug.
598             Optional fifth argument: send any true value to dump the search results.
599             Optional sixth argument: reference to hash of search options (see backend documentation).
600             Optional seventh argument: send any true value to NOT escape the query string.
601              
602             If the minimum is undef, assumes zero.
603             If the maximum is undef, does not check.
604              
605             Prints 'ok' or 'not ok' and the test number.
606              
607             =cut
608              
609             sub run_test
610             {
611 0     0 1   return &_run_our_test('normal', @_);
612             } # run_test
613              
614             =head2 run_gui_test
615              
616             Same as run_test(), but calls gui_query() instead of native_query().
617              
618             =cut
619              
620             sub run_gui_test
621             {
622 0     0 1   return &_run_our_test('gui', @_);
623             } # run_gui_test
624              
625              
626             =head2 tm_run_test
627              
628             Same as run_test(), but uses Test::More rather than just printing 'ok'.
629              
630             Note: If you use this function inside a TODO block,
631             you must set global variable $TODO rather than a local $TODO,
632             and you must set the global $TODO back to empty-string (or undef) at the end of your TODO block.
633             For example:
634              
635             TODO:
636             {
637             $TODO = 'I have not fixed this yet';
638             tm_run_test(...);
639             $TODO = '';
640             } # end of TODO block
641              
642             =cut
643              
644             sub tm_run_test
645             {
646 0     0 1   _tm_run_test(@_, 1);
647             } # tm_run_test
648              
649             sub _tm_run_test
650             {
651             # Last argument is boolean, whether to check approx_result_count:
652 0   0 0     my $iApprox = pop(@_) || 0;
653             # Remaining args, same as count_results():
654 0           my ($sType, $sQuery, $iMin, $iMax) = @_;
655 0           my $iCount = count_results(@_);
656 0           my $iAnyFailure = 0;
657 0 0         $iAnyFailure++ unless Test::More::is($oSearch->response->code, 200, 'got valid HTTP response');
658 0 0         if (defined $iMin)
659             {
660 0 0         $iAnyFailure++ unless Test::More::cmp_ok($iMin, '<=', $iCount,
661             qq{lower-bound num-hits for query=$sQuery});
662 0 0         if ($iApprox)
663             {
664 0 0         $iAnyFailure++ unless Test::More::cmp_ok($iMin, '<=', $oSearch->approximate_result_count,
665             qq{lower-bound approximate_result_count});
666             } # if
667             } # if
668 0 0         if (defined $iMax)
669             {
670 0 0         $iAnyFailure++ unless Test::More::cmp_ok($iCount, '<=', $iMax,
671             qq{upper-bound num-hits for query=$sQuery});
672 0 0         if ($iApprox)
673             {
674 0 0         $iAnyFailure++ unless Test::More::cmp_ok($oSearch->approximate_result_count, '<=', $iMax,
675             qq{upper-bound approximate_result_count});
676             } # if
677             } # if
678 0   0       $sSaveOnError ||= q'';
679 0 0 0       if ($iAnyFailure && ($sSaveOnError ne q''))
680             {
681 0           write_file($sSaveOnError, { err_mode => 'quiet'}, $oSearch->response->content);
682 0           Test::More::diag(qq'HTML was saved in $sSaveOnError');
683             } # if
684             } # _tm_run_test
685              
686             =head2 tm_run_test_no_approx
687              
688             Same as tm_run_test, but does NOT check the approximate_result_count.
689              
690             =cut
691              
692             sub tm_run_test_no_approx
693             {
694 0     0 1   _tm_run_test(@_, 0);
695             } # tm_run_test_no_approx
696              
697             =head2 count_results
698              
699             Run a query, and return the actual (not approximate) number of hits.
700             Required first argument determines which backend query method to call: 'gui' to call gui_query(), anything else to call native_query().
701             Remaining arguments are same as all the run_test() arguments.
702              
703             =cut
704              
705             sub count_results
706             {
707 0     0 1   my ($sType, $sQuery, $iMin, $iMax, $iDebug, $iPrintResults, $rh, $iDoNotEscape) = @_;
708             # print STDERR qq{ DDD count_results raw args($sType,$sQuery,$iMin,$iMax,$iDebug,$iPrintResults,$rh,$iDoNotEscape)\n};
709 0   0       $iDebug ||= 0;
710 0   0       $iPrintResults ||= 0;
711 0           $rh->{'search_debug'} = $iDebug;
712 0 0 0       carp ' --- min/max values out of order?' if (defined($iMin) && defined($iMax) && ($iMax < $iMin));
      0        
713 0           $oSearch->reset_search;
714 0   0       $iMin ||= 0;
715             # While $iMax is the number the user wants to compare, $iMaxAbs is
716             # the actual number we apply to the search:
717 0           my $iMaxAbs;
718 0 0         if (! defined($iMax))
719             {
720             # User said upper limit is 'undef'; just make sure we get the
721             # mininum:
722 0           $iMaxAbs = $iMin + 1;
723             } # if
724             else
725             {
726             # Give a little breathing room, so we'll notice if there are too
727             # many returned:
728 0           $iMaxAbs = $iMax + 1;
729             }
730 0           $oSearch->maximum_to_retrieve($iMaxAbs);
731 0           $iTest++;
732 0 0         $sQuery = WWW::Search::escape_query($sQuery) unless $iDoNotEscape;
733             # print STDERR " + in WWW::Search::Test::count_results, iDebug = $iDebug\n";
734 0 0         if ($sType eq 'gui')
735             {
736 0           $oSearch->gui_query($sQuery, $rh);
737             }
738             else
739             {
740 0           $oSearch->native_query($sQuery, $rh);
741             }
742 0           $oSearch->login($ENV{WWW_SEARCH_USERNAME}, $ENV{WWW_SEARCH_PASSWORD});
743 0           my @aoResults = $oSearch->results();
744 0 0         if ($iPrintResults)
745             {
746 0           my $i = 1;
747 0           foreach my $oResult (@aoResults)
748             {
749 0           print $i++, '. ', $oResult->url, "\n";
750 0           foreach my $sField (qw( title description score change_date index_date size company location source ))
751             {
752 0 0         print " $sField==", $oResult->$sField, "==\n" if defined($oResult->$sField);
753             } # foreach
754             } # foreach
755             } # if
756 0           return scalar(@aoResults);
757             } # count_results
758              
759              
760             sub _run_our_test
761             {
762 0     0     my ($sType, $sQuery, $iMin, $iMax, $iDebug, $iPrintResults) = @_;
763 0           my $iResults = &count_results(@_);
764 0           my $sExpect;
765 0 0         if (! defined($iMax))
    0          
766             {
767 0           $sExpect = "more than $iMin";
768             }
769             elsif (! defined($iMin))
770             {
771 0           $sExpect = "fewer than $iMax";
772             }
773             else
774             {
775 0           $sExpect = "$iMin..$iMax";
776             }
777 0 0         $iMax = 999999 unless defined ($iMax);
778 0 0 0       if (($iResults < $iMin) || ($iMax < $iResults))
779             {
780 0           print STDERR " --- got $iResults results for $sType $sEngine query '$sQuery', but expected $sExpect\n";
781 0           print STDOUT 'not ';
782             } # if
783 0           print STDOUT "ok $iTest\n";
784             } # _run_our_test
785              
786              
787             =head2 skip_test
788              
789             You can call this function instead of run_test() or run_gui_test()
790             if the current test must be skipped for any reason.
791              
792             =cut
793              
794             sub skip_test
795             {
796 0     0 1   $iTest++;
797 0           print STDOUT "skip $iTest\n";
798             } # skip_test
799              
800              
801             =head2 test_most_results
802              
803             Given an arrayref of things to test,
804             runs all those things against all the results of the most-recently executed test search.
805              
806             =cut
807              
808             sub test_most_results
809             {
810 0     0 1   my $rara = shift;
811 0   0       my $fPct = shift || 0.80;
812 0           my $iCount = scalar(@$rara);
813 0           my $iAnyFailed = my $iResult = 0;
814 0           my %hioExemplar;
815             my %hiiFailed;
816             # Create a bit vector large enough to hold one bit for each test:
817 0           my $oV = new Bit::Vector($iCount);
818             # Turn on all the bits (we will turn off bits when tests fail):
819 0           $oV->Fill;
820 0           my $iVall = $oV->to_Dec;
821 0           my $sCodeAll = q{};
822 0           my $iTest = 0;
823             TEST:
824 0           foreach my $ra (@$rara)
825             {
826             # print STDERR " DDD ra is ", Dumper($ra);
827 0           my ($sField, $sCmp, $sValue, $sDesc) = @$ra;
828 0   0       $sDesc ||= qq{test #$iTest};
829 0           my $sCode;
830 0 0         if ($sCmp eq 'like')
    0          
    0          
831             {
832 0           $sCode = "(\$oResult->$sField =~ m!$sValue!)";
833             } # if
834             elsif ($sCmp eq 'unlike')
835             {
836 0           $sCode = "(\$oResult->$sField !~ m!$sValue!)";
837             } # if
838             elsif ($sCmp eq 'date')
839             {
840 0           $sCode = "((ParseDate(\$oResult->$sField) || '') ne q{})";
841             } # if
842             else
843             {
844 0           $sCode = "(\$oResult->$sField $sCmp $sValue)";
845             }
846 0           $sCode = <<"ENDCODE";
847             if (! $sCode)
848             {
849             \$oV->Bit_Off($iTest);
850             \$hiiFailed{'$sDesc'}++;
851             } # if
852             ENDCODE
853 0           $sCodeAll .= $sCode;
854 0           $iTest++;
855             } # foreach TEST
856 0           $sCodeAll .= "1;\n";
857             # print STDERR " DDD the test is ===$sCodeAll===\n";
858             RESULT:
859 0           foreach my $oResult ($oSearch->results())
860             {
861 0           $iResult++;
862             # Turn on all the bits (we will turn off bits when tests fail):
863 0           $oV->Fill;
864             # print STDERR " DDD eval the test...\n";
865 0 0         if (! eval $sCodeAll)
866             {
867 0           print STDERR $@;
868             } # if
869             # Now look at the value of the Bit::Vector after running the tests:
870 0           my $iV = $oV->to_Dec;
871 0 0         if ($iV < $iVall)
872             {
873             # At least one of the bits got turned off (i.e. a test failed):
874 0           $hioExemplar{$iV} = $oResult;
875 0           $iAnyFailed++;
876             # For debugging:
877             # print STDERR Dumper($oResult);
878             # last RESULT;
879             } # if
880             } # foreach RESULT
881 0           ok($iResult, qq{got more than zero results ($iResult, to be exact)});
882             # Now make sure all the sub-tests passed at least N% of the time.
883             # We only need to look at sub-tests that had any failures (sub-tests
884             # with no failures are 100% correct, so there's no need to check
885             # them 8-)
886 0           while (my ($sItem, $iFailed) = each %hiiFailed)
887             {
888 0           my $fPctFailed = ($iFailed / $iResult);
889 0           ok($fPctFailed < (1 - $fPct), sprintf(qq{%0.1f%% of '%s' tests failed}, $fPctFailed * 100, $sItem));
890             } # while
891 0 0         if ($iAnyFailed)
892             {
893 0           Test::More::diag(" Here are result(s) that exemplify test failure(s):");
894 0           foreach my $oResult (values %hioExemplar)
895             {
896 0           Test::More::diag(Dumper($oResult));
897             } # while
898 0   0       $sSaveOnError ||= q'';
899 0 0         if ($sSaveOnError ne q'')
900             {
901 0           write_file($sSaveOnError, { err_mode => 'quiet'}, $oSearch->response->content);
902 0           Test::More::diag(qq'HTML was saved in $sSaveOnError');
903             } # if
904             } # if
905             } # test_most_results
906              
907             1;
908              
909             __END__