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