5 use BookStack\Entities\Models\Entity;
6 use BookStack\Settings\SettingService;
7 use BookStack\Uploads\HttpFetcher;
9 use GuzzleHttp\Handler\MockHandler;
10 use GuzzleHttp\HandlerStack;
11 use GuzzleHttp\Middleware;
12 use Illuminate\Contracts\Console\Kernel;
13 use Illuminate\Foundation\Testing\DatabaseTransactions;
14 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
15 use Illuminate\Http\JsonResponse;
16 use Illuminate\Support\Env;
17 use Illuminate\Support\Facades\DB;
18 use Illuminate\Support\Facades\Log;
19 use Illuminate\Testing\Assert as PHPUnit;
21 use Monolog\Handler\TestHandler;
23 use Psr\Http\Client\ClientInterface;
24 use Ssddanbrown\AssertHtml\TestsHtml;
25 use Tests\Helpers\EntityProvider;
26 use Tests\Helpers\PermissionsProvider;
27 use Tests\Helpers\TestServiceProvider;
28 use Tests\Helpers\UserRoleProvider;
30 abstract class TestCase extends BaseTestCase
32 use CreatesApplication;
33 use DatabaseTransactions;
36 protected EntityProvider $entities;
37 protected UserRoleProvider $users;
38 protected PermissionsProvider $permissions;
40 protected function setUp(): void
42 $this->entities = new EntityProvider();
43 $this->users = new UserRoleProvider();
44 $this->permissions = new PermissionsProvider($this->users);
50 * The base URL to use while testing the application.
52 protected string $baseUrl = 'http://localhost';
55 * Creates the application.
57 * @return \Illuminate\Foundation\Application
59 public function createApplication()
61 /** @var \Illuminate\Foundation\Application $app */
62 $app = require __DIR__ . '/../bootstrap/app.php';
63 $app->register(TestServiceProvider::class);
64 $app->make(Kernel::class)->bootstrap();
70 * Set the current user context to be an admin.
72 public function asAdmin()
74 return $this->actingAs($this->users->admin());
78 * Set the current user context to be an editor.
80 public function asEditor()
82 return $this->actingAs($this->users->editor());
86 * Set the current user context to be a viewer.
88 public function asViewer()
90 return $this->actingAs($this->users->viewer());
94 * Quickly sets an array of settings.
96 protected function setSettings(array $settingsArray): void
98 $settings = app(SettingService::class);
99 foreach ($settingsArray as $key => $value) {
100 $settings->put($key, $value);
105 * Mock the HttpFetcher service and return the given data on fetch.
107 protected function mockHttpFetch($returnData, int $times = 1)
109 $mockHttp = Mockery::mock(HttpFetcher::class);
110 $this->app[HttpFetcher::class] = $mockHttp;
111 $mockHttp->shouldReceive('fetch')
113 ->andReturn($returnData);
117 * Mock the http client used in BookStack.
118 * Returns a reference to the container which holds all history of http transactions.
120 * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
122 protected function &mockHttpClient(array $responses = []): array
125 $history = Middleware::history($container);
126 $mock = new MockHandler($responses);
127 $handlerStack = new HandlerStack($mock);
128 $handlerStack->push($history);
129 $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
135 * Run a set test with the given env variable.
136 * Remembers the original and resets the value after test.
137 * Database config is juggled so the value can be restored when
138 * parallel testing are used, where multiple databases exist.
140 protected function runWithEnv(string $name, $value, callable $callback)
142 Env::disablePutenv();
143 $originalVal = $_SERVER[$name] ?? null;
145 if (is_null($value)) {
146 unset($_SERVER[$name]);
148 $_SERVER[$name] = $value;
151 $database = config('database.connections.mysql_testing.database');
152 $this->refreshApplication();
155 config()->set('database.connections.mysql_testing.database', $database);
156 DB::beginTransaction();
162 if (is_null($originalVal)) {
163 unset($_SERVER[$name]);
165 $_SERVER[$name] = $originalVal;
170 * Check the keys and properties in the given map to include
171 * exist, albeit not exclusively, within the map to check.
173 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
177 foreach ($mapToInclude as $key => $value) {
178 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
183 $toIncludeStr = print_r($mapToInclude, true);
184 $toCheckStr = print_r($mapToCheck, true);
185 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
189 * Assert a permission error has occurred.
191 protected function assertPermissionError($response)
193 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
197 * Assert a permission error has occurred.
199 protected function assertNotPermissionError($response)
201 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
205 * Check if the given response is a permission error.
207 private function isPermissionError($response): bool
209 return $response->status() === 302
212 $response->headers->get('Location') === url('/')
213 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
217 $response instanceof JsonResponse &&
218 $response->json(['error' => 'You do not have permission to perform the requested action.'])
224 * Assert that the session has a particular error notification message set.
226 protected function assertSessionError(string $message)
228 $error = session()->get('error');
229 PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
233 * Assert the session contains a specific entry.
235 protected function assertSessionHas(string $key): self
237 $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
242 protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
244 return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
248 * Set a test handler as the logging interface for the application.
249 * Allows capture of logs for checking against during tests.
251 protected function withTestLogger(): TestHandler
253 $monolog = new Logger('testing');
254 $testHandler = new TestHandler();
255 $monolog->pushHandler($testHandler);
257 Log::extend('testing', function () use ($monolog) {
260 Log::setDefaultDriver('testing');
266 * Assert that an activity entry exists of the given key.
267 * Checks the activity belongs to the given entity if provided.
269 protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
271 $detailsToCheck = ['type' => $type];
274 $detailsToCheck['entity_type'] = $entity->getMorphClass();
275 $detailsToCheck['entity_id'] = $entity->id;
279 $detailsToCheck['detail'] = $detail;
282 $this->assertDatabaseHas('activities', $detailsToCheck);