File: plan_cmd.t

package info (click to toggle)
sqitch 1.5.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,836 kB
  • sloc: perl: 37,498; sql: 2,590; makefile: 9
file content (713 lines) | stat: -rw-r--r-- 28,114 bytes parent folder | download
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
#!/usr/bin/perl -w

use strict;
use warnings;
use utf8;
use Test::More tests => 234;
# use Test::More 'no_plan';
use App::Sqitch;
use Locale::TextDomain qw(App-Sqitch);
use Test::NoWarnings;
use Test::Exception;
use Test::Warn;
use Test::MockModule;
use Path::Class;
use Term::ANSIColor qw(color);
use Encode;
use lib 't/lib';
use MockOutput;
use TestConfig;
use LC;

local $ENV{TZ} = 'Asia/Tokyo';
my $CLASS = 'App::Sqitch::Command::plan';
require_ok $CLASS;

my $config = TestConfig->new(
    'core.engine'    => 'sqlite',
    'core.top_dir'   => dir('test-plan_cmd')->stringify,
    'core.plan_file' => file(qw(t plans dependencies.plan))->stringify,
);
ok my $sqitch = App::Sqitch->new(config => $config),
    'Load a sqitch sqitch object';
isa_ok my $cmd = App::Sqitch::Command->load({
    sqitch  => $sqitch,
    command => 'plan',
    config  => $config,
}), $CLASS, 'plan command';

can_ok $cmd, qw(
    target
    change_pattern
    planner_pattern
    max_count
    skip
    reverse
    format
    options
    execute
    configure
    headers
);

is_deeply [$CLASS->options], [qw(
    event=s
    target|t=s
    change-pattern|change=s
    planner-pattern|planner=s
    format|f=s
    date-format|date=s
    max-count|n=i
    skip=i
    reverse!
    color=s
    no-color
    abbrev=i
    oneline
   headers!
)], 'Options should be correct';

warning_is {
    Getopt::Long::Configure(qw(bundling pass_through));
    ok Getopt::Long::GetOptionsFromArray(
        [], {}, App::Sqitch->_core_opts, $CLASS->options,
    ), 'Should parse options';
} undef, 'Options should not conflict with core options';

##############################################################################
# Test configure().
my $configured = $CLASS->configure($config, {});
isa_ok delete $configured->{formatter}, 'App::Sqitch::ItemFormatter', 'Formatter';
is_deeply $configured, {},
    'Should get empty hash for no config or options';

# Test date_format validation.
$config->update('plan.date_format' => 'nonesuch');
throws_ok { $CLASS->configure($config, {}), {} } 'App::Sqitch::X',
    'Should get error for invalid date format in config';
is $@->ident, 'datetime',
    'Invalid date format error ident should be "datetime"';
is $@->message, __x(
    'Unknown date format "{format}"',
    format => 'nonesuch',
), 'Invalid date format error message should be correct';

throws_ok { $CLASS->configure($config, { date_format => 'non'}), {} }
    'App::Sqitch::X',
    'Should get error for invalid date format in optsions';
is $@->ident, 'datetime',
    'Invalid date format error ident should be "plan"';
is $@->message, __x(
    'Unknown date format "{format}"',
    format => 'non',
), 'Invalid date format error message should be correct';

# Test format validation.
$config = TestConfig->new('plan.format' => 'nonesuch');
throws_ok { $CLASS->configure($config, {}), {} } 'App::Sqitch::X',
    'Should get error for invalid format in config';
is $@->ident, 'plan',
    'Invalid format error ident should be "plan"';
is $@->message, __x(
    'Unknown plan format "{format}"',
    format => 'nonesuch',
), 'Invalid format error message should be correct';

throws_ok { $CLASS->configure($config, { format => 'non'}), {} }
    'App::Sqitch::X',
    'Should get error for invalid format in optsions';
is $@->ident, 'plan',
    'Invalid format error ident should be "plan"';
is $@->message, __x(
    'Unknown plan format "{format}"',
    format => 'non',
), 'Invalid format error message should be correct';

