5 use BookStack\Entities\Models\Entity;
6 use BookStack\Settings\SettingService;
7 use BookStack\Uploads\HttpFetcher;
8 use BookStack\Users\Models\User;
10 use GuzzleHttp\Handler\MockHandler;
11 use GuzzleHttp\HandlerStack;
12 use GuzzleHttp\Middleware;
13 use Illuminate\Contracts\Console\Kernel;
14 use Illuminate\Foundation\Testing\DatabaseTransactions;
15 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
16 use Illuminate\Http\JsonResponse;
17 use Illuminate\Support\Env;
18 use Illuminate\Support\Facades\DB;
19 use Illuminate\Support\Facades\Log;
20 use Illuminate\Testing\Assert as PHPUnit;
22 use Monolog\Handler\TestHandler;
24 use Psr\Http\Client\ClientInterface;
25 use Ssddanbrown\AssertHtml\TestsHtml;
26 use Tests\Helpers\EntityProvider;
27 use Tests\Helpers\FileProvider;
28 use Tests\Helpers\PermissionsProvider;
29 use Tests\Helpers\TestServiceProvider;
30 use Tests\Helpers\UserRoleProvider;
32 abstract class TestCase extends BaseTestCase
34 use CreatesApplication;
35 use DatabaseTransactions;
38 protected EntityProvider $entities;
39 protected UserRoleProvider $users;
40 protected PermissionsProvider $permissions;
41 protected FileProvider $files;
43 protected function setUp(): void
45 $this->entities = new EntityProvider();
46 $this->users = new UserRoleProvider();
47 $this->permissions = new PermissionsProvider($this->users);
48 $this->files = new FileProvider();
53 // We can uncomment the below to run tests with failings upon deprecations.
54 // Can't leave on since some deprecations can only be fixed upstream.
55 // $this->withoutDeprecationHandling();
59 * The base URL to use while testing the application.
61 protected string $baseUrl = 'http://localhost';
64 * Creates the application.
66 * @return \Illuminate\Foundation\Application
68 public function createApplication()
70 /** @var \Illuminate\Foundation\Application $app */
71 $app = require __DIR__ . '/../bootstrap/app.php';
72 $app->register(TestServiceProvider::class);
73 $app->make(Kernel::class)->bootstrap();
79 * Set the current user context to be an admin.
81 public function asAdmin()
83 return $this->actingAs($this->users->admin());
87 * Set the current user context to be an editor.
89 public function asEditor()
91 return $this->actingAs($this->users->editor());
95 * Set the current user context to be a viewer.
97 public function asViewer()
99 return $this->actingAs($this->users->viewer());
103 * Quickly sets an array of settings.
105 protected function setSettings(array $settingsArray): void
107 $settings = app(SettingService::class);
108 foreach ($settingsArray as $key => $value) {
109 $settings->put($key, $value);
114 * Mock the HttpFetcher service and return the given data on fetch.
116 protected function mockHttpFetch($returnData, int $times = 1)
118 $mockHttp = Mockery::mock(HttpFetcher::class);
119 $this->app[HttpFetcher::class] = $mockHttp;
120 $mockHttp->shouldReceive('fetch')
122 ->andReturn($returnData);
126 * Mock the http client used in BookStack.
127 * Returns a reference to the container which holds all history of http transactions.
129 * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
131 protected function &mockHttpClient(array $responses = []): array
134 $history = Middleware::history($container);
135 $mock = new MockHandler($responses);
136 $handlerStack = new HandlerStack($mock);
137 $handlerStack->push($history);
138 $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
144 * Run a set test with the given env variable.
145 * Remembers the original and resets the value after test.
146 * Database config is juggled so the value can be restored when
147 * parallel testing are used, where multiple databases exist.
149 protected function runWithEnv(string $name, $value, callable $callback)
151 Env::disablePutenv();
152 $originalVal = $_SERVER[$name] ?? null;
154 if (is_null($value)) {
155 unset($_SERVER[$name]);
157 $_SERVER[$name] = $value;
160 $database = config('database.connections.mysql_testing.database');
161 $this->refreshApplication();
164 config()->set('database.connections.mysql_testing.database', $database);
165 DB::beginTransaction();
171 if (is_null($originalVal)) {
172 unset($_SERVER[$name]);
174 $_SERVER[$name] = $originalVal;
179 * Check the keys and properties in the given map to include
180 * exist, albeit not exclusively, within the map to check.
182 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
186 foreach ($mapToInclude as $key => $value) {
187 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
192 $toIncludeStr = print_r($mapToInclude, true);
193 $toCheckStr = print_r($mapToCheck, true);
194 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
198 * Assert a permission error has occurred.
200 protected function assertPermissionError($response)
202 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
206 * Assert a permission error has occurred.
208 protected function assertNotPermissionError($response)
210 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
214 * Check if the given response is a permission error.
216 private function isPermissionError($response): bool
218 if ($response->status() === 403 && $response instanceof JsonResponse) {
219 $errMessage = $response->getData(true)['error']['message'] ?? '';
220 return $errMessage === 'You do not have permission to perform the requested action.';
223 return $response->status() === 302
224 && $response->headers->get('Location') === url('/')
225 && str_starts_with(session()->pull('error', ''), 'You do not have permission to access');
229 * Assert that the session has a particular error notification message set.
231 protected function assertSessionError(string $message)
233 $error = session()->get('error');
234 PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
238 * Assert the session contains a specific entry.
240 protected function assertSessionHas(string $key): self
242 $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
247 protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
249 return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
253 * Set a test handler as the logging interface for the application.
254 * Allows capture of logs for checking against during tests.
256 protected function withTestLogger(): TestHandler
258 $monolog = new Logger('testing');
259 $testHandler = new TestHandler();
260 $monolog->pushHandler($testHandler);
262 Log::extend('testing', function () use ($monolog) {
265 Log::setDefaultDriver('testing');
271 * Assert that an activity entry exists of the given key.
272 * Checks the activity belongs to the given entity if provided.
274 protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
276 $detailsToCheck = ['type' => $type];
279 $detailsToCheck['entity_type'] = $entity->getMorphClass();
280 $detailsToCheck['entity_id'] = $entity->id;
284 $detailsToCheck['detail'] = $detail;
287 $this->assertDatabaseHas('activities', $detailsToCheck);