blib/lib/Smolder/DB/SmokeReport.pm untested

filter: Statementstmt 0.0% 0 / 236 Branchbran 0.0% 0 / 48 Conditioncond 0.0% 0 / 77 MC/DCmcdc 0.0% 0 / 44 Subroutinesub 0.0% 0 / 35 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 456 CC 25 SCAR 41.2
CC
25
Cov
0%
update_from_tap_archive
210.0
_send_emails
72.0
data_dir
6.0
CRAP 61.4
1 package Smolder::DB::SmokeReport;
2 use strict;
3 use warnings;
4 use base 'Smolder::DB';
5 use Smolder::Conf qw(DataDir TruncateTestFilenames);
6 use Smolder::Email;
7 use File::Spec::Functions qw(catdir catfile);
8 use File::Basename qw(basename);
9 use File::Path qw(mkpath rmtree);
10 use File::Copy qw(move copy);
11 use File::Temp qw(tempdir);
12 use Cwd qw(fastcwd);
13 use DateTime;
14 use Smolder::TAPHTMLMatrix;
15 use Smolder::DB::TestFile;
16 use Smolder::DB::TestFileResult;
17 use Carp qw(croak);
18 use TAP::Harness::Archive;
19 use IO::Zlib;
20  
21 __PACKAGE__->set_up_table('smoke_report');
22  
23 # exceptions
24 use Exception::Class (
25 'Smolder::Exception::InvalidTAP' => {description => 'Could not parse TAP files!',},
26 'Smolder::Exception::InvalidArchive' => {description => 'Could not unpack file!',},
27 );
28  
29 =head1 NAME
30  
31 Smolder::DB::SmokeReport
32  
33 =head1 DESCRIPTION
34  
35 L<Class::DBI> based model class for the 'smoke_report' table in the database.
36  
37 =head1 METHODS
38  
39 =head2 ACCESSSOR/MUTATORS
40  
41 Each column in the borough table has a method with the same name
42 that can be used as an accessor and mutator.
43  
44 The following columns will return objects instead of the value contained in the table:
45  
46 =cut
47  
48 __PACKAGE__->has_a(
49 added => 'DateTime',
50 inflate => sub { __PACKAGE__->parse_datetime(shift) },
51 deflate => sub { __PACKAGE__->format_datetime(shift) },
52 );
53 __PACKAGE__->has_a(developer => 'Smolder::DB::Developer');
54 __PACKAGE__->has_a(project => 'Smolder::DB::Project');
55  
56 # when a new object is created, set 'added' to now()
57 __PACKAGE__->add_trigger(
58 before_create => sub {
59 my $self = shift;
60 $self->_attribute_set(added => DateTime->now(time_zone => 'local'));
61 },
62 );
63  
64 =over
65  
66 =item added
67  
68 A L<DateTime> object representing the datetime stored.
69  
70 =item developer
71  
72 The L<Smolder::DB::Developer> object who added this report
73  
74 =item project
75  
76 The L<Smolder::DB::Project> object that this report is about
77  
78 =back
79  
80 =head2 OBJECT METHODS
81  
82 =head3 add_tag
83  
84 This method will add a tag to a given smoke report
85  
86 $report->add_tag('foo');
87  
88 =cut
89  
90 sub add_tag {
91 my ($self, $tag) = @_;
92 my $sth = $self->db_Main->prepare_cached(
93 q/
94 INSERT INTO smoke_report_tag (smoke_report, tag) VALUES (?,?)
95 /
96 );
97 $sth->execute($self->id, $tag);
98 }
99  
100 =head3 delete_tag
101  
102 This method will remove a tag from a given smoke report
103  
104 $report->delete_tag('foo');
105  
106 =cut
107  
108 sub delete_tag {
109 my ($self, $tag) = @_;
110 my $sth = $self->db_Main->prepare_cached(
111 q/
112 DELETE FROM smoke_report_tag WHERE smoke_report = ? AND tag = ?
113 /
114 );
115 $sth->execute($self->id, $tag);
116 }
117  
118 =head3 tags
119  
120 Returns a list of all of tags that have been added to this smoke report.
121 (in the smoke_report_tag table).
122  
123 # returns a simple list of scalars
124 my @tags = $report->tags();
125  
126 =cut
127  
128 sub tags {
129 my ($self, %args) = @_;
130 my @tags;
131 my $sth = $self->db_Main->prepare_cached(
132 q/
133 SELECT DISTINCT(srt.tag) FROM smoke_report_tag srt
134 WHERE srt.smoke_report = ? ORDER BY srt.tag/
135 );
136 $sth->execute($self->id);
137 my $tags = $sth->fetchall_arrayref([0]);
138 return map { $_->[0] } @$tags;
139 }
140  
141 =head3 data_dir
142  
143 The directory in which the data files for this report reside.
144 If it doesn't exist it will be created.
145  
146 =cut
147  
148 sub data_dir {
149 my $self = shift;
150 my $dir = catdir(DataDir, 'smoke_reports', $self->project->id, $self->id);
151  
152 # create it if it doesn't exist
153 mkpath($dir) if (!-d $dir);
154 return $dir;
155 }
156  
157 =head3 file
158  
159 This returns the file name of where the full report file for this
160 smoke report does (or will) reside. If the directory does not
161 yet exist, it will be created.
162  
163 =cut
164  
165 sub file {
166 my $self = shift;
167 return catfile($self->data_dir, 'report.tar.gz');
168 }
169  
170 =head3 html
171  
172 A reference to the HTML text of this Test Report.
173  
174 =cut
175  
176 sub html {
177 my $self = shift;
178 return $self->_slurp_file(catfile($self->data_dir, 'html', 'report.html'));
179 }
180  
181 =head3 html_test_detail
182  
183 This method will return the HTML for the details of an individual
184 test file. This is useful when you only need the details for some
185 of the test files (such as an AJAX request).
186  
187 It receives one argument, which is the index of the test file to
188 show.
189  
190 =cut
191  
192 sub html_test_detail {
193 my ($self, $num) = @_;
194 my $file = catfile($self->data_dir, 'html', "$num.html");
195  
196 return $self->_slurp_file($file);
197 }
198  
199 =head3 tap_stream
200  
201 This method will return the file name that holds the recorded TAP stream
202 given the index of that stream.
203  
204 =cut
205  
206 sub tap_stream {
207 my ($self, $index) = @_;
208 return $self->_slurp_file(catfile($self->data_dir, 'tap', "$index.tap"));
209 }
210  
211 # just return the file
212 # TODO - do something else if the file no longer exists
213 sub _slurp_file {
214 my ($self, $file_name) = @_;
215 my $text;
216 local $/;
217 open(my $IN, '<', $file_name)
218 or croak "Could not open file '$file_name' for reading! $!";
219  
220 $text = <$IN>;
221 close($IN)
222 or croak "Could not close file '$file_name'! $!";
223 return \$text;
224 }
225  
226 # This method will send the appropriate email to all developers of this Smoke
227 # Report's project who requested email notification (through their preferences),
228 # depending on this report's status.
229  
230 sub _send_emails {
231 my ($self, $results) = @_;
232  
233 # setup some stuff for the emails that we only need to do once
234 my $subject =
235 "[" . $self->project->name . "] new " . ($self->failed ? "failed " : '') . "Smolder report";
236 my $matrix = Smolder::TAPHTMLMatrix->new(
237 smoke_report => $self,
238 test_results => $results,
239 );
240 my $tt_params = {
241 report => $self,
242 matrix => $matrix,
243 results => $results,
244 };
245  
246 # get all the developers of this project
247 my @devs = $self->project->developers();
248 my %sent;
249 foreach my $dev (@devs) {
250  
251 # get their preference for this project
252 my $pref = $dev->project_pref($self->project);
253  
254 # skip it, if they don't want to receive it
255 next
256 if ($pref->email_freq eq 'never'
257 or (!$self->failed and $pref->email_freq eq 'on_fail'));
258  
259 # see if we need to reset their email_sent_timestamp
260 # if we've started a new day
261 my $last_sent = $pref->email_sent_timestamp;
262 my $now = DateTime->now(time_zone => 'local');
263 my $interval = $last_sent ? ($now - $last_sent) : undef;
264  
265 if (!$interval or ($interval->delta_days >= 1)) {
266 $pref->email_sent_timestamp($now);
267 $pref->email_sent(0);
268 $pref->update;
269 }
270  
271 # now check to see if we've passed their limit
272 next if ($pref->email_limit && $pref->email_sent >= $pref->email_limit);
273  
274 # now send the type of email they want to receive
275 my $type = $pref->email_type;
276 my $email = $dev->email;
277 next if $sent{"$email $type"}++;
278 my $error = Smolder::Email->send_mime_mail(
279 to => $email,
280 name => "smoke_report_$type",
281 subject => $subject,
282 tt_params => $tt_params,
283 );
284  
285 warn "Could not send 'smoke_report_$type' email to '$email': $error" if $error;
286  
287 # now increment their sent count
288 $pref->email_sent($pref->email_sent + 1);
289 $pref->update();
290 }
291 }
292  
293 =head3 delete_files
294  
295 This method will delete all of the files that can be created and stored in association
296 with a smoke test report (the 'data_dir' directory). It will C<croak> if the
297 files can't be deleted for some reason. Returns true if all is good.
298  
299 =cut
300  
301 sub delete_files {
302 my $self = shift;
303 rmtree($self->data_dir);
304 $self->update();
305 return 1;
306 }
307  
308 =head3 summary
309  
310 Returns a text string summarizing the whole test run.
311  
312 =cut
313  
314 sub summary {
315 my $self = shift;
316 return
317 sprintf('%i test cases: %i ok, %i failed, %i todo, %i skipped and %i unexpectedly succeeded',
318 $self->total, $self->pass, $self->fail, $self->todo, $self->skip, $self->todo_pass,)
319 . ", tags: "
320 . join(', ', map { qq("$_") } $self->tags);
321 }
322  
323 =head3 total_percentage
324  
325 Returns the total percentage of passed tests.
326  
327 =cut
328  
329 sub total_percentage {
330 my $self = shift;
331 if ($self->total && $self->failed) {
332 return sprintf('%i', (($self->total - $self->failed) / $self->total) * 100);
333 } else {
334 return 100;
335 }
336 }
337  
338 =head2 CLASS METHODS
339  
340 =head3 upload_report
341  
342 This method will take the name of the uploaded file and the project it's being
343 added, and various other details and process them. If everything is successful
344 then the resulting Smolder::DB::SmokeReport object will be returned.
345  
346 If the given file is compressed, it will be uncompressed before being processed.
347 After all processing is done, the details file will also be compressed.
348  
349 It takes the following named arguments
350  
351 =over
352  
353 =item file
354  
355 The full path to the uploaded file.
356 This is required.
357  
358 =item project
359  
360 The L<Smolder::DB::Project> object that this report is being associated with.
361 This is required.
362  
363 =item developer
364  
365 The L<Smolder::DB::Developer> who is uploading this file. If none is given,
366 then the anonymous guest account will be used.
367 This is optional.
368  
369 =item architecture
370  
371 The architecture this test was run on.
372 This is optional.
373  
374 =item platform
375  
376 The platform this test was run on.
377 This is optional.
378  
379 =item comments
380  
381 Any comments associated with this report.
382 This is optional.
383  
384 =back
385  
386 =cut
387  
388 sub upload_report {
389  
390 # TODO - validate params
391 my ($class, %args) = @_;
392  
393 my $file = $args{file};
394 my $dev = $args{developer} ||= Smolder::DB::Developer->get_guest();
395 my $project = $args{project};
396  
397 # create our initial report
398 my $report = $class->create(
399 {
400 developer => $dev,
401 project => $args{project},
402 architecture => ($args{architecture} || ''),
403 platform => ($args{platform} || ''),
404 comments => ($args{comments} || ''),
405 revision => ($args{revision} || ''),
406 }
407 );
408  
409 my $tags = $args{tags} || [];
410 $report->add_tag($_) foreach (@$tags);
411  
412 my $results = $report->update_from_tap_archive($file);
413  
414 # send an email to all the user's who want this report
415 $report->_send_emails($results);
416  
417 # move the tmp file to it's real destination
418 my $dest = $report->file;
419 my $out_fh;
420 if ($file =~ /\.gz$/ or $file =~ /\.zip$/) {
421 open($out_fh, '>', $dest)
422 or die "Could not open file $dest for writing:$!";
423 } else {
424  
425 #compress it if it's not already
426 $out_fh = IO::Zlib->new();
427 $out_fh->open($dest, 'wb9')
428 or die "Could not open file $dest for writing compressed!";
429 }
430  
431 my $in_fh;
432 open($in_fh, $file)
433 or die "Could not open file $file for reading! $!";
434 my $buffer;
435 while (read($in_fh, $buffer, 10240)) {
436 print $out_fh $buffer;
437 }
438 close($in_fh);
439 $out_fh->close();
440  
441 # purge old reports
442 $project->purge_old_reports();
443  
444 return $report;
445 }
446  
447 sub update_from_tap_archive {
448 my ($self, $file) = @_;
449 $file ||= $self->file;
450  
451 # our data structures for holding the info about the TAP parsing
452 my ($duration, @suite_results, @tests, $label);
453 my ($total, $failed, $skipped, $planned) = (0, 0, 0, 0);
454 my $file_index = 0;
455 my $next_file_index = 0;
456  
457 # make our tap directory if it doesn't already exist
458 my $tap_dir = catdir($self->data_dir, 'tap');
459 unless (-d $tap_dir) {
460 mkdir($tap_dir) or die "Could not create directory $tap_dir: $!";
461 }
462  
463 my $meta;
464  
465 # keep track of some things on our own because TAP::Parser::Aggregator
466 # doesn't handle total or failed right when a test exits early
467 my %suite_data;
468 my $aggregator = TAP::Harness::Archive->aggregator_from_archive(
469 {
470 archive => $file,
471 made_parser_callback => sub {
472 my ($parser, $file, $full_path) = @_;
473 $label = TruncateTestFilenames ? basename($file) : $file;
474  
475 # clear them out for a new run
476 @tests = ();
477 ($failed, $skipped) = (0, 0, 0);
478  
479 # save the raw TAP stream somewhere we can use it later
480 $file_index = $next_file_index++;
481 my $new_file = catfile($self->data_dir, 'tap', "$file_index.tap");
482 copy($full_path, $new_file) or die "Could not copy $full_path to $new_file. $!\n";
483 },
484 meta_yaml_callback => sub {
485 my $yaml = shift;
486 $meta = $yaml->[0];
487 $duration = $meta->{stop_time} - $meta->{start_time};
488 },
489 parser_callbacks => {
490 ALL => sub {
491 my $line = shift;
492 if ($line->type eq 'test') {
493 my %details = (
494 ok => ($line->is_ok || 0),
495 skip => ($line->has_skip || 0),
496 todo => ($line->has_todo || 0),
497 comment => ($line->as_string || 0),
498 );
499 $failed++ if !$line->is_ok && !$line->has_skip && !$line->has_todo;
500 $skipped++ if $line->has_skip;
501 push(@tests, \%details);
502 } elsif ($line->type eq 'comment' || $line->type eq 'unknown') {
503 my $slot = $line->type eq 'comment' ? 'comment' : 'uknonwn';
504  
505 # TAP doesn't have an explicit way to associate a comment
506 # with a test (yet) so we'll assume it goes with the last
507 # test. Look backwards through the stack for the last test
508 my $last_test = $tests[-1];
509 if ($last_test) {
510 $last_test->{$slot} ||= '';
511 $last_test->{$slot} .= ("\n" . $line->as_string);
512 }
513 }
514 },
515 EOF => sub {
516 my $parser = shift;
517  
518 # did we run everything we planned to?
519 my $planned = $parser->tests_planned;
520 my $run = $parser->tests_run;
521 my $total;
522 if ($planned && $planned > $run) {
523 $total = $planned;
524 foreach (1 .. $planned - $run) {
525 $failed++;
526 push(
527 @tests,
528 {
529 ok => 0,
530 skip => 0,
531 todo => 0,
532 comment => "test died after test # $run",
533 died => 1,
534 }
535 );
536 }
537 } else {
538 $total = $run;
539 }
540  
541 my $percent = $total ? sprintf('%i', (($total - $failed) / $total) * 100) : 100;
542  
543 # record the individual test file and test file result
544 my $test_file = Smolder::DB::TestFile->find_or_create(
545 {
546 project => $self->project,
547 label => $label
548 }
549 ) or die "could not find or create test file '$label'";
550 Smolder::DB::TestFileResult->insert_or_replace(
551 {
552 test_file => $test_file->id,
553 smoke_report => $self->id,
554 project => $self->project->id,
555 total => $total,
556 failed => $failed,
557 percent => $percent,
558 file_index => $file_index,
559 }
560 ) or die "could not set result for test file '$label'";
561  
562 # push a hash onto the list of results for TAPHTMLMatrix
563 push(
564 @suite_results,
565 {
566 label => $label,
567 tests => [@tests],
568 total => $total,
569 failed => $failed,
570 percent => $percent,
571 all_skipped => ($skipped == $total),
572 is_muted => $test_file->is_muted,
573 mute_until => $test_file->is_muted
574 ? $test_file->mute_until->strftime("%a %b %d")
575 : '',
576 file_index => $file_index,
577 test_file => $test_file->id,
578 }
579 );
580 $suite_data{total} += $total;
581 $suite_data{failed} += $failed;
582 }
583 },
584 }
585 );
586  
587 # update
588 $self->set(
589 pass => scalar $aggregator->passed,
590 fail => $suite_data{failed}, # aggregator doesn't calculate these 2 right
591 total => $suite_data{total},
592 skip => scalar $aggregator->skipped,
593 todo => scalar $aggregator->todo,
594 todo_pass => scalar $aggregator->todo_passed,
595 test_files => scalar @suite_results,
596 failed => !!$aggregator->failed,
597 duration => $duration,
598 );
599  
600 # we can take some things from the meta information in the archive
601 # if they weren't provided during the upload
602 if ($meta->{extra_properties}) {
603 foreach my $k (keys %{$meta->{extra_properties}}) {
604 foreach my $field qw(architecture platform comments) {
605 if (lc($k) eq $field && !$self->get($field)) {
606 $self->set($field => delete $meta->{extra_properties}->{$k});
607 last;
608 }
609 }
610 }
611 }
612  
613 # generate the HTML reports
614 my $matrix = Smolder::TAPHTMLMatrix->new(
615 smoke_report => $self,
616 test_results => \@suite_results,
617 meta => $meta,
618 );
619 $matrix->generate_html();
620 $self->update();
621  
622 return \@suite_results;
623 }
624  
625 =head3 update_all_report_html
626  
627 Look at all existing reports in the database and regenerate
628 the HTML for each of these reports. This is useful for development
629 and also upgrading when the report HTML template files have changed
630 and you want that change to propagate.
631  
632 =cut
633  
634 sub update_all_report_html {
635 my $class = shift;
636 my @reports = $class->search(purged => 0);
637 foreach my $report (@reports) {
638 warn "Updating report #$report\n";
639 eval { $report->update_from_tap_archive() };
640 warn " Problem updating report #$report: $@\n" if $@;
641 }
642  
643 }
644  
645 1;