Consolidation and extended test runs
[kivitendo-erp.git] / t / 000setup_database.t
1 #!/usr/bin/perl
2
3 use strict;
4
5 use lib 't';
6
7 use Data::Dumper;
8 use Test::More;
9
10 use SL::Auth;
11 use SL::DBConnect;
12 use SL::Form;
13 use SL::InstanceConfiguration;
14 use SL::LXDebug;
15 use SL::Layout::None;
16 use SL::LxOfficeConf;
17
18 our ($db_cfg, $dbh);
19
20 sub dbg {
21   # diag(@_);
22 }
23
24 sub dbh_do {
25   my ($dbh, $query, %params) = @_;
26
27   if (ref($query)) {
28     return if $query->execute(@{ $params{bind} || [] });
29     BAIL_OUT($dbh->errstr);
30   }
31
32   return if $dbh->do($query, undef, @{ $params{bind} || [] });
33
34   BAIL_OUT($params{message} . ": " . $dbh->errstr) if $params{message};
35   BAIL_OUT("Query failed: " . $dbh->errstr . " ; query: $query");
36 }
37
38 sub verify_configuration {
39   SL::LxOfficeConf->read;
40
41   my %config = %{ $::lx_office_conf{'testing/database'} || {} };
42   my @unset  = sort grep { !$config{$_} } qw(host port db user template);
43
44   BAIL_OUT("Missing entries in configuration in section [testing/database]: " . join(' ', @unset)) if @unset;
45 }
46
47 sub setup {
48   package main;
49
50   $SIG{__DIE__}    = sub { Carp::confess( @_ ) } if $::lx_office_conf{debug}->{backtrace_on_die};
51   $::lxdebug       = LXDebug->new(target => LXDebug::STDERR_TARGET);
52   $::lxdebug->disable_sub_tracing;
53   $::locale        = Locale->new($::lx_office_conf{system}->{language});
54   $::form          = Form->new;
55   $::auth          = SL::Auth->new(unit_tests_database => 1);
56   $::locale        = Locale->new('de');
57   $::instance_conf = SL::InstanceConfiguration->new;
58   $db_cfg          = $::lx_office_conf{'testing/database'};
59 }
60
61 sub drop_and_create_database {
62   my @dbi_options = (
63     'dbi:Pg:dbname=' . $db_cfg->{template} . ';host=' . $db_cfg->{host} . ';port=' . $db_cfg->{port},
64     $db_cfg->{user},
65     $db_cfg->{password},
66     SL::DBConnect->get_options,
67   );
68
69   $::auth->reset;
70   my $dbh_template = SL::DBConnect->connect(@dbi_options) || BAIL_OUT("No database connection to the template database: " . $DBI::errstr);
71   my $auth_dbh     = $::auth->dbconnect(1);
72
73   if ($auth_dbh) {
74     dbg("Database exists; dropping");
75     $auth_dbh->disconnect;
76
77     dbh_do($dbh_template, "DROP DATABASE \"" . $db_cfg->{db} . "\"", message => "Database could not be dropped");
78
79     $::auth->reset;
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   ok(1, "Database has been setup sucessfully.");
91   done_testing();
92 }
93
94 sub apply_dbupgrade {
95   my ($dbupdater, $control_or_file) = @_;
96
97   my $file    = ref($control_or_file) ? ("sql/Pg-upgrade2" . ($dbupdater->{auth} ? "-auth" : "") . "/$control_or_file->{file}") : $control_or_file;
98   my $control = ref($control_or_file) ? $control_or_file                                                                        : undef;
99
100   dbg("Applying $file");
101
102   my $error = $dbupdater->process_file($dbh, $file, $control);
103
104   BAIL_OUT("Error applying $file: $error") if $error;
105 }
106
107 sub create_initial_schema {
108   dbg("Creating initial schema");
109
110   my @dbi_options = (
111     'dbi:Pg:dbname=' . $db_cfg->{db} . ';host=' . $db_cfg->{host} . ';port=' . $db_cfg->{port},
112     $db_cfg->{user},
113     $db_cfg->{password},
114     SL::DBConnect->get_options(PrintError => 0, PrintWarn => 0),
115   );
116
117   $dbh           = SL::DBConnect->connect(@dbi_options) || BAIL_OUT("Database connection failed: " . $DBI::errstr);
118   $::auth->{dbh} = $dbh;
119   my $dbupdater  = SL::DBUpgrade2->new(form => $::form, return_on_error => 1, silent => 1);
120   my $defaults   = SL::DefaultManager->new($::lx_office_conf{system}->{default_manager});
121   my $coa        = $defaults->chart_of_accounts( 'Germany-DATEV-SKR03EU' );
122   my $am         = $defaults->accounting_method( 'cash' );
123   my $pd         = $defaults->profit_determination( 'balance' );
124   my $is         = $defaults->inventory_system( 'periodic' );
125   my $curr       = $defaults->currency( 'EUR' );
126
127   apply_dbupgrade($dbupdater, "sql/lx-office.sql");
128   apply_dbupgrade($dbupdater, "sql/${coa}-chart.sql");
129
130   dbh_do($dbh, qq|UPDATE defaults SET coa = '${coa}', accounting_method = '${am}', profit_determination = '${pd}', inventory_system = '${is}', curr = '${curr}'|);
131   dbh_do($dbh, qq|CREATE TABLE schema_info (tag TEXT, login TEXT, itime TIMESTAMP DEFAULT now(), PRIMARY KEY (tag))|);
132 }
133
134 sub create_initial_auth_schema {
135   dbg("Creating initial auth schema");
136
137   my $dbupdater = SL::DBUpgrade2->new(form => $::form, return_on_error => 1, auth => 1);
138   apply_dbupgrade($dbupdater, 'sql/auth_db.sql');
139 }
140
141 sub apply_upgrades {
142   my %params            = @_;
143   my $dbupdater         = SL::DBUpgrade2->new(form => $::form, return_on_error => 1, auth => $params{auth});
144   my @unapplied_scripts = $dbupdater->unapplied_upgrade_scripts($dbh);
145
146   apply_dbupgrade($dbupdater, $_) for @unapplied_scripts;
147
148   # some dpupgrades are hardcoded for Germany and will be recovered by the same nasty code
149   if ((not defined $params{auth}) && ($::lx_office_conf{system}->{default_manager} eq "swiss")) {
150     # buchungsgruppen_sortkey.sql depends release_2_4_1
151     dbh_do($dbh, qq|UPDATE buchungsgruppen SET sortkey=1  WHERE description='Standard 8%'|);
152     dbh_do($dbh, qq|UPDATE buchungsgruppen SET sortkey=2  WHERE description='Standard 2.5%'|);
153     # steuerfilterung.pl depends release_3_0_0
154     dbh_do($dbh, qq|ALTER TABLE tax ADD chart_categories TEXT|);
155     dbh_do($dbh, qq|UPDATE tax SET chart_categories = 'I' WHERE (taxnumber='2200') OR (taxnumber='2201')|);
156     dbh_do($dbh, qq|UPDATE tax SET chart_categories = 'E' WHERE (taxnumber='1170') OR (taxnumber='1171')|);
157     dbh_do($dbh, qq|UPDATE tax SET chart_categories = 'ALQCIE' WHERE chart_categories IS NULL|);
158     dbh_do($dbh, qq|ALTER TABLE tax ALTER COLUMN chart_categories SET NOT NULL|);
159     # taxzone_id_in_oe_delivery_orders.sql depends release_3_1_0
160     dbh_do($dbh, qq|UPDATE oe SET taxzone_id = (SELECT id FROM tax_zones WHERE description = 'Schweiz') WHERE (taxzone_id = 0) OR (taxzone_id IS NULL)|);
161     dbh_do($dbh, qq|UPDATE delivery_orders SET taxzone_id = (SELECT id FROM tax_zones WHERE description = 'Schweiz') WHERE (taxzone_id = 0) OR (taxzone_id IS NULL)|);
162     dbh_do($dbh, qq|UPDATE ar SET taxzone_id = (SELECT id FROM tax_zones WHERE description = 'Schweiz') WHERE (taxzone_id = 0) OR (taxzone_id IS NULL)|);
163     dbh_do($dbh, qq|UPDATE ap SET taxzone_id = (SELECT id FROM tax_zones WHERE description = 'Schweiz') WHERE (taxzone_id = 0) OR (taxzone_id IS NULL)|);
164     # tax_skonto_automatic.sql depends release_3_2_0
165     dbh_do($dbh, qq|UPDATE tax SET skonto_purchase_chart_id = (SELECT id FROM chart WHERE accno = '4900')|);
166     dbh_do($dbh, qq|UPDATE tax SET skonto_sales_chart_id = (SELECT id FROM chart WHERE accno = '3800')|);
167     # not available
168     dbh_do($dbh, qq|UPDATE defaults SET rndgain_accno_id = (SELECT id FROM CHART WHERE accno='6953')|);
169     dbh_do($dbh, qq|UPDATE defaults SET rndloss_accno_id = (SELECT id FROM CHART WHERE accno='6943')|);
170   }
171 }
172
173 sub create_client_user_and_employee {
174   dbg("Creating client, user, group and employee");
175
176   dbh_do($dbh, qq|DELETE FROM auth.clients|);
177   dbh_do($dbh, qq|INSERT INTO auth.clients (id, name, dbhost, dbport, dbname, dbuser, dbpasswd, is_default) VALUES (1, 'Unit-Tests', ?, ?, ?, ?, ?, TRUE)|,
178          bind => [ @{ $db_cfg }{ qw(host port db user password) } ]);
179   dbh_do($dbh, qq|INSERT INTO auth."user"         (id,        login)    VALUES (1, 'unittests')|);
180   dbh_do($dbh, qq|INSERT INTO auth."group"        (id,        name)     VALUES (1, 'Vollzugriff')|);
181   dbh_do($dbh, qq|INSERT INTO auth.clients_users  (client_id, user_id)  VALUES (1, 1)|);
182   dbh_do($dbh, qq|INSERT INTO auth.clients_groups (client_id, group_id) VALUES (1, 1)|);
183   dbh_do($dbh, qq|INSERT INTO auth.user_group     (user_id,   group_id) VALUES (1, 1)|);
184
185   my %config                 = (
186     default_printer_id       => '',
187     template_format          => '',
188     default_media            => '',
189     email                    => 'unit@tester',
190     tel                      => '',
191     dateformat               => 'dd.mm.yy',
192     show_form_details        => '',
193     name                     => 'Unit Tester',
194     signature                => '',
195     hide_cvar_search_options => '',
196     numberformat             => '1.000,00',
197     vclimit                  => 0,
198     favorites                => '',
199     copies                   => '',
200     menustyle                => 'v3',
201     fax                      => '',
202     stylesheet               => 'lx-office-erp.css',
203     mandatory_departments    => 0,
204     countrycode              => 'de',
205   );
206
207   my $sth = $dbh->prepare(qq|INSERT INTO auth.user_config (user_id, cfg_key, cfg_value) VALUES (1, ?, ?)|) || BAIL_OUT($dbh->errstr);
208   dbh_do($dbh, $sth, bind => [ $_, $config{$_} ]) for sort keys %config;
209   $sth->finish;
210
211   $sth = $dbh->prepare(qq|INSERT INTO auth.group_rights (group_id, "right", granted) VALUES (1, ?, TRUE)|) || BAIL_OUT($dbh->errstr);
212   dbh_do($dbh, $sth, bind => [ $_ ]) for sort $::auth->all_rights;
213   $sth->finish;
214
215   dbh_do($dbh, qq|INSERT INTO employee (id, login, name) VALUES (1, 'unittests', 'Unit Tester')|);
216
217   $::auth->set_client(1) || BAIL_OUT("\$::auth->set_client(1) failed");
218   %::myconfig = $::auth->read_user(login => 'unittests');
219 }
220
221 verify_configuration();
222 setup();
223 drop_and_create_database();
224 create_initial_schema();
225 create_initial_auth_schema();
226 apply_upgrades(auth => 1);
227 create_client_user_and_employee();
228 apply_upgrades();
229 report_success();
230
231 1;