Converted all tests to use File::Temp instead of t/test.db
[dbsrgits/DBM-Deep.git] / t / 27_filehandle.t
1 ##
2 # DBM::Deep Test
3 ##
4 use strict;
5 use Test::More tests => 11;
6 use Test::Exception;
7 use File::Temp qw( tempfile tempdir );
8
9 use_ok( 'DBM::Deep' );
10
11 my $dir = tempdir( CLEANUP => 1 );
12 my ($fh, $filename) = tempfile( 'tmpXXXX', UNLINK => 1, DIR => $dir );
13
14 # Create the datafile to be used
15 {
16     my $db = DBM::Deep->new( $filename );
17     $db->{hash} = { foo => [ 'a' .. 'c' ] };
18 }
19
20 {
21     open(FILE, $filename) || die("Can't open '$filename' for reading: $!\n");
22
23     my $db;
24
25     # test if we can open and read a db using its filehandle
26
27     ok(($db = DBM::Deep->new(fh => *FILE)), "open db in filehandle");
28     ok($db->{hash}->{foo}->[1] eq 'b', "and get at stuff in the database");
29     throws_ok {
30         $db->{foo} = 1;
31     } qr/Cannot write to a readonly filehandle/, "Can't write to a read-only filehandle";
32     ok( !$db->exists( 'foo' ), "foo doesn't exist" );
33
34     my $db_obj = $db->_get_self;
35     ok( $db_obj->_root->{inode}, "The inode has been set" );
36
37     close(FILE);
38 }
39
40 # now the same, but with an offset into the file.  Use the database that's
41 # embedded in the test for the DATA filehandle.  First, find the database ...
42 open(FILE, "t/28_DATA.t") || die("Can't open t/28_DATA.t\n");
43 while(my $line = <FILE>) {
44     last if($line =~ /^__DATA__/);
45 }
46 my $offset = tell(FILE);
47 close(FILE);
48
49 {
50     open(FILE, "t/28_DATA.t");
51
52     my $db;
53
54     ok(($db = DBM::Deep->new(fh => *FILE, file_offset => $offset)), "open db in filehandle with offset");
55
56     ok($db->{hash}->{foo}->[1] eq 'b', "and get at stuff in the database");
57
58     ok( !$db->exists( 'foo' ), "foo doesn't exist yet" );
59     throws_ok {
60         $db->{foo} = 1;
61     } qr/Cannot write to a readonly filehandle/, "Can't write to a read-only filehandle";
62     ok( !$db->exists( 'foo' ), "foo doesn't exist" );
63
64     close FILE;
65 }