xref: /openbsd-src/gnu/usr.bin/perl/cpan/ExtUtils-Constant/t/Constant.t (revision be691f3bb6417f04a68938fadbcaee2d5795e764)
1#!/usr/bin/perl -w
2
3use Config;
4unless ($Config{usedl}) {
5    print "1..0 # no usedl, skipping\n";
6    exit 0;
7}
8
9# use warnings;
10use strict;
11use ExtUtils::MakeMaker;
12use ExtUtils::Constant qw (C_constant autoload);
13use File::Spec;
14use Cwd;
15
16my $do_utf_tests = $] > 5.006;
17my $better_than_56 = $] > 5.007;
18# For debugging set this to 1.
19my $keep_files = 0;
20$| = 1;
21
22# Because were are going to be changing directory before running Makefile.PL
23# 5.005 doesn't have new enough File::Spec to have rel2abs. But actually we
24# only need it when $^X isn't absolute, which is going to be 5.8.0 or later
25# (where ExtUtils::Constant is in the core, and tests against the uninstalled
26# perl)
27my $perl = $] < 5.006 ? $^X : File::Spec->rel2abs($^X);
28# ExtUtils::Constant::C_constant uses $^X inside a comment, and we want to
29# compare output to ensure that it is the same. We were probably run as ./perl
30# whereas we will run the child with the full path in $perl. So make $^X for
31# us the same as our child will see.
32$^X = $perl;
33# 5.005 doesn't have rel2abs, but also doesn't need to load an uninstalled
34# module from blib
35@INC = map {File::Spec->rel2abs($_)} @INC if $] < 5.007 && $] >= 5.006;
36
37my $make = $Config{make};
38$make = $ENV{MAKE} if exists $ENV{MAKE};
39if ($^O eq 'MSWin32' && $make eq 'nmake') { $make .= " -nologo"; }
40
41# VMS may be using something other than MMS/MMK
42my $mms_or_mmk = ($make =~ m/^MM(S|K)/i) ? 1 : 0;
43
44# Renamed by make clean
45my $makefile = ($mms_or_mmk ? 'descrip' : 'Makefile');
46my $makefile_ext = ($mms_or_mmk ? '.mms' : '');
47my $makefile_rename = $makefile . ($mms_or_mmk ? '.mms_old' : '.old');
48
49my $output = "output";
50my $package = "ExtTest";
51my $dir = "ext-$$";
52my $subdir = 0;
53# The real test counter.
54my $realtest = 1;
55
56my $orig_cwd = cwd;
57my $updir = File::Spec->updir;
58die "Can't get current directory: $!" unless defined $orig_cwd;
59
60print "# $dir being created...\n";
61mkdir $dir, 0777 or die "mkdir: $!\n";
62
63END {
64  if (defined $orig_cwd and length $orig_cwd) {
65    chdir $orig_cwd or die "Can't chdir back to '$orig_cwd': $!";
66    use File::Path;
67    print "# $dir being removed...\n";
68    rmtree($dir) unless $keep_files;
69  } else {
70    # Can't get here.
71    die "cwd at start was empty, but directory '$dir' was created" if $dir;
72  }
73}
74
75chdir $dir or die $!;
76push @INC, '../../lib', '../../../lib';
77
78package TieOut;
79
80sub TIEHANDLE {
81    my $class = shift;
82    bless(\( my $ref = ''), $class);
83}
84
85sub PRINT {
86    my $self = shift;
87    $$self .= join('', @_);
88}
89
90sub PRINTF {
91    my $self = shift;
92    $$self .= sprintf shift, @_;
93}
94
95sub read {
96    my $self = shift;
97    return substr($$self, 0, length($$self), '');
98}
99
100package main;
101
102sub check_for_bonus_files {
103  my $dir = shift;
104  my %expect = map {($^O eq 'VMS' ? lc($_) : $_), 1} @_;
105
106  my $fail;
107  opendir DIR, $dir or die "opendir '$dir': $!";
108  while (defined (my $entry = readdir DIR)) {
109    $entry =~ s/(.*?)\.?$/\L$1/ if $^O eq 'VMS';
110    next if $expect{$entry};
111    print "# Extra file '$entry'\n";
112    $fail = 1;
113  }
114
115  closedir DIR or warn "closedir '.': $!";
116  if ($fail) {
117    print "not ok $realtest\n";
118  } else {
119    print "ok $realtest\n";
120  }
121  $realtest++;
122}
123
124sub build_and_run {
125  my ($tests, $expect, $files) = @_;
126  my $core = $ENV{PERL_CORE} ? ' PERL_CORE=1' : '';
127  my @perlout = `$perl Makefile.PL $core`;
128  if ($?) {
129    print "not ok $realtest # $perl Makefile.PL failed: $?\n";
130    print "# $_" foreach @perlout;
131    exit($?);
132  } else {
133    print "ok $realtest\n";
134  }
135  $realtest++;
136
137  if (-f "$makefile$makefile_ext") {
138    print "ok $realtest\n";
139  } else {
140    print "not ok $realtest\n";
141  }
142  $realtest++;
143
144  my @makeout;
145
146  if ($^O eq 'VMS') { $make .= ' all'; }
147
148  # Sometimes it seems that timestamps can get confused
149
150  # make failed: 256
151  # Makefile out-of-date with respect to Makefile.PL
152  # Cleaning current config before rebuilding Makefile...
153  # make -f Makefile.old clean > /dev/null 2>&1 || /bin/sh -c true
154  # ../../perl "-I../../../lib" "-I../../../lib" Makefile.PL "PERL_CORE=1"
155  # Checking if your kit is complete...
156  # Looks good
157  # Writing Makefile for ExtTest
158  # ==> Your Makefile has been rebuilt. <==
159  # ==> Please rerun the make command.  <==
160  # false
161
162  my $timewarp = (-M "Makefile.PL") - (-M "$makefile$makefile_ext");
163  # Convert from days to seconds
164  $timewarp *= 86400;
165  print "# Makefile.PL is $timewarp second(s) older than $makefile$makefile_ext\n";
166  if ($timewarp < 0) {
167      # Sleep for a while to catch up.
168      $timewarp = -$timewarp;
169      $timewarp+=2;
170      $timewarp = 10 if $timewarp > 10;
171      print "# Sleeping for $timewarp second(s) to try to resolve this\n";
172      sleep $timewarp;
173  }
174
175  print "# make = '$make'\n";
176  @makeout = `$make`;
177  if ($?) {
178    print "not ok $realtest # $make failed: $?\n";
179    print "# $_" foreach @makeout;
180    exit($?);
181  } else {
182    print "ok $realtest\n";
183  }
184  $realtest++;
185
186  if ($^O eq 'VMS') { $make =~ s{ all}{}; }
187
188  if ($Config{usedl}) {
189    print "ok $realtest # This is dynamic linking, so no need to make perl\n";
190  } else {
191    my $makeperl = "$make perl";
192    print "# make = '$makeperl'\n";
193    @makeout = `$makeperl`;
194    if ($?) {
195      print "not ok $realtest # $makeperl failed: $?\n";
196      print "# $_" foreach @makeout;
197      exit($?);
198    } else {
199      print "ok $realtest\n";
200    }
201  }
202  $realtest++;
203
204  my $maketest = "$make test";
205  print "# make = '$maketest'\n";
206
207  @makeout = `$maketest`;
208
209  if (open OUTPUT, "<$output") {
210    local $/; # Slurp it - faster.
211    print <OUTPUT>;
212    close OUTPUT or print "# Close $output failed: $!\n";
213  } else {
214    # Harness will report missing test results at this point.
215    print "# Open <$output failed: $!\n";
216  }
217
218  $realtest += $tests;
219  if ($?) {
220    print "not ok $realtest # $maketest failed: $?\n";
221    print "# $_" foreach @makeout;
222  } else {
223    print "ok $realtest - maketest\n";
224  }
225  $realtest++;
226
227  if (defined $expect) {
228      # -x is busted on Win32 < 5.6.1, so we emulate it.
229      my $regen;
230      if( $^O eq 'MSWin32' && $] <= 5.006001 ) {
231	  open(REGENTMP, ">regentmp") or die $!;
232	  open(XS, "$package.xs")     or die $!;
233	  my $saw_shebang;
234	  while(<XS>) {
235	      $saw_shebang++ if /^#!.*/i ;
236	      print REGENTMP $_ if $saw_shebang;
237	  }
238	  close XS;  close REGENTMP;
239	  $regen = `$perl regentmp`;
240	  unlink 'regentmp';
241      }
242      else {
243	  $regen = `$perl -x $package.xs`;
244      }
245      if ($?) {
246	  print "not ok $realtest # $perl -x $package.xs failed: $?\n";
247	  } else {
248	      print "ok $realtest - regen\n";
249	  }
250      $realtest++;
251
252      if ($expect eq $regen) {
253	  print "ok $realtest - regen worked\n";
254      } else {
255	  print "not ok $realtest - regen worked\n";
256	  # open FOO, ">expect"; print FOO $expect;
257	  # open FOO, ">regen"; print FOO $regen; close FOO;
258      }
259      $realtest++;
260  } else {
261    for (0..1) {
262      print "ok $realtest # skip no regen or expect for this set of tests\n";
263      $realtest++;
264    }
265  }
266
267  my $makeclean = "$make clean";
268  print "# make = '$makeclean'\n";
269  @makeout = `$makeclean`;
270  if ($?) {
271    print "not ok $realtest # $make failed: $?\n";
272    print "# $_" foreach @makeout;
273  } else {
274    print "ok $realtest\n";
275  }
276  $realtest++;
277
278  check_for_bonus_files ('.', @$files, $output, $makefile_rename, '.', '..');
279
280  rename $makefile_rename, $makefile . $makefile_ext
281    or die "Can't rename '$makefile_rename' to '$makefile$makefile_ext': $!";
282
283  unlink $output or warn "Can't unlink '$output': $!";
284
285  # Need to make distclean to remove ../../lib/ExtTest.pm
286  my $makedistclean = "$make distclean";
287  print "# make = '$makedistclean'\n";
288  @makeout = `$makedistclean`;
289  if ($?) {
290    print "not ok $realtest # $make failed: $?\n";
291    print "# $_" foreach @makeout;
292  } else {
293    print "ok $realtest\n";
294  }
295  $realtest++;
296
297  check_for_bonus_files ('.', @$files, '.', '..');
298
299  unless ($keep_files) {
300    foreach (@$files) {
301      unlink $_ or warn "unlink $_: $!";
302    }
303  }
304
305  check_for_bonus_files ('.', '.', '..');
306}
307
308sub Makefile_PL {
309  my $package = shift;
310  ################ Makefile.PL
311  # We really need a Makefile.PL because make test for a no dynamic linking perl
312  # will run Makefile.PL again as part of the "make perl" target.
313  my $makefilePL = "Makefile.PL";
314  open FH, ">$makefilePL" or die "open >$makefilePL: $!\n";
315  print FH <<"EOT";
316#!$perl -w
317use ExtUtils::MakeMaker;
318WriteMakefile(
319              'NAME'		=> "$package",
320              'VERSION_FROM'	=> "$package.pm", # finds \$VERSION
321              (\$] >= 5.005 ?
322               (#ABSTRACT_FROM => "$package.pm", # XXX add this
323                AUTHOR     => "$0") : ())
324             );
325EOT
326
327  close FH or die "close $makefilePL: $!\n";
328  return $makefilePL;
329}
330
331sub MANIFEST {
332  my (@files) = @_;
333  ################ MANIFEST
334  # We really need a MANIFEST because make distclean checks it.
335  my $manifest = "MANIFEST";
336  push @files, $manifest;
337  open FH, ">$manifest" or die "open >$manifest: $!\n";
338  print FH "$_\n" foreach @files;
339  close FH or die "close $manifest: $!\n";
340  return @files;
341}
342
343sub write_and_run_extension {
344  my ($name, $items, $export_names, $package, $header, $testfile, $num_tests,
345      $wc_args) = @_;
346
347  local *C;
348  local *XS;
349
350  my $c = tie *C, 'TieOut';
351  my $xs = tie *XS, 'TieOut';
352
353  ExtUtils::Constant::WriteConstants(C_FH => \*C,
354				     XS_FH => \*XS,
355				     NAME => $package,
356				     NAMES => $items,
357				     @$wc_args,
358				     );
359
360  my $C_code = $c->read();
361  my $XS_code = $xs->read();
362
363  undef $c;
364  undef $xs;
365
366  untie *C;
367  untie *XS;
368
369  # Don't check the regeneration code if we specify extra arguments to
370  # WriteConstants. (Fix this to give finer grained control if needed)
371  my $expect;
372  $expect = $C_code . "\n#### XS Section:\n" . $XS_code unless $wc_args;
373
374  print "# $name\n# $dir/$subdir being created...\n";
375  mkdir $subdir, 0777 or die "mkdir: $!\n";
376  chdir $subdir or die $!;
377
378  my @files;
379
380  ################ Header
381  my $header_name = "test.h";
382  push @files, $header_name;
383  open FH, ">$header_name" or die "open >$header_name: $!\n";
384  print FH $header or die $!;
385  close FH or die "close $header_name: $!\n";
386
387  ################ XS
388  my $xs_name = "$package.xs";
389  push @files, $xs_name;
390  open FH, ">$xs_name" or die "open >$xs_name: $!\n";
391
392  print FH <<"EOT";
393#include "EXTERN.h"
394#include "perl.h"
395#include "XSUB.h"
396#include "$header_name"
397
398
399$C_code
400MODULE = $package		PACKAGE = $package
401PROTOTYPES: ENABLE
402$XS_code;
403EOT
404
405  close FH or die "close $xs: $!\n";
406
407  ################ PM
408  my $pm = "$package.pm";
409  push @files, $pm;
410  open FH, ">$pm" or die "open >$pm: $!\n";
411  print FH "package $package;\n";
412  print FH "use $];\n";
413
414  print FH <<'EOT';
415
416use strict;
417EOT
418  printf FH "use warnings;\n" unless $] < 5.006;
419  print FH <<'EOT';
420use Carp;
421
422require Exporter;
423require DynaLoader;
424use vars qw ($VERSION @ISA @EXPORT_OK $AUTOLOAD);
425
426$VERSION = '0.01';
427@ISA = qw(Exporter DynaLoader);
428EOT
429  # Having this qw( in the here doc confuses cperl mode far too much to be
430  # helpful. And I'm using cperl mode to edit this, even if you're not :-)
431  print FH "\@EXPORT_OK = qw(\n";
432
433  # Print the names of all our autoloaded constants
434  print FH "\t$_\n" foreach (@$export_names);
435  print FH ");\n";
436  # Print the AUTOLOAD subroutine ExtUtils::Constant generated for us
437  print FH autoload ($package, $]);
438  print FH "bootstrap $package \$VERSION;\n1;\n__END__\n";
439  close FH or die "close $pm: $!\n";
440
441  ################ test.pl
442  my $testpl = "test.pl";
443  push @files, $testpl;
444  open FH, ">$testpl" or die "open >$testpl: $!\n";
445  # Standard test header (need an option to suppress this?)
446  print FH <<"EOT" or die $!;
447use strict;
448use $package qw(@$export_names);
449
450print "1..2\n";
451if (open OUTPUT, ">$output") {
452  print "ok 1\n";
453  select OUTPUT;
454} else {
455  print "not ok 1 # Failed to open '$output': \$!\n";
456  exit 1;
457}
458EOT
459  print FH $testfile or die $!;
460  print FH <<"EOT" or die $!;
461select STDOUT;
462if (close OUTPUT) {
463  print "ok 2\n";
464} else {
465  print "not ok 2 # Failed to close '$output': \$!\n";
466}
467EOT
468  close FH or die "close $testpl: $!\n";
469
470  push @files, Makefile_PL($package);
471  @files = MANIFEST (@files);
472
473  build_and_run ($num_tests, $expect, \@files);
474
475  chdir $updir or die "chdir '$updir': $!";
476  ++$subdir;
477}
478
479# Tests are arrayrefs of the form
480# $name, [items], [export_names], $package, $header, $testfile, $num_tests
481my @tests;
482my $before_tests = 4; # Number of "ok"s emitted to build extension
483my $after_tests = 8; # Number of "ok"s emitted after make test run
484my $dummytest = 1;
485
486my $here;
487sub start_tests {
488  $dummytest += $before_tests;
489  $here = $dummytest;
490}
491sub end_tests {
492  my ($name, $items, $export_names, $header, $testfile, $args) = @_;
493  push @tests, [$name, $items, $export_names, $package, $header, $testfile,
494               $dummytest - $here, $args];
495  $dummytest += $after_tests;
496}
497
498my $pound;
499if (ord('A') == 193) {  # EBCDIC platform
500  $pound = chr 177; # A pound sign. (Currency)
501} else { # ASCII platform
502  $pound = chr 163; # A pound sign. (Currency)
503}
504my @common_items = (
505                    {name=>"perl", type=>"PV",},
506                    {name=>"*/", type=>"PV", value=>'"CLOSE"', macro=>1},
507                    {name=>"/*", type=>"PV", value=>'"OPEN"', macro=>1},
508                    {name=>$pound, type=>"PV", value=>'"Sterling"', macro=>1},
509                   );
510
511my @args = undef;
512push @args, [PROXYSUBS => 1] if $] > 5.009002;
513foreach my $args (@args)
514{
515  # Simple tests
516  start_tests();
517  my $parent_rfc1149 =
518    'A Standard for the Transmission of IP Datagrams on Avian Carriers';
519  # Test the code that generates 1 and 2 letter name comparisons.
520  my %compass = (
521                 N => 0, 'NE' => 45, E => 90, SE => 135,
522                 S => 180, SW => 225, W => 270, NW => 315
523                );
524
525  my $header = << "EOT";
526#define FIVE 5
527#define OK6 "ok 6\\n"
528#define OK7 1
529#define FARTHING 0.25
530#define NOT_ZERO 1
531#define Yes 0
532#define No 1
533#define Undef 1
534#define RFC1149 "$parent_rfc1149"
535#undef NOTDEF
536#define perl "rules"
537EOT
538
539  while (my ($point, $bearing) = each %compass) {
540    $header .= "#define $point $bearing\n"
541  }
542
543  my @items = ("FIVE", {name=>"OK6", type=>"PV",},
544               {name=>"OK7", type=>"PVN",
545                value=>['"not ok 7\\n\\0ok 7\\n"', 15]},
546               {name => "FARTHING", type=>"NV"},
547               {name => "NOT_ZERO", type=>"UV", value=>"~(UV)0"},
548               {name => "OPEN", type=>"PV", value=>'"/*"', macro=>1},
549               {name => "CLOSE", type=>"PV", value=>'"*/"',
550                macro=>["#if 1\n", "#endif\n"]},
551               {name => "ANSWER", default=>["UV", 42]}, "NOTDEF",
552               {name => "Yes", type=>"YES"},
553               {name => "No", type=>"NO"},
554               {name => "Undef", type=>"UNDEF"},
555  # OK. It wasn't really designed to allow the creation of dual valued
556  # constants.
557  # It was more for INADDR_ANY INADDR_BROADCAST INADDR_LOOPBACK INADDR_NONE
558               {name=>"RFC1149", type=>"SV", value=>"sv_2mortal(temp_sv)",
559                pre=>"SV *temp_sv = newSVpv(RFC1149, 0); "
560                . "(void) SvUPGRADE(temp_sv,SVt_PVIV); SvIOK_on(temp_sv); "
561                . "SvIV_set(temp_sv, 1149);"},
562              );
563
564  push @items, $_ foreach keys %compass;
565
566  # Automatically compile the list of all the macro names, and make them
567  # exported constants.
568  my @export_names = map {(ref $_) ? $_->{name} : $_} @items;
569
570  # Exporter::Heavy (currently) isn't able to export the last 3 of these:
571  push @items, @common_items;
572
573  my $test_body = <<"EOT";
574
575my \$test = $dummytest;
576
577EOT
578
579  $test_body .= <<'EOT';
580# What follows goes to the temporary file.
581# IV
582my $five = FIVE;
583if ($five == 5) {
584  print "ok $test\n";
585} else {
586  print "not ok $test # \$five\n";
587}
588$test++;
589
590# PV
591if (OK6 eq "ok 6\n") {
592  print "ok $test\n";
593} else {
594  print "not ok $test # \$five\n";
595}
596$test++;
597
598# PVN containing embedded \0s
599$_ = OK7;
600s/.*\0//s;
601s/7/$test/;
602$test++;
603print;
604
605# NV
606my $farthing = FARTHING;
607if ($farthing == 0.25) {
608  print "ok $test\n";
609} else {
610  print "not ok $test # $farthing\n";
611}
612$test++;
613
614EOT
615
616  my $cond;
617  if ($] >= 5.006 || $Config{longsize} < 8) {
618    $cond = '$not_zero > 0 && $not_zero == ~0';
619  } else {
620    $cond = q{pack 'Q', $not_zero eq ~pack 'Q', 0};
621  }
622
623  $test_body .= sprintf <<'EOT', $cond;
624# UV
625my $not_zero = NOT_ZERO;
626if (%s) {
627  print "ok $test\n";
628} else {
629  print "not ok $test # \$not_zero=$not_zero ~0=" . (~0) . "\n";
630}
631$test++;
632
633EOT
634
635  $test_body .= <<'EOT';
636
637# Value includes a "*/" in an attempt to bust out of a C comment.
638# Also tests custom cpp #if clauses
639my $close = CLOSE;
640if ($close eq '*/') {
641  print "ok $test\n";
642} else {
643  print "not ok $test # \$close='$close'\n";
644}
645$test++;
646
647# Default values if macro not defined.
648my $answer = ANSWER;
649if ($answer == 42) {
650  print "ok $test\n";
651} else {
652  print "not ok $test # What do you get if you multiply six by nine? '$answer'\n";
653}
654$test++;
655
656# not defined macro
657my $notdef = eval { NOTDEF; };
658if (defined $notdef) {
659  print "not ok $test # \$notdef='$notdef'\n";
660} elsif ($@ !~ /Your vendor has not defined ExtTest macro NOTDEF/) {
661  print "not ok $test # \$@='$@'\n";
662} else {
663  print "ok $test\n";
664}
665$test++;
666
667# not a macro
668my $notthere = eval { &ExtTest::NOTTHERE; };
669if (defined $notthere) {
670  print "not ok $test # \$notthere='$notthere'\n";
671} elsif ($@ !~ /NOTTHERE is not a valid ExtTest macro/) {
672  chomp $@;
673  print "not ok $test # \$@='$@'\n";
674} else {
675  print "ok $test\n";
676}
677$test++;
678
679# Truth
680my $yes = Yes;
681if ($yes) {
682  print "ok $test\n";
683} else {
684  print "not ok $test # $yes='\$yes'\n";
685}
686$test++;
687
688# Falsehood
689my $no = No;
690if (defined $no and !$no) {
691  print "ok $test\n";
692} else {
693  print "not ok $test # \$no=" . defined ($no) ? "'$no'\n" : "undef\n";
694}
695$test++;
696
697# Undef
698my $undef = Undef;
699unless (defined $undef) {
700  print "ok $test\n";
701} else {
702  print "not ok $test # \$undef='$undef'\n";
703}
704$test++;
705
706# invalid macro (chosen to look like a mix up between No and SW)
707$notdef = eval { &ExtTest::So };
708if (defined $notdef) {
709  print "not ok $test # \$notdef='$notdef'\n";
710} elsif ($@ !~ /^So is not a valid ExtTest macro/) {
711  print "not ok $test # \$@='$@'\n";
712} else {
713  print "ok $test\n";
714}
715$test++;
716
717# invalid defined macro
718$notdef = eval { &ExtTest::EW };
719if (defined $notdef) {
720  print "not ok $test # \$notdef='$notdef'\n";
721} elsif ($@ !~ /^EW is not a valid ExtTest macro/) {
722  print "not ok $test # \$@='$@'\n";
723} else {
724  print "ok $test\n";
725}
726$test++;
727
728my %compass = (
729EOT
730
731while (my ($point, $bearing) = each %compass) {
732  $test_body .= "'$point' => $bearing, "
733}
734
735$test_body .= <<'EOT';
736
737);
738
739my $fail;
740while (my ($point, $bearing) = each %compass) {
741  my $val = eval $point;
742  if ($@) {
743    print "# $point: \$@='$@'\n";
744    $fail = 1;
745  } elsif (!defined $bearing) {
746    print "# $point: \$val=undef\n";
747    $fail = 1;
748  } elsif ($val != $bearing) {
749    print "# $point: \$val=$val, not $bearing\n";
750    $fail = 1;
751  }
752}
753if ($fail) {
754  print "not ok $test\n";
755} else {
756  print "ok $test\n";
757}
758$test++;
759
760EOT
761
762$test_body .= <<"EOT";
763my \$rfc1149 = RFC1149;
764if (\$rfc1149 ne "$parent_rfc1149") {
765  print "not ok \$test # '\$rfc1149' ne '$parent_rfc1149'\n";
766} else {
767  print "ok \$test\n";
768}
769\$test++;
770
771if (\$rfc1149 != 1149) {
772  printf "not ok \$test # %d != 1149\n", \$rfc1149;
773} else {
774  print "ok \$test\n";
775}
776\$test++;
777
778EOT
779
780$test_body .= <<'EOT';
781# test macro=>1
782my $open = OPEN;
783if ($open eq '/*') {
784  print "ok $test\n";
785} else {
786  print "not ok $test # \$open='$open'\n";
787}
788$test++;
789EOT
790$dummytest+=18;
791
792  end_tests("Simple tests", \@items, \@export_names, $header, $test_body,
793	    $args);
794}
795
796if ($do_utf_tests) {
797  # utf8 tests
798  start_tests();
799  my ($inf, $pound_bytes, $pound_utf8);
800
801  $inf = chr 0x221E;
802  # Check that we can distiguish the pathological case of a string, and the
803  # utf8 representation of that string.
804  $pound_utf8 = $pound . '1';
805  if ($better_than_56) {
806    $pound_bytes = $pound_utf8;
807    utf8::encode ($pound_bytes);
808  } else {
809    # Must have that "U*" to generate a zero length UTF string that forces
810    # top bit set chars (such as the pound sign) into UTF8, so that the
811    # unpack 'C*' then gets the byte form of the UTF8.
812    $pound_bytes =  pack 'C*', unpack 'C*', $pound_utf8 . pack "U*";
813  }
814
815  my @items = (@common_items,
816               {name=>$inf, type=>"PV", value=>'"Infinity"', macro=>1},
817               {name=>$pound_utf8, type=>"PV", value=>'"1 Pound"', macro=>1},
818               {name=>$pound_bytes, type=>"PV", value=>'"1 Pound (as bytes)"',
819                macro=>1},
820              );
821
822=pod
823
824The above set of names seems to produce a suitably bad set of compile
825problems on a Unicode naive version of ExtUtils::Constant (ie 0.11):
826
827nick@thinking-cap 15439-32-utf$ PERL_CORE=1 ./perl lib/ExtUtils/t/Constant.t
8281..33
829# perl=/stuff/perl5/15439-32-utf/perl
830# ext-30370 being created...
831Wide character in print at lib/ExtUtils/t/Constant.t line 140.
832ok 1
833ok 2
834# make = 'make'
835ExtTest.xs: In function `constant_1':
836ExtTest.xs:80: warning: multi-character character constant
837ExtTest.xs:80: warning: case value out of range
838ok 3
839
840=cut
841
842# Grr `
843
844  # Do this in 7 bit in case someone is testing with some settings that cause
845  # 8 bit files incapable of storing this character.
846  my @values
847    = map {"'" . join (",", unpack "U*", $_ . pack "U*") . "'"}
848      ($pound, $inf, $pound_bytes, $pound_utf8);
849  # Values is a list of strings, such as ('194,163,49', '163,49')
850
851  my $test_body .= "my \$test = $dummytest;\n";
852  $dummytest += 7 * 3; # 3 tests for each of the 7 things:
853
854  $test_body .= << 'EOT';
855
856use utf8;
857my $better_than_56 = $] > 5.007;
858
859my ($pound, $inf, $pound_bytes, $pound_utf8) = map {eval "pack 'U*', $_"}
860EOT
861
862  $test_body .= join ",", @values;
863
864  $test_body .= << 'EOT';
865;
866
867foreach (["perl", "rules", "rules"],
868	 ["/*", "OPEN", "OPEN"],
869	 ["*/", "CLOSE", "CLOSE"],
870	 [$pound, 'Sterling', []],
871         [$inf, 'Infinity', []],
872	 [$pound_utf8, '1 Pound', '1 Pound (as bytes)'],
873	 [$pound_bytes, '1 Pound (as bytes)', []],
874        ) {
875  # Flag an expected error with a reference for the expect string.
876  my ($string, $expect, $expect_bytes) = @$_;
877  (my $name = $string) =~ s/([^ !"#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~])/sprintf '\x{%X}', ord $1/ges;
878  print "# \"$name\" => \'$expect\'\n";
879  # Try to force this to be bytes if possible.
880  if ($better_than_56) {
881    utf8::downgrade ($string, 1);
882  } else {
883    if ($string =~ tr/0-\377// == length $string) {
884      # No chars outside range 0-255
885      $string = pack 'C*', unpack 'U*', ($string . pack 'U*');
886    }
887  }
888EOT
889
890  $test_body .=  "my (\$error, \$got) = ${package}::constant (\$string);\n";
891
892  $test_body .= <<'EOT';
893  if ($error or $got ne $expect) {
894    print "not ok $test # error '$error', got '$got'\n";
895  } else {
896    print "ok $test\n";
897  }
898  $test++;
899  print "# Now upgrade '$name' to utf8\n";
900  if ($better_than_56) {
901    utf8::upgrade ($string);
902  } else {
903    $string = pack ('U*') . $string;
904  }
905EOT
906
907  $test_body .=  "my (\$error, \$got) = ${package}::constant (\$string);\n";
908
909  $test_body .= <<'EOT';
910  if ($error or $got ne $expect) {
911    print "not ok $test # error '$error', got '$got'\n";
912  } else {
913    print "ok $test\n";
914  }
915  $test++;
916  if (defined $expect_bytes) {
917    print "# And now with the utf8 byte sequence for name\n";
918    # Try the encoded bytes.
919    if ($better_than_56) {
920      utf8::encode ($string);
921    } else {
922      $string = pack 'C*', unpack 'C*', $string . pack "U*";
923    }
924EOT
925
926    $test_body .= "my (\$error, \$got) = ${package}::constant (\$string);\n";
927
928    $test_body .= <<'EOT';
929    if (ref $expect_bytes) {
930      # Error expected.
931      if ($error) {
932        print "ok $test # error='$error' (as expected)\n";
933      } else {
934        print "not ok $test # expected error, got no error and '$got'\n";
935      }
936    } elsif ($got ne $expect_bytes) {
937      print "not ok $test # error '$error', expect '$expect_bytes', got '$got'\n";
938    } else {
939      print "ok $test\n";
940    }
941    $test++;
942  }
943}
944EOT
945
946  end_tests("utf8 tests", \@items, [], "#define perl \"rules\"\n", $test_body);
947}
948
949# XXX I think that I should merge this into the utf8 test above.
950sub explict_call_constant {
951  my ($string, $expect) = @_;
952  # This does assume simple strings suitable for ''
953  my $test_body = <<"EOT";
954{
955  my (\$error, \$got) = ${package}::constant ('$string');\n;
956EOT
957
958  if (defined $expect) {
959    # No error expected
960    $test_body .= <<"EOT";
961  if (\$error or \$got ne "$expect") {
962    print "not ok $dummytest # error '\$error', expect '$expect', got '\$got'\n";
963  } else {
964    print "ok $dummytest\n";
965    }
966  }
967EOT
968  } else {
969    # Error expected.
970    $test_body .= <<"EOT";
971  if (\$error) {
972    print "ok $dummytest # error='\$error' (as expected)\n";
973  } else {
974    print "not ok $dummytest # expected error, got no error and '\$got'\n";
975  }
976EOT
977  }
978  $dummytest++;
979  return $test_body . <<'EOT';
980}
981EOT
982}
983
984# Simple tests to verify bits of the switch generation system work.
985sub simple {
986  start_tests();
987  # Deliberately leave $name in @_, so that it is indexed from 1.
988  my ($name, @items) = @_;
989  my $test_header;
990  my $test_body = "my \$value;\n";
991  foreach my $counter (1 .. $#_) {
992    my $thisname = $_[$counter];
993    $test_header .= "#define $thisname $counter\n";
994    $test_body .= <<"EOT";
995\$value = $thisname;
996if (\$value == $counter) {
997  print "ok $dummytest\n";
998} else {
999  print "not ok $dummytest # $thisname gave \$value\n";
1000}
1001EOT
1002    ++$dummytest;
1003    # Yes, the last time round the loop appends a z to the string.
1004    for my $i (0 .. length $thisname) {
1005      my $copyname = $thisname;
1006      substr ($copyname, $i, 1) = 'z';
1007      $test_body .= explict_call_constant ($copyname,
1008                                           $copyname eq $thisname
1009                                             ? $thisname : undef);
1010    }
1011  }
1012  # Ho. This seems to be buggy in 5.005_03:
1013  # # Now remove $name from @_:
1014  # shift @_;
1015  end_tests($name, \@items, \@items, $test_header, $test_body);
1016}
1017
1018# Check that the memeq clauses work correctly when there isn't a switch
1019# statement to bump off a character
1020simple ("Singletons", "A", "AB", "ABC", "ABCD", "ABCDE");
1021# Check the three code.
1022simple ("Three start", qw(Bea kea Lea lea nea pea rea sea tea Wea yea Zea));
1023# There were 162 2 letter words in /usr/share/dict/words on FreeBSD 4.6, which
1024# I felt was rather too many. So I used words with 2 vowels.
1025simple ("Twos and three middle", qw(aa ae ai ea eu ie io oe era eta));
1026# Given the choice go for the end, else the earliest point
1027simple ("Three end and four symetry", qw(ean ear eat barb marm tart));
1028
1029
1030# Need this if the single test below is rolled into @tests :
1031# --$dummytest;
1032print "1..$dummytest\n";
1033
1034write_and_run_extension @$_ foreach @tests;
1035
1036# This was causing an assertion failure (a C<confess>ion)
1037# Any single byte > 128 should do it.
1038C_constant ($package, undef, undef, undef, undef, undef, chr 255);
1039print "ok $realtest\n"; $realtest++;
1040
1041print STDERR "# You were running with \$keep_files set to $keep_files\n"
1042  if $keep_files;
1043