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);
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 HttpFetcher service and return the given data on fetch.
111 protected function mockHttpFetch($returnData, int $times = 1)
113 $mockHttp = Mockery::mock(HttpFetcher::class);
114 $this->app[HttpFetcher::class] = $mockHttp;
115 $mockHttp->shouldReceive('fetch')
117 ->andReturn($returnData);
121 * Mock the http client used in BookStack.
122 * Returns a reference to the container which holds all history of http transactions.
124 * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
126 protected function &mockHttpClient(array $responses = []): array
129 $history = Middleware::history($container);
130 $mock = new MockHandler($responses);
131 $handlerStack = new HandlerStack($mock);
132 $handlerStack->push($history);
133 $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
139 * Run a set test with the given env variable.
140 * Remembers the original and resets the value after test.
141 * Database config is juggled so the value can be restored when
142 * parallel testing are used, where multiple databases exist.
144 protected function runWithEnv(string $name, $value, callable $callback)
146 Env::disablePutenv();
147 $originalVal = $_SERVER[$name] ?? null;
149 if (is_null($value)) {
150 unset($_SERVER[$name]);
152 $_SERVER[$name] = $value;
155 $database = config('database.connections.mysql_testing.database');
156 $this->refreshApplication();
159 config()->set('database.connections.mysql_testing.database', $database);
160 DB::beginTransaction();
166 if (is_null($originalVal)) {
167 unset($_SERVER[$name]);
169 $_SERVER[$name] = $originalVal;
174 * Check the keys and properties in the given map to include
175 * exist, albeit not exclusively, within the map to check.
177 protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
181 foreach ($mapToInclude as $key => $value) {
182 if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
187 $toIncludeStr = print_r($mapToInclude, true);
188 $toCheckStr = print_r($mapToCheck, true);
189 self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
193 * Assert a permission error has occurred.
195 protected function assertPermissionError($response)
197 PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
201 * Assert a permission error has occurred.
203 protected function assertNotPermissionError($response)
205 PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
209 * Check if the given response is a permission error.
211 private function isPermissionError($response): bool
213 return $response->status() === 302
216 $response->headers->get('Location') === url('/')
217 && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
221 $response instanceof JsonResponse &&
222 $response->json(['error' => 'You do not have permission to perform the requested action.'])
228 * Assert that the session has a particular error notification message set.
230 protected function assertSessionError(string $message)
232 $error = session()->get('error');
233 PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
237 * Assert the session contains a specific entry.
239 protected function assertSessionHas(string $key): self
241 $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
246 protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
248 return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
252 * Set a test handler as the logging interface for the application.
253 * Allows capture of logs for checking against during tests.
255 protected function withTestLogger(): TestHandler
257 $monolog = new Logger('testing');
258 $testHandler = new TestHandler();
259 $monolog->pushHandler($testHandler);
261 Log::extend('testing', function () use ($monolog) {
264 Log::setDefaultDriver('testing');
270 * Assert that an activity entry exists of the given key.
271 * Checks the activity belongs to the given entity if provided.
273 protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
275 $detailsToCheck = ['type' => $type];
278 $detailsToCheck['entity_type'] = $entity->getMorphClass();
279 $detailsToCheck['entity_id'] = $entity->id;
283 $detailsToCheck['detail'] = $detail;
286 $this->assertDatabaseHas('activities', $detailsToCheck);