blob: 63e1a3093bc07bbfe8c3d0b8edcb7a8f29eb2aed (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
# Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#
# Some simple utilities to allow unit tests to mock behavior.
#
package Yahoo::Vespa::Utils;
use strict;
use warnings;
use Carp ();
use Sys::Hostname qw(hostname);
BEGIN { # - Define exports from this module
use base 'Exporter';
our @EXPORT = qw(
exitApplication
getHostname
confess
assertNotUnitTest
dumpStructure
);
}
my $HOSTNAME;
my $EXIT_HANDLER;
my $IS_UNIT_TEST;
&initialize();
return 1;
########################## Default exported functions ########################
# Use this function to get hostname to allow unit test mocking for tests to be
# independent of computer they run on.
sub getHostname { # ()
if (!defined $HOSTNAME) {
$HOSTNAME = hostname;
&assertNotUnitTest();
$HOSTNAME = `hostname`;
chomp $HOSTNAME;
}
return $HOSTNAME;
}
# Use instead of exit() to allow unit tests to mock the call to avoid aborting
sub exitApplication { #(ExitCode)
if ($IS_UNIT_TEST && $EXIT_HANDLER == \&defaultExitHandler) {
&confess("Exit handler not overridden in unit test");
}
&$EXIT_HANDLER(@_);
}
# Use instead of die to get backtrace when dieing
sub confess { # (Reason)
Carp::confess(@_);
}
# Call for behavior that you want to ensure is not used in unit tests.
# Typically unit tests have to mock commands that for instance fetch host name
# or require that terminal is set etc. Unit tests use mocks for this. This
# command can be used in code, such that unit tests die if they reach the
# non-mocked code.
sub assertNotUnitTest { # ()
if ($IS_UNIT_TEST) {
confess "Unit tests should not reach here. Mock required. "
. "Initialize mock";
}
}
# Use to look at content of a perl struct.
sub dumpStructure { # (ObjTree) -> ReadableString
my ($var) = @_;
use Data::Dumper;
local $Data::Dumper::Indent = 1;
local $Data::Dumper::Sortkeys = 1;
return Dumper($var);
}
################## Functions for unit tests to mock internals ################
sub initializeUnitTest { # (Hostname, ExitHandler)
my ($host, $exitHandler) = @_;
$IS_UNIT_TEST = 1;
$HOSTNAME = $host;
$EXIT_HANDLER = $exitHandler;
}
############## Utility functions - Not intended for external use #############
sub initialize { # ()
$EXIT_HANDLER = \&defaultExitHandler;
}
sub defaultExitHandler { # ()
my ($exitcode) = @_;
exit($exitcode);
}
|