Mojolicious Testing
Mojolicious is an open-source full-stack web development framework for the Perl programming language. It was created by Sebastian Riedel in 2009 and is designed to be user-friendly, powerful, and flexible. Mojolicious utilizes an MVC (Model-View-Controller) approach for development. The framework provides many tools and features to aid developers in building web applications quickly and easily. These include a robust routing engine, a built-in web server, template rendering, session management, and support for web sockets, among others.
A key feature of Mojolicious is its emphasis on real-time web development, with built-in support for web sockets and server-sent events. This feature makes it an excellent fit for building interactive web applications, such as chat applications, real-time analytics dashboards, and more. It is also renowned for its modern and expressive syntax, making it easy to write clean and maintainable code. The framework is fully compatible with the latest versions of Perl and has a thriving community of developers and users who contribute to its development and support.
The goal of unit tests is to inspect various individual units in your code. These units could be part of the model, view, controller, route, or middleware. The main goal is to focus on individual methods and verify their outcomes using techniques such as mocking. Checking scenarios like positive and negative flows, and error-handling cases will help you create high-quality test cases.
Testing using the Test framework
The Test framework offers many helper modules that facilitate the testing of Perl code. Some examples of Test modules in Perl include Test::Exception, Test::MockObject, Test::Deep, and Test::WWW::Mechanize, among many others.
use strict; use Test; # use a BEGIN block so we print our plan before MyModule is loaded BEGIN { plan tests => 14, todo => [3,4] } # load your module... use MyModule; print "# I'm testing MyModule version $MyModule::VERSION\n"; ok(0); # failure ok(1); # success ok(0); # ok, expected failure (see todo list, above) ok(1); # surprise success! # and so on...
Next, we'll explore some of the modules that the Test framework offers to assist with testing.
Testing using Test::Mojo
Test::Mojo comes bundled with Mojolicious, offering a means to write tests that simulate HTTP requests and responses to your application. It makes it easy to test controllers, routes, and templates, and is typically used in conjunction with Test::More.
use Mojo::Base -strict; use Test::Mojo; use Test::More; # Start a Mojolicious app named "Celestial" my $t = Test::Mojo->new('Celestial'); # Post a JSON document $t->post_ok('/notifications' => json => {event => 'full moon'}) ->status_is(201) ->json_is('/message' => 'notification created'); # Perform GET requests and look at the responses $t->get_ok('/sunrise') ->status_is(200) ->content_like(qr/ am$/); $t->get_ok('/sunset') ->status_is(200) ->content_like(qr/ pm$/); # Post a URL-encoded form $t->post_ok('/insurance' => form => {name => 'Jimmy', amount => '€3.000.000'}) ->status_is(200); # Use Test::More's like() to check the response like $t->tx->res->dom->at('div#thanks')->text, qr/thank you/, 'thanks'; done_testing();
The above test makes several HTTP requests to the application using Test::Mojo's testing methods, such as post_ok, get_ok, status_is, content_like, and json_is. The responses are then verified using Test::More's like method. The done_testing() method at the end of the script signifies the completion of the unit tests, and the number of tests executed is automatically determined by the testing framework.
Testing using Test::More
Test::More offers a simple yet powerful API for writing and executing tests. It includes an array of methods for making assertions about the behavior of your code, such as ok(), is(), like(), cmp_ok(), and isa_ok(). These methods allow developers to test a wide range of conditions, from simple equality checks to more complex object comparisons. Test::More also includes features for test planning, output formatting, and error reporting.
Testing using Test::Unit
Test::Unit is another module used for testing Perl code. However, for Mojolicious, Test::Mojo is generally the preferred choice. If you're accustomed to Test::Unit, you can certainly write your tests using this module.
Integration Testing
Integration testing focuses on verifying the interaction and communication between different components or modules of a software system. It is performed after unit testing, where individual units or components are tested in isolation. The purpose of integration testing is to expose defects in the interfaces and interactions between these units when they are integrated.
The main objective of integration testing is to ensure that the integrated components work together correctly as a whole and fulfill the intended functionality and requirements. It aims to identify any issues such as incompatible interfaces, data inconsistencies, communication failures, or incorrect assumptions made by the individual components.
These tests are expected to be lighter weight compared to end-to-end tests, and hence, you can use mocking or data fixtures in place of the real deal to simulate your integration tests. However, certain parts of the test, such as the modules being tested for integration, should not be simulated.
- Mojo::Client: This module allows you to make requests to URLs, handling the low-level details of setting up the connection, sending the request, and managing the response. It offers various methods for making different types of requests, including GET, POST, PUT, DELETE, and PATCH. Additionally, it also supports WebSocket connections using the websocket() method.
- Mojo::DOM: Built on top of the Mojo::DOM::HTML and Mojo::DOM::XML parsers (which are in turn based on the Mojo::DOM::Tree module), Mojo::DOM can manage different markup languages and encodings, automatically detecting and repairing errors in the input document. With Mojo::DOM, you can select elements in an HTML or XML document using CSS-like selectors and then manipulate those elements by adding or modifying attributes, changing their text content, or even adding or removing entire nodes.
- Test::WWW::Mechanize::Mojo: This module enables you to test Mojolicious applications using the WWW::Mechanize interface, incorporating features of web application testing. It supports various HTTP methods and offers methods for checking the status code, headers, and content of the response. Importantly, the module doesn't require you to launch a server or make real HTTP requests.
- Test::Mojo::Role::*: With roles, you can extend the Test::Mojo module with additional functionalities. Some examples of available roles include Test::Mojo::Role::Session, Test::Mojo::Role::Debug, and Test::Mojo::Role::SubmitForm.
my $req_number = 0; $client->websocket( # First request '/' => sub { my $self = shift; $self->receive_message( sub { my ($self, $message) = @_; if ($req_number == 0) { # first request like($message, qr/{"text":"Guest\d+ has joined chat"}/); } elsif { ... # end of last message $self->finish; } $req_number++; });
This example uses the websocket() method to simulate a WebSocket connection and perform integration testing on client-server interaction.
End-to-End Testing
- Test::Mojo's modules
- testRigor
Test::Mojo's modules
Test::Mojo provides modules for writing and testing end-to-end scenarios. Some of these modules include Test::Mojo::Role::Phantom, Test::Mojo::Role::Selenium, Test::Mojo::Role::JSON, Test::Mojo::Role::XML, Test::Mojo::Role::Content, Test::Mojo::Role::Header, Test::Mojo::Role::UA, Test::Mojo::Role::WebSocket, and Test::Mojo::Role::Moai, which are used for different testing purposes.
use Mojo::Base -strict; use Test::Mojo::WithRoles "Selenium"; use Test::More; $ENV{MOJO_SELENIUM_DRIVER} ||= 'Selenium::Chrome'; my $t = Test::Mojo::WithRoles->new->setup_or_skip_all; $t->set_window_size([1024, 768]); $t->navigate_ok('/perldoc'); $t->current_url_is("http://mojolicious.org/perldoc"); $t->live_text_is('a[href="#GUIDES"]' => 'GUIDES'); $t->driver->execute_script(qq[document.querySelector("form").removeAttribute("target")]); $t->element_is_displayed("input[name=q]") ->send_keys_ok("input[name=q]", ["render", \"return"]); $t->wait_until(sub { $_->get_current_url =~ qr{q=render} }); $t->live_value_is("input[name=search]", "render"); done_testing;
testRigor
While Mojolicious offers built-in support for web testing, implementing complex business scenarios can be challenging. For those unfamiliar with Perl or coding, such as manual testers and business analysts, a more accessible tool like testRigor may be necessary.
testRigor is a no-code cloud-platform that supports web, mobile and desktop testing. The scripts are written in plain English, thus eliminating the hassle of writing code. Moreover, test runs are so stable that you can even use them to monitor your application's health. Known for its ease of test maintenance, it is a great tool for end-to-end automation testing. It comes loaded with features like visual testing, API testing, referencing UI elements using relative locations (instead of XPaths or other locators), generating test data, accessing databases, audio testing, and many more. It comes with support for third-party integrations with various CI/CD tools, test case management, infrastructure and databases.
check that “GUIDES” is clickable execute JavaScript in the browser text starting from next line and ending with [END] document.querySelector("form").removeAttribute("target"); [END] check if page contains “Search…” enter “render” in “Search…” enter enter grab url and save it as "URL" check that stored value "URL" itself contains "q=render" check that input “Search” has value “render”
Conclusion
No application is entirely immune to bugs, even one as powerful as Mojolicious. Therefore, it's important to have a robust testing strategy in place. The tools discussed above are among the best available in the market and will likely deliver the desired results.