summaryrefslogtreecommitdiffstats
path: root/xt/config/generate_test_data.pl
blob: ab186698dcfe19d82852a8d9464f282132b1b73f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
#!/usr/bin/perl

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# This Source Code Form is "Incompatible With Secondary Licenses", as
# defined by the Mozilla Public License, v. 2.0.

# -*- Mode: perl; indent-tabs-mode: nil -*-

use 5.10.1;
use strict;
use warnings;

use Cwd;

my $conf_path;
my $config;

BEGIN {
    say 'reading the config file...';
    my $conf_file = 'selenium_test.conf';
    $config = do "$conf_file"
        or die "can't read configuration '$conf_file': $!$@";

    $conf_path = $config->{bugzilla_path};

    # We don't want randomly-generated keys. We want the ones specified
    # in the config file so that we can use them in tests scripts.
    *Bugzilla::User::APIKey::_check_api_key = sub { return $_[1]; };
}

use lib $conf_path;

use Bugzilla;
use Bugzilla::Attachment;
use Bugzilla::Bug;
use Bugzilla::User;
use Bugzilla::Install;
use Bugzilla::Milestone;
use Bugzilla::Product;
use Bugzilla::Component;
use Bugzilla::Group;
use Bugzilla::Version;
use Bugzilla::Constants;
use Bugzilla::Keyword;
use Bugzilla::Config qw(:admin);
use Bugzilla::User::Setting;
use Bugzilla::User::APIKey;

my $dbh = Bugzilla->dbh;

# set Bugzilla usage mode to USAGE_MODE_CMDLINE
Bugzilla->usage_mode(USAGE_MODE_CMDLINE);

##########################################################################
# Set Parameters
##########################################################################

# Some parameters must be turned on to create bugs requiring them.
# They are also expected to be turned on by some webservice_*.t scripts.
my ($urlbase, $sslbase);
$urlbase = $config->{browser_url} . '/' . $config->{bugzilla_installation};
$urlbase .= '/' unless $urlbase =~ /\/$/;

if ($urlbase =~ /^https/) {
    $sslbase = $urlbase;
    $urlbase =~ s/^https(.+)$/http$1/;
}

my %set_params = (
    urlbase => $urlbase,
    sslbase => $sslbase,
    useqacontact  => 1,
    mail_delivery_method => 'Test',
    maxattachmentsize => 256,
);

my $params_modified;
foreach my $param (keys %set_params) {
    my $value = $set_params{$param};
    next unless defined $value && Bugzilla->params->{$param} ne $value;
    SetParam($param, $value);
    $params_modified = 1;
}

write_params() if $params_modified;

##########################################################################
# Set Default User Preferences
##########################################################################

# When editing a bug, the page being displayed depends on the
# post_bug_submit_action user pref. We set it globally so that we know
# the exact behavior of process_bug.cgi.
my %user_prefs = (post_bug_submit_action => 'nothing');

foreach my $pref (keys %user_prefs) {
    my $value = $user_prefs{$pref};
    Bugzilla::User::Setting::set_default($pref, $value, 0);
}

##########################################################################
# Create Users
##########################################################################

# First of all, remove the default .* regexp for the editbugs group.
my $group = Bugzilla::Group->new({ name => 'editbugs' });
$group->set_user_regexp('');
$group->update();

my @usernames = (
    'admin',            'no-privs',
    'QA-Selenium-TEST', 'canconfirm',
    'tweakparams',      'permanent_user',
    'editbugs',         'disabled',
);

say 'creating user accounts...';
foreach my $username (@usernames) {
    my ($password, $login);

    my $prefix = $username;
    if ($username eq 'permanent_user') {
        $password = $config->{admin_user_passwd};
        $login = $config->{$username};
    }
    elsif ($username eq 'no-privs') {
        $prefix = 'unprivileged';
    }
    elsif ($username eq 'QA-Selenium-TEST') {
        $prefix = 'QA_Selenium_TEST';
    }

    $password ||= $config->{"${prefix}_user_passwd"};
    $login ||= $config->{"${prefix}_user_login"};
    my $api_key = $config->{"${prefix}_user_api_key"};

    if (is_available_username($login)) {
        my %extra_args;
        if ($username eq 'disabled') {
            $extra_args{disabledtext} = '!!This is the text!!';
        }

        my $user = Bugzilla::User->create(
            { login_name    => $login,
              realname      => $username,
              cryptpassword => $password,
              %extra_args,
            }
        );

        if ($api_key) {
            Bugzilla::User::APIKey->create(
                { user_id     => $user->id,
                  description => 'API key for QA tests',
                  api_key     => $api_key }
            );
        }

        if ($username eq 'admin' or $username eq 'permanent_user') {
            Bugzilla::Install::make_admin($login);
        }
    }
}

