5 use BookStack\Entities\Models\Book;
8 class ApiListingTest extends TestCase
12 protected $endpoint = '/api/books';
14 public function test_count_parameter_limits_responses()
16 $this->actingAsApiEditor();
17 $bookCount = min(Book::visible()->count(), 100);
19 $resp = $this->get($this->endpoint);
20 $resp->assertJsonCount($bookCount, 'data');
22 $resp = $this->get($this->endpoint . '?count=1');
23 $resp->assertJsonCount(1, 'data');
26 public function test_offset_parameter()
28 $this->actingAsApiEditor();
29 $books = Book::visible()->orderBy('id')->take(3)->get();
31 $resp = $this->get($this->endpoint . '?count=1');
32 $resp->assertJsonMissing(['name' => $books[1]->name]);
34 $resp = $this->get($this->endpoint . '?count=1&offset=1000');
35 $resp->assertJsonCount(0, 'data');
38 public function test_sort_parameter()
40 $this->actingAsApiEditor();
43 '-id' => Book::visible()->orderBy('id', 'desc')->first(),
44 '+name' => Book::visible()->orderBy('name', 'asc')->first(),
45 'name' => Book::visible()->orderBy('name', 'asc')->first(),
46 '-name' => Book::visible()->orderBy('name', 'desc')->first(),
49 foreach ($sortChecks as $sortOption => $result) {
50 $resp = $this->get($this->endpoint . '?count=1&sort=' . $sortOption);
51 $resp->assertJson(['data' => [
54 'name' => $result->name,
60 public function test_filter_parameter()
62 $this->actingAsApiEditor();
63 $book = Book::visible()->first();
64 $nameSubstr = substr($book->name, 0, 4);
65 $encodedNameSubstr = rawurlencode($nameSubstr);
68 // Test different types of filter
69 "filter[id]={$book->id}" => 1,
70 "filter[id:ne]={$book->id}" => Book::visible()->where('id', '!=', $book->id)->count(),
71 "filter[id:gt]={$book->id}" => Book::visible()->where('id', '>', $book->id)->count(),
72 "filter[id:gte]={$book->id}" => Book::visible()->where('id', '>=', $book->id)->count(),
73 "filter[id:lt]={$book->id}" => Book::visible()->where('id', '<', $book->id)->count(),
74 "filter[name:like]={$encodedNameSubstr}%" => Book::visible()->where('name', 'like', $nameSubstr . '%')->count(),
76 // Test mulitple filters 'and' together
77 "filter[id]={$book->id}&filter[name]=random_non_existing_string" => 0,
80 foreach ($filterChecks as $filterOption => $resultCount) {
81 $resp = $this->get($this->endpoint . '?count=1&' . $filterOption);
82 $resp->assertJson(['total' => $resultCount]);
86 public function test_total_on_results_shows_correctly()
88 $this->actingAsApiEditor();
89 $bookCount = Book::query()->count();
90 $resp = $this->get($this->endpoint . '?count=1');
91 $resp->assertJson(['total' => $bookCount]);
94 public function test_total_on_results_shows_correctly_when_offset_provided()
96 $this->actingAsApiEditor();
97 $bookCount = Book::query()->count();
98 $resp = $this->get($this->endpoint . '?count=1&offset=1');
99 $resp->assertJson(['total' => $bookCount]);