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();
49 * The base URL to use while testing the application.
51 protected string $baseUrl = 'http://localhost';
54 * Creates the application.
56 * @return \Illuminate\Foundation\Application
58 public function createApplication()
60 /** @var \Illuminate\Foundation\Application $app */
61 $app = require __DIR__ . '/../bootstrap/app.php';
62 $app->register(TestServiceProvider::class);
63 $app->make(Kernel::class)->bootstrap();
69 * Set the current user context to be an admin.
71 public function asAdmin()
73 return $this->actingAs($this->getAdmin());
77 * Get the current admin user.
79 public function getAdmin(): User
81 if (is_null($this->admin)) {
82 $adminRole = Role::getSystemRole('admin');
83 $this->admin = $adminRole->users->first();
90 * Set the current user context to be an editor.
92 public function asEditor()
94 return $this->actingAs($this->getEditor());
100 protected function getEditor(): User
102 if ($this->editor === null) {
103 $editorRole = Role::getRole('editor');
104 $this->editor = $editorRole->users->first();
107 return $this->editor;
111 * Set the current user context to be a viewer.
113 public function asViewer()
115 return $this->actingAs($this->getViewer());
119 * Get an instance of a user with 'viewer' permissions.
121 protected function getViewer(array $attributes = []): User
123 $user = Role::getRole('viewer')->users()->first();
124 if (!empty($attributes)) {
125 $user->forceFill($attributes)->save();
132 * Get a user that's not a system user such as the guest user.
134 public function getNormalUser(): User
136 return User::query()->where('system_name', '=', null)->get()->last();
140 * Quickly sets an array of settings.
142 protected function setSettings(array $settingsArray): void
144 $settings = app(SettingService::class);
145 foreach ($settingsArray as $key => $value) {
146 $settings->put($key, $value);
151 * Give the given user some permissions.
153 protected function giveUserPermissions(User $user, array $permissions = []): void
155 $newRole = $this->createNewRole($permissions);
156 $user->attachRole($newRole);
157 $user->load('roles');
158 $user->clearPermissionCache();
162 * Completely remove the given permission name from the given user.
164 protected function removePermissionFromUser(User $user, string $permissionName)
166 $permissionBuilder = app()->make(JointPermissionBuilder::class);
168 /** @var RolePermission $permission */
169 $permission = RolePermission::query()->where('name', '=', $permissionName)->firstOrFail();
171 $roles = $user->roles()->whereHas('permissions', function ($query) use ($permission) {
172 $query->where('id', '=', $permission->id);
175 /** @var Role $role */
176 foreach ($roles as $role) {
177 $role->detachPermission($permission);
178 $permissionBuilder->rebuildForRole($role);
181 $user->clearPermissionCache();
185 * Create a new basic role for testing purposes.
187 protected function createNewRole(array $permissions = []): Role
189 $permissionRepo = app(PermissionsRepo::class);
190 $roleData = Role::factory()->make()->toArray();
191 $roleData['permissions'] = array_flip($permissions);
193 return $permissionRepo->saveNewRole($roleData);
197 * Mock the HttpFetcher service and return the given data on fetch.
199 protected function mockHttpFetch($returnData, int $times = 1)
201 $mockHttp = Mockery::mock(HttpFetcher::class);
202 $this->app[HttpFetcher::class] = $mockHttp;
203 $mockHttp->shouldReceive('fetch')
205 ->andReturn($returnData);
209 * Mock the http client used in BookStack.
210 * Returns a reference to the container which holds all history of http transactions.
212 * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
214 protected function &mockHttpClient(array $responses = []): array
217 $history = Middleware::history($container);
218 $mock = new MockHandler($responses);
219 $handlerStack = new HandlerStack($mock);
220 $handlerStack->push($history);
221 $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
227 * Run a set test with the given env variable.
228 * Remembers the original and resets the value after test.
229 * Database config is juggled so the value can be restored when
230 * parallel testing are used, where multiple databases exist.
232 protected function runWithEnv(string $name, $value, callable $callback)
234 Env::disablePutenv();
235 $originalVal = $_SERVER[$name] ?? null;
237 if (is_null($value)) {
238 unset($_SERVER[$name]);
240 $_SERVER[$name] = $value;
243 $database = config('database.connections.mysql_testing.database');
244 $this->refreshApplication();
247 config()->set('database.connections.mysql_testing.database', $database);
251 if (is_null($originalVal)) {
252 unset($_SERVER[$name]);
254 $_SERVER[$name] = $originalVal;
259 * Check the keys and properties in the given map to include
260 * exist, albeit not exclusively, within the map to check.
262 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
266 foreach ($mapToInclude as $key => $value) {
267 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
272 $toIncludeStr = print_r($mapToInclude, true);
273 $toCheckStr = print_r($mapToCheck, true);
274 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
278 * Assert a permission error has occurred.
280 protected function assertPermissionError($response)
282 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
286 * Assert a permission error has occurred.
288 protected function assertNotPermissionError($response)
290 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
294 * Check if the given response is a permission error.
296 private function isPermissionError($response): bool
298 return $response->status() === 302
301 $response->headers->get('Location') === url('/')
302 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
306 $response instanceof JsonResponse &&
307 $response->json(['error' => 'You do not have permission to perform the requested action.'])
313 * Assert that the session has a particular error notification message set.
315 protected function assertSessionError(string $message)
317 $error = session()->get('error');
318 PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
322 * Assert the session contains a specific entry.
324 protected function assertSessionHas(string $key): self
326 $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
331 protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
333 return $this->withHtml($resp)->assertElementContains('[notification]', $text);
337 * Set a test handler as the logging interface for the application.
338 * Allows capture of logs for checking against during tests.
340 protected function withTestLogger(): TestHandler
342 $monolog = new Logger('testing');
343 $testHandler = new TestHandler();
344 $monolog->pushHandler($testHandler);
346 Log::extend('testing', function () use ($monolog) {
349 Log::setDefaultDriver('testing');
355 * Assert that an activity entry exists of the given key.
356 * Checks the activity belongs to the given entity if provided.
358 protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
360 $detailsToCheck = ['type' => $type];
363 $detailsToCheck['entity_type'] = $entity->getMorphClass();
364 $detailsToCheck['entity_id'] = $entity->id;
368 $detailsToCheck['detail'] = $detail;
371 $this->assertDatabaseHas('activities', $detailsToCheck);