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;
31 abstract class TestCase extends BaseTestCase
33 use CreatesApplication;
34 use DatabaseTransactions;
37 protected ?User $admin = null;
38 protected ?User $editor = null;
39 protected EntityProvider $entities;
41 protected function setUp(): void
43 $this->entities = new EntityProvider();
48 * The base URL to use while testing the application.
50 protected string $baseUrl = 'http://localhost';
53 * Creates the application.
55 * @return \Illuminate\Foundation\Application
57 public function createApplication()
59 /** @var \Illuminate\Foundation\Application $app */
60 $app = require __DIR__ . '/../bootstrap/app.php';
61 $app->register(TestServiceProvider::class);
62 $app->make(Kernel::class)->bootstrap();
68 * Set the current user context to be an admin.
70 public function asAdmin()
72 return $this->actingAs($this->getAdmin());
76 * Get the current admin user.
78 public function getAdmin(): User
80 if (is_null($this->admin)) {
81 $adminRole = Role::getSystemRole('admin');
82 $this->admin = $adminRole->users->first();
89 * Set the current user context to be an editor.
91 public function asEditor()
93 return $this->actingAs($this->getEditor());
99 protected function getEditor(): User
101 if ($this->editor === null) {
102 $editorRole = Role::getRole('editor');
103 $this->editor = $editorRole->users->first();
106 return $this->editor;
110 * Set the current user context to be a viewer.
112 public function asViewer()
114 return $this->actingAs($this->getViewer());
118 * Get an instance of a user with 'viewer' permissions.
120 protected function getViewer(array $attributes = []): User
122 $user = Role::getRole('viewer')->users()->first();
123 if (!empty($attributes)) {
124 $user->forceFill($attributes)->save();
131 * Get a user that's not a system user such as the guest user.
133 public function getNormalUser(): User
135 return User::query()->where('system_name', '=', null)->get()->last();
139 * Quickly sets an array of settings.
141 protected function setSettings(array $settingsArray): void
143 $settings = app(SettingService::class);
144 foreach ($settingsArray as $key => $value) {
145 $settings->put($key, $value);
150 * Give the given user some permissions.
152 protected function giveUserPermissions(User $user, array $permissions = []): void
154 $newRole = $this->createNewRole($permissions);
155 $user->attachRole($newRole);
156 $user->load('roles');
157 $user->clearPermissionCache();
161 * Completely remove the given permission name from the given user.
163 protected function removePermissionFromUser(User $user, string $permissionName)
165 $permissionBuilder = app()->make(JointPermissionBuilder::class);
167 /** @var RolePermission $permission */
168 $permission = RolePermission::query()->where('name', '=', $permissionName)->firstOrFail();
170 $roles = $user->roles()->whereHas('permissions', function ($query) use ($permission) {
171 $query->where('id', '=', $permission->id);
174 /** @var Role $role */
175 foreach ($roles as $role) {
176 $role->detachPermission($permission);
177 $permissionBuilder->rebuildForRole($role);
180 $user->clearPermissionCache();
184 * Create a new basic role for testing purposes.
186 protected function createNewRole(array $permissions = []): Role
188 $permissionRepo = app(PermissionsRepo::class);
189 $roleData = Role::factory()->make()->toArray();
190 $roleData['permissions'] = array_flip($permissions);
192 return $permissionRepo->saveNewRole($roleData);
196 * Mock the HttpFetcher service and return the given data on fetch.
198 protected function mockHttpFetch($returnData, int $times = 1)
200 $mockHttp = Mockery::mock(HttpFetcher::class);
201 $this->app[HttpFetcher::class] = $mockHttp;
202 $mockHttp->shouldReceive('fetch')
204 ->andReturn($returnData);
208 * Mock the http client used in BookStack.
209 * Returns a reference to the container which holds all history of http transactions.
211 * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
213 protected function &mockHttpClient(array $responses = []): array
216 $history = Middleware::history($container);
217 $mock = new MockHandler($responses);
218 $handlerStack = new HandlerStack($mock);
219 $handlerStack->push($history);
220 $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
226 * Run a set test with the given env variable.
227 * Remembers the original and resets the value after test.
228 * Database config is juggled so the value can be restored when
229 * parallel testing are used, where multiple databases exist.
231 protected function runWithEnv(string $name, $value, callable $callback)
233 Env::disablePutenv();
234 $originalVal = $_SERVER[$name] ?? null;
236 if (is_null($value)) {
237 unset($_SERVER[$name]);
239 $_SERVER[$name] = $value;
242 $database = config('database.connections.mysql_testing.database');
243 $this->refreshApplication();
246 config()->set('database.connections.mysql_testing.database', $database);
250 if (is_null($originalVal)) {
251 unset($_SERVER[$name]);
253 $_SERVER[$name] = $originalVal;
258 * Check the keys and properties in the given map to include
259 * exist, albeit not exclusively, within the map to check.
261 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
265 foreach ($mapToInclude as $key => $value) {
266 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
271 $toIncludeStr = print_r($mapToInclude, true);
272 $toCheckStr = print_r($mapToCheck, true);
273 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
277 * Assert a permission error has occurred.
279 protected function assertPermissionError($response)
281 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
285 * Assert a permission error has occurred.
287 protected function assertNotPermissionError($response)
289 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
293 * Check if the given response is a permission error.
295 private function isPermissionError($response): bool
297 return $response->status() === 302
300 $response->headers->get('Location') === url('/')
301 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
305 $response instanceof JsonResponse &&
306 $response->json(['error' => 'You do not have permission to perform the requested action.'])
312 * Assert that the session has a particular error notification message set.
314 protected function assertSessionError(string $message)
316 $error = session()->get('error');
317 PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
321 * Assert the session contains a specific entry.
323 protected function assertSessionHas(string $key): self
325 $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
330 protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
332 return $this->withHtml($resp)->assertElementContains('[notification]', $text);
336 * Set a test handler as the logging interface for the application.
337 * Allows capture of logs for checking against during tests.
339 protected function withTestLogger(): TestHandler
341 $monolog = new Logger('testing');
342 $testHandler = new TestHandler();
343 $monolog->pushHandler($testHandler);
345 Log::extend('testing', function () use ($monolog) {
348 Log::setDefaultDriver('testing');
354 * Assert that an activity entry exists of the given key.
355 * Checks the activity belongs to the given entity if provided.
357 protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
359 $detailsToCheck = ['type' => $type];
362 $detailsToCheck['entity_type'] = $entity->getMorphClass();
363 $detailsToCheck['entity_id'] = $entity->id;
367 $detailsToCheck['detail'] = $detail;
370 $this->assertDatabaseHas('activities', $detailsToCheck);