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