test cleanup
[Fuse-DBI] / t / 02sqlite.t
1 #!/usr/bin/perl -w
2
3 use strict;
4 use warnings;
5
6 use Test::More;
7 use File::Find;
8 use blib;
9
10 eval "use DBD::SQLite";
11 plan skip_all => "DBD::SQLite required for testing" if $@;
12 plan tests => 37;
13
14 use_ok('DBI');
15 use_ok('Fuse::DBI');
16
17 my $test_db = 'fusedbi.db';
18 my $dsn = "DBI:SQLite:dbname=$test_db";
19 my $mount = '/tmp/fuse_dbi_mnt';
20
21 ok((! -e $test_db || unlink $test_db), "test db: $test_db");
22
23 ok((! -e $mount || rmdir $mount), "mount point $mount");
24
25 mkdir $mount || die "mkdir $mount: $!";
26 ok(-d $mount, "mkdir $mount");
27
28 ok(my $dbh = DBI->connect($dsn, , '', '', { RaiseError => 1 }),
29         "connect fusedbi test database");
30
31 ok($dbh->do(qq{
32         create table files (
33                 name text primary key,
34                 data text
35         )
36 }), "create table files");
37
38 ok(my $sth = $dbh->prepare(qq{
39         insert into files (name,data) values (?,?)
40 }), "prepare");
41
42 my @files = qw(file dir/file dir/subdir/file);
43 my %file_data;
44
45 foreach my $file (@files) {
46         $file_data{$file} = ("this is test data on ".localtime()."\n") x length($file);
47         ok($sth->execute($file,$file_data{$file}), "insert $file");
48 }
49
50 ok($dbh->disconnect, "disconnect after insert");
51
52 my $sql_filenames = qq{
53         select
54                 name as id,
55                 name as filename,
56                 length(data) as size,
57                 1 as writable
58         from files
59 };
60
61 my $sql_read = qq{
62         select data
63                 from files
64                 where name = ?;
65 };
66
67 my $sql_update = qq{
68         update files
69                 set data = ?    
70                 where name = ?;
71 };
72
73 system "fusermount -q -u $mount" || diag "nothing mounted at $mount, ok";
74
75 my $mnt = Fuse::DBI->mount({
76         filenames => $sql_filenames,
77         read => $sql_read,
78         update => $sql_update,
79         dsn => $dsn,
80         mount => $mount,
81         fork => 1,
82 });
83
84 ok($mnt, "mount");
85
86 sub test_file {
87         my $f = $File::Find::name;
88
89         ok($f, "file $f");
90
91         return unless (-f $f);
92
93         ok(open(F, $f), "open");
94         my $tmp = '';
95         while(<F>) {
96                 $tmp .= $_;
97         }
98         ok(close(F), "close");
99
100         # strip mountpoint
101         $f =~ s#^\Q$mount\E/##;
102
103         ok($file_data{$f}, "$f exists");
104
105         cmp_ok(length($file_data{$f}), '==', length($tmp), "size");
106         cmp_ok($file_data{$f}, 'eq', $tmp, "content");
107 }
108
109 # small delay so that filesystem could mount
110 sleep(1);
111
112 find({ wanted => \&test_file, no_chdir => 1 }, $mount);
113
114 ok($mnt->umount,"umount");
115
116 ok(unlink $test_db,"rm $test_db");
117
118 ok(!-e $test_db,"cleanup");