Debian Codegraph @

lib/Test/Snapshot.pm

raw
1 package Test::Snapshot;
2 use 5.008001;
3 use strict;
4 use warnings;
5 use Test2::API qw(context test2_add_callback_pre_subtest);
6 use Exporter 'import';
7 require Carp;
8 require File::Spec;
9 require File::Path;
10 require File::Basename;
11 require Data::Dumper;
12 use Text::Diff;
13
14 our $VERSION = "0.061";
15 our @EXPORT = qw(is_deeply_snapshot);
16
17 # capture subtest names
18 test2_add_callback_pre_subtest(sub {
19 my ($name, $code, @args) = @_;
20 my $ctx = context();
21 my $hub = $ctx->hub;
22 my @existing = @{$hub->get_meta('Test::Snapshot::subtest_names') // []};
23 push @existing, $name;
24 $hub->set_meta('Test::Snapshot::subtest_names', \@existing);
25 $ctx->release;
26 });
27
28 sub is_deeply_snapshot {
29 my ($got, $description) = @_;
30 my $ctx = context();
31 my $expected = "undef\n";
32 my $filename = _get_filename($ctx, $description);
33 if (-f $filename) {
34 no strict;
35 local $@;
36 $expected = eval { _read_file($filename) };
37 $ctx->diag("Error in snapshot '$filename': $@") if $@;
38 } else {
39 $ctx->diag("No snapshot filename '$filename' found");
40 }
41 my $dumper = Data::Dumper->new([$got]);
42 $dumper->Indent(1)->Terse(1);
43 $dumper->Sortkeys(1) if $dumper->can("Sortkeys");
44 my $dump = $dumper->Dump;
45 my $result = $dump eq $expected;
46 if ($result) {
47 $ctx->pass($description);
48 } else {
49 $ctx->fail($description);
50 $ctx->diag(diff \$expected, \$dump);
51 if ($ENV{TEST_SNAPSHOT_UPDATE}) {
52 _make_dir_for($filename);
53 _write_file($filename, $dump);
54 }
55 }
56 $ctx->release;
57 $result;
58 }
59
60 sub _get_filename {
61 my ($ctx, $description) = @_;
62 Carp::croak("No description given") if !defined $description;
63 my @stack = map $_->get_meta('Test::Snapshot::subtest_names'), $ctx->stack->all;
64 @stack = map @$_, grep $_, @stack;
65 my $topfile = $0;
66 my ($v, $d, $f) = File::Spec->splitpath(File::Spec->rel2abs($topfile));
67 unshift @stack, $f;
68 push @stack, $description;
69 @stack = map { my $t = $_; $t =~ s#[^a-z\-0-9]+#_#gi; $t } @stack;
70 my $basename = pop @stack;
71 File::Spec->catpath(
72 $v,
73 File::Spec->catdir($d, 'snapshots', @stack),
74 $basename,
75 );
76 }
77
78 sub _read_file {
79 my ($filename) = @_;
80 local $/;
81 open my $fh, '<', $filename or die "$filename: $!\n";
82 <$fh>;
83 }
84
85 sub _write_file {
86 my ($filename, $data) = @_;
87 open my $fh, '>', $filename or die "$filename: $!\n";
88 print $fh $data or die "$filename: $!\n";
89 }
90
91 sub _make_dir_for {
92 my ($filename) = @_;
93 my $dir = File::Basename::dirname($filename);
94 File::Path::make_path($dir); # will croak if fails
95 }
96
97 =encoding utf-8
98
99 =head1 NAME
100
101 Test::Snapshot - test against data stored in automatically-named file
102
103 =begin markdown
104
105 # PROJECT STATUS
106
107 | OS | Build status |
108 |:-------:|--------------:|
109 | Linux | [![Build Status](https://travis-ci.org/mohawk2/Test-Snapshot.svg?branch=master)](https://travis-ci.org/mohawk2/Test-Snapshot) |
110
111 [![CPAN version](https://badge.fury.io/pl/Test-Snapshot.svg)](https://metacpan.org/pod/Test::Snapshot)
112
113 =end markdown
114
115 =head1 SYNOPSIS
116
117 use Test::Snapshot;
118 my $got = function_generating_data();
119 is_deeply_snapshot $got, 'test description'; # could also be in a subtest
120
121 # command line:
122 TEST_SNAPSHOT_UPDATE=1 prove -lr t
123 # or
124 TEST_SNAPSHOT_UPDATE=1 make test
125 # if your code means the expected data should change, then inspect with
126 git diff -w
127
128 =head1 DESCRIPTION
129
130 Not connected with L<Test::Snapshots>, which is based on a similar
131 concept but for running executables.
132
133 As of 0.061, supports use under L<Test2::V0>.
134
135 Implements a function to automate the storing and updating of expected
136 test outputs. This is based on the idea known in frontend development
137 circles as "snapshot testing", hence the module name.
138
139 These snapshots will be stored in files whose names are automatically
140 generated from:
141
142 =over
143
144 =item the test filename (C<$0>)
145
146 =item any subtests' names surrounding and including this one
147
148 =item the test description if any
149
150 =back
151
152 If that file is not present, it will be treated as though it contains
153 an C<undef>.
154
155 =head1 FUNCTIONS
156
157 =head2 is_deeply_snapshot
158
159 Exported by default. Takes two mandatory arguments:
160
161 =over
162
163 =item
164
165 The "got" data (mandatory), a scalar which might be a reference. It will
166 be passed to L<Test::More/is_deeply> to be compared to the snapshotted
167 data.
168
169 =item
170
171 A text description of this test (mandatory). It will be used for reporting
172 results, but also to derive the filename in which the "expected" data
173 is stored.
174
175 =back
176
177 Will return the truth value of whether the test passed this time -
178 see below for automatic updating of "expected" data.
179
180 =head1 ENVIRONMENT
181
182 To have this module automatically update its "expected" data, set
183 environment variable C<TEST_SNAPSHOT_UPDATE> to a true value. If the
184 got and expected data do not match, a test failure will be reported,
185 but the "expected" data will be updated anyway.
186
187 This means it is safe to always have the variable set to a true value,
188 so long as you are using source control (you I<are> using source control,
189 right?) and check your diffs before committing.
190
191 =head1 FILE FORMAT
192
193 The "expected" data will be stored in a format generated by
194 L<Data::Dumper/Dumper>, with these values set to true, to maximise
195 readability (and to minimise diffs) of the stored data:
196
197 =over
198
199 =item Sortkeys
200
201 =item Indent
202
203 =item Terse
204
205 =back
206
207 =head1 AUTHOR
208
209 Ed J, C<< <etj at cpan.org> >>
210
211 =head1 LICENSE
212
213 Copyright (C) Ed J
214
215 This library is free software; you can redistribute it and/or modify
216 it under the same terms as Perl itself.
217
218 =cut
219
220 1;