<?php
namespace Tests\Support\Models;
use CodeIgniter\Model;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\DatabaseTestTrait;
use PHPUnit\Framework\Attributes\DataProvider;
use function PHPUnit\Framework\assertNotEmpty;
use function PHPUnit\Framework\assertNotFalse;
use function PHPUnit\Framework\assertTrue;
abstract class BaseModelTest extends CIUnitTestCase
{
use DatabaseTestTrait;
/** @var Model */
protected $model = null;
private $tableFields = null;
/**
* DataProvider for testModel, to override
*
* @return array<array<...>> Arrays of arrays of args
* */
public static function modelProvider(): array
{
// Example of a returned array structure, needs to be overrided
return [
[ 'value' ]
];
}
#[DataProvider('modelProvider')]
public function testModel(string $model)
{
$this->model = new $model();
$table = $this->getPrivateProperty($this->model, 'table');
$this->tableFields = $this->model->db->getFieldData($table);
$this->checkPrimaryKey();
$this->checkFields();
assert(true);
}
private function checkPrimaryKey(): void
{
// Assert PK is defined
$primaryKey = $this->getPrivateProperty($this->model, 'primaryKey');
assertNotEmpty($primaryKey, "primaryKey is not defined in model");
// Assert PK exists in DB
$fieldNames = array_column($this->tableFields, 'name');
assertNotFalse(array_search($primaryKey, $fieldNames), "PK '$primaryKey' not found in DB.");
}
protected function checkFields(): void
{
$allowedFields = $this->getPrivateProperty($this->model, 'allowedFields');
$fieldNames = array_column($this->tableFields, 'name');
foreach ($allowedFields as $field) {
assertNotFalse(array_search($field, $fieldNames), "column '$field' not found in DB.");
}
}
}