Files

60 lines
2.7 KiB
PHP

<?php
namespace Tests\Unit;
use App\Http\Controllers\GlobalSearchController;
use App\Services\SearchTerms;
use Illuminate\Database\PostgresConnection;
use PHPUnit\Framework\TestCase;
final class SearchTermsTest extends TestCase
{
public function test_matches_all_words_in_any_order_without_case_or_accents(): void
{
$search = new SearchTerms;
$tokens = $search->tokens(' NAMPULA agronegócio Agronegócio ');
$this->assertSame(['nampula', 'agronegocio'], $tokens);
$this->assertTrue($search->matches('Agronegócio em Nampula', $tokens));
$this->assertFalse($search->matches('Agronegócio em Gaza', $tokens));
$this->assertSame([], $search->tokens(' '));
}
public function test_sql_matches_each_word_across_fields_with_bound_literal_patterns(): void
{
$connection = new PostgresConnection(fn () => throw new \LogicException('A database must not be opened.'));
$query = $connection->table('records');
$search = new SearchTerms;
$search->constrain($query, ['title', 'description'], $search->tokens('100% a_b'));
$sql = $query->toSql();
$this->assertStringContainsString('translate(lower(coalesce(title::text', $sql);
$this->assertStringContainsString(' or ', $sql);
$this->assertStringContainsString(' and ', $sql);
$this->assertSame(['%100!%%', '%100!%%', '%a!_b%', '%a!_b%'], $query->getBindings());
$this->assertStringNotContainsString('100%', $sql);
}
public function test_static_services_can_be_found_without_a_database(): void
{
$pages = (new \ReflectionMethod(GlobalSearchController::class, 'pages'))->invoke(new GlobalSearchController);
$search = new SearchTerms;
$matches = array_values(array_filter($pages, fn ($page) => $search->matches(implode(' ', $page), $search->tokens('FISCAL simulador'))));
$this->assertCount(1, $matches);
$this->assertSame('/simulador-fiscal', $matches[0]['url']);
}
public function test_spelling_variants_common_words_and_title_relevance(): void
{
$search = new SearchTerms;
$tokens = $search->tokens('setores de investimento');
$this->assertTrue($search->matches('Sectores de investimento', $tokens));
$this->assertFalse($search->matches('Sector de saúde', $tokens));
$this->assertTrue($search->matches('Projectos âncora', $search->tokens('projeto')));
$this->assertTrue($search->matches('Oportunidades de investimento em energia', $search->tokens('Como investir em energia?')));
$this->assertGreaterThan($search->score('Como investir', 'investir', ['investir']), $search->score('Investir', 'investir', ['investir']));
$this->assertSame(['de'], $search->tokens('de'));
}
}