]> wagnertech.de Git - mfinanz.git/blob - t/000setup_database.t
restart apache2 in postinst
[mfinanz.git] / t / 000setup_database.t
1 #!/usr/bin/perl
2
3 use strict;
4
5 use lib 't';
6
7 use SL::DB::Helper::ALL;
8
9 use Data::Dumper;
10 use Test::More;
11
12 use SL::Auth;
13 use SL::DBConnect;
14 use SL::Form;
15 use SL::InstanceConfiguration;
16 use SL::LXDebug;
17 use SL::Layout::None;
18 use SL::LxOfficeConf;
19 use Support::TestSetup;
20
21 our ($db_cfg, $dbh, $superuser_dbh);
22
23 sub dbg {
24   # diag(@_);
25 }
26
27 sub dbh_do {
28   my ($dbh, $query, %params) = @_;
29
30   if (ref($query)) {
31     return if $query->execute(@{ $params{bind} || [] });
32     BAIL_OUT($dbh->errstr);
33   }
34
35   return if $dbh->do($query, undef, @{ $params{bind} || [] });
36
37   BAIL_OUT($params{message} . ": " . $dbh->errstr) if $params{message};
38   BAIL_OUT("Query failed: " . $dbh->errstr . " ; query: $query");
39 }
40
41 sub verify_configuration {
42   SL::LxOfficeConf->read;
43
44   my %config = %{ $::lx_office_conf{'testing/database'} || {} };
45   my @unset  = sort grep { !$config{$_} } qw(host port db user template);
46
47   BAIL_OUT("Missing entries in configuration in section [testing/database]: " . join(' ', @unset)) if @unset;
48 }
49
50 sub setup {
51   package main;
52
53   $SIG{__DIE__}    = sub { Carp::confess( @_ ) } if $::lx_office_conf{debug}->{backtrace_on_die};
54   $::lxdebug       = LXDebug->new(target => LXDebug::STDERR_TARGET);
55   $::lxdebug->disable_sub_tracing;
56   $::locale        = Locale->new($::lx_office_conf{system}->{language});
57   $::form          = Support::TestSetup->create_new_form;
58   $::auth          = SL::Auth->new(unit_tests_database => 1);
59   $::locale        = Locale->new('de');
60   $::instance_conf = SL::InstanceConfiguration->new;
61   $db_cfg          = $::lx_office_conf{'testing/database'};
62 }
63
64 sub drop_and_create_database {
65   my @dbi_options = (
66     'dbi:Pg:dbname=' . $db_cfg->{template} . ';host=' . $db_cfg->{host} . ';port=' . $db_cfg->{port},
67     $db_cfg->{user},
68     $db_cfg->{password},
69     SL::DBConnect->get_options,
70   );
71
72   my $dbh_template = SL::DBConnect->connect(@dbi_options) || BAIL_OUT("No database connection to the template database: " . $DBI::errstr);
73   my $auth_dbh     = $::auth->dbconnect(1);
74
75   if ($auth_dbh) {
76     dbg("Database exists; dropping");
77     $auth_dbh->disconnect;
78
79     dbh_do($dbh_template, "DROP DATABASE \"" . $db_cfg->{db} . "\"", message => "Database could not be dropped");
80   }
81
82   dbg("Creating database");
83
84   dbh_do($dbh_template, "CREATE DATABASE \"" . $db_cfg->{db} . "\" TEMPLATE \"" . $db_cfg->{template} . "\" ENCODING 'UNICODE'", message => "Database could not be created");
85   $dbh_template->disconnect;
86 }
87
88 sub report_success {
89   $dbh->disconnect;
90   $superuser_dbh->disconnect if $superuser_dbh;
91   ok(1, "Database has been set up successfully.");
92   done_testing();
93 }
94
95 sub apply_dbupgrade {
96   my ($dbupdater, $control_or_file) = @_;
97
98   my $file    = ref($control_or_file) ? ("sql/Pg-upgrade2" . ($dbupdater->{auth} ? "-auth" : "") . "/$control_or_file->{file}") : $control_or_file;
99   my $control = ref($control_or_file) ? $control_or_file                                                                        : undef;
100
101   dbg("Applying $file");
102
103   my $script_dbh = $control && $control->{superuser_privileges} ? ($superuser_dbh // $dbh) : $dbh;
104   my $error      = $dbupdater->process_file($script_dbh, $file, $control);
105
106   BAIL_OUT("Error applying $file: $error") if $error;
107 }
108
109 sub create_initial_schema {
110   dbg("Creating initial schema");
111
112   my @dbi_options = (
113     'dbi:Pg:dbname=' . $db_cfg->{db} . ';host=' . $db_cfg->{host} . ';port=' . $db_cfg->{port},
114     $db_cfg->{user},
115     $db_cfg->{password},
116     SL::DBConnect->get_options(PrintError => 0, PrintWarn => 0),
117   );
118
119   $dbh           = SL::DBConnect->connect(@dbi_options) || BAIL_OUT("Database connection failed: " . $DBI::errstr);
120   $::auth->{dbh} = $dbh;
121   my $dbupdater  = SL::DBUpgrade2->new(form => $::form, return_on_error => 1, silent => 1);
122   my $coa        = 'Germany-DATEV-SKR03EU';
123
124   if ($db_cfg->{superuser_user} && ($db_cfg->{superuser_user} ne $db_cfg->{user})) {
125     @dbi_options = (
126       'dbi:Pg:dbname=' . $db_cfg->{db} . ';host=' . $db_cfg->{host} . ';port=' . $db_cfg->{port},
127       $db_cfg->{superuser_user},
128       $db_cfg->{superuser_password},
129       SL::DBConnect->get_options(PrintError => 0, PrintWarn => 0),
130     );
131
132     $superuser_dbh = SL::DBConnect->connect(@dbi_options) || BAIL_OUT("Database superuser connection failed: " . $DBI::errstr);
133   }
134
135   apply_dbupgrade($dbupdater, "sql/lx-office.sql");
136   apply_dbupgrade($dbupdater, "sql/${coa}-chart.sql");
137
138   dbh_do($dbh, qq|UPDATE defaults SET coa = '${coa}', accounting_method = 'cash', profit_determination = 'income', inventory_system = 'periodic', curr = 'EUR'|);
139   dbh_do($dbh, qq|CREATE TABLE schema_info (tag TEXT, login TEXT, itime TIMESTAMP DEFAULT now(), PRIMARY KEY (tag))|);
140 }
141
142 sub create_initial_auth_schema {
143   dbg("Creating initial auth schema");
144
145   my $dbupdater = SL::DBUpgrade2->new(form => $::form, return_on_error => 1, auth => 1);
146   apply_dbupgrade($dbupdater, 'sql/auth_db.sql');
147 }
148
149 sub apply_upgrades {
150   my %params            = @_;
151   my $dbupdater         = SL::DBUpgrade2->new(form => $::form, return_on_error => 1, auth => $params{auth});
152   my @unapplied_scripts = $dbupdater->unapplied_upgrade_scripts($dbh);
153
154   apply_dbupgrade($dbupdater, $_) for @unapplied_scripts;
155 }
156
157 sub create_client_user_and_employee {
158   dbg("Creating client, user, group and employee");
159
160   dbh_do($dbh, qq|DELETE FROM auth.clients|);
161   dbh_do($dbh, qq|INSERT INTO auth.clients (id, name, dbhost, dbport, dbname, dbuser, dbpasswd, is_default) VALUES (1, 'Unit-Tests', ?, ?, ?, ?, ?, TRUE)|,
162          bind => [ @{ $db_cfg }{ qw(host port db user password) } ]);
163   dbh_do($dbh, qq|INSERT INTO auth."user"         (id,        login)    VALUES (1, 'unittests')|);
164   dbh_do($dbh, qq|INSERT INTO auth."group"        (id,        name)     VALUES (1, 'Vollzugriff')|);
165   dbh_do($dbh, qq|INSERT INTO auth.clients_users  (client_id, user_id)  VALUES (1, 1)|);
166   dbh_do($dbh, qq|INSERT INTO auth.clients_groups (client_id, group_id) VALUES (1, 1)|);
167   dbh_do($dbh, qq|INSERT INTO auth.user_group     (user_id,   group_id) VALUES (1, 1)|);
168
169   my %config                 = (
170     default_printer_id       => '',
171     template_format          => '',
172     default_media            => '',
173     email                    => 'unit@tester',
174     tel                      => '',
175     dateformat               => 'dd.mm.yy',
176     show_form_details        => '',
177     name                     => 'Unit Tester',
178     signature                => '',
179     hide_cvar_search_options => '',
180     numberformat             => '1.000,00',
181     favorites                => '',
182     copies                   => '',
183     menustyle                => 'v3',
184     fax                      => '',
185     stylesheet               => 'lx-office-erp.css',
186     mandatory_departments    => 0,
187     countrycode              => 'de',
188   );
189
190   my $sth = $dbh->prepare(qq|INSERT INTO auth.user_config (user_id, cfg_key, cfg_value) VALUES (1, ?, ?)|) || BAIL_OUT($dbh->errstr);
191   dbh_do($dbh, $sth, bind => [ $_, $config{$_} ]) for sort keys %config;
192   $sth->finish;
193
194   $sth = $dbh->prepare(qq|INSERT INTO auth.group_rights (group_id, "right", granted) VALUES (1, ?, TRUE)|) || BAIL_OUT($dbh->errstr);
195   dbh_do($dbh, $sth, bind => [ $_ ]) for sort $::auth->all_rights;
196   $sth->finish;
197
198   dbh_do($dbh, qq|INSERT INTO employee (id, login, name) VALUES (1, 'unittests', 'Unit Tester')|);
199
200   $::auth->set_client(1) || BAIL_OUT("\$::auth->set_client(1) failed");
201   %::myconfig = $::auth->read_user(login => 'unittests');
202 }
203
204 verify_configuration();
205 setup();
206 drop_and_create_database();
207 create_initial_schema();
208 create_initial_auth_schema();
209 apply_upgrades(auth => 1);
210 create_client_user_and_employee();
211 apply_upgrades();
212 report_success();
213
214 1;