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();
48 // We can uncomment the below to run tests with failings upon deprecations.
49 // Can't leave on since some deprecations can only be fixed upstream.
50 // $this->withoutDeprecationHandling();
54 * The base URL to use while testing the application.
56 protected string $baseUrl = 'http://localhost';
59 * Creates the application.
61 * @return \Illuminate\Foundation\Application
63 public function createApplication()
65 /** @var \Illuminate\Foundation\Application $app */
66 $app = require __DIR__ . '/../bootstrap/app.php';
67 $app->register(TestServiceProvider::class);
68 $app->make(Kernel::class)->bootstrap();
74 * Set the current user context to be an admin.
76 public function asAdmin()
78 return $this->actingAs($this->users->admin());
82 * Set the current user context to be an editor.
84 public function asEditor()
86 return $this->actingAs($this->users->editor());
90 * Set the current user context to be a viewer.
92 public function asViewer()
94 return $this->actingAs($this->users->viewer());
98 * Quickly sets an array of settings.
100 protected function setSettings(array $settingsArray): void
102 $settings = app(SettingService::class);
103 foreach ($settingsArray as $key => $value) {
104 $settings->put($key, $value);
109 * Mock the http client used in BookStack http calls.
111 protected function mockHttpClient(array $responses = []): HttpClientHistory
113 return $this->app->make(HttpRequestService::class)->mockClient($responses);
117 * Run a set test with the given env variable.
118 * Remembers the original and resets the value after test.
119 * Database config is juggled so the value can be restored when
120 * parallel testing are used, where multiple databases exist.
122 protected function runWithEnv(string $name, $value, callable $callback)
124 Env::disablePutenv();
125 $originalVal = $_SERVER[$name] ?? null;
127 if (is_null($value)) {
128 unset($_SERVER[$name]);
130 $_SERVER[$name] = $value;
133 $database = config('database.connections.mysql_testing.database');
134 $this->refreshApplication();
137 config()->set('database.connections.mysql_testing.database', $database);
138 DB::beginTransaction();
144 if (is_null($originalVal)) {
145 unset($_SERVER[$name]);
147 $_SERVER[$name] = $originalVal;
152 * Check the keys and properties in the given map to include
153 * exist, albeit not exclusively, within the map to check.
155 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
159 foreach ($mapToInclude as $key => $value) {
160 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
165 $toIncludeStr = print_r($mapToInclude, true);
166 $toCheckStr = print_r($mapToCheck, true);
167 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
171 * Assert a permission error has occurred.
173 protected function assertPermissionError($response)
175 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
179 * Assert a permission error has occurred.
181 protected function assertNotPermissionError($response)
183 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
187 * Check if the given response is a permission error.
189 private function isPermissionError($response): bool
191 if ($response->status() === 403 && $response instanceof JsonResponse) {
192 $errMessage = $response->getData(true)['error']['message'] ?? '';
193 return $errMessage === 'You do not have permission to perform the requested action.';
196 return $response->status() === 302
197 && $response->headers->get('Location') === url('/')
198 && str_starts_with(session()->pull('error', ''), 'You do not have permission to access');
202 * Assert that the session has a particular error notification message set.
204 protected function assertSessionError(string $message)
206 $error = session()->get('error');
207 PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
211 * Assert the session contains a specific entry.
213 protected function assertSessionHas(string $key): self
215 $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
220 protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
222 return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
226 * Set a test handler as the logging interface for the application.
227 * Allows capture of logs for checking against during tests.
229 protected function withTestLogger(): TestHandler
231 $monolog = new Logger('testing');
232 $testHandler = new TestHandler();
233 $monolog->pushHandler($testHandler);
235 Log::extend('testing', function () use ($monolog) {
238 Log::setDefaultDriver('testing');
244 * Assert that an activity entry exists of the given key.
245 * Checks the activity belongs to the given entity if provided.
247 protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
249 $detailsToCheck = ['type' => $type];
252 $detailsToCheck['entity_type'] = $entity->getMorphClass();
253 $detailsToCheck['entity_id'] = $entity->id;
257 $detailsToCheck['detail'] = $detail;
260 $this->assertDatabaseHas('activities', $detailsToCheck);