# Test color configuration.
$config = TestConfig->new;
$configured = $CLASS->configure( $config, { no_color => 1 } );
is $configured->{formatter}->color, 'never',
    'Configuration should respect --no-color, setting "never"';

# Test oneline configuration.
$configured = $CLASS->configure( $config, { oneline => 1 });
is $configured->{format}, '%{:event}C%h %l%{reset}C %n%{cyan}C%t%{reset}C',
    '--oneline should set format';
is $configured->{formatter}{abbrev}, 6, '--oneline should set abbrev to 6';

$configured = $CLASS->configure( $config, { oneline => 1, format => 'format:foo', abbrev => 5 });
is $configured->{format}, 'foo', '--oneline should not override --format';
is $configured->{formatter}{abbrev}, 5, '--oneline should not overrride --abbrev';

$config->update('plan.color' => 'auto');
$configured = $CLASS->configure( $config, { no_color => 1 } );
is $configured->{formatter}->color, 'never',
    'Configuration should respect --no-color even when configure is set';

NEVER: {
    my $configured = $CLASS->configure( $config, { color => 'never' } );
    is $configured->{formatter}->color, 'never',
        'Configuration should respect color option';

    # Try it with config.
    $config->update('plan.color' => 'never');
    $configured = $CLASS->configure( $config, {} );
    is $configured->{formatter}->color, 'never',
        'Configuration should respect color config';
}

ALWAYS: {
    my $configured = $CLASS->configure( $config, { color => 'always' } );
    is_deeply $configured->{formatter}->color, 'always',
        'Configuration should respect color option';

    # Try it with config.
    $config->update('plan.color' => 'always');
    $configured = $CLASS->configure( $config, {} );
    is_deeply $configured->{formatter}->color, 'always',
        'Configuration should respect color config';
}

AUTO: {
    for my $enabled (0, 1) {
        $config->update('plan.color' => 'always');
        my $configured = $CLASS->configure( $config, { color => 'auto' } );
        is_deeply $configured->{formatter}->color, 'auto',
            'Configuration should respect color option';

        # Try it with config.
        $config->update('plan.color' => 'auto');
        $configured = $CLASS->configure( $config, {} );
        is_deeply $configured->{formatter}->color, 'auto',
            'Configuration should respect color config';
    }
}

###############################################################################
# Test named formats.
my $cdt = App::Sqitch::DateTime->now;
my $pdt = $cdt->clone->subtract(days => 1);
my $change = {
    event           => 'deploy',
    project         => 'planit',
    change_id       => '000011112222333444',
    change          => 'lolz',
    tags            => [ '@beta', '@gamma' ],
    planner_name    => 'damian',
    planner_email   => 'damian@example.com',
    planned_at      => $pdt,
    note            => "For the LOLZ.\n\nYou know, funny stuff and cute kittens, right?",
    requires        => [qw(foo bar)],
    conflicts       => []
};

