Re: Global Variables?

From: Alban Hertroys <haramrae(at)gmail(dot)com>
To: Eric Radman <ericshane(at)eradman(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Global Variables?
Date: 2011-10-11 14:26:47
Message-ID: CAF-3MvM70mLEe1XmbF_5bAcfKonGfmhwrGsFzA1W=KMyYM6bvg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 11 October 2011 16:06, Eric Radman <ericshane(at)eradman(dot)com> wrote:
> When writing unit tests it's sometimes useful to stub functions such as
> the current date and time

> Is it possible to declare a global variable that can be referenced from
> the user-defined function _now()? I'm looking for a means of abstraction
> that allows me to avoid issuing CREATE OR REPLACE FUNCTION ... before
> each assert()
>
> current_time := '2012-01-01'::timestamp
> SELECT assert(5, (SELECT count(*) FROM expired_accounts)::integer);

You could crate a table for such "constants" and read your
current-time from that table.

Additionally, I would put such stub functions in a separate schema and
create a test role with that schema as the top of their search_path.

That way, you could even override system function implementations (and
other definitions) and only have them apply to the role you're using
for unit testing.

CREATE ROLE unit_tester;
CREATE SCHEMA unit_tests AUTHORIZATION unit_tester;
SET search_path TO unit_tests, my_schema, public;

CREATE TABLE unit_test_parameters (
current_time timestamp without time zone NOT NULL DEFAULT now()
);

CREATE OR REPLACE FUNCTION now() RETURNS timestamp without time zone AS $$
SELECT current_time FROM unit_test_parameters LIMIT 1;
$$ LANGUAGE SQL

...etc...

UPDATE unit_test_parameters SET current_time = '2012-01-01'::timestamp;
SELECT assert(5, (SELECT count(*) FROM expired_accounts)::integer);

I'm not sure how you planned to use that _now() function with the
assert; I expected a WHERE clause in that query, but it isn't there.

--
If you can't see the forest for the trees,
Cut the trees and you'll see there is no forest.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Alban Hertroys 2011-10-11 14:34:35 Re: Should casting to integer produce same result as trunc()
Previous Message Eric Radman 2011-10-11 14:06:50 Global Variables?