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