my $piso = $pdt->as_string( format => 'iso' );
my $praw = $pdt->as_string( format => 'raw' );
for my $spec (
    [ raw => "deploy 000011112222333444 (\@beta, \@gamma)\n"
        . "name      lolz\n"
        . "project   planit\n"
        . "requires  foo, bar\n"
        . "planner   damian <damian\@example.com>\n"
        . "planned   $praw\n\n"
        . "    For the LOLZ.\n    \n    You know, funny stuff and cute kittens, right?\n"
    ],
    [ full =>  __('Deploy') . " 000011112222333444 (\@beta, \@gamma)\n"
        . __('Name:     ') . " lolz\n"
        . __('Project:  ') . " planit\n"
        . __('Requires: ') . " foo, bar\n"
        . __('Planner:  ') . " damian <damian\@example.com>\n"
        . __('Planned:  ') . " __PDATE__\n\n"
        . "    For the LOLZ.\n    \n    You know, funny stuff and cute kittens, right?\n"
    ],
    [ long =>  __('Deploy') . " 000011112222333444 (\@beta, \@gamma)\n"
        . __('Name:     ') . " lolz\n"
        . __('Project:  ') . " planit\n"
        . __('Planner:  ') . " damian <damian\@example.com>\n\n"
        . "    For the LOLZ.\n    \n    You know, funny stuff and cute kittens, right?\n"
    ],
    [ medium =>  __('Deploy') . " 000011112222333444\n"
        . __('Name:     ') . " lolz\n"
        . __('Planner:  ') . " damian <damian\@example.com>\n"
        . __('Date:     ') . " __PDATE__\n\n"
        . "    For the LOLZ.\n    \n    You know, funny stuff and cute kittens, right?\n"
    ],
    [ short =>  __('Deploy') . " 000011112222333444\n"
        . __('Name:     ') . " lolz\n"
        . __('Planner:  ') . " damian <damian\@example.com>\n\n"
        . "    For the LOLZ.\n",
    ],
    [ oneline => '000011112222333444 ' . __('deploy') . ' lolz @beta, @gamma' ],
) {
    local $ENV{ANSI_COLORS_DISABLED} = 1;
    my $configured = $CLASS->configure( $config, { format => $spec->[0] } );
    my $format = $configured->{format};
    ok my $cmd = $CLASS->new( sqitch => $sqitch, %{ $configured } ),
        qq{Instantiate with format "$spec->[0]"};
    (my $exp = $spec->[1]) =~ s/__PDATE__/$piso/;
    is $cmd->formatter->format( $cmd->format, $change ), $exp,
        qq{Format "$spec->[0]" should output correctly};

    if ($spec->[1] =~ /__PDATE__/) {
        # Test different date formats.
        for my $date_format (qw(rfc long medium)) {
            ok my $cmd = $CLASS->new(
                sqitch => $sqitch,
                format => $format,
                formatter => App::Sqitch::ItemFormatter->new(date_format => $date_format),
            ), qq{Instantiate with format "$spec->[0]" and date format "$date_format"};
            my $date = $pdt->as_string( format => $date_format );
            (my $exp = $spec->[1]) =~ s/__PDATE__/$date/;
            is $cmd->formatter->format( $cmd->format, $change ), $exp,
                qq{Format "$spec->[0]" and date format "$date_format" should output correctly};
        }
    }

    if ($spec->[1] =~ s/\s+[(]?[@]beta,\s+[@]gamma[)]?//) {
        # Test without tags.
        local $change->{tags} = [];
        (my $exp = $spec->[1]) =~ s/__PDATE__/$piso/;
        is $cmd->formatter->format( $cmd->format, $change ), $exp,
            qq{Format "$spec->[0]" should output correctly without tags};
    }
}

###############################################################################
# Test all formatting characters.
my $local_pdt = $pdt->clone;
$local_pdt->set_time_zone('local');
$local_pdt->set_locale($LC::TIME);

