Tests for Perl modules

Last modified
Saturday, May 20, 2017 - 13:15

Introduction

Tests in this category test behaviours that can be tested without a database connection. Tests that fall into this category would be testing a function that does tax calculations based on a set of provided inputs -- without retrieving those inputs from the database.

Examples of such tests can be found in t/14-*.t.

Such tests can be used to determine if the installed code with the selected installed dependencies is working correctly. This will catch cases where dependencies may be installed of newer or older versions than has been previously tested with. This type of verification only works in case sufficient tests have been implemented on the side of the using application or library (in this case: LedgerSMB).

Test structure

All tests follow the structure of the code block below.

#!/usr/bin/perl
# Note that the line above isn't quite necessary, but helps
# editors to identify this is a Perl code file for correct
# syntax highlighting
 
use Test::More (tests => 10);
# you can leave out the "(tests => 10)" bit,
# but you'll need the "done_testing;" bit below
use strict;
use warnings;
 
use <module you want to test>;
#e.g.: use LedgerSMB::Report;
# in case you don't have the "tests => (number)" above,
# close with:
 
done_testing;
# The line above must not be included if you have
# the number of tests indicated elsewhere in the file

Tests use the assertion primitives from Test::Simple or (as is the case above) from Test::More, e.g.:

  • ok()
  • is()
  • isnt()
  • use_ok()
  • require_ok()

Test execution

A single test file can be executed using this command:

$ prove t/14-<your-script>.t

Tests depending on a database

An example of a test which depends on a LedgerSMB company database being available, is xt/44-templates.t: it needs to load document templates out of the database in order to render test documents.

Tests like these should expect the following environment variables to be defined:

  • LSMB_NEW_DB
  • PGUSER
  • PGPASSWORD

These tests should not be executed if the environment variable LSMB_TEST_DB isn't defined.

The full set of environment variables which could be available has been enumerated in the t/README.md in the repository.

The above invocation for test execution can be amended to:

$ LSMB_TEST_DB=1 LSMB_NEW_DB=<your-test-db> PGUSER=postgres PGPASSWORD=password prove xt/44-<yourscript>.t

Please note that these tests can't be executed during installation of the software (because no database exists yet to test against), so these tests belong in xt/.