5 use BookStack\Entities\Models\Entity;
6 use BookStack\Http\HttpClientHistory;
7 use BookStack\Http\HttpRequestService;
8 use BookStack\Settings\SettingService;
9 use BookStack\Users\Models\User;
10 use Illuminate\Contracts\Console\Kernel;
11 use Illuminate\Foundation\Testing\DatabaseTransactions;
12 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
13 use Illuminate\Http\JsonResponse;
14 use Illuminate\Support\Env;
15 use Illuminate\Support\Facades\DB;
16 use Illuminate\Support\Facades\Log;
17 use Illuminate\Testing\Assert as PHPUnit;
18 use Monolog\Handler\TestHandler;
20 use Ssddanbrown\AssertHtml\TestsHtml;
21 use Tests\Helpers\EntityProvider;
22 use Tests\Helpers\FileProvider;
23 use Tests\Helpers\PermissionsProvider;
24 use Tests\Helpers\TestServiceProvider;
25 use Tests\Helpers\UserRoleProvider;
27 abstract class TestCase extends BaseTestCase
29 use CreatesApplication;
30 use DatabaseTransactions;
33 protected EntityProvider $entities;
34 protected UserRoleProvider $users;
35 protected PermissionsProvider $permissions;
36 protected FileProvider $files;
38 protected function setUp(): void
40 $this->entities = new EntityProvider();
41 $this->users = new UserRoleProvider();
42 $this->permissions = new PermissionsProvider($this->users);
43 $this->files = new FileProvider();
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->users->admin());
81 * Set the current user context to be an editor.
83 public function asEditor()
85 return $this->actingAs($this->users->editor());
89 * Set the current user context to be a viewer.
91 public function asViewer()
93 return $this->actingAs($this->users->viewer());
97 * Quickly sets an array of settings.
99 protected function setSettings(array $settingsArray): void
101 $settings = app(SettingService::class);
102 foreach ($settingsArray as $key => $value) {
103 $settings->put($key, $value);
108 * Mock the http client used in BookStack http calls.
110 protected function mockHttpClient(array $responses = []): HttpClientHistory
112 return $this->app->make(HttpRequestService::class)->mockClient($responses);
116 * Run a set test with the given env variable.
117 * Remembers the original and resets the value after test.
118 * Database config is juggled so the value can be restored when
119 * parallel testing are used, where multiple databases exist.
121 protected function runWithEnv(string $name, $value, callable $callback)
123 Env::disablePutenv();
124 $originalVal = $_SERVER[$name] ?? null;
126 if (is_null($value)) {
127 unset($_SERVER[$name]);
129 $_SERVER[$name] = $value;
132 $database = config('database.connections.mysql_testing.database');
133 $this->refreshApplication();
136 config()->set('database.connections.mysql_testing.database', $database);
137 DB::beginTransaction();
143 if (is_null($originalVal)) {
144 unset($_SERVER[$name]);
146 $_SERVER[$name] = $originalVal;
151 * Check the keys and properties in the given map to include
152 * exist, albeit not exclusively, within the map to check.
154 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
158 foreach ($mapToInclude as $key => $value) {
159 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
164 $toIncludeStr = print_r($mapToInclude, true);
165 $toCheckStr = print_r($mapToCheck, true);
166 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
170 * Assert a permission error has occurred.
172 protected function assertPermissionError($response)
174 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
178 * Assert a permission error has occurred.
180 protected function assertNotPermissionError($response)
182 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
186 * Check if the given response is a permission error.
188 private function isPermissionError($response): bool
190 if ($response->status() === 403 && $response instanceof JsonResponse) {
191 $errMessage = $response->getData(true)['error']['message'] ?? '';
192 return $errMessage === 'You do not have permission to perform the requested action.';
195 return $response->status() === 302
196 && $response->headers->get('Location') === url('/')
197 && str_starts_with(session()->pull('error', ''), 'You do not have permission to access');
201 * Assert that the session has a particular error notification message set.
203 protected function assertSessionError(string $message)
205 $error = session()->get('error');
206 PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
210 * Assert the session contains a specific entry.
212 protected function assertSessionHas(string $key): self
214 $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
219 protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
221 return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
225 * Set a test handler as the logging interface for the application.
226 * Allows capture of logs for checking against during tests.
228 protected function withTestLogger(): TestHandler
230 $monolog = new Logger('testing');
231 $testHandler = new TestHandler();
232 $monolog->pushHandler($testHandler);
234 Log::extend('testing', function () use ($monolog) {
237 Log::setDefaultDriver('testing');
243 * Assert that an activity entry exists of the given key.
244 * Checks the activity belongs to the given entity if provided.
246 protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
248 $detailsToCheck = ['type' => $type];
251 $detailsToCheck['loggable_type'] = $entity->getMorphClass();
252 $detailsToCheck['loggable_id'] = $entity->id;
256 $detailsToCheck['detail'] = $detail;
259 $this->assertDatabaseHas('activities', $detailsToCheck);