my $formatter = $cmd->formatter;
for my $spec (
    ['%e', { event => 'deploy' }, 'deploy' ],
    ['%e', { event => 'revert' }, 'revert' ],
    ['%e', { event => 'fail' },   'fail' ],

    ['%L', { event => 'deploy' }, __ 'Deploy' ],
    ['%L', { event => 'revert' }, __ 'Revert' ],
    ['%L', { event => 'fail' },   __ 'Fail' ],

    ['%l', { event => 'deploy' }, __ 'deploy' ],
    ['%l', { event => 'revert' }, __ 'revert' ],
    ['%l', { event => 'fail' },   __ 'fail' ],

    ['%{event}_',     {}, __ 'Event:    ' ],
    ['%{change}_',    {}, __ 'Change:   ' ],
    ['%{planner}_',   {}, __ 'Planner:  ' ],
    ['%{by}_',        {}, __ 'By:       ' ],
    ['%{date}_',      {}, __ 'Date:     ' ],
    ['%{planned}_',   {}, __ 'Planned:  ' ],
    ['%{name}_',      {}, __ 'Name:     ' ],
    ['%{email}_',     {}, __ 'Email:    ' ],
    ['%{requires}_',  {}, __ 'Requires: ' ],
    ['%{conflicts}_', {}, __ 'Conflicts:' ],

    ['%H', { change_id => '123456789' }, '123456789' ],
    ['%h', { change_id => '123456789' }, '123456789' ],
    ['%{5}h', { change_id => '123456789' }, '12345' ],
    ['%{7}h', { change_id => '123456789' }, '1234567' ],

    ['%n', { change => 'foo' }, 'foo'],
    ['%n', { change => 'bar' }, 'bar'],
    ['%o', { project => 'foo' }, 'foo'],
    ['%o', { project => 'bar' }, 'bar'],

    ['%F', { deploy_file => 'deploy/change_file.sql' }, 'deploy/change_file.sql'],
    ['%F', { deploy_file => 'deploy/change_file_with_tag@tag.sql' }, 'deploy/change_file_with_tag@tag.sql'],

    ['%p', { planner_name => 'larry', planner_email => 'larry@example.com'  }, 'larry <larry@example.com>'],
    ['%{n}p', { planner_name => 'damian' }, 'damian'],
    ['%{name}p', { planner_name => 'chip' }, 'chip'],
    ['%{e}p', { planner_email => 'larry@example.com'  }, 'larry@example.com'],
    ['%{email}p', { planner_email => 'damian@example.com' }, 'damian@example.com'],

    ['%{date}p', { planned_at => $pdt }, $pdt->as_string( format => 'iso' ) ],
    ['%{date:rfc}p', { planned_at => $pdt }, $pdt->as_string( format => 'rfc' ) ],
    ['%{d:long}p', { planned_at => $pdt }, $pdt->as_string( format => 'long' ) ],
    ["%{d:cldr:HH'h' mm'm'}p", { planned_at => $pdt }, $local_pdt->format_cldr( q{HH'h' mm'm'} ) ],
    ["%{d:strftime:%a at %H:%M:%S}p", { planned_at => $pdt }, $local_pdt->strftime('%a at %H:%M:%S') ],

    ['%t', { tags => [] }, '' ],
    ['%t', { tags => ['@foo'] }, ' @foo' ],
    ['%t', { tags => ['@foo', '@bar'] }, ' @foo, @bar' ],
    ['%{|}t', { tags => [] }, '' ],
    ['%{|}t', { tags => ['@foo'] }, ' @foo' ],
    ['%{|}t', { tags => ['@foo', '@bar'] }, ' @foo|@bar' ],

    ['%T', { tags => [] }, '' ],
    ['%T', { tags => ['@foo'] }, ' (@foo)' ],
    ['%T', { tags => ['@foo', '@bar'] }, ' (@foo, @bar)' ],
    ['%{|}T', { tags => [] }, '' ],
    ['%{|}T', { tags => ['@foo'] }, ' (@foo)' ],
    ['%{|}T', { tags => ['@foo', '@bar'] }, ' (@foo|@bar)' ],

    ['%r', { requires => [] }, '' ],
    ['%r', { requires => ['foo'] }, ' foo' ],
    ['%r', { requires => ['foo', 'bar'] }, ' foo, bar' ],
    ['%{|}r', { requires => [] }, '' ],
    ['%{|}r', { requires => ['foo'] }, ' foo' ],
    ['%{|}r', { requires => ['foo', 'bar'] }, ' foo|bar' ],

    ['%R', { requires => [] }, '' ],
    ['%R', { requires => ['foo'] }, __('Requires: ') . " foo\n" ],
    ['%R', { requires => ['foo', 'bar'] }, __('Requires: ') . " foo, bar\n" ],
    ['%{|}R', { requires => [] }, '' ],
    ['%{|}R', { requires => ['foo'] }, __('Requires: ') . " foo\n" ],
    ['%{|}R', { requires => ['foo', 'bar'] }, __('Requires: ') . " foo|bar\n" ],

    ['%x', { conflicts => [] }, '' ],
    ['%x', { conflicts => ['foo'] }, ' foo' ],
    ['%x', { conflicts => ['foo', 'bax'] }, ' foo, bax' ],
    ['%{|}x', { conflicts => [] }, '' ],
    ['%{|}x', { conflicts => ['foo'] }, ' foo' ],
    ['%{|}x', { conflicts => ['foo', 'bax'] }, ' foo|bax' ],

    ['%X', { conflicts => [] }, '' ],
    ['%X', { conflicts => ['foo'] }, __('Conflicts:') . " foo\n" ],
    ['%X', { conflicts => ['foo', 'bar'] }, __('Conflicts:') . " foo, bar\n" ],
    ['%{|}X', { conflicts => [] }, '' ],
    ['%{|}X', { conflicts => ['foo'] }, __('Conflicts:') . " foo\n" ],
    ['%{|}X', { conflicts => ['foo', 'bar'] }, __('Conflicts:') . " foo|bar\n" ],

    ['%{yellow}C', {}, '' ],
    ['%{:event}C', { event => 'deploy' }, '' ],
    ['%v', {}, "\n" ],
    ['%%', {}, '%' ],

    ['%s', { note => 'hi there' }, 'hi there' ],
    ['%s', { note => "hi there\nyo" }, 'hi there' ],
    ['%s', { note => "subject line\n\nfirst graph\n\nsecond graph\n\n" }, 'subject line' ],
    ['%{  }s', { note => 'hi there' }, '  hi there' ],
    ['%{xx}s', { note => 'hi there' }, 'xxhi there' ],

    ['%b', { note => 'hi there' }, '' ],
    ['%b', { note => "hi there\nyo" }, 'yo' ],
    ['%b', { note => "subject line\n\nfirst graph\n\nsecond graph\n\n" }, "first graph\n\nsecond graph\n\n" ],
    ['%{  }b', { note => 'hi there' }, '' ],
    ['%{xxx }b', { note => "hi there\nyo" }, "xxx yo" ],
    ['%{x}b', { note => "subject line\n\nfirst graph\n\nsecond graph\n\n" }, "xfirst graph\nx\nxsecond graph\nx\n" ],
    ['%{ }b', { note => "hi there\r\nyo" }, " yo" ],

    ['%B', { note => 'hi there' }, 'hi there' ],
    ['%B', { note => "hi there\nyo" }, "hi there\nyo" ],
    ['%B', { note => "subject line\n\nfirst graph\n\nsecond graph\n\n" }, "subject line\n\nfirst graph\n\nsecond graph\n\n" ],
    ['%{  }B', { note => 'hi there' }, '  hi there' ],
    ['%{xxx }B', { note => "hi there\nyo" }, "xxx hi there\nxxx yo" ],
    ['%{x}B', { note => "subject line\n\nfirst graph\n\nsecond graph\n\n" }, "xsubject line\nx\nxfirst graph\nx\nxsecond graph\nx\n" ],
    ['%{ }B', { note => "hi there\r\nyo" }, " hi there\r\n yo" ],

    ['%{change}a',    $change, "change    $change->{change}\n" ],
    ['%{change_id}a', $change, "change_id $change->{change_id}\n" ],
    ['%{event}a',     $change, "event     $change->{event}\n" ],
    ['%{tags}a',      $change, 'tags      ' . join(', ', @{ $change->{tags} }) . "\n" ],
    ['%{requires}a',  $change, 'requires  ' . join(', ', @{ $change->{requires} }) . "\n" ],
    ['%{conflicts}a', $change, '' ],
) {
    local $ENV{ANSI_COLORS_DISABLED} = 1;
    (my $desc = encode_utf8 $spec->[2]) =~ s/\n/[newline]/g;
    is $formatter->format( $spec->[0], $spec->[1] ), $spec->[2],
        qq{Format "$spec->[0]" should output "$desc"};
}

