make tests more robust
[dbsrgits/DBIx-Data-Store-old.git] / t / 01basic_collection.t
1 use Test::More;
2 use DBIx::Data::Store;
3 use DBIx::Data::Store::CRUD;
4 use DBIx::Data::Collection::Set;
5 use DBI;
6
7 use strict;
8 use warnings FATAL => 'all';
9
10 my $dsn = 'dbi:SQLite:tmp.db';
11
12 my @expect;
13
14 sub sort_set {
15   sort { $a->{name} cmp $b->{name} } @_
16 }
17
18 {
19   unlink('tmp.db');
20   my $dbh = DBI->connect($dsn);
21   $dbh->do(q{
22     CREATE TABLE person (
23       id INTEGER NOT NULL PRIMARY KEY,
24       name VARCHAR(255) NOT NULL
25     )
26   });
27   my $pop = $dbh->prepare(q{INSERT INTO person (name) VALUES (?)});
28   my @names = qw(Joe Jim Bob Pterry);
29   $pop->execute($_) for @names;
30   @expect = sort_set do {
31     my $id = 0; map +{ id => ++$id, name => $_ }, @names
32   };
33 }
34
35 sub make_set {
36   my ($set, $crud) = @_;
37   DBIx::Data::Collection::Set->new(
38     store => DBIx::Data::Store::CRUD->new(
39       raw_store => DBIx::Data::Store->connect($dsn),
40       select_sql => q{SELECT id, name FROM person},
41       select_column_order => [ qw(id name) ],
42       %$crud,
43     ),
44     %$set
45   );
46 }
47
48 my $set = make_set;
49
50 is_deeply([ sort_set $set->flatten ], \@expect, 'Basic data out ok (flatten)');
51
52 {
53   my $stream = $set->as_stream;
54
55   my @got; while (my ($next) = $stream->next) { push @got, $next }
56
57   is_deeply([ sort_set @got ], \@expect, 'Basic data out ok (stream)');
58 }
59
60 $set = make_set { class => 'Spoon' };
61
62 is_deeply(
63   [ sort_set $set->flatten ],
64   [ map { bless({ %$_ }, 'Spoon') } @expect ],
65   'Basic data with class out ok'
66 );
67
68 done_testing;