Move mention of different "stash styles" to Ch2
[catagits/Catalyst-Manual.git] / lib / Catalyst / Manual / Tutorial / 08_Testing.pod
CommitLineData
d442cc9f 1=head1 NAME
2
3ab6187c 3Catalyst::Manual::Tutorial::08_Testing - Catalyst Tutorial - Chapter 8: Testing
d442cc9f 4
5
6=head1 OVERVIEW
7
4b4d3884 8This is B<Chapter 8 of 10> for the Catalyst tutorial.
d442cc9f 9
10L<Tutorial Overview|Catalyst::Manual::Tutorial>
11
12=over 4
13
14=item 1
15
3ab6187c 16L<Introduction|Catalyst::Manual::Tutorial::01_Intro>
d442cc9f 17
18=item 2
19
3ab6187c 20L<Catalyst Basics|Catalyst::Manual::Tutorial::02_CatalystBasics>
d442cc9f 21
22=item 3
23
3ab6187c 24L<More Catalyst Basics|Catalyst::Manual::Tutorial::03_MoreCatalystBasics>
d442cc9f 25
26=item 4
27
3ab6187c 28L<Basic CRUD|Catalyst::Manual::Tutorial::04_BasicCRUD>
d442cc9f 29
30=item 5
31
3ab6187c 32L<Authentication|Catalyst::Manual::Tutorial::05_Authentication>
d442cc9f 33
34=item 6
35
3ab6187c 36L<Authorization|Catalyst::Manual::Tutorial::06_Authorization>
d442cc9f 37
38=item 7
39
3ab6187c 40L<Debugging|Catalyst::Manual::Tutorial::07_Debugging>
d442cc9f 41
42=item 8
43
3ab6187c 44B<08_Testing>
d442cc9f 45
46=item 9
47
3ab6187c 48L<Advanced CRUD|Catalyst::Manual::Tutorial::09_AdvancedCRUD>
3533daff 49
50=item 10
51
3ab6187c 52L<Appendices|Catalyst::Manual::Tutorial::10_Appendices>
d442cc9f 53
54=back
55
3533daff 56
d442cc9f 57=head1 DESCRIPTION
58
4b4d3884 59You may have noticed that the Catalyst Helper scripts automatically
60create basic C<.t> test scripts under the C<t> directory. This
61chapter of the tutorial briefly looks at how these tests can be used
3b1fa91b 62not only to ensure that your application is working correctly at the
4b4d3884 63present time, but also provide automated regression testing as you
64upgrade various pieces of your application over time.
d442cc9f 65
4d63a0d5 66You can check out the source code for this example from the Catalyst
67Subversion repository as per the instructions in
3ab6187c 68L<Catalyst::Manual::Tutorial::01_Intro|Catalyst::Manual::Tutorial::01_Intro>.
1390ef0e 69
3b1fa91b 70For an excellent introduction to learning the many benefits of testing
71your Perl applications and modules, you might want to read 'Perl Testing:
72A Developer's Notebook' by Ian Langworth and chromatic.
73
d442cc9f 74
75=head1 RUNNING THE "CANNED" CATALYST TESTS
76
77There are a variety of ways to run Catalyst and Perl tests (for example,
78C<perl Makefile.PL> and C<make test>), but one of the easiest is with the
79C<prove> command. For example, to run all of the tests in the C<t>
80directory, enter:
81
da59dbea 82 $ prove -wl t
d442cc9f 83
028b4e1a 84There will be a lot of output because we have the C<-Debug> flag
85enabled in C<lib/MyApp.pm> (see the C<CATALYST_DEBUG=0> tip below for
86a quick and easy way to reduce the clutter). Look for lines like this
87for errors:
3533daff 88
89 # Failed test 'Request should succeed'
3b1fa91b 90 # at t/controller_Books.t line 8.
3533daff 91 # Looks like you failed 1 test of 3.
92
93The redirection used by the Authentication plugins will cause several
94failures in the default tests. You can fix this by making the following
95changes:
96
acbd7bdd 971) Change the line in C<t/01app.t> that reads:
d442cc9f 98
99 ok( request('/')->is_success, 'Request should succeed' );
100
101to:
102
103 ok( request('/login')->is_success, 'Request should succeed' );
104
3b1fa91b 1052) Change the line in C<t/controller_Logout.t> that reads:
106
107 ok( request('/logout')->is_success, 'Request should succeed' );
108
109to:
110
111 ok( request('/logout')->is_redirect, 'Request should succeed' );
112
1133) Change the line in C<t/controller_Books.t> that reads:
114
115 ok( request('/books')->is_success, 'Request should succeed' );
116
117to:
118
119 ok( request('/books')->is_redirect, 'Request should succeed' );
d442cc9f 120
3b1fa91b 1214) Add the following statement to the top of C<t/view_TT.t>:
d442cc9f 122
3b1fa91b 123 use MyApp;
6a72d1bf 124
d442cc9f 125As you can see in the C<prove> command line above, the C<--lib> option
126is used to set the location of the Catalyst C<lib> directory. With this
127command, you will get all of the usual development server debug output,
128something most people prefer to disable while running tests cases.
129Although you can edit the C<lib/MyApp.pm> to comment out the C<-Debug>
130plugin, it's generally easier to simply set the C<CATALYST_DEBUG=0>
131environment variable. For example:
132
da59dbea 133 $ CATALYST_DEBUG=0 prove -wl t
d442cc9f 134
ebde193e 135B<Note:> Depending on the versions of various modules you have
136installed, you might get some C<used only once> warnings -- you can
3b1fa91b 137ignore these. If you want to eliminate the warnings, you can
ebde193e 138edit C<Template::Base> to disable and then re-enable warnings
139are the C</usr/lib/perl5/Template/Base.pm> line in C<sub new>.
140You can locate where C<Template::Base> is located with the
141following command (it's probably in a place similar to
142C</usr/lib/perl5/Template/Base.pm>):
143
144 perldoc -l Template::Base
145
146Edit the file and modify C<sub new> to match:
147
148 ...
149 { no strict qw( refs );
150 # Disable warnings
151 no warnings;
152 $argnames = \@{"$class\::BASEARGS"} || [ ];
153 # Turn warnings back on
154 use warnings;
155 }
156 ...
157
d442cc9f 158During the C<t/02pod> and C<t/03podcoverage> tests, you might notice the
159C<all skipped: set TEST_POD to enable this test> warning message. To
160execute the Pod-related tests, add C<TEST_POD=1> to the C<prove>
161command:
162
da59dbea 163 $ CATALYST_DEBUG=0 TEST_POD=1 prove -wl t
d442cc9f 164
165If you omitted the Pod comments from any of the methods that were
166inserted, you might have to go back and fix them to get these tests to
167pass. :-)
168
169Another useful option is the C<verbose> (C<-v>) option to C<prove>. It
170prints the name of each test case as it is being run:
171
da59dbea 172 $ CATALYST_DEBUG=0 TEST_POD=1 prove -vwl t
d442cc9f 173
3533daff 174
d442cc9f 175=head1 RUNNING A SINGLE TEST
176
177You can also run a single script by appending its name to the C<prove>
178command. For example:
179
da59dbea 180 $ CATALYST_DEBUG=0 prove -wl t/01app.t
d442cc9f 181
3533daff 182Also note that you can also run tests directly from Perl without C<prove>.
d442cc9f 183For example:
184
da59dbea 185 $ CATALYST_DEBUG=0 perl -w -Ilib t/01app.t
d442cc9f 186
3533daff 187
d442cc9f 188=head1 ADDING YOUR OWN TEST SCRIPT
189
190Although the Catalyst helper scripts provide a basic level of checks
191"for free," testing can become significantly more helpful when you write
192your own script to exercise the various parts of your application. The
193L<Test::WWW::Mechanize::Catalyst|Test::WWW::Mechanize::Catalyst> module
194is very popular for writing these sorts of test cases. This module
195extends L<Test::WWW::Mechanize|Test::WWW::Mechanize> (and therefore
196L<WWW::Mechanize|WWW::Mechanize>) to allow you to automate the action of
197a user "clicking around" inside your application. It gives you all the
198benefits of testing on a live system without the messiness of having to
199use an actual web server, and a real person to do the clicking.
200
201To create a sample test case, open the C<t/live_app01.t> file in your
202editor and enter the following:
203
204 #!/usr/bin/perl
205
206 use strict;
207 use warnings;
da59dbea 208 use Test::More;
d442cc9f 209
210 # Need to specify the name of your app as arg on next line
211 # Can also do:
212 # use Test::WWW::Mechanize::Catalyst "MyApp";
213
214 use ok "Test::WWW::Mechanize::Catalyst" => "MyApp";
215
216 # Create two 'user agents' to simulate two different users ('test01' & 'test02')
217 my $ua1 = Test::WWW::Mechanize::Catalyst->new;
218 my $ua2 = Test::WWW::Mechanize::Catalyst->new;
219
220 # Use a simplified for loop to do tests that are common to both users
221 # Use get_ok() to make sure we can hit the base URL
222 # Second arg = optional description of test (will be displayed for failed tests)
223 # Note that in test scripts you send everything to 'http://localhost'
224 $_->get_ok("http://localhost/", "Check redirect of base URL") for $ua1, $ua2;
225 # Use title_is() to check the contents of the <title>...</title> tags
226 $_->title_is("Login", "Check for login title") for $ua1, $ua2;
227 # Use content_contains() to match on text in the html body
228 $_->content_contains("You need to log in to use this application",
229 "Check we are NOT logged in") for $ua1, $ua2;
230
231 # Log in as each user
232 # Specify username and password on the URL
233 $ua1->get_ok("http://localhost/login?username=test01&password=mypass", "Login 'test01'");
2a6eb5f9 234 # Could make user2 like user1 above, but use the form to show another way
235 $ua2->submit_form(
236 fields => {
237 username => 'test02',
238 password => 'mypass',
239 });
d442cc9f 240
241 # Go back to the login page and it should show that we are already logged in
242 $_->get_ok("http://localhost/login", "Return to '/login'") for $ua1, $ua2;
243 $_->title_is("Login", "Check for login page") for $ua1, $ua2;
244 $_->content_contains("Please Note: You are already logged in as ",
245 "Check we ARE logged in" ) for $ua1, $ua2;
246
247 # 'Click' the 'Logout' link (see also 'text_regex' and 'url_regex' options)
028b4e1a 248 $_->follow_link_ok({n => 4}, "Logout via first link on page") for $ua1, $ua2;
d442cc9f 249 $_->title_is("Login", "Check for login title") for $ua1, $ua2;
250 $_->content_contains("You need to log in to use this application",
251 "Check we are NOT logged in") for $ua1, $ua2;
252
253 # Log back in
254 $ua1->get_ok("http://localhost/login?username=test01&password=mypass", "Login 'test01'");
255 $ua2->get_ok("http://localhost/login?username=test02&password=mypass", "Login 'test02'");
256 # Should be at the Book List page... do some checks to confirm
257 $_->title_is("Book List", "Check for book list title") for $ua1, $ua2;
258
259 $ua1->get_ok("http://localhost/books/list", "'test01' book list");
260 $ua1->get_ok("http://localhost/login", "Login Page");
261 $ua1->get_ok("http://localhost/books/list", "'test01' book list");
262
263 $_->content_contains("Book List", "Check for book list title") for $ua1, $ua2;
264 # Make sure the appropriate logout buttons are displayed
fbbb9084 265 $_->content_contains("/logout\">User Logout</a>",
d442cc9f 266 "Both users should have a 'User Logout'") for $ua1, $ua2;
6290bf87 267 $ua1->content_contains("/books/form_create\">Admin Create</a>",
87058ad4 268 "'test01' should have a create link");
269 $ua2->content_lacks("/books/form_create\">Admin Create</a>",
270 "'test02' should NOT have a create link");
d442cc9f 271
272 $ua1->get_ok("http://localhost/books/list", "View book list as 'test01'");
273
274 # User 'test01' should be able to create a book with the "formless create" URL
275 $ua1->get_ok("http://localhost/books/url_create/TestTitle/2/4",
276 "'test01' formless create");
277 $ua1->title_is("Book Created", "Book created title");
278 $ua1->content_contains("Added book 'TestTitle'", "Check title added OK");
279 $ua1->content_contains("by 'Stevens'", "Check author added OK");
280 $ua1->content_contains("with a rating of 2.", "Check rating added");
281 # Try a regular expression to combine the previous 3 checks & account for whitespace
282 $ua1->content_like(qr/Added book 'TestTitle'\s+by 'Stevens'\s+with a rating of 2./, "Regex check");
283
284 # Make sure the new book shows in the list
285 $ua1->get_ok("http://localhost/books/list", "'test01' book list");
286 $ua1->title_is("Book List", "Check logged in and at book list");
287 $ua1->content_contains("Book List", "Book List page test");
288 $ua1->content_contains("TestTitle", "Look for 'TestTitle'");
289
290 # Make sure the new book can be deleted
291 # Get all the Delete links on the list page
292 my @delLinks = $ua1->find_all_links(text => 'Delete');
293 # Use the final link to delete the last book
294 $ua1->get_ok($delLinks[$#delLinks]->url, 'Delete last book');
295 # Check that delete worked
296 $ua1->content_contains("Book List", "Book List page test");
297 $ua1->content_contains("Book deleted", "Book was deleted");
298
299 # User 'test02' should not be able to add a book
300 $ua2->get_ok("http://localhost/books/url_create/TestTitle2/2/5", "'test02' add");
301 $ua2->content_contains("Unauthorized!", "Check 'test02' cannot add");
302
da59dbea 303 done_testing;
304
d442cc9f 305The C<live_app.t> test cases uses copious comments to explain each step
306of the process. In addition to the techniques shown here, there are a
307variety of other methods available in
308L<Test::WWW::Mechanize::Catalyst|Test::WWW::Mechanize::Catalyst> (for
309example, regex-based matching). Consult the documentation for more
310detail.
311
312B<TIP>: For I<unit tests> vs. the "full application tests" approach used
313by L<Test::WWW::Mechanize::Catalyst|Test::WWW::Mechanize::Catalyst>, see
314L<Catalyst::Test|Catalyst::Test>.
315
316B<Note:> The test script does not test the C<form_create> and
317C<form_create_do> actions. That is left as an exercise for the reader
318(you should be able to complete that logic using the existing code as a
319template).
320
321To run the new test script, use a command such as:
322
da59dbea 323 $ CATALYST_DEBUG=0 prove -vwl t/live_app01.t
d442cc9f 324
325or
326
da59dbea 327 $ DBIC_TRACE=0 CATALYST_DEBUG=0 prove -vwl t/live_app01.t
d442cc9f 328
4b4d3884 329Experiment with the C<DBIC_TRACE>, C<CATALYST_DEBUG> and C<-v>
330settings. If you find that there are errors, use the techniques
331discussed in the "Catalyst Debugging" section (Chapter 7) to isolate
332and fix any problems.
d442cc9f 333
334If you want to run the test case under the Perl interactive debugger,
335try a command such as:
336
337 $ DBIC_TRACE=0 CATALYST_DEBUG=0 perl -d -Ilib t/live_app01.t
338
339Note that although this tutorial uses a single custom test case for
340simplicity, you may wish to break your tests into different files for
341better organization.
342
343B<TIP:> If you have a test case that fails, you will receive an error
344similar to the following:
345
346 # Failed test 'Check we are NOT logged in'
347 # in t/live_app01.t at line 31.
348 # searched: "\x{0a}<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Tran"...
349 # can't find: "You need to log in to use this application."
350
351Unfortunately, this only shows us the first 50 characters of the HTML
352returned by the request -- not enough to determine where the problem
353lies. A simple technique that can be used in such situations is to
354temporarily insert a line similar to the following right after the
355failed test:
356
6daaedc0 357 diag $ua1->content;
d442cc9f 358
359This will cause the full HTML returned by the request to be displayed.
360
fbbb9084 361Another approach to see the full HTML content at the failure point in
362a series of tests would be to insert a "C<$DB::single=1;> right above
363the location of the failure and run the test under the perl debugger
364(with C<-d>) as shown above. Then you can use the debugger to explore
365the state of the application right before or after the failure.
366
d442cc9f 367
368=head1 SUPPORTING BOTH PRODUCTION AND TEST DATABASES
369
370You may wish to leverage the techniques discussed in this tutorial to
371maintain both a "production database" for your live application and a
372"testing database" for your test cases. One advantage to
373L<Test::WWW::Mechanize::Catalyst|Test::WWW::Mechanize::Catalyst> is that
374it runs your full application; however, this can complicate things when
375you want to support multiple databases. One solution is to allow the
376database specification to be overridden with an environment variable.
d0496197 377For example, open C<lib/MyApp/Model/DB.pm> in your editor and
d442cc9f 378change the C<__PACKAGE__-E<gt>config(...> declaration to resemble:
379
380 my $dsn = $ENV{MYAPP_DSN} ||= 'dbi:SQLite:myapp.db';
381 __PACKAGE__->config(
d0496197 382 schema_class => 'MyApp::Schema',
da59dbea 383
384 connect_info => {
385 dsn => $dsn,
386 ...
d442cc9f 387
388Then, when you run your test case, you can use commands such as:
389
390 $ cp myapp.db myappTEST.db
da59dbea 391 $ CATALYST_DEBUG=0 MYAPP_DSN="dbi:SQLite:myappTEST.db" prove -vwl t/live_app01.t
d442cc9f 392
393This will modify the DSN only while the test case is running. If you
394launch your normal application without the C<MYAPP_DSN> environment
395variable defined, it will default to the same C<dbi:SQLite:myapp.db> as
396before.
397
398
399=head1 AUTHOR
400
401Kennedy Clark, C<hkclark@gmail.com>
402
403Please report any errors, issues or suggestions to the author. The
404most recent version of the Catalyst Tutorial can be found at
59884771 405L<http://dev.catalyst.perl.org/repos/Catalyst/Catalyst-Manual/5.80/trunk/lib/Catalyst/Manual/Tutorial/>.
d442cc9f 406
45c7830f 407Copyright 2006-2008, Kennedy Clark, under Creative Commons License
8482d557 408(L<http://creativecommons.org/licenses/by-sa/3.0/us/>).
d442cc9f 409