throws_ok { $formatter->format( '%_', {} ) } 'App::Sqitch::X',
    'Should get exception for format "%_"';
is $@->ident, 'format', '%_ error ident should be "format"';
is $@->message, __ 'No label passed to the _ format',
    '%_ error message should be correct';
throws_ok { $formatter->format( '%{foo}_', {} ) } 'App::Sqitch::X',
    'Should get exception for unknown label in format "%_"';
is $@->ident, 'format', 'Invalid %_ label error ident should be "format"';
is $@->message, __x(
    'Unknown label "{label}" passed to the _ format',
    label => 'foo'
), 'Invalid %_ label error message should be correct';

ok $cmd = $CLASS->new(
    sqitch    => $sqitch,
    formatter => App::Sqitch::ItemFormatter->new(abbrev => 4)
), 'Instantiate with abbrev => 4';
is $cmd->formatter->format( '%h', { change_id => '123456789' } ),
    '1234', '%h should respect abbrev';
is $cmd->formatter->format( '%H', { change_id => '123456789' } ),
    '123456789', '%H should not respect abbrev';

ok $cmd = $CLASS->new(
    sqitch    => $sqitch,
    formatter => App::Sqitch::ItemFormatter->new(date_format => 'rfc')
), 'Instantiate with date_format => "rfc"';
is $cmd->formatter->format( '%{date}p', { planned_at => $cdt } ),
    $cdt->as_string( format => 'rfc' ),
    '%{date}p should respect the date_format attribute';