##########################################################################
# Create Bugs
##########################################################################

# login to bugzilla
my $admin_user = Bugzilla::User->check($config->{admin_user_login});
Bugzilla->set_user($admin_user);

my %field_values = (
    'priority'     => 'Highest',
    'bug_status'   => 'CONFIRMED',
    'version'      => 'unspecified',
    'bug_file_loc' => '',
    'comment'      => 'please ignore this bug',
    'component'    => 'TestComponent',
    'rep_platform' => 'All',
    'short_desc'   => 'This is a testing bug only',
    'product'      => 'TestProduct',
    'op_sys'       => 'Linux',
    'bug_severity' => 'normal',
);

say 'creating bugs...';
my $bug = Bugzilla::Bug->create( \%field_values );
say 'Bug ' . $bug->id . ' created';
if (Bugzilla::Bug->new('public_bug')->{error}) {
    # The deadline must be set so that this bug can be used to test
    # timetracking fields using WebServices.
    $bug = Bugzilla::Bug->create({ %field_values, alias => 'public_bug', deadline => '2010-01-01' });
    say 'Bug ' . $bug->id . ' (alias: public_bug) created';
}

##########################################################################
# Create Classifications
##########################################################################

my @classifications = ({ name        => 'Class2_QA',
                         description => "required by Selenium... DON'T DELETE" },
);

say 'creating classifications...';
for my $class (@classifications) {
    my $new_class = Bugzilla::Classification->new({ name => $class->{name} });
    if (!$new_class) {
        $dbh->do('INSERT INTO classifications (name, description) VALUES (?, ?)',
                 undef, ($class->{name}, $class->{description}));
    }
}
##########################################################################
# Create Products
##########################################################################

my @products = (
    {   product_name     => 'QA-Selenium-TEST',
        description      => "used by Selenium test.. DON'T DELETE",
        versions         => ['unspecified', 'QAVersion'],
        milestones       => ['QAMilestone'],
        defaultmilestone => '---',
        components       => [
            {   name             => 'QA-Selenium-TEST',
                description      => "used by Selenium test.. DON'T DELETE",
                initialowner     => $config->{QA_Selenium_TEST_user_login},
                initialqacontact => $config->{QA_Selenium_TEST_user_login},
                initial_cc       => [$config->{QA_Selenium_TEST_user_login}],
            }
        ],
    },

    {   product_name => 'Another Product',
        description  => 'Alternate product used by Selenium. <b>Do not edit!</b>',
        versions         => ['unspecified', 'Another1', 'Another2'],
        milestones       => ['AnotherMS1', 'AnotherMS2', 'Milestone'],
        defaultmilestone => '---',
        components       => [
            {   name             => 'c1',
                description      => 'c1',
                initialowner     => $config->{permanent_user},
                initialqacontact => '',
                initial_cc       => [],
            },
            {   name             => 'c2',
                description      => 'c2',
                initialowner     => $config->{permanent_user},
                initialqacontact => '',
                initial_cc       => [],
            },
        ],
    },

    {   product_name     => 'C2 Forever',
        description      => 'I must remain in the Class2_QA classification ' .
                            'in all cases! Do not edit!',
        classification   => 'Class2_QA',
        versions         => ['unspecified', 'C2Ver'],
        milestones       => ['C2Mil'],
        defaultmilestone => '---',
        components       => [
            {   name             => 'Helium',
                description      => 'Feel free to add bugs to me',
                initialowner     => $config->{permanent_user},
                initialqacontact => '',
                initial_cc       => [],
            }
        ],
    },

    {   product_name     => 'QA Entry Only',
        description      => 'Only the QA group may enter bugs here.',
        versions         => ['unspecified'],
        milestones       => [],
        defaultmilestone => '---',
        components       => [
            {   name             => 'c1',
                description      => "Same name as Another Product's component",
                initialowner     => $config->{QA_Selenium_TEST_user_login},
                initialqacontact => '',
                initial_cc       => [],
            }
        ],
    },

    {   product_name     => 'QA Search Only',
        description      => 'Only the QA group may search for bugs here.',
        versions         => ['unspecified'],
        milestones       => [],
        defaultmilestone => '---',
        components       => [
            {   name             => 'c1',
                description      => 'Still same name as the Another component',
                initialowner     => $config->{QA_Selenium_TEST_user_login},
                initialqacontact => '',
                initial_cc       => [],
            }
        ],
    },
);

