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