is $cmd->formatter->format( '%{d:iso}p', { planned_at => $cdt } ),
    $cdt->as_string( format => 'iso' ),
    '%{iso}p should override the date_format attribute';

throws_ok { $formatter->format( '%{foo}a', {}) } 'App::Sqitch::X',
    'Should get exception for unknown attribute passed to %a';
is $@->ident, 'format', '%a error ident should be "format"';
is $@->message, __x(
    '{attr} is not a valid change attribute', attr => 'foo'
), '%a error message should be correct';

delete $ENV{ANSI_COLORS_DISABLED};
for my $color (qw(yellow red blue cyan magenta)) {
    is $formatter->format( "%{$color}C", {} ), color($color),
        qq{Format "%{$color}C" should output }
        . color($color) . $color . color('reset');
}

for my $spec (
    [ ':event', { event => 'deploy' }, 'green', 'deploy' ],
    [ ':event', { event => 'revert' }, 'blue',  'revert' ],
    [ ':event', { event => 'fail'   }, 'red',   'fail'   ],
) {
    is $formatter->format( "%{$spec->[0]}C", $spec->[1] ), color($spec->[2]),
        qq{Format "%{$spec->[0]}C" on "$spec->[3]" should output }
        . color($spec->[2]) . $spec->[2] . color('reset');
}

# Make sure other colors work.
my $yellow = color('yellow') . '%s' . color('reset');
my $green  = color('green')  . '%s' . color('reset');
my $cyan   = color('cyan')   . ' %s' . color('reset');
$change->{conflicts} = [qw(dr_evil)];
for my $spec (
    [ full => sprintf($green, __ ('Deploy') . ' 000011112222333444')
        . " (\@beta, \@gamma)\n"
        . __ ('Name:     ') . " lolz\n"
        . __ ('Project:  ') . " planit\n"
        . __ ('Requires: ') . " foo, bar\n"
        . __ ('Conflicts:') . " dr_evil\n"
        . __ ('Planner:  ') . " damian <damian\@example.com>\n"
        . __ ('Planned:  ') . " __PDATE__\n\n"
        . "    For the LOLZ.\n    \n    You know, funny stuff and cute kittens, right?\n"
    ],
    [ long => sprintf($green, __ ('Deploy') . ' 000011112222333444')
        . " (\@beta, \@gamma)\n"
        . __ ('Name:     ') . " lolz\n"
        . __ ('Project:  ') . " planit\n"
        . __ ('Planner:  ') . " damian <damian\@example.com>\n\n"
        . "    For the LOLZ.\n    \n    You know, funny stuff and cute kittens, right?\n"
    ],
    [ medium => sprintf($green, __ ('Deploy') . ' 000011112222333444') . "\n"
        . __ ('Name:     ') . " lolz\n"
        . __ ('Planner:  ') . " damian <damian\@example.com>\n"
        . __ ('Date:     ') . " __PDATE__\n\n"
        . "    For the LOLZ.\n    \n    You know, funny stuff and cute kittens, right?\n"
    ],
    [ short => sprintf($green, __ ('Deploy') . ' 000011112222333444') . "\n"
        . __ ('Name:     ') . " lolz\n"
        . __ ('Planner:  ') . " damian <damian\@example.com>\n\n"
        . "    For the LOLZ.\n",
    ],
    [ oneline => sprintf "$green %s$cyan", '000011112222333444' . ' '
        . __('deploy'), 'lolz', '@beta, @gamma',
    ],
) {
    my $format = $CLASS->configure( $config, { format => $spec->[0] } )->{format};
    ok my $cmd = $CLASS->new( sqitch => $sqitch, format => $format ),
        qq{Instantiate with format "$spec->[0]" again};
    (my $exp = $spec->[1]) =~ s/__PDATE__/$piso/;
    is $cmd->formatter->format( $cmd->format, $change ), $exp,
        qq{Format "$spec->[0]" should output correctly with color};
}

