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