Update string comparision in perl module test
[pspp] / perl-module / t / Pspp.t
1 # -*-perl-*-
2 # Before `make install' is performed this script should be runnable
3 # with `make test' as long as libpspp-core-$VERSION.so is in
4 # LD_LIBRARY_PATH.  After `make install' it should work as `perl
5 # PSPP.t'
6
7 #########################
8
9 # change 'tests => 1' to 'tests => last_test_to_print';
10
11 use Test::More tests => 36;
12 use Text::Diff;
13 use File::Temp qw/ tempfile tempdir /;
14 BEGIN { use_ok('PSPP') };
15
16 #########################
17
18 sub compare
19 {
20     my $file = shift;
21     my $pattern = shift;
22     return ! diff ("$file", \$pattern);
23 }
24
25 my $pspp_cmd = $ENV{PSPP_TEST_CMD};
26
27 if ( ! $pspp_cmd)
28 {
29     $pspp_cmd="pspp";
30 }
31
32 sub run_pspp_syntax
33 {
34     my $tempdir = shift;
35     my $syntax = shift;
36
37     my $syntaxfile = "$tempdir/foo.sps";
38
39     open (FH, ">$syntaxfile");
40     print FH "$syntax";
41     close (FH);
42
43     system ("cd $tempdir; $pspp_cmd -o pspp.csv $syntaxfile");
44 }
45
46 sub run_pspp_syntax_cmp
47 {
48     my $tempdir = shift;
49     my $syntax = shift;
50
51     my $result = shift;
52
53     run_pspp_syntax ($tempdir, $syntax);
54
55     my $diff =  diff ("$tempdir/pspp.csv", \$result);
56
57     if ( ! ($diff eq ""))
58     {
59         diag ("$diff");
60     }
61
62     return ($diff eq "");
63 }
64
65
66 # Insert your test code below, the Test::More module is used here so read
67 # its man page ( perldoc Test::More ) for help writing this test script.
68
69 {
70   my $d = PSPP::Dict->new();
71   ok (ref $d, "Dictionary Creation");
72   ok ($d->get_var_cnt () == 0);
73
74   $d->set_label ("My Dictionary");
75   $d->set_documents ("These Documents");
76
77   # Tests for variable creation
78
79   my $var0 = PSPP::Var->new ($d, "le");
80   ok (!ref $var0, "Trap illegal variable name");
81   ok ($d->get_var_cnt () == 0);
82
83   $var0 = PSPP::Var->new ($d, "legal");
84   ok (ref $var0, "Accept legal variable name");
85   ok ($d->get_var_cnt () == 1);
86
87   my $var1 = PSPP::Var->new ($d, "legal");
88   ok (!ref $var1, "Trap duplicate variable name");
89   ok ($d->get_var_cnt () == 1);
90
91   $var1 = PSPP::Var->new ($d, "money", 
92                           (fmt=>PSPP::Fmt::DOLLAR, 
93                            width=>4, decimals=>2) );
94   ok (ref $var1, "Accept valid format");
95   ok ($d->get_var_cnt () == 2);
96
97   $d->set_weight ($var1);
98
99
100   # Tests for system file creation
101   # Make sure a system file can be created
102   {
103       my $tempdir = tempdir( CLEANUP => 1 );
104       my $tempfile = "$tempdir/testfile.sav";
105       my $syntaxfile = "$tempdir/syntax.sps";
106       my $sysfile = PSPP::Sysfile->new ("$tempfile", $d);
107       ok (ref $sysfile, "Create sysfile object");
108
109       $sysfile->close ();
110       ok (-s "$tempfile", "Write system file");
111   }
112 }
113
114
115 # Make sure we can write cases to a file
116 {
117   my $d = PSPP::Dict->new();
118   PSPP::Var->new ($d, "id",
119                          (
120                           fmt=>PSPP::Fmt::F, 
121                           width=>2, 
122                           decimals=>0
123                           )
124                          );
125
126   PSPP::Var->new ($d, "name",
127                          (
128                           fmt=>PSPP::Fmt::A, 
129                           width=>20, 
130                           )
131                          );
132
133   $d->set_documents ("This should not appear");
134   $d->clear_documents ();
135   $d->add_document ("This is a document line");
136
137   $d->set_label ("This is the file label");
138
139   # Check that we can write system files
140   {
141       my $tempdir = tempdir( CLEANUP => 1 );
142       my $tempfile = "$tempdir/testfile.sav";
143       my $sysfile = PSPP::Sysfile->new ("$tempfile", $d);
144
145       my $res = $sysfile->append_case ( [34, "frederick"]);
146       ok ($res, "Append Case");
147
148       $res = $sysfile->append_case ( [34, "frederick", "extra"]);
149       ok (!$res, "Appending Case with too many variables");
150
151       $sysfile->close ();
152       ok (-s  "$tempfile", "existance");
153   }
154
155   # Check that sysfiles are closed properly
156   {
157       my $tempdir = tempdir( CLEANUP => 1 );
158       my $tempfile = "$tempdir/testfile.sav";
159       {
160           my $sysfile = PSPP::Sysfile->new ("$tempfile", $d);
161
162           my $res = $sysfile->append_case ( [21, "wheelbarrow"]);
163           ok ($res, "Append Case 2");
164
165           # Don't close.  We want to test that the destructor  does that 
166           # automatically 
167       }
168       ok (-s "$tempfile", "existance2");
169
170     ok (run_pspp_syntax_cmp ($tempdir, <<SYNTAX, <<RESULT), "Check output");
171
172         GET FILE='$tempfile'.
173         DISPLAY DICTIONARY.
174         DISPLAY FILE LABEL.
175         DISPLAY DOCUMENTS.
176         LIST.
177 SYNTAX
178 Variable,Description,,Position
179 id,Format: F2.0,,1
180 ,Measure: Scale,,
181 ,Display Alignment: Right,,
182 ,Display Width: 8,,
183 name,Format: A20,,2
184 ,Measure: Nominal,,
185 ,Display Alignment: Left,,
186 ,Display Width: 20,,
187
188 File label:
189
190 This is the file label
191
192 Documents in the active file:
193
194 This is a document line
195
196 Table: Data List
197 id,name
198 21,wheelbarrow         
199 RESULT
200
201
202   }
203
204   # Now do some tests to make sure all the variable parameters 
205   # can be written properly.
206
207   {
208       my $tempdir = tempdir( CLEANUP => 1 );
209       my $tempfile = "$tempdir/testfile.sav";      
210       my $dict = PSPP::Dict->new();
211       ok (ref $dict, "Dictionary Creation 2");
212
213       my $int = PSPP::Var->new ($dict, "integer", 
214                                 (width=>8, decimals=>0) );
215
216       $int->set_label ("My Integer");
217       
218       $int->add_value_label (99, "Silly");
219       $int->clear_value_labels ();
220       $int->add_value_label (0, "Zero");
221       $int->add_value_label (1, "Unity");
222       $int->add_value_label (2, "Duality");
223
224       my $str = PSPP::Var->new ($dict, "string", 
225                                 (fmt=>PSPP::Fmt::A, width=>8) );
226
227
228       $str->set_label ("My String");
229       ok ($str->add_value_label ("xx", "foo"), "Value label for short string");
230       diag ($PSPP::errstr);
231       $str->add_value_label ("yy", "bar");
232
233       $str->set_missing_values ("this", "that");
234
235       my $longstr = PSPP::Var->new ($dict, "longstring", 
236                                 (fmt=>PSPP::Fmt::A, width=>9) );
237
238
239       $longstr->set_label ("My Long String");
240       my $re = $longstr->add_value_label ("xxx", "xfoo");
241       ok ($re, "Value label for long string");
242
243       $int->set_missing_values (9, 99);
244
245       my $sysfile = PSPP::Sysfile->new ("$tempfile", $dict);
246
247
248       $sysfile->close ();
249
250       ok (run_pspp_syntax_cmp ($tempdir, <<SYNTAX, <<RESULT), "Check output 2");
251 GET FILE='$tempfile'.
252 DISPLAY DICTIONARY.
253 SYNTAX
254 Variable,Description,,Position
255 integer,My Integer,,1
256 ,Format: F8.0,,
257 ,Measure: Scale,,
258 ,Display Alignment: Right,,
259 ,Display Width: 8,,
260 ,Missing Values: 9; 99,,
261 ,0,Zero,
262 ,1,Unity,
263 ,2,Duality,
264 string,My String,,2
265 ,Format: A8,,
266 ,Measure: Nominal,,
267 ,Display Alignment: Left,,
268 ,Display Width: 8,,
269 ,"Missing Values: ""this    ""; ""that    """,,
270 ,xx      ,foo,
271 ,yy      ,bar,
272 longstring,My Long String,,3
273 ,Format: A9,,
274 ,Measure: Nominal,,
275 ,Display Alignment: Left,,
276 ,Display Width: 9,,
277 ,xxx      ,xfoo,
278 RESULT
279
280   }
281
282 }
283
284 sub generate_sav_file 
285 {
286     my $filename = shift;
287     my $tempdir = shift;
288
289     run_pspp_syntax_cmp ($tempdir, <<SYNTAX, <<RESULT);
290 data list notable list /string (a8) longstring (a12) numeric (f10) date (date11) dollar (dollar8.2) datetime (datetime17)
291 begin data.
292 1111 One   1 1/1/1 1   1/1/1+01:01
293 2222 Two   2 2/2/2 2   2/2/2+02:02
294 3333 Three 3 3/3/3 3   3/3/3+03:03
295 .    .     . .     .   .
296 5555 Five  5 5/5/5 5   5/5/5+05:05
297 end data.
298
299
300 variable labels string 'A Short String Variable'
301   /longstring 'A Long String Variable'
302   /numeric 'A Numeric Variable'
303   /date 'A Date Variable'
304   /dollar 'A Dollar Variable'
305   /datetime 'A Datetime Variable'.
306
307
308 missing values numeric (9, 5, 999).
309
310 missing values string ("3333").
311
312 add value labels
313   /string '1111' 'ones' '2222' 'twos' '3333' 'threes'
314   /numeric 1 'Unity' 2 'Duality' 3 'Thripality'.
315
316 variable attribute
317     variables = numeric
318     attribute=colour[1]('blue') colour[2]('pink') colour[3]('violet')
319     attribute=size('large') nationality('foreign').
320
321
322 save outfile='$filename'.
323 SYNTAX
324
325 RESULT
326
327 }
328
329
330 # Test to make sure that the dictionary survives the sysfile.
331 # Thanks to Rob Messer for reporting this problem
332 {
333     my $tempdir = tempdir( CLEANUP => 1 );
334     my $tempfile = "$tempdir/testfile.sav";
335     my $sysfile ;
336
337     {
338         my $d = PSPP::Dict->new();
339
340         PSPP::Var->new ($d, "id",
341                         (
342                          fmt=>PSPP::Fmt::F, 
343                          width=>2, 
344                          decimals=>0
345                          )
346                         );
347
348         $sysfile = PSPP::Sysfile->new ("$tempfile", $d);
349     }
350
351     my $res = $sysfile->append_case ([3]);
352
353     ok ($res, "Dictionary survives sysfile");
354 }
355
356
357 # Basic reader test
358 {
359  my $tempdir = tempdir( CLEANUP => 1 );
360
361  generate_sav_file ("$tempdir/in.sav", "$tempdir");
362
363  my $sf = PSPP::Reader->open ("$tempdir/in.sav");
364
365  my $dict = $sf->get_dict ();
366
367  open (MYFILE, ">$tempdir/out.txt");
368  for ($v = 0 ; $v < $dict->get_var_cnt() ; $v++)
369  {
370     my $var = $dict->get_var ($v);
371     my $name = $var->get_name ();
372     my $label = $var->get_label ();
373
374     print MYFILE "Variable $v is \"$name\", label is \"$label\"\n";
375     
376     my $vl = $var->get_value_labels ();
377
378     print MYFILE "Value Labels:\n";
379     print MYFILE "$_ => $vl->{$_}\n" for keys %$vl;
380  }
381
382  while (my @c = $sf->get_next_case () )
383  {
384     for ($v = 0; $v < $dict->get_var_cnt(); $v++)
385     {
386         print MYFILE "val$v: \"$c[$v]\"\n";
387     }
388     print MYFILE "\n";
389  }
390
391  close (MYFILE);
392
393 ok (compare ("$tempdir/out.txt", <<EOF), "Basic reader operation");
394 Variable 0 is "string", label is "A Short String Variable"
395 Value Labels:
396 3333     => threes
397 1111     => ones
398 2222     => twos
399 Variable 1 is "longstring", label is "A Long String Variable"
400 Value Labels:
401 Variable 2 is "numeric", label is "A Numeric Variable"
402 Value Labels:
403 1 => Unity
404 3 => Thripality
405 2 => Duality
406 Variable 3 is "date", label is "A Date Variable"
407 Value Labels:
408 Variable 4 is "dollar", label is "A Dollar Variable"
409 Value Labels:
410 Variable 5 is "datetime", label is "A Datetime Variable"
411 Value Labels:
412 val0: "1111    "
413 val1: "One         "
414 val2: "1"
415 val3: "13197686400"
416 val4: "1"
417 val5: "13197690060"
418
419 val0: "2222    "
420 val1: "Two         "
421 val2: "2"
422 val3: "13231987200"
423 val4: "2"
424 val5: "13231994520"
425
426 val0: "3333    "
427 val1: "Three       "
428 val2: "3"
429 val3: "13266028800"
430 val4: "3"
431 val5: "13266039780"
432
433 val0: ".       "
434 val1: ".           "
435 val2: ""
436 val3: ""
437 val4: ""
438 val5: ""
439
440 val0: "5555    "
441 val1: "Five        "
442 val2: "5"
443 val3: "13334630400"
444 val4: "5"
445 val5: "13334648700"
446
447 EOF
448
449 }
450
451
452 # Check that we can stream one file into another
453 {
454  my $tempdir = tempdir( CLEANUP => 1 );
455
456  generate_sav_file ("$tempdir/in.sav", "$tempdir");
457
458  my $input = PSPP::Reader->open ("$tempdir/in.sav");
459
460  my $dict = $input->get_dict ();
461
462  my $output = PSPP::Sysfile->new ("$tempdir/out.sav", $dict);
463
464  while (my (@c) = $input->get_next_case () )
465  {
466    $output->append_case (\@c);
467  }
468
469  $output->close ();
470
471
472  #Check the two files are the same (except for metadata)
473
474  run_pspp_syntax ($tempdir, <<SYNTAX);
475  get file='$tempdir/in.sav'.
476  display dictionary.
477  list.
478
479 SYNTAX
480
481  system ("cp $tempdir/pspp.csv $tempdir/in.txt");
482
483  run_pspp_syntax ($tempdir, <<SYNTAX);
484  get file='$tempdir/out.sav'.
485  display dictionary.
486  list.
487
488 SYNTAX
489  
490  ok (! diff ("$tempdir/pspp.csv", "$tempdir/in.txt"), "Streaming of files");
491 }
492
493
494
495 # Check that the format_value function works properly
496 {
497  my $tempdir = tempdir( CLEANUP => 1 );
498
499  run_pspp_syntax ($tempdir, <<SYNTAX);
500
501 data list list /d (datetime17).
502 begin data.
503 11/9/2001+08:20
504 end data.
505
506 save outfile='$tempdir/dd.sav'.
507
508 SYNTAX
509
510  my $sf = PSPP::Reader->open ("$tempdir/dd.sav");
511
512  my $dict = $sf->get_dict ();
513
514  my (@c) = $sf->get_next_case ();
515
516  my $var = $dict->get_var (0);
517  my $val = $c[0];
518  my $formatted = PSPP::format_value ($val, $var);
519  my $str = gmtime ($val - PSPP::PERL_EPOCH);
520  print "Formatted string is \"$formatted\"\n";
521  ok ( $formatted eq "11-SEP-2001 08:20", "format_value function");
522  ok ( $str eq "Tue Sep 11 08:20:00 2001", "Perl representation of time");
523 }
524
525
526 # Check that attempting to open a non-existent file results in an error
527 {
528   my $tempdir = tempdir( CLEANUP => 1 );
529
530   unlink ("$tempdir/no-such-file.sav");
531
532   my $sf = PSPP::Reader->open ("$tempdir/no-such-file.sav");
533
534   ok ( !ref $sf, "Returns undef on opening failure");
535
536   ok ("$PSPP::errstr" eq "Error opening `$tempdir/no-such-file.sav' for reading as a system file: No such file or directory.",
537       "Error string on open failure");
538 }
539
540
541 # Missing value tests. 
542 {
543  my $tempdir = tempdir( CLEANUP => 1 );
544
545  generate_sav_file ("$tempdir/in.sav", "$tempdir");
546
547  my $sf = PSPP::Reader->open ("$tempdir/in.sav");
548
549  my $dict = $sf->get_dict ();
550
551
552  my (@c) = $sf->get_next_case ();
553
554  my $stringvar = $dict->get_var (0);
555  my $numericvar = $dict->get_var (2);
556  my $val = $c[0];
557
558  ok ( !PSPP::value_is_missing ($val, $stringvar), "Missing Value Negative String");
559
560  $val = $c[2];
561
562  ok ( !PSPP::value_is_missing ($val, $numericvar), "Missing Value Negative Num");
563
564  @c = $sf->get_next_case (); 
565  @c = $sf->get_next_case (); 
566
567  $val = $c[0];
568  ok ( PSPP::value_is_missing ($val, $stringvar), "Missing Value Positive");
569
570  @c = $sf->get_next_case (); 
571  $val = $c[2];
572  ok ( PSPP::value_is_missing ($val, $numericvar), "Missing Value Positive SYS");
573
574  @c = $sf->get_next_case (); 
575  $val = $c[2];
576  ok ( PSPP::value_is_missing ($val, $numericvar), "Missing Value Positive Num");
577 }
578
579
580 #Test reading of custom attributes
581 {
582     my $tempdir = tempdir( CLEANUP => 1 );
583
584     generate_sav_file ("$tempdir/in.sav", "$tempdir");
585
586     my $sf = PSPP::Reader->open ("$tempdir/in.sav");
587
588     my $dict = $sf->get_dict ();
589
590     my $var = $dict->get_var_by_name ("numeric");
591
592     my $attr = $var->get_attributes ();
593
594     open (MYFILE, ">$tempdir/out.txt");
595
596     foreach $k (keys %$attr)
597     {
598         my $ll = $attr->{$k};
599         print MYFILE "$k =>";
600         print MYFILE map "$_\n", join ', ', @$ll;
601     }
602
603     close (MYFILE);
604
605     ok (compare ("$tempdir/out.txt", <<EOF), "Custom Attributes");
606 colour =>blue, pink, violet
607 nationality =>foreign
608 size =>large
609 EOF
610
611 }