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