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