# -*- Perl -*-

# Base class for DNSDB.pm unit testing
# Sets up DB connection and repopulates it for a consistent test reference
##
# $Id: DNSTest.pm 949 2025-12-24 18:17:17Z kdeugau $
# Copyright 2025 Kris Deugau <kdeugau@deepnet.cx>
# 
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version. 
# 
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
# 
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
##

package DNSTest;
use strict;
use warnings;
use Exporter;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
@ISA		= qw(Exporter);
@EXPORT		= qw($dnsdb $dbh);

use Test::More;

use lib '.';
use DNSDB;

our $dnsdb;
our $dbh;
our $debug;

sub new {
  $dnsdb = new DNSDB(
	dbhost => 'localhost',
	dbname => 'dnstest',
	dbuser => 'dnstest',
	dbpass => 'dnstestpwd',
  );
  ok( defined $dnsdb );
  ok( $dnsdb->isa('DNSDB') );

  ## Prepare the DB
  # Check that we aren't in an obviously production DB before blowing it away.
  # A DB instantiated for these tests should NEVER have more than a handful of domains and maybe 20-30 records.

  $dbh = $dnsdb->{dbh};

  my ($dcount) = $dbh->selectrow_array("SELECT count(*) FROM domains");
  BAIL_OUT("# DB looks like it may not be a test DB, found $dcount > 10 domains!\n")
	if $dcount > 10;
  cmp_ok( $dcount, '<=', 10, "domain count ($dcount): looks like a test DB" );

  my ($rcount) = $dbh->selectrow_array("SELECT count(*) FROM records");
  BAIL_OUT("# DB looks like it may not be a test DB, found $rcount > 30 records!\n")
        if $rcount > 50;
  cmp_ok( $rcount, '<=', 50, "record ($rcount): looks like a test DB" );

  # drop all tables etc
  $ENV{PGPASSWORD} = $dnsdb->{dbpass};
# neither diag or note seem to suppress output from qx
  my $dropdata = qx( psql -h $dnsdb->{dbhost} -U $dnsdb->{dbuser} $dnsdb->{dbname} 2>&1 < t/dropall.sql );
  diag( $dropdata ) if $debug;
  # load some standard test data
  my $reload = qx( psql -h $dnsdb->{dbhost} -U $dnsdb->{dbuser} $dnsdb->{dbname} 2>&1 < t/dns-unitbase.sql );
  diag( $reload ) if $debug;
  undef $ENV{PGPASSWORD};
} # new()

sub DESTROY {
  $dnsdb->finish;
}

1;