say 'creating products...';
foreach my $product (@products) {
    my $new_product = Bugzilla::Product->new({ name => $product->{product_name} });
    if (!$new_product) {
        my $class_id = 1;
        if ($product->{classification}) {
            $class_id = Bugzilla::Classification->new({ name => $product->{classification} })->id;
        }
        $dbh->do('INSERT INTO products (name, description, classification_id) VALUES (?, ?, ?)',
            undef, ($product->{product_name}, $product->{description}, $class_id));

        $new_product = Bugzilla::Product->new({ name => $product->{product_name} });

        $dbh->do('INSERT INTO milestones (product_id, value) VALUES (?, ?)',
            undef, ($new_product->id, $product->{defaultmilestone} ));

        # Now clear the internal list of accessible products.
        delete Bugzilla->user->{selectable_products};

        foreach my $component (@{ $product->{components} }) {
            Bugzilla::Component->create(
                {   name             => $component->{name},
                    product          => $new_product,
                    description      => $component->{description},
                    initialowner     => $component->{initialowner},
                    initialqacontact => $component->{initialqacontact},
                    initial_cc       => $component->{initial_cc},
                }
            );
        }
    }

    foreach my $version (@{ $product->{versions} }) {
        my $new_version = Bugzilla::Version->new({ name => $version, product => $new_product });
        if (!$new_version) {
            Bugzilla::Version->create({ value => $version, product => $new_product });
        }
    }

    foreach my $milestone (@{ $product->{milestones} }) {
        my $new_milestone = Bugzilla::Milestone->new({ name => $milestone, product => $new_product });
        if (!$new_milestone) {
            # We don't use Bugzilla::Milestone->create because we want to
            # bypass security checks.
            $dbh->do('INSERT INTO milestones (product_id, value) VALUES (?,?)',
                     undef, $new_product->id, $milestone);
        }
    }
}

##########################################################################
# Create Groups
##########################################################################

# create Master group
my ($group_name, $group_desc) = ('Master', 'Master Selenium Group <b>DO NOT EDIT!</b>');

say 'creating groups...';
my $new_group = Bugzilla::Group->new({ name => $group_name });
if (!$new_group) {
    my $group = Bugzilla::Group->create({ name => $group_name,
                                          description => $group_desc,
                                          isbuggroup => 1});

    $dbh->do('INSERT INTO group_control_map
              (group_id, product_id, entry, membercontrol, othercontrol, canedit)
              SELECT ?, products.id, 0, ?, ?, 0 FROM products',
              undef, ($group->id, CONTROLMAPSHOWN, CONTROLMAPSHOWN));
}

# create QA-Selenium-TEST group. Do not use Group->create() so that
# the admin group doesn't inherit membership (yes, that's what we want!).
($group_name, $group_desc) = ('QA-Selenium-TEST', "used by Selenium test.. DON'T DELETE");