throws_ok { $formatter->format( '%{BLUELOLZ}C', {} ) } 'App::Sqitch::X',
    'Should get an error for an invalid color';
is $@->ident, 'format', 'Invalid color error ident should be "format"';
is $@->message, __x(
    '{color} is not a valid ANSI color', color => 'BLUELOLZ'
), 'Invalid color error message should be correct';


##############################################################################
# Test execute().
my $pmock = Test::MockModule->new('App::Sqitch::Plan');

# First, test for no changes.
$pmock->mock(count => 0);

my $plan = $cmd->default_target->plan;
throws_ok { $cmd->execute } 'App::Sqitch::X',
    'Should get error for no changes';
is $@->ident, 'plan', 'no changes error ident should be "plan"';
is $@->exitval, 1, 'no changes exit val should be 1';
is $@->message, __x(
    'No changes in {file}',
    file => $plan->file,
), 'no changes error message should be correct';
$pmock->unmock('count');

# Okay, let's see some changes.
my @changes;
my $iter = sub { shift @changes };
my $search_args;
$pmock->mock(search_changes => sub {
    shift;
    $search_args = [@_];
    return $iter;
});

$change = $plan->change_at(0);
push @changes => $change;
ok $cmd->execute, 'Execute plan';
is_deeply $search_args, [
    operation => undef,
    name      => undef,
    planner   => undef,
    limit     => undef,
    offset    => undef,
    direction => 'ASC'
], 'The proper args should have been passed to search_events';

my $fmt_params = {
    event         => $change->is_deploy ? 'deploy' : 'revert',
    project       => $change->project,
    change_id     => $change->id,
    change        => $change->name,
    note          => $change->note,
    deploy_file   => $change->deploy_file,
    tags          => [ map { $_->format_name } $change->tags ],
    requires      => [ map { $_->as_string } $change->requires ],
    conflicts     => [ map { $_->as_string } $change->conflicts ],
    planned_at    => $change->timestamp,
    planner_name  => $change->planner_name,
    planner_email => $change->planner_email,
};
is_deeply +MockOutput->get_page, [
    ['# ', __x 'Project: {project}', project => $plan->project ],
    ['# ', __x 'File:    {file}', file => $plan->file ],
    [''],
    [ $cmd->formatter->format( $cmd->format, $fmt_params ) ],
], 'The event should have been paged';

# Set attributes and add more events.
isa_ok $cmd = $CLASS->new(
    sqitch            => $sqitch,
    event             => 'deploy',
    change_pattern    => '.+',
    project_pattern   => '.+',
    planner_pattern   => '.+',
    max_count         => 10,
    skip              => 5,
    reverse           => 1,
    headers           => 0,
), $CLASS, 'plan with attributes';
$plan = $cmd->default_target->plan;

$change = $plan->change_at(0);
my $change2 = $plan->change_at(1);
push @changes => $change, $change2;
ok $cmd->execute, 'Execute plan with attributes';
is_deeply $search_args, [
    operation => 'deploy',
    name      => '.+',
    planner   => '.+',
    limit     => 10,
    offset    => 5,
    direction => 'DESC'
], 'All params should have been passed to search_events';

