5 use BookStack\Auth\Permissions\JointPermissionBuilder;
6 use BookStack\Auth\Permissions\PermissionsRepo;
7 use BookStack\Auth\Permissions\RolePermission;
8 use BookStack\Auth\Role;
9 use BookStack\Auth\User;
10 use BookStack\Entities\Models\Entity;
11 use BookStack\Settings\SettingService;
12 use BookStack\Uploads\HttpFetcher;
13 use GuzzleHttp\Client;
14 use GuzzleHttp\Handler\MockHandler;
15 use GuzzleHttp\HandlerStack;
16 use GuzzleHttp\Middleware;
17 use Illuminate\Contracts\Console\Kernel;
18 use Illuminate\Foundation\Testing\DatabaseTransactions;
19 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
20 use Illuminate\Http\JsonResponse;
21 use Illuminate\Support\Env;
22 use Illuminate\Support\Facades\DB;
23 use Illuminate\Support\Facades\Log;
24 use Illuminate\Testing\Assert as PHPUnit;
25 use Monolog\Handler\TestHandler;
27 use Psr\Http\Client\ClientInterface;
28 use Ssddanbrown\AssertHtml\TestsHtml;
29 use Tests\Helpers\EntityProvider;
30 use Tests\Helpers\TestServiceProvider;
32 abstract class TestCase extends BaseTestCase
34 use CreatesApplication;
35 use DatabaseTransactions;
38 protected ?User $admin = null;
39 protected ?User $editor = null;
40 protected EntityProvider $entities;
42 protected function setUp(): void
44 $this->entities = new EntityProvider();
47 // We can uncomment the below to run tests with failings upon deprecations.
48 // Can't leave on since some deprecations can only be fixed upstream.
49 // $this->withoutDeprecationHandling();
53 * The base URL to use while testing the application.
55 protected string $baseUrl = 'http://localhost';
58 * Creates the application.
60 * @return \Illuminate\Foundation\Application
62 public function createApplication()
64 /** @var \Illuminate\Foundation\Application $app */
65 $app = require __DIR__ . '/../bootstrap/app.php';
66 $app->register(TestServiceProvider::class);
67 $app->make(Kernel::class)->bootstrap();
73 * Set the current user context to be an admin.
75 public function asAdmin()
77 return $this->actingAs($this->getAdmin());
81 * Get the current admin user.
83 public function getAdmin(): User
85 if (is_null($this->admin)) {
86 $adminRole = Role::getSystemRole('admin');
87 $this->admin = $adminRole->users->first();
94 * Set the current user context to be an editor.
96 public function asEditor()
98 return $this->actingAs($this->getEditor());
104 protected function getEditor(): User
106 if ($this->editor === null) {
107 $editorRole = Role::getRole('editor');
108 $this->editor = $editorRole->users->first();
111 return $this->editor;
115 * Set the current user context to be a viewer.
117 public function asViewer()
119 return $this->actingAs($this->getViewer());
123 * Get an instance of a user with 'viewer' permissions.
125 protected function getViewer(array $attributes = []): User
127 $user = Role::getRole('viewer')->users()->first();
128 if (!empty($attributes)) {
129 $user->forceFill($attributes)->save();
136 * Get a user that's not a system user such as the guest user.
138 public function getNormalUser(): User
140 return User::query()->where('system_name', '=', null)->get()->last();
144 * Quickly sets an array of settings.
146 protected function setSettings(array $settingsArray): void
148 $settings = app(SettingService::class);
149 foreach ($settingsArray as $key => $value) {
150 $settings->put($key, $value);
155 * Give the given user some permissions.
157 protected function giveUserPermissions(User $user, array $permissions = []): void
159 $newRole = $this->createNewRole($permissions);
160 $user->attachRole($newRole);
161 $user->load('roles');
162 $user->clearPermissionCache();
166 * Completely remove the given permission name from the given user.
168 protected function removePermissionFromUser(User $user, string $permissionName)
170 $permissionBuilder = app()->make(JointPermissionBuilder::class);
172 /** @var RolePermission $permission */
173 $permission = RolePermission::query()->where('name', '=', $permissionName)->firstOrFail();
175 $roles = $user->roles()->whereHas('permissions', function ($query) use ($permission) {
176 $query->where('id', '=', $permission->id);
179 /** @var Role $role */
180 foreach ($roles as $role) {
181 $role->detachPermission($permission);
182 $permissionBuilder->rebuildForRole($role);
185 $user->clearPermissionCache();
189 * Create a new basic role for testing purposes.
191 protected function createNewRole(array $permissions = []): Role
193 $permissionRepo = app(PermissionsRepo::class);
194 $roleData = Role::factory()->make()->toArray();
195 $roleData['permissions'] = array_flip($permissions);
197 return $permissionRepo->saveNewRole($roleData);
201 * Mock the HttpFetcher service and return the given data on fetch.
203 protected function mockHttpFetch($returnData, int $times = 1)
205 $mockHttp = Mockery::mock(HttpFetcher::class);
206 $this->app[HttpFetcher::class] = $mockHttp;
207 $mockHttp->shouldReceive('fetch')
209 ->andReturn($returnData);
213 * Mock the http client used in BookStack.
214 * Returns a reference to the container which holds all history of http transactions.
216 * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
218 protected function &mockHttpClient(array $responses = []): array
221 $history = Middleware::history($container);
222 $mock = new MockHandler($responses);
223 $handlerStack = new HandlerStack($mock);
224 $handlerStack->push($history);
225 $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
231 * Run a set test with the given env variable.
232 * Remembers the original and resets the value after test.
233 * Database config is juggled so the value can be restored when
234 * parallel testing are used, where multiple databases exist.
236 protected function runWithEnv(string $name, $value, callable $callback)
238 Env::disablePutenv();
239 $originalVal = $_SERVER[$name] ?? null;
241 if (is_null($value)) {
242 unset($_SERVER[$name]);
244 $_SERVER[$name] = $value;
247 $database = config('database.connections.mysql_testing.database');
248 $this->refreshApplication();
251 config()->set('database.connections.mysql_testing.database', $database);
255 if (is_null($originalVal)) {
256 unset($_SERVER[$name]);
258 $_SERVER[$name] = $originalVal;
263 * Check the keys and properties in the given map to include
264 * exist, albeit not exclusively, within the map to check.
266 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
270 foreach ($mapToInclude as $key => $value) {
271 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
276 $toIncludeStr = print_r($mapToInclude, true);
277 $toCheckStr = print_r($mapToCheck, true);
278 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
282 * Assert a permission error has occurred.
284 protected function assertPermissionError($response)
286 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
290 * Assert a permission error has occurred.
292 protected function assertNotPermissionError($response)
294 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
298 * Check if the given response is a permission error.
300 private function isPermissionError($response): bool
302 return $response->status() === 302
305 $response->headers->get('Location') === url('/')
306 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
310 $response instanceof JsonResponse &&
311 $response->json(['error' => 'You do not have permission to perform the requested action.'])
317 * Assert that the session has a particular error notification message set.
319 protected function assertSessionError(string $message)
321 $error = session()->get('error');
322 PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
326 * Assert the session contains a specific entry.
328 protected function assertSessionHas(string $key): self
330 $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
335 protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
337 return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
341 * Set a test handler as the logging interface for the application.
342 * Allows capture of logs for checking against during tests.
344 protected function withTestLogger(): TestHandler
346 $monolog = new Logger('testing');
347 $testHandler = new TestHandler();
348 $monolog->pushHandler($testHandler);
350 Log::extend('testing', function () use ($monolog) {
353 Log::setDefaultDriver('testing');
359 * Assert that an activity entry exists of the given key.
360 * Checks the activity belongs to the given entity if provided.
362 protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
364 $detailsToCheck = ['type' => $type];
367 $detailsToCheck['entity_type'] = $entity->getMorphClass();
368 $detailsToCheck['entity_id'] = $entity->id;
372 $detailsToCheck['detail'] = $detail;
375 $this->assertDatabaseHas('activities', $detailsToCheck);