Files

230 lines
7.7 KiB
PHP
Executable File

<?php
namespace Tests\Feature\Integrations\SearchXNG;
use App\Enums\IntegratedServices;
use App\Filament\Resources\ProductResource\Actions\AddSearchResultUrlBulkAction;
use App\Filament\Resources\ProductResource\Widgets\CreateViaSearchForm;
use App\Filament\Resources\ProductResource\Widgets\CreateViaSearchTable;
use App\Jobs\CacheSearchResults;
use App\Models\Product;
use App\Models\UrlResearch;
use App\Models\User;
use App\Services\Helpers\IntegrationHelper;
use App\Services\SearchService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Once;
use Livewire\Livewire;
use Tests\TestCase;
class SearchResearchTest extends TestCase
{
use RefreshDatabase;
protected string $searchUrl = 'http://searxng.example.com/search';
protected string $searchTerm = 'air+pods';
protected string $createUrl = '/admin/products/create';
protected int $rawResultsCount = 24;
protected int $rawResultsCountFiltered = 23; // One pdf gets excluded.
protected User $user;
protected function setUp(): void
{
parent::setUp(); // TODO: Change the autogenerated stub
$this->setUpSearchFake();
UrlResearch::truncate();
$this->user = User::factory()->createOne();
$this->actingAs($this->user);
}
public function test_can_get_results()
{
$service = $this->getSearchService();
$service->getRawResults();
$this->assertSame($this->rawResultsCount, $service->getResults()->count());
$firstResult = (array) $service->getResults()->first();
$this->assertSame('https://www.apple.com/airpods/', $firstResult['url']);
$this->assertSame('AirPods - Apple', $firstResult['title']);
$this->assertArrayHasKey('content', $firstResult);
$this->assertArrayHasKey('category', $firstResult);
}
public function test_normalize_and_filter_results()
{
$service = $this->getSearchService();
$service->getRawResults()->filterResults()->normalizeStructure();
// One pdf gets excluded.
$this->assertSame($this->rawResultsCountFiltered, $service->getResults()->count());
// Check normalization.
$firstResult = $service->getResults()->first();
$this->assertSame('https://www.apple.com/airpods/', $firstResult['url']);
$this->assertSame('AirPods - Apple', $firstResult['title']);
$this->assertSame('', $firstResult['thumbnail']);
$this->assertSame('www.apple.com', $firstResult['domain']);
$this->assertSame(0, $firstResult['relevance']);
$this->assertNotEmpty($firstResult['snippet']);
}
public function test_build_results()
{
Product::all()->each(fn ($product) => $product->delete());
$this->assertSame(0, UrlResearch::count());
$service = $this->getSearchService();
$service->build($this->searchTerm);
$resultModels = UrlResearch::all();
$resultModelsWithPrice = $resultModels->whereNotNull('price');
$this->assertSame($this->rawResultsCountFiltered, $resultModels->count());
$this->assertSame(8, $resultModelsWithPrice->count());
$this->assertNotFalse($service->getIsComplete());
$this->assertFalse($service->getInProgress());
$log = collect($service->getLog());
$this->assertSame(15, $log->where(fn ($row) => str_starts_with(strtolower($row['message']), 'no price found'))->count());
$this->assertSame(8, $log->where(fn ($row) => str_starts_with(strtolower($row['message']), 'price found'))->count());
$this->assertSame(1, $log->where(fn ($row) => str_starts_with(strtolower($row['message']), 'completed research for: air+pods'))->count());
$actionableResults = $resultModelsWithPrice->take(3);
Livewire::test(CreateViaSearchTable::class, ['searchQuery' => 'air+pods'])
->callTableBulkAction(AddSearchResultUrlBulkAction::class, $actionableResults);
$product = Product::query()->where('title', 'air+pods')->first();
$this->assertStringEndsWith('.jpg', $product->image);
$this->assertSame(35.0, $product->current_price);
}
public function test_create_component_only_visible_if_enabled()
{
self::setSearchSettings([
'enabled' => false,
'url' => null,
]);
$this->get($this->createUrl)
->assertDontSeeLivewire(CreateViaSearchForm::class);
self::setSearchSettings([
'enabled' => true,
'url' => $this->searchUrl,
]);
$this->get($this->createUrl)
->assertSeeLivewire(CreateViaSearchForm::class);
}
public function test_create_via_search_form_component()
{
Queue::fake();
Livewire::test(CreateViaSearchForm::class)
->set('searchQuery', $this->searchTerm)
->set('data.keyword', $this->searchTerm)
->call('save')
->assertSee('Search via the web')
->assertHasNoErrors();
Queue::assertPushed(function (CacheSearchResults $job) {
$this->assertSame($this->searchTerm, $job->searchQuery);
return true;
});
}
public function test_create_via_product_component()
{
Queue::fake();
$product = Product::factory()->createOne([
'title' => $this->searchTerm,
]);
Livewire::test(CreateViaSearchForm::class)
->set('product', $product)
->set('data.keyword', $this->searchTerm)
->call('save')
->assertSee('Product name')
->assertDontSee('Search via the web')
->assertHasNoErrors();
Queue::assertPushed(function (CacheSearchResults $job) {
$this->assertSame($this->searchTerm, $job->searchQuery);
return true;
});
}
public function test_dispatch_search_job()
{
$this->assertSame(0, UrlResearch::count());
CacheSearchResults::dispatchSync($this->searchTerm);
$this->assertSame($this->rawResultsCountFiltered, UrlResearch::count());
}
public static function setSearchSettings(array $settings): void
{
$allSettings = IntegrationHelper::getSettings();
$allSettings[IntegratedServices::SearXng->value] = $settings;
IntegrationHelper::setSettings($allSettings);
Once::flush();
}
public function setUpSearchFake(): void
{
$fakeResponse = $this->getFixture('SearchXng/results.json');
self::setSearchSettings([
'enabled' => true,
'url' => $this->searchUrl,
]);
$responses = [
$this->searchUrl.'*' => Http::response($fakeResponse),
];
foreach (['www.apple.com', 'www.amazon.com', 'www.walmart.com'] as $domain) {
$responses[$domain.'/*'] = Http::response($this->getPageHtml($domain));
}
$responses['*'] = Http::response($this->getPageHtml('invalid.com'));
Http::fake($responses);
}
public function getPageHtml(string $domain): string
{
return match ($domain) {
'www.apple.com' => $this->getFixture('AutoCreateStore/basic-meta.html'),
'www.amazon.com' => $this->getFixture('AutoCreateStore/unstructured-regex-1.html'),
'www.walmart.com' => $this->getFixture('AutoCreateStore/unstructured-selector-1.html'),
default => '<html><body>foo</body></html>',
};
}
protected function getSearchService(): SearchService
{
return SearchService::new($this->searchTerm)->flushRawResultsCache();
}
protected function getFixture(string $path): string
{
return file_get_contents(__DIR__.'/../../../Fixtures/'.$path);
}
}