my $fmt_params2 = {
    event         => $change2->is_deploy ? 'deploy' : 'revert',
    project       => $change2->project,
    change_id     => $change2->id,
    change        => $change2->name,
    note          => $change2->note,
    deploy_file   => $change2->deploy_file,
    tags          => [ map { $_->format_name } $change2->tags ],
    requires      => [ map { $_->as_string } $change2->requires ],
    conflicts     => [ map { $_->as_string } $change2->conflicts ],
    planned_at    => $change2->timestamp,
    planner_name  => $change2->planner_name,
    planner_email => $change2->planner_email,
};

is_deeply +MockOutput->get_page, [
    [ $cmd->formatter->format( $cmd->format, $fmt_params  ) ],
    [ $cmd->formatter->format( $cmd->format, $fmt_params2 ) ],
], 'Both events should have been paged without headers';

# Now try raw format of all the changes.
my $cfg = $CLASS->configure( $config, { format => 'raw' } );
ok $cmd = $CLASS->new( sqitch => $sqitch, %{ $cfg } ),
    'Create command with raw format';
$plan = $cmd->default_target->plan;

push @changes => $plan->changes;
ok $cmd->execute, 'Execute plan with all changes';
is_deeply +MockOutput->get_page, [
    ['# ', __x 'Project: {project}', project => $plan->project ],
    ['# ', __x 'File:    {file}', file => $plan->file ],
    [''],
    map { [ $cmd->formatter->format( $cmd->format, {
        event         => $_->is_deploy ? 'deploy' : 'revert',
        project       => $_->project,
        change_id     => $_->id,
        change        => $_->name,
        note          => $_->note,
        deploy_file   => $_->deploy_file,
        tags          => [ map { $_->format_name } $_->tags ],
        requires      => [ map { $_->as_string } $_->requires ],
        conflicts     => [ map { $_->as_string } $_->conflicts ],
        planned_at    => $_->timestamp,
        planner_name  => $_->planner_name,
        planner_email => $_->planner_email,
    } ) ] } $plan->changes
], 'Should have paged all changes';

# Make sure we catch bad format codes.
isa_ok $cmd = $CLASS->new(
    sqitch => $sqitch,
    format => '%Z',
), $CLASS, 'plan with bad format';
$plan = $cmd->default_target->plan;

$change = $plan->change_at(0);
push @changes, $change;
throws_ok { $cmd->execute } 'App::Sqitch::X',
    'Should get an exception for a bad format code';
is $@->ident, 'format',
    'bad format code format error ident should be "format"';
is $@->message, __x(
    'Unknown format code "{code}"', code => 'Z',
), 'bad format code format error message should be correct';

# Gotta make sure params are parsed.
my $mock_cmd = Test::MockModule->new($CLASS);
my (@params, $orig_parse);
$mock_cmd->mock(parse_args => sub {
    my $self = shift;
    @params = @_;
    $self->$orig_parse(@_);
});
$orig_parse = $mock_cmd->original('parse_args');

# Try specifying an unknown target.
ok $cmd = $CLASS->new( sqitch => $sqitch, target => 'foo'),
    'Create plan command with unknown target option';
throws_ok { $cmd->execute } 'App::Sqitch::X',
    'Should get error for unknown target';
is $@->ident, 'target', 'Unknown target error ident should be "plan"';
is $@->exitval, 2, 'Unknown target changes exit val should be 2';
is $@->message, __x('Cannot find target "{target}"', target => 'foo'),
    'Unknown target error message should be correct';
is_deeply \@params, [ target => 'foo', args => [] ],
    'Should have passed target for parsing';

# Try passing an engine target.
ok $cmd = $CLASS->new( sqitch => $sqitch),
    'Create plan command with target option';
ok $cmd->execute('sqlite'), 'Execute with engine arg';
is_deeply \@params, [ target => undef, args => [qw(sqlite)] ],
    'Should have passed engine for parsing';

# Try both --target and arg..
ok $cmd = $CLASS->new( sqitch => $sqitch, target => 'db:pg:'),
    'Create plan command with target option';
ok $cmd->execute('sqlite'), 'Execute with multiple targets';
is_deeply +MockOutput->get_warn, [[__x(
    'Too many targets specified; using {target}',
    target => 'db:pg:',
)]], 'Should have got warning for two targets';