unit PSQLErrorsTest;
{$IFDEF DUNITX}
  {$M+}
{$ENDIF}
{

  Delphi DUnit Test Case
  ----------------------
  This unit contains a skeleton test case class generated by the Test Case Wizard.
  Modify the generated code to correctly setup and call the methods from the unit
  being tested.

}

interface

uses
  PSQLTypes, Classes, SysUtils, PSQLDbTables,
  {$IFNDEF DUNITX}
  TestFramework, TestExtensions, TestHelper
  {$ELSE}
  DUnitX.TestFramework, ioUtils, TestXHelper
  {$ENDIF};

type

  {$IFDEF DUNITX}[TestFixture]{$ENDIF}
  TestTPSQLErrors = class({$IFNDEF DUNITX}TTestCase{$ELSE}TTestXCase{$ENDIF})
  published
    procedure TestFailedConnect;
    procedure TestSyntaxError;
    procedure TestConstraintViolation;
    {$IFDEF DUNITX}
    [SetupFixture]
    procedure SetupFixture;
    {$ENDIF}
  end;

var
  FilePath: string;
  ErrorsFileName: string;

implementation

procedure InternalSetUp;
begin

end;

{$IFDEF DUNITX}
procedure TestTPSQLErrors.SetupFixture;
begin

end;
{$ENDIF}

procedure TestTPSQLErrors.TestConstraintViolation;
begin
 if TestDBSetup.Database.ServerVersionAsInt < 090300 then Exit; //feature unsupported
 TestDBSetup.Database.Execute('CREATE TABLE IF NOT EXISTS aa (a int PRIMARY KEY);');
 try
   TestDBSetup.Database.Execute('INSERT INTO aa VALUES (1)');
   try
     TestDBSetup.Database.Execute('INSERT INTO aa VALUES (1)');
   except
     on E: EPSQLDatabaseError do
     begin
      Check(E.ErrorConstraintName > '', 'Error constraint name is empty');
      Check(E.ErrorTableName > '', 'Error table name is empty');
      Status(E.ErrorPrimary);
      Status(E.ErrorConstraintName);
     end;
   end;
 finally
   TestDBSetup.Database.Execute('DROP TABLE aa CASCADE')
 end;
end;

procedure TestTPSQLErrors.TestFailedConnect;
var D: TPSQLDatabase;
begin
  D := TPSQLDatabase.Create(nil);
  try
    D.Host := 'some.unreal.host';
    D.UserName := 'some unreal user';
    D.UserPassword := 'some wrong pwd';
    D.DatabaseName := 'some unexistent db';
    try
     D.Open;
    except
     on E: EPSQLDatabaseError do
     begin
       Check(E.Message > '', 'Error message is empty');
       Status(E.Message);
     end;
    end;
  finally
    {$IFNDEF NEXTGEN}
    D.Free;
    {$ELSE}
    D.DisposeOf;
    {$ENDIF}
  end;
end;

procedure TestTPSQLErrors.TestSyntaxError;
begin
 try
   TestDBSetup.Database.Execute('SOMETHING STUPID');
 except
   on E: EPSQLDatabaseError do
   begin
    Check(E.ErrorSeverity > '', 'Error severity is empty');
    Check(E.ErrorSqlState > '', 'Error SQL state is empty');
    Check(E.ErrorPrimary > '', 'Error primary message is empty');
   end;
 end;
end;

initialization

{$IFDEF DUNITX}
  TDUnitX.RegisterTestFixture(TestTPSQLErrors);
{$ENDIF}
  FilePath := {$IFDEF DUNITX}
                      TPath.GetDocumentsPath + PathDelim
                     {$ELSE}
                     'TestOut\'
                     {$ENDIF};
  ErrorsFileName := FilePath + 'TestErrorsToFile.backup';

end.

