]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - tests/maketest.pl
Test all available backends, not just file
[SourceForge/phpwiki.git] / tests / maketest.pl
1 #!/usr/bin/perl
2
3 # $Id: maketest.pl,v 1.3 2002-01-29 22:10:24 wainstead Exp $
4
5 # read in a file, generate Java code to run a test.
6 # Steve Wainstead, March 2001.
7
8 # Naturally, this is not a recursive descent parser (sorry to disappoint you)
9 # but a fairly cut and dry script relying on "if" clauses to parse the input
10 # files. It was the shortest route to the answer for now, though certainly not
11 # the best one.
12
13 use constant BASEURL => 'http://127.0.0.1/~swain/projects/phpwiki-1.3.x/';
14
15 die <<"EOLN" unless $ARGV[0];
16
17 Usage: $0 <inputfile0> [ <inputfile1> <inputfile2> ... <inputfileN> ]
18     where 'inputfile' is the name of a configuration file that specifies
19     the form fields and values. The name of the file should be similar to
20     ClassName.inputs, and this script will produce a Java file called
21     ClassName.java. 
22 EOLN
23
24 #print "passed in: ", join(" ", @ARGV), "\n";
25
26 my ($start_of_file, $end_of_file);
27
28 # read in the skeleton file from this script below the END tag
29 while (<DATA>) {
30     last if /PRINT_TEST_CODE/;
31     $start_of_file .= $_;
32 }
33
34 while (<DATA>) {
35     $end_of_file .= $_;
36 }
37     
38
39 while ($inputfile = shift(@ARGV)) {
40     
41     $inputfile =~ /(\w+)\.inputs$/;
42     my $classname = $1 || 'Test';
43     $start_of_file =~ s/__CLASSNAME__/$classname/g;
44     $end_of_file    =~ s/__CLASSNAME__/$classname/g;
45     
46     open OUTFILE, ">${classname}.java" 
47         or die "Can't open '${classname}.java' for writing: $!\n";
48     
49     
50     # start each new file with a timestamp and user name
51     print OUTFILE "// This file was automatically generated on ", 
52         scalar localtime(), " by $ENV{USER}\n";
53     
54
55     print OUTFILE $start_of_file;
56
57     # read in the file in chunks with "go\n" as the record separator
58     local($/) = "go\n";
59
60     open FILE, "<$inputfile" 
61         or do {
62            close OUTFILE;
63            unlink "${classname}.java";
64            die "Can't read config file '$inputfile': $!\n";
65         };
66     
67
68     # set the response message/output... this is output after each "go" block
69     # is run.
70     $response = <<"EOLN";
71     
72                 //System.out.println( "Here's the metadata for the response:" );
73                 //System.out.println( "URL: " + response.getURL() );
74                 //System.out.println( "Page title: " + response.getTitle() );
75                 //System.out.println( "Response code: " + response.getResponseCode() );
76                 //System.out.println( response );
77                 //System.out.println( transaction_boundary );
78     
79 EOLN
80
81
82     # here is where we do the "parsing" of the .inputs file.
83     while ($block = <FILE>) {
84     
85         next unless $block =~ /go$/;
86         
87         if ($block =~ /type:\s*starting_page/) {
88             starting_page($block);
89         } elsif ($block =~ /type:\s*fill_and_submit_form/) {
90             fill_and_submit_form($block);
91         } elsif ($block =~ /type:\s*follow_link/) {
92             follow_link($block);
93         } elsif ($block =~ /type:\s*follow_image_link/) {
94             follow_image_link($block);
95         } else {
96         # error
97             die "This block does not match any known action:\n$block\n";
98         }
99         
100     }
101     
102     print OUTFILE $end_of_file;
103
104 }    
105
106
107
108 # End of main... subs are next, followed by the boilerplate code for the 
109 # java files after the END thingie. What is that thingie called?
110
111 sub starting_page {
112     my $block = shift;
113     $block =~ m/start_url:\s*(http.*?)$/m;
114     my $start_url = BASEURL . $1;
115     my $assertions = &get_assertions($block);
116
117     print OUTFILE <<"EOLN"
118
119             System.out.println( "Name for this test: " + dealname );
120
121             // make a request object for the conversation object
122             try {
123                 myurl = "$start_url";
124                 request = new GetMethodWebRequest( myurl );
125                 response = conversation.getResponse( request );
126             } catch (Exception e) {
127                 throw new Exception("Couldn't get a page from URL '$start_url'\\n" + e);
128             }
129             $assertions
130             $response
131
132 EOLN
133 }
134
135 sub follow_link {
136     my $block = shift;
137     $block =~ m/follow_link:\s*(".*?")$/m;
138     my $link_text = $1;
139     my $assertions = &get_assertions($block);
140
141     print OUTFILE <<"EOLN";
142
143             // follow a plain link with text '$link_text'
144             linkname = $link_text;
145             link_to_follow = response.getLinkWith(linkname);
146
147             if (link_to_follow == null)
148                 throw new Exception("The link '" + linkname + "' was not found.");
149
150             request = link_to_follow.getRequest();
151             System.out.println( request );
152
153             try {
154                 response = conversation.getResponse( request );
155             } catch (Exception r) {
156                 throw new Exception(r + "\\nCouldn't follow the link!\\n" +
157                                     "Request was:\\n" + request + "\\n");
158             }
159             $assertions
160             $response
161
162 EOLN
163
164 }
165
166 sub follow_image_link {
167     my $block = shift;
168     $block =~ m/follow_image_link:\s*(".*?")$/m;
169     my $link_name = $1;
170     my $assertions = &get_assertions($block);
171
172     print OUTFILE <<"EOLN";
173
174             // follow an image link with text '$link_name'
175             linkname = $link_name;
176             link_to_follow = response.getLinkWithImageText(linkname);
177
178             if (link_to_follow == null)
179                 throw new Exception("The link '" + linkname + "' was not found.");
180
181             request = link_to_follow.getRequest();
182             System.out.println( request );
183
184             try {
185                 response = conversation.getResponse( request );
186             } catch (Exception r) {
187                 throw new Exception(r + "\\nCouldn't follow the image link!\\n" +
188                                     "Request was:\\n" + request + "\\n");
189             }
190             $assertions
191             $response
192
193 EOLN
194
195 }
196
197 sub fill_and_submit_form {
198     my $block = shift;
199     @lines = make_array_from_block($block);
200
201     my ($form_num, $submit_num, $form_name, $submit_name);
202     my $requests = "\n";
203     my $assertions = &get_assertions($block);
204
205     for (@lines) { 
206         if ( /form_num:\s*(\d)/ ) {
207             $form_num = $1;
208         } elsif ( /submitbutton_num:\s*(\d)/ ) {
209             $submit_num = $1;
210         } elsif ( /form_name:\s*(\w+)/ ) {
211             $form_name = $1;
212             #print "form name: '$form_name'\n";
213         } elsif ( /submitbutton_name:\s*(\w+)/ ) {
214             $submit_name = $1;
215             #print "submit name: '$submit_name'\n";
216         } elsif ( /setparam:\s*(.+)$/ ) {
217             $requests .= "            request.setParameter($1);\n";
218         }
219     }
220     unless ( (defined $form_num || defined $form_name)
221             && (defined $submit_num || defined $submit_name)
222             && defined $requests) {
223         die <<"        EOLN";
224
225             Missing variable:
226             form_num: '$form_num' (you need either form_num or form_name)
227             submit_num: '$submit_num' (you need either submit_num or submit_name)
228             form_name: '$form_name'
229             submit_name: '$submit_name'
230             requests: '$requests'
231         EOLN
232     }
233
234     # provide a bit of minor error detection...
235     if ( defined $form_num && defined $form_name) {
236         die <<"        EOLN";
237
238         You can't have both a form number and a form name defined
239         (got form_num '$form_num' and form_name '$form_name' for
240         block:\n$block
241         EOLN
242     }
243
244     if ( defined $submit_num && defined $submit_name) {
245         die <<"        EOLN";
246
247         You can't have both a submit button number and a 
248         submit button name defined
249         (got submit_num '$submit_num' and submit_name '$submit_name' for
250         block:\n$block
251         EOLN
252     }
253
254     if (defined $form_num) {
255         $form_code = <<"EOLN";
256
257             htmlforms = response.getForms();
258
259             if (htmlforms == null || htmlforms.length == 0)
260                 throw new Exception("No HTML form found for:\\n" + response);
261
262             htmlform = htmlforms[$form_num];
263 EOLN
264     } elsif (defined $form_name) {
265         $form_code = <<"EOLN";
266
267             htmlform = response.getFormWithName("$form_name");
268             if (htmlform == null)
269                 throw new Exception("No HTML form named '$form_name' found for:\\n" 
270                                    + response);
271 EOLN
272
273     } else {
274         # error
275         die "Didn't get a form_name or form_num for this block:\n$block\n";
276     }
277
278
279     if (defined $submit_num) {
280         $submit_button_code = <<"EOLN";
281
282             submitButtonArray = htmlform.getSubmitButtons();
283
284             if (submitButtonArray == null || submitButtonArray.length == 0)
285                 throw new Exception("Didn't get a submit button array in "
286                                     + "response object:\\n");
287
288
289             request = htmlform.getRequest(submitButtonArray[$submit_num]);
290 EOLN
291     } elsif (defined $submit_name) {
292         $submit_button_code = <<"EOLN";
293
294             submitbutton = htmlform.getSubmitButton("$submit_name");
295             if (submitbutton == null)
296                 throw new Exception("Couldn't fine a submit button "
297                                   + "named '$submit_name'\\n"
298                                   + response);
299             request = htmlform.getRequest(submitbutton);
300
301 EOLN
302     } else {
303         # error
304         die "Didn't get a submit_num or submit_name for this block:\n$block\n";
305     }
306         
307     print OUTFILE <<"    EOLN";
308
309             // get and fill the HTML form
310             $form_code
311             $submit_button_code
312             try {
313                 $requests
314             } catch (Exception n) {
315                 throw new Exception( n
316                                      + "\\nCouldn't set a parameter in this request:\\n"
317                                      + request );
318             }
319
320             try {
321                 response = conversation.getResponse( request );
322             } catch (Exception r) {
323                 throw new Exception(r + "\\nCouldn't submit the form!\\n" +
324                                     "Request was:\\n" + request + "\\n");
325             }
326             $assertions
327             $response
328
329     EOLN
330
331 }
332
333
334 sub get_assertions {
335     my $block = shift;
336     my $return_text = &assert_url($block);
337     $return_text .=   &assert_title($block);
338     $return_text .=   &assert_field($block);
339     $return_text .=   &assert_text($block);
340     #print "Return text:\n$return_text\n";
341     return $return_text;
342 }
343
344 sub assert_url {
345  
346     my $block = shift;
347     return unless $block =~ /^assert_url:\s*(.*?)$/m;
348
349     my $url = $1;
350     
351     return <<"EOLN";
352
353             // assert the URL
354             if ( response.getURL().toString().indexOf( "$url" ) != -1)
355                 System.out.println("\tURL match: matched '$url' OK");
356             else
357                 throw new Exception ("URL match: Didn't match URL '$url' ERROR");
358 EOLN
359 }
360
361 # assert that the title of the page is correct
362 sub assert_title {
363
364     my $block = shift;
365     return unless $block =~ /^assert_title:\s*(.*?)$/m;
366
367     my $title = $1;
368
369     return <<"EOLN";
370
371             // assert the page title
372             if ( response.getTitle().toString().indexOf( "$title" ) != -1)
373                 System.out.println("\tTitle match: Matched '$title' OK");
374             else
375                 throw new Exception("Title match: did not match title '$title' ERROR");
376 EOLN
377 }
378
379 # assert that a form field matches a value
380 sub assert_field {
381
382     my $block = shift;
383     return unless $block =~ /assert_field/m;
384
385     my @lines = &make_array_from_block($block);
386     my $return_text = "";
387
388     foreach my $line (@lines) {
389
390         if ($line =~ /^assert_field:\s*(\d|"\w+")\s*("[^"]+")\s*("[^"]+")\s*$/) {
391             my $form   = $1;
392             my $field_name = $2;
393             my $field_val  = $3;
394
395             if ($form =~ /^\d+$/) {
396                 $getform_string = "response.getForms()[$form].getParameterValue($field_name)";
397             } else {
398                 $getform_string = "response.getFormWithName($form).getParameterValue($field_name)";
399             }
400
401             #print "$getform_string\n";
402
403             $return_text .= <<"EOLN";
404
405             // assertion: form '$form', field '$field_name' == '$field_val'
406             if ( ${field_val}.equals($getform_string) )
407                 System.out.println("\tField match: '" + $field_name + "' held '" + $field_val + "' OK");
408             else
409                 throw new Exception ("Field match: Field '" + $field_name + "' didn't match '" + $field_val + "' ERROR");
410 EOLN
411
412
413         }
414     }
415
416     return $return_text;
417 }
418
419
420 sub assert_text {
421     my $block = shift;
422     return unless $block =~ /assert_text/m;
423
424     my @lines = &make_array_from_block($block);
425     my $return_text = "";
426
427     foreach my $line (@lines) {
428         if ($line =~ /^assert_text:\s*(.*)$/) {
429             my $search_string = $1;
430
431             $return_text .= <<"EOLN";
432
433             // find the text string '$search_string' in the page source
434             if ( response.getText().indexOf( "$search_string" ) != -1)
435                 System.out.println( "I found the text '$search_string' in the page OK" );
436             else 
437                 throw new Exception( "Couldn't find text: '$search_string'" );
438
439 EOLN
440
441     return $return_text;
442
443         }
444     }
445 }
446
447 sub make_array_from_block {
448     my $block = shift;
449     my @return_array;
450     my @lines = split /\n/, $block;
451     foreach $line (@lines) {
452         next if $line =~ /^#/;
453         next unless $line =~ /\w/;
454         next if $line =~ /^go/;
455         push @return_array, $line;
456     }
457     return @return_array;
458 }
459
460
461 __END__
462 import com.meterware.httpunit.*;
463
464 import java.io.IOException;
465 import java.net.MalformedURLException;
466 import java.util.*;
467 import java.text.*;
468
469 import org.xml.sax.*;
470
471 public class __CLASSNAME__ {
472
473     public static void main( String[] params ) {
474
475         boolean             success = true;
476
477         try {
478             WebRequest          request;
479             WebResponse         response;
480             WebConversation     conversation = new WebConversation();
481             WebForm[]           htmlforms;
482             WebForm             htmlform;
483             SubmitButton[]      submitButtonArray;
484             SubmitButton        submitbutton;
485             WebLink             link_to_follow;
486             String              myurl;
487             String              linkname;
488             String              dealname = makeUniqueDealName("__CLASSNAME__ Test");
489             String              transaction_boundary = "This is a transaction boundary.";
490
491             /* PRINT_TEST_CODE */
492
493         } catch (Exception e) {
494             System.err.println( "Exception: " + e );
495             success = false;
496         } finally {
497             if (success == true) {
498                 System.out.println( "__CLASSNAME__ test successful." );
499             } else {
500                 System.out.println( "__CLASSNAME__ test failed." );
501             }
502
503         }
504     }
505
506
507     public static String makeUniqueDealName(String dealname) {
508         Date today = new Date();
509         DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT,
510                                                        DateFormat.MEDIUM);
511         return dealname + " " + df.format(today);
512     }
513
514 }
515