$new_group = Bugzilla::Group->new({ name => $group_name });
if (!$new_group) {
    $dbh->do('INSERT INTO groups (name, description, isbuggroup, isactive)
              VALUES (?, ?, 1, 1)', undef, ($group_name, $group_desc));
}

##########################################################################
# Add Users to Groups
##########################################################################

my @users_groups = (
    { user => $config->{QA_Selenium_TEST_user_login}, group => 'QA-Selenium-TEST' },
    { user => $config->{tweakparams_user_login},      group => 'tweakparams' },
    { user => $config->{canconfirm_user_login},       group => 'canconfirm' },
    { user => $config->{editbugs_user_login},         group => 'editbugs' },
);

say 'adding users to groups...';
foreach my $user_group (@users_groups) {
    my $group = Bugzilla::Group->new({ name => $user_group->{group} });
    my $user = Bugzilla::User->new({ name => $user_group->{user} });

    my $sth_add_mapping =
      $dbh->prepare('INSERT INTO user_group_map (user_id, group_id, isbless, grant_type)
                     VALUES (?, ?, ?, ?)');
    # Don't crash if the entry already exists.
    eval { $sth_add_mapping->execute($user->id, $group->id, 0, GRANT_DIRECT); };
}

##########################################################################
# Associate Products with groups
##########################################################################

# Associate the QA-Selenium-TEST group with the QA-Selenium-TEST.
my $created_group   = Bugzilla::Group->new({ name => 'QA-Selenium-TEST' });
my $secret_product = Bugzilla::Product->new({ name => 'QA-Selenium-TEST' });
my $no_entry = Bugzilla::Product->new({ name => 'QA Entry Only' });
my $no_search = Bugzilla::Product->new({ name => 'QA Search Only' });

say 'restricting products to groups...';
# Don't crash if the entries already exist.
my $sth = $dbh->prepare('INSERT INTO group_control_map
                         (group_id, product_id, entry, membercontrol, othercontrol, canedit)
                         VALUES (?, ?, ?, ?, ?, ?)');
eval { $sth->execute($created_group->id, $secret_product->id, 1, CONTROLMAPMANDATORY, CONTROLMAPMANDATORY, 0); };
eval { $sth->execute($created_group->id, $no_entry->id,       1, CONTROLMAPNA,        CONTROLMAPNA,        0); };
eval { $sth->execute($created_group->id, $no_search->id,      0, CONTROLMAPMANDATORY, CONTROLMAPMANDATORY, 0); };

##########################################################################
# Create flag types
##########################################################################

my @flagtypes = (
    {name => 'spec_multi_flag', desc => 'Specifically requestable and multiplicable bug flag',
     is_requestable => 1, is_requesteeble => 1, is_multiplicable => 1, grant_group => 'editbugs',
     target_type => 'b', cc_list => '', inclusions => ['Another Product:c1']},
);

say 'creating flag types...';
foreach my $flag (@flagtypes) {
    # The name is not unique, even within a single product/component, so there is NO WAY
    # to know if the existing flag type is the one we want or not.
    # As our Selenium scripts would be confused anyway if there is already such a flag name,
    # we simply skip it and assume the existing flag type is the one we want.
    next if Bugzilla::FlagType->new({ name => $flag->{name} });

    my $grant_group_id = $flag->{grant_group} ? Bugzilla::Group->new({ name => $flag->{grant_group} })->id : undef;
    my $request_group_id = $flag->{request_group} ? Bugzilla::Group->new({ name => $flag->{request_group} })->id : undef;

    $dbh->do('INSERT INTO flagtypes (name, description, cc_list, target_type, is_requestable,
                                     is_requesteeble, is_multiplicable, grant_group_id, request_group_id)
                             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
             undef, ($flag->{name}, $flag->{desc}, $flag->{cc_list}, $flag->{target_type},
                     $flag->{is_requestable}, $flag->{is_requesteeble}, $flag->{is_multiplicable},
                     $grant_group_id, $request_group_id));

    my $type_id = $dbh->bz_last_key('flagtypes', 'id');

    foreach my $inclusion (@{$flag->{inclusions}}) {
        my ($product, $component) = split(':', $inclusion);
        my ($prod_id, $comp_id);
        if ($product) {
            my $prod_obj = Bugzilla::Product->new({ name => $product });
            $prod_id = $prod_obj->id;
            if ($component) {
                $comp_id = Bugzilla::Component->new({ name => $component, product => $prod_obj})->id;
            }
        }
        $dbh->do('INSERT INTO flaginclusions (type_id, product_id, component_id)
                  VALUES (?, ?, ?)',
                 undef, ($type_id, $prod_id, $comp_id));
    }
}

##########################################################################
# Create custom fields
##########################################################################

my @fields = (
    { name        => 'cf_QA_status',
      description => 'QA Status',
      type        => FIELD_TYPE_MULTI_SELECT,
      sortkey     => 100,
      mailhead    => 0,
      enter_bug   => 1,
      obsolete    => 0,
      custom      => 1,
      values      => ['verified', 'in progress', 'untested']
    },
    { name        => 'cf_single_select',
      description => 'SingSel',
      type        => FIELD_TYPE_SINGLE_SELECT,
      mailhead    => 0,
      enter_bug   => 1,
      custom      => 1,
      values      => [qw(one two three)],
    },
);

say 'creating custom fields...';
foreach my $f (@fields) {
    # Skip existing custom fields.
    next if Bugzilla::Field->new({ name => $f->{name} });

    my @values;
    if (exists $f->{values}) {
        @values = @{$f->{values}};
        # We have to delete this key, else create() will complain
        # that 'values' is not an existing column name.
        delete $f->{values};
    }
    my $field = Bugzilla::Field->create($f);

    # Now populate the table with valid values, if necessary.
    next unless scalar @values;

    my $sth = $dbh->prepare('INSERT INTO ' . $field->name . ' (value) VALUES (?)');
    foreach my $value (@values) {
        $sth->execute($value);
    }
}

####################################################################
# Set Parameters That Require Other Things To Have Been Done First #
####################################################################

if (Bugzilla->params->{insidergroup} ne 'QA-Selenium-TEST') {
    SetParam('insidergroup', 'QA-Selenium-TEST');
    write_params();
}

if (Bugzilla->params->{timetrackinggroup} ne 'editbugs') {
    SetParam('timetrackinggroup', 'editbugs');
    write_params();
}

########################
# Create a Private Bug #
########################

my $test_user = Bugzilla::User->check($config->{QA_Selenium_TEST_user_login});
$test_user->{'groups'} = [
    Bugzilla::Group->new({ name => 'editbugs' }),
    Bugzilla::Group->new({ name => 'QA-Selenium-TEST' })
]; # editbugs is needed for alias creation
Bugzilla->set_user($test_user);

if (Bugzilla::Bug->new('private_bug')->{error}) {
    say 'Creating private bug...';
    my %priv_values = %field_values;
    $priv_values{alias} = 'private_bug';
    $priv_values{product} = 'QA-Selenium-TEST';
    $priv_values{component} = 'QA-Selenium-TEST';
    my $bug = Bugzilla::Bug->create(\%priv_values);
    say 'Bug ' . $bug->id . ' (alias: private_bug) created';
}

######################
# Create Attachments #
######################

say 'creating attachments...';
# We use the contents of this script as the attachment.
open(my $attachment_fh, '<', __FILE__) or die __FILE__ . ": $!";
my $attachment_contents;
{
    local $/;
    $attachment_contents = <$attachment_fh>;
}
close($attachment_fh);

foreach my $alias (qw(public_bug private_bug)) {
    my $bug = Bugzilla::Bug->new($alias);

    foreach my $is_private (0, 1) {
        Bugzilla::Attachment->create({
            bug  => $bug,
            data => $attachment_contents,
            description => "${alias}_${is_private}",
            filename  => "${alias}_${is_private}.pl",
            mimetype  => 'application/x-perl',
            isprivate => $is_private,
        });
    }
}

###################
# Create Keywords #
###################

my @keywords = (
    { name => 'test-keyword-1',
      description => 'Created for Bugzilla QA Tests, Keyword 1' },
    { name => 'test-keyword-2',
      description => 'Created for Bugzilla QA Tests, Keyword 2' },
);

say 'creating keywords...';
foreach my $kw (@keywords) {
    next if Bugzilla::Keyword->new({ name => $kw->{name} });
    Bugzilla::Keyword->create($kw);
}

############################
# Install the QA extension #
############################

say 'copying the QA extension...';
my $output = `cp -R ../extensions/QA $conf_path/extensions/.`;
print $output if $output;

my $cwd = cwd();
chdir($conf_path);
$output = `perl contrib/fixperms.pl`;
print $output if $output;
chdir($cwd);

say 'installation and configuration complete!';