]> BookStack Code Mirror - bookstack/blob - tests/TestCase.php
Fixed role entity permissions ignoring inheritance
[bookstack] / tests / TestCase.php
1 <?php
2
3 namespace Tests;
4
5 use BookStack\Entities\Models\Entity;
6 use BookStack\Settings\SettingService;
7 use BookStack\Uploads\HttpFetcher;
8 use GuzzleHttp\Client;
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;
20 use Mockery;
21 use Monolog\Handler\TestHandler;
22 use Monolog\Logger;
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;
29
30 abstract class TestCase extends BaseTestCase
31 {
32     use CreatesApplication;
33     use DatabaseTransactions;
34     use TestsHtml;
35
36     protected EntityProvider $entities;
37     protected UserRoleProvider $users;
38     protected PermissionsProvider $permissions;
39
40     protected function setUp(): void
41     {
42         $this->entities = new EntityProvider();
43         $this->users = new UserRoleProvider();
44         $this->permissions = new PermissionsProvider($this->users);
45
46         parent::setUp();
47     }
48
49     /**
50      * The base URL to use while testing the application.
51      */
52     protected string $baseUrl = 'http://localhost';
53
54     /**
55      * Creates the application.
56      *
57      * @return \Illuminate\Foundation\Application
58      */
59     public function createApplication()
60     {
61         /** @var \Illuminate\Foundation\Application  $app */
62         $app = require __DIR__ . '/../bootstrap/app.php';
63         $app->register(TestServiceProvider::class);
64         $app->make(Kernel::class)->bootstrap();
65
66         return $app;
67     }
68
69     /**
70      * Set the current user context to be an admin.
71      */
72     public function asAdmin()
73     {
74         return $this->actingAs($this->users->admin());
75     }
76
77     /**
78      * Set the current user context to be an editor.
79      */
80     public function asEditor()
81     {
82         return $this->actingAs($this->users->editor());
83     }
84
85     /**
86      * Set the current user context to be a viewer.
87      */
88     public function asViewer()
89     {
90         return $this->actingAs($this->users->viewer());
91     }
92
93     /**
94      * Quickly sets an array of settings.
95      */
96     protected function setSettings(array $settingsArray): void
97     {
98         $settings = app(SettingService::class);
99         foreach ($settingsArray as $key => $value) {
100             $settings->put($key, $value);
101         }
102     }
103
104     /**
105      * Mock the HttpFetcher service and return the given data on fetch.
106      */
107     protected function mockHttpFetch($returnData, int $times = 1)
108     {
109         $mockHttp = Mockery::mock(HttpFetcher::class);
110         $this->app[HttpFetcher::class] = $mockHttp;
111         $mockHttp->shouldReceive('fetch')
112             ->times($times)
113             ->andReturn($returnData);
114     }
115
116     /**
117      * Mock the http client used in BookStack.
118      * Returns a reference to the container which holds all history of http transactions.
119      *
120      * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
121      */
122     protected function &mockHttpClient(array $responses = []): array
123     {
124         $container = [];
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]);
130
131         return $container;
132     }
133
134     /**
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.
139      */
140     protected function runWithEnv(string $name, $value, callable $callback)
141     {
142         Env::disablePutenv();
143         $originalVal = $_SERVER[$name] ?? null;
144
145         if (is_null($value)) {
146             unset($_SERVER[$name]);
147         } else {
148             $_SERVER[$name] = $value;
149         }
150
151         $database = config('database.connections.mysql_testing.database');
152         $this->refreshApplication();
153
154         DB::purge();
155         config()->set('database.connections.mysql_testing.database', $database);
156         DB::beginTransaction();
157
158         $callback();
159
160         DB::rollBack();
161
162         if (is_null($originalVal)) {
163             unset($_SERVER[$name]);
164         } else {
165             $_SERVER[$name] = $originalVal;
166         }
167     }
168
169     /**
170      * Check the keys and properties in the given map to include
171      * exist, albeit not exclusively, within the map to check.
172      */
173     protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
174     {
175         $passed = true;
176
177         foreach ($mapToInclude as $key => $value) {
178             if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
179                 $passed = false;
180             }
181         }
182
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}");
186     }
187
188     /**
189      * Assert a permission error has occurred.
190      */
191     protected function assertPermissionError($response)
192     {
193         PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
194     }
195
196     /**
197      * Assert a permission error has occurred.
198      */
199     protected function assertNotPermissionError($response)
200     {
201         PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
202     }
203
204     /**
205      * Check if the given response is a permission error.
206      */
207     private function isPermissionError($response): bool
208     {
209         return $response->status() === 302
210             && (
211                 (
212                     $response->headers->get('Location') === url('/')
213                     && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
214                 )
215                 ||
216                 (
217                     $response instanceof JsonResponse &&
218                     $response->json(['error' => 'You do not have permission to perform the requested action.'])
219                 )
220             );
221     }
222
223     /**
224      * Assert that the session has a particular error notification message set.
225      */
226     protected function assertSessionError(string $message)
227     {
228         $error = session()->get('error');
229         PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
230     }
231
232     /**
233      * Assert the session contains a specific entry.
234      */
235     protected function assertSessionHas(string $key): self
236     {
237         $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
238
239         return $this;
240     }
241
242     protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
243     {
244         return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
245     }
246
247     /**
248      * Set a test handler as the logging interface for the application.
249      * Allows capture of logs for checking against during tests.
250      */
251     protected function withTestLogger(): TestHandler
252     {
253         $monolog = new Logger('testing');
254         $testHandler = new TestHandler();
255         $monolog->pushHandler($testHandler);
256
257         Log::extend('testing', function () use ($monolog) {
258             return $monolog;
259         });
260         Log::setDefaultDriver('testing');
261
262         return $testHandler;
263     }
264
265     /**
266      * Assert that an activity entry exists of the given key.
267      * Checks the activity belongs to the given entity if provided.
268      */
269     protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
270     {
271         $detailsToCheck = ['type' => $type];
272
273         if ($entity) {
274             $detailsToCheck['entity_type'] = $entity->getMorphClass();
275             $detailsToCheck['entity_id'] = $entity->id;
276         }
277
278         if ($detail) {
279             $detailsToCheck['detail'] = $detail;
280         }
281
282         $this->assertDatabaseHas('activities', $detailsToCheck);
283     }
284 }