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