forked from laravel/scout
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTypesenseEngineTest.php
More file actions
385 lines (325 loc) · 14.2 KB
/
Copy pathTypesenseEngineTest.php
File metadata and controls
385 lines (325 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
<?php
namespace Laravel\Scout\Tests\Unit;
use Http\Client\Exception;
use Illuminate\Container\Container;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Laravel\Scout\Builder;
use Laravel\Scout\Engines\TypesenseEngine;
use Laravel\Scout\Tests\Fixtures\SearchableModel;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use Typesense\Client as TypesenseClient;
use Typesense\Collection as TypesenseCollection;
use Typesense\Documents;
use Typesense\Exceptions\TypesenseClientError;
class TypesenseEngineTest extends TestCase
{
protected TypesenseEngine $engine;
protected function setUp(): void
{
parent::setUp();
// Mock the Typesense client and pass it to the engine constructor
$typesenseClient = $this->createMock(TypesenseClient::class);
$this->engine = $this->getMockBuilder(TypesenseEngine::class)
->setConstructorArgs([$typesenseClient, 1000])
->onlyMethods(['getOrCreateCollectionFromModel', 'buildSearchParameters'])
->getMock();
}
protected function tearDown(): void
{
Container::getInstance()->flush();
m::close();
}
/**
* Call protected/private method of a class.
*
* @param object &$object Instantiated object that we will run method on.
* @param string $methodName Method name to call
* @param array $parameters Array of parameters to pass into method.
* @return mixed Method return.
*/
public function invokeMethod(&$object, $methodName, array $parameters = [])
{
$reflection = new \ReflectionClass(get_class($object));
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invokeArgs($object, $parameters);
}
public function test_filters_method()
{
$builder = m::mock(Builder::class);
$builder->wheres = [
'status' => 'active',
'age' => 25,
];
$builder->whereIns = [
'category' => ['electronics', 'books'],
];
$builder->whereNotIns = [
'category' => ['furniture', 'phones'],
];
$result = $this->invokeMethod($this->engine, 'filters', [$builder]);
$expected = 'status:=active && age:=25 && category:=[electronics, books] && category:!=[furniture, phones]';
$this->assertEquals($expected, $result);
}
public function test_parse_filter_value_method()
{
$this->assertEquals('true', $this->invokeMethod($this->engine, 'parseFilterValue', [true]));
$this->assertEquals('false', $this->invokeMethod($this->engine, 'parseFilterValue', [false]));
$this->assertEquals('25', $this->invokeMethod($this->engine, 'parseFilterValue', [25]));
$this->assertEquals('3.14', $this->invokeMethod($this->engine, 'parseFilterValue', [3.14]));
$this->assertEquals('test', $this->invokeMethod($this->engine, 'parseFilterValue', ['test']));
$this->assertEquals('test "quoted"', $this->invokeMethod($this->engine, 'parseFilterValue', ['test "quoted"']));
$this->assertEquals('`special value`', $this->invokeMethod($this->engine, 'parseFilterValue', ['`special value`']));
$nestedArray = ['a', ['b', 'c'], 'd'];
$expectedNested = ['a', ['b', 'c'], 'd'];
$this->assertEquals($expectedNested, $this->invokeMethod($this->engine, 'parseFilterValue', [$nestedArray]));
}
public function test_parse_where_filter_method()
{
$this->assertEquals('status:=active', $this->invokeMethod($this->engine, 'parseWhereFilter', ['active', 'status']));
$this->assertEquals('age:=25', $this->invokeMethod($this->engine, 'parseWhereFilter', ['25', 'age']));
$this->assertEquals('tags:tag1tag2tag3', $this->invokeMethod($this->engine, 'parseWhereFilter', [['tag1', 'tag2', 'tag3'], 'tags']));
}
public function test_parse_where_in_filter_method()
{
$this->assertEquals('category:=[electronics, books]', $this->invokeMethod($this->engine, 'parseWhereInFilter', [['electronics', 'books'], 'category']));
$this->assertEquals('id:=[1, 2, 3]', $this->invokeMethod($this->engine, 'parseWhereInFilter', [[1, 2, 3], 'id']));
}
public function test_parse_where_not_in_filter_metheod()
{
$this->assertEquals('category:!=[electronics, books]', $this->invokeMethod($this->engine, 'parseWhereNotInFilter', [['electronics', 'books'], 'category']));
$this->assertEquals('id:!=[1, 2, 3]', $this->invokeMethod($this->engine, 'parseWhereNotInFilter', [[1, 2, 3], 'id']));
}
public function test_update_method(): void
{
// Mock models and their methods
$models = [
$this->createMock(SearchableModel::class),
];
$models[0]->expects($this->once())
->method('toSearchableArray')
->willReturn(['id' => 1, 'name' => 'Model 1']);
$models[0]->expects($this->once())
->method('scoutMetadata')
->willReturn([]);
// Mock the getOrCreateCollectionFromModel method
$collection = $this->createMock(TypesenseCollection::class);
$documents = $this->createMock(Documents::class);
$collection->expects($this->once())
->method('getDocuments')
->willReturn($documents);
$documents->expects($this->once())
->method('import')
->with(
[['id' => 1, 'name' => 'Model 1']], ['action' => 'emplace'],
)
->willReturn([[
'success' => true,
]]);
$this->engine->expects($this->once())
->method('getOrCreateCollectionFromModel')
->willReturn($collection);
// Call the update method
$this->engine->update(collect($models));
}
public function test_delete_method(): void
{
// Mock models and their methods
$models = [
$this->createMock(SearchableModel::class),
];
$models[0]->expects($this->once())
->method('getScoutKey')
->willReturn(1);
// Mock the getOrCreateCollectionFromModel and deleteDocument methods
$collection = $this->createMock(TypesenseCollection::class);
$documents = $this->createMock(Documents::class);
$collection->expects($this->once())
->method('getDocuments')
->willReturn($documents);
$this->engine->expects($this->once())
->method('getOrCreateCollectionFromModel')
->willReturn($collection);
// Call the delete method
$this->engine->delete(collect($models));
}
public function test_search_method(): void
{
// Mock the Builder
$builder = $this->createMock(Builder::class);
// Mock the buildSearchParameters method
$this->engine->expects($this->once())
->method('buildSearchParameters')
->with($builder, 1)
->willReturn([
'q' => $builder->query,
'query_by' => 'id',
'filter_by' => '',
'per_page' => 10,
'page' => 1,
'highlight_start_tag' => '<mark>',
'highlight_end_tag' => '</mark>',
'snippet_threshold' => 30,
'exhaustive_search' => false,
'use_cache' => false,
'cache_ttl' => 60,
'prioritize_exact_match' => true,
'enable_overrides' => true,
'highlight_affix_num_tokens' => 4,
]);
// Call the search method
$this->engine->search($builder);
}
public function test_paginate_method(): void
{
// Mock the Builder
$builder = $this->createMock(Builder::class);
// Mock the buildSearchParameters method
$this->engine->expects($this->once())
->method('buildSearchParameters')
->with($builder, 2, 10)
->willReturn([
'q' => $builder->query,
'query_by' => 'id',
'filter_by' => '',
'per_page' => 10,
'page' => 2,
'highlight_start_tag' => '<mark>',
'highlight_end_tag' => '</mark>',
'snippet_threshold' => 30,
'exhaustive_search' => false,
'use_cache' => false,
'cache_ttl' => 60,
'prioritize_exact_match' => true,
'enable_overrides' => true,
'highlight_affix_num_tokens' => 4,
]);
// Call the paginate method
$this->engine->paginate($builder, 10, 2);
}
public function test_map_ids_method(): void
{
// Sample search results
$results = [
'hits' => [
['document' => ['id' => 1]],
['document' => ['id' => 2]],
['document' => ['id' => 3]],
],
];
// Call the mapIds method
$mappedIds = $this->engine->mapIds($results);
// Assert that the result is an instance of Collection
$this->assertInstanceOf(Collection::class, $mappedIds);
// Assert that the mapped IDs match the expected IDs
$this->assertEquals([1, 2, 3], $mappedIds->toArray());
}
public function test_get_total_count_method(): void
{
// Sample search results with 'found' key
$resultsWithFound = ['found' => 5];
// Sample search results without 'found' key
$resultsWithoutFound = ['hits' => []];
// Call the getTotalCount method with results containing 'found'
$totalCountWithFound = $this->engine->getTotalCount($resultsWithFound);
// Call the getTotalCount method with results without 'found'
$totalCountWithoutFound = $this->engine->getTotalCount($resultsWithoutFound);
// Assert that the total count is correctly extracted from the results
$this->assertEquals(5, $totalCountWithFound);
$this->assertEquals(0, $totalCountWithoutFound);
}
public function test_flush_method(): void
{
// Mock a model instance
$model = $this->createMock(Model::class);
$collection = $this->createMock(TypesenseCollection::class);
// Mock the getOrCreateCollectionFromModel method
$this->engine->expects($this->once())
->method('getOrCreateCollectionFromModel')
->with($model)
->willReturn($collection);
// Mock the delete method of the TypesenseCollection
$collection->expects($this->once())
->method('delete');
// Call the flush method
$this->engine->flush($model);
}
public function test_create_index_method_throws_exception(): void
{
// Define the expected exception class and message
$expectedException = \Exception::class;
$expectedExceptionMessage = 'Typesense indexes are created automatically upon adding objects.';
// Use PHPUnit's expectException method to assert that the specified exception is thrown
$this->expectException($expectedException);
$this->expectExceptionMessage($expectedExceptionMessage);
// Call the createIndex method which should throw an exception
$this->engine->createIndex('test_index');
}
/**
* @throws Exception
* @throws TypesenseClientError
*/
public function test_set_search_params_method(): void
{
// Mock the Builder
$builder = $this->createMock(Builder::class);
// Mock the buildSearchParameters method
$this->engine->expects($this->once())
->method('buildSearchParameters')
->with($builder, 1)
->willReturn([
'q' => $builder->query,
'query_by' => 'id',
'filter_by' => '',
'per_page' => 10,
'page' => 1,
'highlight_start_tag' => '<mark>',
'highlight_end_tag' => '</mark>',
'snippet_threshold' => 30,
'exhaustive_search' => false,
'use_cache' => false,
'cache_ttl' => 60,
'prioritize_exact_match' => true,
'enable_overrides' => true,
'highlight_affix_num_tokens' => 4,
]);
// Set search options
$builder->options(['query_by' => 'id']);
// Call the search method
$this->engine->search($builder);
}
public function test_soft_deleted_objects_are_returned_with_only_trashed_method()
{
// Create a mock of SearchableModel
$searchableModel = m::mock(SearchableModel::class)->makePartial();
// Mock the search method to return a collection with a soft-deleted object
$searchableModel->shouldReceive('search')->with('Soft Deleted Object')->andReturnSelf();
$searchableModel->shouldReceive('onlyTrashed')->andReturnSelf();
$searchableModel->shouldReceive('get')->andReturn(collect([
new SearchableModel(['id' => 1, 'name' => 'Soft Deleted Object']),
]));
// Perform the search with onlyTrashed() using the mocked model
$results = $searchableModel::search('Soft Deleted Object')->onlyTrashed()->get();
// Assert that the soft deleted object is returned
$this->assertCount(1, $results);
$this->assertEquals(1, $results->first()->id);
}
public function test_soft_deleted_objects_are_returned_with_with_trashed_method()
{
// Create a mock of SearchableModel
$searchableModel = m::mock(SearchableModel::class)->makePartial();
// Mock the search method to return a collection with a soft-deleted object
$searchableModel->shouldReceive('search')->with('Soft Deleted Object')->andReturnSelf();
$searchableModel->shouldReceive('withTrashed')->andReturnSelf();
$searchableModel->shouldReceive('get')->andReturn(collect([
new SearchableModel(['id' => 1, 'name' => 'Soft Deleted Object']),
]));
// Perform the search with withTrashed() using the mocked model
$results = $searchableModel::search('Soft Deleted Object')->withTrashed()->get();
// Assert that the soft deleted object is returned
$this->assertCount(1, $results);
$this->assertEquals(1, $results->first()->id);
}
}