Update StackTrace wording
[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
bf4d990b 59You may have noticed that the Catalyst Helper scripts automatically
60create basic C<.t> test scripts under the C<t> directory. This chapter
61of the tutorial briefly looks at how these tests can be used not only to
62ensure that your application is working correctly at the present time,
63but also provide automated regression testing as you upgrade various
64pieces 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
2217b252 68L<Catalyst::Manual::Tutorial::01_Intro>.
1390ef0e 69
3b1fa91b 70For an excellent introduction to learning the many benefits of testing
bf4d990b 71your Perl applications and modules, you might want to read 'Perl
72Testing: A Developer's Notebook' by Ian Langworth and chromatic.
3b1fa91b 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,
bf4d990b 78C<perl Makefile.PL> and C<make test>), but one of the easiest is with
79the C<prove> command. For example, to run all of the tests in the C<t>
d442cc9f 80directory, enter:
81
da59dbea 82 $ prove -wl t
d442cc9f 83
bf4d990b 84There will be a lot of output because we have the C<-Debug> flag enabled
85in C<lib/MyApp.pm> (see the C<CATALYST_DEBUG=0> tip below for a quick
86and easy way to reduce the clutter). Look for lines like this for
87errors:
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
bf4d990b 93The redirection used by the Authentication plugins will cause several
3533daff 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
335a4fdf 1214) Add the following statement to the top of C<t/view_HTML.t>:
d442cc9f 122
3b1fa91b 123 use MyApp;
6a72d1bf 124
0e662618 125As you can see in the C<prove> command line above, the C<-l> option (or
126C<--lib> if you prefer) is used to set the location of the Catalyst
127C<lib> directory. With this command, you will get all of the usual
128development server debug output, something most people prefer to disable
129while running tests cases. Although you can edit the C<lib/MyApp.pm> to
130comment out the C<-Debug> plugin, it's generally easier to simply set
131the C<CATALYST_DEBUG=0> environment variable. For example:
d442cc9f 132
da59dbea 133 $ CATALYST_DEBUG=0 prove -wl t
d442cc9f 134
135During the C<t/02pod> and C<t/03podcoverage> tests, you might notice the
136C<all skipped: set TEST_POD to enable this test> warning message. To
137execute the Pod-related tests, add C<TEST_POD=1> to the C<prove>
138command:
139
da59dbea 140 $ CATALYST_DEBUG=0 TEST_POD=1 prove -wl t
d442cc9f 141
142If you omitted the Pod comments from any of the methods that were
143inserted, you might have to go back and fix them to get these tests to
144pass. :-)
145
146Another useful option is the C<verbose> (C<-v>) option to C<prove>. It
147prints the name of each test case as it is being run:
148
0e662618 149 $ CATALYST_DEBUG=0 prove -vwl t
d442cc9f 150
3533daff 151
d442cc9f 152=head1 RUNNING A SINGLE TEST
153
154You can also run a single script by appending its name to the C<prove>
155command. For example:
156
da59dbea 157 $ CATALYST_DEBUG=0 prove -wl t/01app.t
d442cc9f 158
bf4d990b 159Also note that you can also run tests directly from Perl without
160C<prove>. For example:
d442cc9f 161
da59dbea 162 $ CATALYST_DEBUG=0 perl -w -Ilib t/01app.t
d442cc9f 163
3533daff 164
d442cc9f 165=head1 ADDING YOUR OWN TEST SCRIPT
166
167Although the Catalyst helper scripts provide a basic level of checks
168"for free," testing can become significantly more helpful when you write
0e662618 169your own tests to exercise the various parts of your application. The
bf4d990b 170L<Test::WWW::Mechanize::Catalyst> module is very popular for writing
171these sorts of test cases. This module extends L<Test::WWW::Mechanize>
172(and therefore L<WWW::Mechanize>) to allow you to automate the action of
d442cc9f 173a user "clicking around" inside your application. It gives you all the
174benefits of testing on a live system without the messiness of having to
175use an actual web server, and a real person to do the clicking.
176
177To create a sample test case, open the C<t/live_app01.t> file in your
178editor and enter the following:
179
0e662618 180 #!/usr/bin/env perl
d442cc9f 181
182 use strict;
183 use warnings;
da59dbea 184 use Test::More;
d442cc9f 185
186 # Need to specify the name of your app as arg on next line
187 # Can also do:
188 # use Test::WWW::Mechanize::Catalyst "MyApp";
189
e5415384 190 BEGIN { use_ok("Test::WWW::Mechanize::Catalyst" => "MyApp") }
3dba69ab 191
d442cc9f 192 # Create two 'user agents' to simulate two different users ('test01' & 'test02')
193 my $ua1 = Test::WWW::Mechanize::Catalyst->new;
194 my $ua2 = Test::WWW::Mechanize::Catalyst->new;
195
196 # Use a simplified for loop to do tests that are common to both users
197 # Use get_ok() to make sure we can hit the base URL
198 # Second arg = optional description of test (will be displayed for failed tests)
199 # Note that in test scripts you send everything to 'http://localhost'
200 $_->get_ok("http://localhost/", "Check redirect of base URL") for $ua1, $ua2;
201 # Use title_is() to check the contents of the <title>...</title> tags
202 $_->title_is("Login", "Check for login title") for $ua1, $ua2;
203 # Use content_contains() to match on text in the html body
204 $_->content_contains("You need to log in to use this application",
205 "Check we are NOT logged in") for $ua1, $ua2;
206
207 # Log in as each user
208 # Specify username and password on the URL
209 $ua1->get_ok("http://localhost/login?username=test01&password=mypass", "Login 'test01'");
2a6eb5f9 210 # Could make user2 like user1 above, but use the form to show another way
211 $ua2->submit_form(
212 fields => {
213 username => 'test02',
214 password => 'mypass',
215 });
d442cc9f 216
217 # Go back to the login page and it should show that we are already logged in
218 $_->get_ok("http://localhost/login", "Return to '/login'") for $ua1, $ua2;
219 $_->title_is("Login", "Check for login page") for $ua1, $ua2;
220 $_->content_contains("Please Note: You are already logged in as ",
221 "Check we ARE logged in" ) for $ua1, $ua2;
222
223 # 'Click' the 'Logout' link (see also 'text_regex' and 'url_regex' options)
028b4e1a 224 $_->follow_link_ok({n => 4}, "Logout via first link on page") for $ua1, $ua2;
d442cc9f 225 $_->title_is("Login", "Check for login title") for $ua1, $ua2;
226 $_->content_contains("You need to log in to use this application",
227 "Check we are NOT logged in") for $ua1, $ua2;
228
229 # Log back in
0e662618 230 $ua1->get_ok("http://localhost/login?username=test01&password=mypass",
231 "Login 'test01'");
232 $ua2->get_ok("http://localhost/login?username=test02&password=mypass",
233 "Login 'test02'");
d442cc9f 234 # Should be at the Book List page... do some checks to confirm
235 $_->title_is("Book List", "Check for book list title") for $ua1, $ua2;
236
237 $ua1->get_ok("http://localhost/books/list", "'test01' book list");
238 $ua1->get_ok("http://localhost/login", "Login Page");
239 $ua1->get_ok("http://localhost/books/list", "'test01' book list");
240
241 $_->content_contains("Book List", "Check for book list title") for $ua1, $ua2;
242 # Make sure the appropriate logout buttons are displayed
fbbb9084 243 $_->content_contains("/logout\">User Logout</a>",
d442cc9f 244 "Both users should have a 'User Logout'") for $ua1, $ua2;
6290bf87 245 $ua1->content_contains("/books/form_create\">Admin Create</a>",
87058ad4 246 "'test01' should have a create link");
247 $ua2->content_lacks("/books/form_create\">Admin Create</a>",
248 "'test02' should NOT have a create link");
d442cc9f 249
250 $ua1->get_ok("http://localhost/books/list", "View book list as 'test01'");
251
252 # User 'test01' should be able to create a book with the "formless create" URL
253 $ua1->get_ok("http://localhost/books/url_create/TestTitle/2/4",
254 "'test01' formless create");
255 $ua1->title_is("Book Created", "Book created title");
256 $ua1->content_contains("Added book 'TestTitle'", "Check title added OK");
257 $ua1->content_contains("by 'Stevens'", "Check author added OK");
258 $ua1->content_contains("with a rating of 2.", "Check rating added");
259 # Try a regular expression to combine the previous 3 checks & account for whitespace
0e662618 260 $ua1->content_like(qr/Added book 'TestTitle'\s+by 'Stevens'\s+with a rating of 2./,
261 "Regex check");
d442cc9f 262
263 # Make sure the new book shows in the list
264 $ua1->get_ok("http://localhost/books/list", "'test01' book list");
265 $ua1->title_is("Book List", "Check logged in and at book list");
266 $ua1->content_contains("Book List", "Book List page test");
267 $ua1->content_contains("TestTitle", "Look for 'TestTitle'");
268
269 # Make sure the new book can be deleted
270 # Get all the Delete links on the list page
271 my @delLinks = $ua1->find_all_links(text => 'Delete');
272 # Use the final link to delete the last book
273 $ua1->get_ok($delLinks[$#delLinks]->url, 'Delete last book');
274 # Check that delete worked
275 $ua1->content_contains("Book List", "Book List page test");
0e662618 276 $ua1->content_like(qr/Deleted book \d+/, "Deleted book #");
d442cc9f 277
278 # User 'test02' should not be able to add a book
279 $ua2->get_ok("http://localhost/books/url_create/TestTitle2/2/5", "'test02' add");
280 $ua2->content_contains("Unauthorized!", "Check 'test02' cannot add");
0a2a4a5a 281
da59dbea 282 done_testing;
283
d442cc9f 284The C<live_app.t> test cases uses copious comments to explain each step
285of the process. In addition to the techniques shown here, there are a
bf4d990b 286variety of other methods available in L<Test::WWW::Mechanize::Catalyst>
0e662618 287(for example, regex-based matching). Consult
288L<Test::WWW::Mechanize::Catalyst>, L<Test::WWW::Mechanize>,
289L<WWW::Mechanize>, and L<Test::More> for more detail.
d442cc9f 290
291B<TIP>: For I<unit tests> vs. the "full application tests" approach used
bf4d990b 292by L<Test::WWW::Mechanize::Catalyst>, see L<Catalyst::Test>.
d442cc9f 293
294B<Note:> The test script does not test the C<form_create> and
295C<form_create_do> actions. That is left as an exercise for the reader
296(you should be able to complete that logic using the existing code as a
297template).
298
299To run the new test script, use a command such as:
300
da59dbea 301 $ CATALYST_DEBUG=0 prove -vwl t/live_app01.t
d442cc9f 302
303or
304
da59dbea 305 $ DBIC_TRACE=0 CATALYST_DEBUG=0 prove -vwl t/live_app01.t
d442cc9f 306
bf4d990b 307Experiment with the C<DBIC_TRACE>, C<CATALYST_DEBUG> and C<-v> settings.
308If you find that there are errors, use the techniques discussed in the
309"Catalyst Debugging" section (Chapter 7) to isolate and fix any
310problems.
d442cc9f 311
312If you want to run the test case under the Perl interactive debugger,
313try a command such as:
314
315 $ DBIC_TRACE=0 CATALYST_DEBUG=0 perl -d -Ilib t/live_app01.t
316
317Note that although this tutorial uses a single custom test case for
318simplicity, you may wish to break your tests into different files for
319better organization.
320
321B<TIP:> If you have a test case that fails, you will receive an error
322similar to the following:
323
324 # Failed test 'Check we are NOT logged in'
325 # in t/live_app01.t at line 31.
326 # searched: "\x{0a}<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Tran"...
327 # can't find: "You need to log in to use this application."
328
329Unfortunately, this only shows us the first 50 characters of the HTML
330returned by the request -- not enough to determine where the problem
bf4d990b 331lies. A simple technique that can be used in such situations is to
332temporarily insert a line similar to the following right after the
d442cc9f 333failed test:
334
6daaedc0 335 diag $ua1->content;
d442cc9f 336
337This will cause the full HTML returned by the request to be displayed.
338
bf4d990b 339Another approach to see the full HTML content at the failure point in a
340series of tests would be to insert a "C<$DB::single=1;> right above the
0e662618 341location of the failure and run the test under the Perl debugger (with
bf4d990b 342C<-d>) as shown above. Then you can use the debugger to explore the
343state of the application right before or after the failure.
fbbb9084 344
d442cc9f 345
346=head1 SUPPORTING BOTH PRODUCTION AND TEST DATABASES
347
348You may wish to leverage the techniques discussed in this tutorial to
349maintain both a "production database" for your live application and a
350"testing database" for your test cases. One advantage to
bf4d990b 351L<Test::WWW::Mechanize::Catalyst> is that it runs your full application;
352however, this can complicate things when you want to support multiple
353databases.
6c0a745e 354
355=head2 DATABASE CONFIG SWITCHING IN YOUR MODEL CLASS
356
bf4d990b 357One solution is to allow the database specification to be overridden
358with an environment variable. For example, open
359C<lib/MyApp/Model/DB.pm> in your editor and change the
360C<__PACKAGE__-E<gt>config(...> declaration to resemble:
d442cc9f 361
362 my $dsn = $ENV{MYAPP_DSN} ||= 'dbi:SQLite:myapp.db';
363 __PACKAGE__->config(
d0496197 364 schema_class => 'MyApp::Schema',
0a2a4a5a 365
da59dbea 366 connect_info => {
367 dsn => $dsn,
0a2a4a5a 368 user => '',
369 password => '',
370 on_connect_do => q{PRAGMA foreign_keys = ON},
371 }
372 );
d442cc9f 373
374Then, when you run your test case, you can use commands such as:
375
376 $ cp myapp.db myappTEST.db
da59dbea 377 $ CATALYST_DEBUG=0 MYAPP_DSN="dbi:SQLite:myappTEST.db" prove -vwl t/live_app01.t
d442cc9f 378
379This will modify the DSN only while the test case is running. If you
380launch your normal application without the C<MYAPP_DSN> environment
381variable defined, it will default to the same C<dbi:SQLite:myapp.db> as
382before.
383
bf4d990b 384
6c0a745e 385=head2 DATABASE CONFIG SWITCHING USING MULTIPLE CONFIG FILES
386
0e662618 387L<Catalyst::Plugin::ConfigLoader> has functionality to load loading
388multiple config files based on environment variablesi, allowing you to
389override your default (production) database connection settings during
390development (or vice versa).
6c0a745e 391
bf4d990b 392Setting C<$ENV{ MYAPP_CONFIG_LOCAL_SUFFIX }> to 'testing' in your test
393script results in loading of an additional config file named
394C<myapp_testing.conf> after C<myapp.conf> which will override any
395parameters in C<myapp.conf>.
6c0a745e 396
bf4d990b 397You should set the environment variable in the BEGIN block of your test
398script to make sure it's set before your Catalyst application is
399started.
6c0a745e 400
bf4d990b 401The following is an example for a config and test script for a
402DBIx::Class model named MyDB and a controller named Foo:
6c0a745e 403
404myapp_testing.conf:
405
406 <Model::MyDB>
407 <connect_info>
408 dsn dbi:SQLite:myapp.db
409 </connect_info>
410 </Model::MyDB>
411
412
413t/controller_Foo.t:
414
415 use strict;
416 use warnings;
417 use Test::More;
3dba69ab 418
6c0a745e 419 BEGIN {
420 $ENV{ MYAPP_CONFIG_LOCAL_SUFFIX } = 'testing';
421 }
3dba69ab 422
6c0a745e 423 eval "use Test::WWW::Mechanize::Catalyst 'MyApp'";
424 plan $@
425 ? ( skip_all => 'Test::WWW::Mechanize::Catalyst required' )
426 : ( tests => 2 );
3dba69ab 427
6c0a745e 428 ok( my $mech = Test::WWW::Mechanize::Catalyst->new, 'Created mech object' );
3dba69ab 429
6c0a745e 430 $mech->get_ok( 'http://localhost/foo' );
431
d442cc9f 432
433=head1 AUTHOR
434
435Kennedy Clark, C<hkclark@gmail.com>
436
53243324 437Feel free to contact the author for any errors or suggestions, but the
438best way to report issues is via the CPAN RT Bug system at
439<https://rt.cpan.org/Public/Dist/Display.html?Name=Catalyst-Manual>.
440
441The most recent version of the Catalyst Tutorial can be found at
59884771 442L<http://dev.catalyst.perl.org/repos/Catalyst/Catalyst-Manual/5.80/trunk/lib/Catalyst/Manual/Tutorial/>.
d442cc9f 443
ec3ef4ad 444Copyright 2006-2010, Kennedy Clark, under the
445Creative Commons Attribution Share-Alike License Version 3.0
8482d557 446(L<http://creativecommons.org/licenses/by-sa/3.0/us/>).