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