f7ff632cf78fdf4407a420a00db7293b62170b74
[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 => 37;
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->add_document ("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->add_document ("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 Table: Variables
179 Name,Position,Label,Measurement Level,Role,Width,Alignment,Print Format,Write Format,Missing Values
180 id,1,,Scale,Input,8,Right,F2.0,F2.0,
181 name,2,,Nominal,Input,20,Left,A20,A20,
182
183 File label: This is the file label
184
185 Documents in the active dataset:
186
187 This is a document line
188
189 Table: Data List
190 id,name
191 21,wheelbarrow         
192 RESULT
193
194
195   }
196
197   # Now do some tests to make sure all the variable parameters 
198   # can be written properly.
199
200   {
201       my $tempdir = tempdir( CLEANUP => 1 );
202       my $tempfile = "$tempdir/testfile.sav";      
203       my $dict = PSPP::Dict->new();
204       ok (ref $dict, "Dictionary Creation 2");
205
206       my $int = PSPP::Var->new ($dict, "integer", 
207                                 (width=>8, decimals=>0) );
208
209       $int->set_label ("My Integer");
210       
211       $int->add_value_label (99, "Silly");
212       $int->clear_value_labels ();
213       $int->add_value_label (0, "Zero");
214       $int->add_value_label (1, "Unity");
215       $int->add_value_label (2, "Duality");
216
217       my $str = PSPP::Var->new ($dict, "string", 
218                                 (fmt=>PSPP::Fmt::A, width=>8) );
219
220
221       $str->set_label ("My String");
222       ok ($str->add_value_label ("xx", "foo"), "Value label for short string");
223       diag ($PSPP::errstr);
224       $str->add_value_label ("yy", "bar");
225
226       $str->set_missing_values ("this", "that");
227
228       my $longstr = PSPP::Var->new ($dict, "longstring", 
229                                 (fmt=>PSPP::Fmt::A, width=>9) );
230
231
232       $longstr->set_label ("My Long String");
233       my $re = $longstr->add_value_label ("xxx", "xfoo");
234       ok ($re, "Value label for long string");
235
236       $int->set_missing_values (9, 99);
237
238       my $sysfile = PSPP::Sysfile->new ("$tempfile", $dict);
239
240
241       $sysfile->close ();
242
243       ok (run_pspp_syntax_cmp ($tempdir, <<SYNTAX, <<RESULT), "Check output 2");
244 GET FILE='$tempfile'.
245 DISPLAY DICTIONARY.
246 SYNTAX
247 Table: Variables
248 Name,Position,Label,Measurement Level,Role,Width,Alignment,Print Format,Write Format,Missing Values
249 integer,1,My Integer,Scale,Input,8,Right,F8.0,F8.0,9; 99
250 string,2,My String,Nominal,Input,8,Left,A8,A8,"""this    ""; ""that    """
251 longstring,3,My Long String,Nominal,Input,9,Left,A9,A9,
252
253 Table: Value Labels
254 Variable,Value,Label
255 integer,0,Zero
256 ,1,Unity
257 ,2,Duality
258 string,xx      ,foo
259 ,yy      ,bar
260 longstring,xxx      ,xfoo
261 RESULT
262
263   }
264
265 }
266
267 sub generate_sav_file 
268 {
269     my $filename = shift;
270     my $tempdir = shift;
271
272     run_pspp_syntax_cmp ($tempdir, <<SYNTAX, <<RESULT);
273 data list notable list /string (a8) longstring (a12) numeric (f10) date (date11) dollar (dollar8.2) datetime (datetime17)
274 begin data.
275 1111 One   1 1/1/1 1   1/1/1+01:01
276 2222 Two   2 2/2/2 2   2/2/2+02:02
277 3333 Three 3 3/3/3 3   3/3/3+03:03
278 .    .     . .     .   .
279 5555 Five  5 5/5/5 5   5/5/5+05:05
280 end data.
281
282
283 variable labels string 'A Short String Variable'
284   /longstring 'A Long String Variable'
285   /numeric 'A Numeric Variable'
286   /date 'A Date Variable'
287   /dollar 'A Dollar Variable'
288   /datetime 'A Datetime Variable'.
289
290
291 missing values numeric (9, 5, 999).
292
293 missing values string ("3333").
294
295 add value labels
296   /string '1111' 'ones' '2222' 'twos' '3333' 'threes'
297   /numeric 1 'Unity' 2 'Duality' 3 'Thripality'.
298
299 variable attribute
300     variables = numeric
301     attribute=colour[1]('blue') colour[2]('pink') colour[3]('violet')
302     attribute=size('large') nationality('foreign').
303
304
305 save outfile='$filename'.
306 SYNTAX
307
308 RESULT
309
310 }
311
312
313 # Test to make sure that the dictionary survives the sysfile.
314 # Thanks to Rob Messer for reporting this problem
315 {
316     my $tempdir = tempdir( CLEANUP => 1 );
317     my $tempfile = "$tempdir/testfile.sav";
318     my $sysfile ;
319
320     {
321         my $d = PSPP::Dict->new();
322
323         PSPP::Var->new ($d, "id",
324                         (
325                          fmt=>PSPP::Fmt::F, 
326                          width=>2, 
327                          decimals=>0
328                          )
329                         );
330
331         $sysfile = PSPP::Sysfile->new ("$tempfile", $d);
332     }
333
334     my $res = $sysfile->append_case ([3]);
335
336     ok ($res, "Dictionary survives sysfile");
337 }
338
339
340 # Basic reader test
341 {
342  my $tempdir = tempdir( CLEANUP => 1 );
343
344  generate_sav_file ("$tempdir/in.sav", "$tempdir");
345
346  my $sf = PSPP::Reader->open ("$tempdir/in.sav");
347
348  my $dict = $sf->get_dict ();
349
350  open (MYFILE, ">$tempdir/out.txt");
351  for ($v = 0 ; $v < $dict->get_var_cnt() ; $v++)
352  {
353     my $var = $dict->get_var ($v);
354     my $name = $var->get_name ();
355     my $label = $var->get_label ();
356
357     print MYFILE "Variable $v is \"$name\", label is \"$label\"\n";
358     
359     my $vl = $var->get_value_labels ();
360
361     print MYFILE "Value Labels:\n";
362     print MYFILE "$_ => $vl->{$_}\n" for (sort keys %$vl);
363  }
364
365  while (my @c = $sf->get_next_case () )
366  {
367     for ($v = 0; $v < $dict->get_var_cnt(); $v++)
368     {
369         print MYFILE "val$v: \"$c[$v]\"\n";
370     }
371     print MYFILE "\n";
372  }
373
374  close (MYFILE);
375
376 ok (compare ("$tempdir/out.txt", <<EOF), "Basic reader operation");
377 Variable 0 is "string", label is "A Short String Variable"
378 Value Labels:
379 1111     => ones
380 2222     => twos
381 3333     => threes
382 Variable 1 is "longstring", label is "A Long String Variable"
383 Value Labels:
384 Variable 2 is "numeric", label is "A Numeric Variable"
385 Value Labels:
386 1 => Unity
387 2 => Duality
388 3 => Thripality
389 Variable 3 is "date", label is "A Date Variable"
390 Value Labels:
391 Variable 4 is "dollar", label is "A Dollar Variable"
392 Value Labels:
393 Variable 5 is "datetime", label is "A Datetime Variable"
394 Value Labels:
395 val0: "1111    "
396 val1: "One         "
397 val2: "1"
398 val3: "13197686400"
399 val4: "1"
400 val5: "13197690060"
401
402 val0: "2222    "
403 val1: "Two         "
404 val2: "2"
405 val3: "13231987200"
406 val4: "2"
407 val5: "13231994520"
408
409 val0: "3333    "
410 val1: "Three       "
411 val2: "3"
412 val3: "13266028800"
413 val4: "3"
414 val5: "13266039780"
415
416 val0: ".       "
417 val1: ".           "
418 val2: ""
419 val3: ""
420 val4: ""
421 val5: ""
422
423 val0: "5555    "
424 val1: "Five        "
425 val2: "5"
426 val3: "13334630400"
427 val4: "5"
428 val5: "13334648700"
429
430 EOF
431
432 }
433
434
435 # Check that we can stream one file into another
436 {
437  my $tempdir = tempdir( CLEANUP => 1 );
438
439  generate_sav_file ("$tempdir/in.sav", "$tempdir");
440
441  my $input = PSPP::Reader->open ("$tempdir/in.sav");
442
443  my $dict = $input->get_dict ();
444
445  my $output = PSPP::Sysfile->new ("$tempdir/out.sav", $dict);
446
447  while (my (@c) = $input->get_next_case () )
448  {
449    $output->append_case (\@c);
450  }
451
452  $output->close ();
453
454
455  #Check the two files are the same (except for metadata)
456
457  run_pspp_syntax ($tempdir, <<SYNTAX);
458  get file='$tempdir/in.sav'.
459  display dictionary.
460  list.
461
462 SYNTAX
463
464  system ("cp $tempdir/pspp.csv $tempdir/in.txt");
465
466  run_pspp_syntax ($tempdir, <<SYNTAX);
467  get file='$tempdir/out.sav'.
468  display dictionary.
469  list.
470
471 SYNTAX
472  
473  ok (! diff ("$tempdir/pspp.csv", "$tempdir/in.txt"), "Streaming of files");
474 }
475
476
477
478 # Check that the format_value function works properly
479 {
480  my $tempdir = tempdir( CLEANUP => 1 );
481
482  run_pspp_syntax ($tempdir, <<SYNTAX);
483
484 data list list /d (datetime17).
485 begin data.
486 11/9/2001+08:20
487 end data.
488
489 save outfile='$tempdir/dd.sav'.
490
491 SYNTAX
492
493  my $sf = PSPP::Reader->open ("$tempdir/dd.sav");
494
495  my $dict = $sf->get_dict ();
496
497  my (@c) = $sf->get_next_case ();
498
499  my $var = $dict->get_var (0);
500  my $val = $c[0];
501  my $formatted = PSPP::format_value ($val, $var);
502  my $str = gmtime ($val - PSPP::PERL_EPOCH);
503  print "Formatted string is \"$formatted\"\n";
504  ok ( $formatted eq "11-SEP-2001 08:20", "format_value function");
505  ok ( $str eq "Tue Sep 11 08:20:00 2001", "Perl representation of time");
506 }
507
508
509 # Check that attempting to open a non-existent file results in an error
510 {
511   my $tempdir = tempdir( CLEANUP => 1 );
512
513   unlink ("$tempdir/no-such-file.sav");
514
515   my $sf = PSPP::Reader->open ("$tempdir/no-such-file.sav");
516
517   ok ( !ref $sf, "Returns undef on opening failure");
518
519   ok ("$PSPP::errstr" eq "An error occurred while opening `$tempdir/no-such-file.sav': No such file or directory.",
520       "Error string on open failure");
521 }
522
523
524 # Missing value tests. 
525 {
526  my $tempdir = tempdir( CLEANUP => 1 );
527
528  generate_sav_file ("$tempdir/in.sav", "$tempdir");
529
530  my $sf = PSPP::Reader->open ("$tempdir/in.sav");
531
532  my $dict = $sf->get_dict ();
533
534
535  my (@c) = $sf->get_next_case ();
536
537  my $stringvar = $dict->get_var (0);
538  my $numericvar = $dict->get_var (2);
539  my $val = $c[0];
540
541  ok ( !PSPP::value_is_missing ($val, $stringvar), "Missing Value Negative String");
542
543  $val = $c[2];
544
545  ok ( !PSPP::value_is_missing ($val, $numericvar), "Missing Value Negative Num");
546
547  @c = $sf->get_next_case (); 
548  @c = $sf->get_next_case (); 
549
550  $val = $c[0];
551  ok ( PSPP::value_is_missing ($val, $stringvar), "Missing Value Positive");
552
553  @c = $sf->get_next_case (); 
554  $val = $c[2];
555  ok ( PSPP::value_is_missing ($val, $numericvar), "Missing Value Positive SYS");
556
557  @c = $sf->get_next_case (); 
558  $val = $c[2];
559  ok ( PSPP::value_is_missing ($val, $numericvar), "Missing Value Positive Num");
560 }
561
562
563 #Test reading of custom attributes
564 {
565     my $tempdir = tempdir( CLEANUP => 1 );
566
567     generate_sav_file ("$tempdir/in.sav", "$tempdir");
568
569     my $sf = PSPP::Reader->open ("$tempdir/in.sav");
570
571     my $dict = $sf->get_dict ();
572
573     my $var = $dict->get_var_by_name ("numeric");
574
575     my $attr = $var->get_attributes ();
576
577     open (MYFILE, ">$tempdir/out.txt");
578
579     foreach $k (sort (keys (%$attr)))
580     {
581         my $ll = $attr->{$k};
582         print MYFILE "$k =>";
583         print MYFILE map "$_\n", join ', ', @$ll;
584     }
585
586     close (MYFILE);
587
588     ok (compare ("$tempdir/out.txt", <<'EOF'), "Custom Attributes");
589 $@Role =>0
590 colour =>blue, pink, violet
591 nationality =>foreign
592 size =>large
593 EOF
594 }
595
596
597 # Test of the get_case_cnt function
598 {
599  my $tempdir = tempdir( CLEANUP => 1 );
600
601  generate_sav_file ("$tempdir/in.sav", "$tempdir");
602
603  my $sf = PSPP::Reader->open ("$tempdir/in.sav");
604
605  my $n = $sf->get_case_cnt ();
606
607  ok ($n == 5, "Case count");
608 }