Bug 21299: Add localReferer function to Util module, add test
[srvgit] / t / Koha / Util / localReferer.t
1 use Modern::Perl;
2
3 use Test::More tests => 1;
4 use Test::MockObject;
5
6 use t::lib::Mocks;
7 use Koha::Util;
8
9 subtest 'Tests for localReferer' => sub {
10     plan tests => 10;
11
12     my ( $referer, $base );
13     my $cgi = Test::MockObject->new;
14     $cgi->mock( 'referer', sub { $referer } );
15     $cgi->mock( 'url', sub { $base } ); # base for [opac-]changelanguage
16
17     # Start with filled OPACBaseIRL
18     t::lib::Mocks::mock_preference('OPACBaseURL', 'https://koha.nl' );
19     $referer = 'https://somewhere.com/myscript';
20     is( Koha::Util::localReferer($cgi), '/', 'External referer' );
21
22     my $search = '/cgi-bin/koha/opac-search.pl?q=perl';
23     $referer = "https://koha.nl$search";
24     is( Koha::Util::localReferer($cgi), $search, 'opac-search' );
25
26     $referer = 'https://koha.nl/custom/stuff';
27     is( Koha::Util::localReferer($cgi), '/', 'custom url' );
28
29     # trailing backslash
30     t::lib::Mocks::mock_preference('OPACBaseURL', 'http://koha.nl/' );
31     $referer = "http://koha.nl$search";
32     is( Koha::Util::localReferer($cgi), $search, 'opac-search, trailing backslash' );
33
34     # no OPACBaseURL
35     t::lib::Mocks::mock_preference('OPACBaseURL', '');
36     $referer = 'https://somewhere.com/myscript';
37     $base = 'http://koha.nl';
38     is( Koha::Util::localReferer($cgi), '/', 'no opacbaseurl, external' );
39
40     $referer = "https://koha.nl$search";
41     $base = 'https://koha.nl';
42     is( Koha::Util::localReferer($cgi), $search, 'no opacbaseurl, opac-search' );
43     $base = 'http://koha.nl';
44     is( Koha::Util::localReferer($cgi), $search, 'no opacbaseurl, opac-search, protocol diff' );
45
46     # base contains https, referer http (this should be very unusual)
47     # test parameters remove_language. staff
48     t::lib::Mocks::mock_preference('staffClientBaseURL', '' );
49     $search = '/cgi-bin/koha/catalogue/search.pl?q=perl'; # staff
50     $referer = "http://koha.nl:8080$search&language=zz-ZZ&debug=1";
51     $base = 'https://koha.nl:8080';
52     is( Koha::Util::localReferer($cgi, { remove_language => 1, staff => 1 }), $search.'&debug=1', 'no baseurl, staff search, protocol diff (base https)' );
53
54     # custom script, test fallback parameter
55     $referer = 'https://koha.nl/custom/stuff';
56     $base = 'https://koha.nl';
57     is( Koha::Util::localReferer($cgi, { fallback => 'ZZZ' }), 'ZZZ', 'no opacbaseurl, custom url, test fallback' );
58     $base = 'http://koha.nl';
59     is( Koha::Util::localReferer($cgi), '/', 'no opacbaseurl, custom url, protocol diff' );
60 };