I have a simple stored procedure whose return value depends on the value of inet_client_addr()
. How can I override inet_client_addr()
for the purpose of unit tests when testing my stored procedure?
The only solution I've come up with so far is to create a wrapper function around inet_client_addr()
:
CREATE FUNCTION my_inet_client_addr() RETURNS INET AS $$
SELECT inet_client_addr();
$$ LANGUAGE sql;
Then use that in my function:
CREATE local_connection() RETURNS BOOLEAN AS $$
SELECT my_inet_client_addr() = '127.0.0.1';
$$ LANGUAGE sql;
Then in my unit test, I can re-define my_inet_client_addr()
:
BEGIN;
SELECT PLAN(2);
REPLACE FUNCTION my_inet_client_addr() RETURNS INET AS $$
SELECT '127.0.0.1'::INET;
$$ LANGUAGE sql;
is(local_connection(),TRUE,'Connection from 127.0.0.1 is local');
REPLACE FUNCTION my_inet_client_addr() RETURNS INET AS $$
SELECT '192.168.1.1'::INET;
$$ LANGUAGE sql;
is(local_connection(),FALSE,'Connection from 192.168.1.1. is not local');
ROLLBACK;
Is there any way to accomplish the same without the wrapper function my_inet_client_addr()
?
your_procedure( inet_client_addr() )
instead of an implicit call to it, no mocking/overriding required.inet_client_addr()
, or if signatures are highly important have the sig without the extra param, delegate to the one with. Either way preserves the existing API while allowing testing of core logic.local_connection(INET)
function (which takes the argument), which is in turn wrapped by alocal_connection()
function which passesinet_client_addr()
. This is probably a cleaner method, which would preserve the existing API.