]> BookStack Code Mirror - bookstack/blobdiff - tests/TestCase.php
Images: Added nulling of image page relation on page delete
[bookstack] / tests / TestCase.php
index abee1d3b3429756cd4173783eab2af35e6dabf5f..2395317482eb856ae389d91eaeac587b7949b133 100644 (file)
@@ -3,12 +3,10 @@
 namespace Tests;
 
 use BookStack\Entities\Models\Entity;
+use BookStack\Http\HttpClientHistory;
+use BookStack\Http\HttpRequestService;
 use BookStack\Settings\SettingService;
-use BookStack\Uploads\HttpFetcher;
-use GuzzleHttp\Client;
-use GuzzleHttp\Handler\MockHandler;
-use GuzzleHttp\HandlerStack;
-use GuzzleHttp\Middleware;
+use Exception;
 use Illuminate\Contracts\Console\Kernel;
 use Illuminate\Foundation\Testing\DatabaseTransactions;
 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
@@ -17,10 +15,9 @@ use Illuminate\Support\Env;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
 use Illuminate\Testing\Assert as PHPUnit;
-use Mockery;
+use Illuminate\Testing\Constraints\HasInDatabase;
 use Monolog\Handler\TestHandler;
 use Monolog\Logger;
-use Psr\Http\Client\ClientInterface;
 use Ssddanbrown\AssertHtml\TestsHtml;
 use Tests\Helpers\EntityProvider;
 use Tests\Helpers\FileProvider;
@@ -109,33 +106,11 @@ abstract class TestCase extends BaseTestCase
     }
 
     /**
-     * Mock the HttpFetcher service and return the given data on fetch.
+     * Mock the http client used in BookStack http calls.
      */
-    protected function mockHttpFetch($returnData, int $times = 1)
+    protected function mockHttpClient(array $responses = []): HttpClientHistory
     {
-        $mockHttp = Mockery::mock(HttpFetcher::class);
-        $this->app[HttpFetcher::class] = $mockHttp;
-        $mockHttp->shouldReceive('fetch')
-            ->times($times)
-            ->andReturn($returnData);
-    }
-
-    /**
-     * Mock the http client used in BookStack.
-     * Returns a reference to the container which holds all history of http transactions.
-     *
-     * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
-     */
-    protected function &mockHttpClient(array $responses = []): array
-    {
-        $container = [];
-        $history = Middleware::history($container);
-        $mock = new MockHandler($responses);
-        $handlerStack = new HandlerStack($mock);
-        $handlerStack->push($history);
-        $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
-
-        return $container;
+        return $this->app->make(HttpRequestService::class)->mockClient($responses);
     }
 
     /**
@@ -144,32 +119,41 @@ abstract class TestCase extends BaseTestCase
      * Database config is juggled so the value can be restored when
      * parallel testing are used, where multiple databases exist.
      */
-    protected function runWithEnv(string $name, $value, callable $callback)
+    protected function runWithEnv(array $valuesByKey, callable $callback, bool $handleDatabase = true): void
     {
         Env::disablePutenv();
-        $originalVal = $_SERVER[$name] ?? null;
-
-        if (is_null($value)) {
-            unset($_SERVER[$name]);
-        } else {
-            $_SERVER[$name] = $value;
+        $originals = [];
+        foreach ($valuesByKey as $key => $value) {
+            $originals[$key] = $_SERVER[$key] ?? null;
+
+            if (is_null($value)) {
+                unset($_SERVER[$key]);
+            } else {
+                $_SERVER[$key] = $value;
+            }
         }
 
         $database = config('database.connections.mysql_testing.database');
         $this->refreshApplication();
 
-        DB::purge();
-        config()->set('database.connections.mysql_testing.database', $database);
-        DB::beginTransaction();
+        if ($handleDatabase) {
+            DB::purge();
+            config()->set('database.connections.mysql_testing.database', $database);
+            DB::beginTransaction();
+        }
 
         $callback();
 
-        DB::rollBack();
+        if ($handleDatabase) {
+            DB::rollBack();
+        }
 
-        if (is_null($originalVal)) {
-            unset($_SERVER[$name]);
-        } else {
-            $_SERVER[$name] = $originalVal;
+        foreach ($originals as $key => $value) {
+            if (is_null($value)) {
+                unset($_SERVER[$key]);
+            } else {
+                $_SERVER[$key] = $value;
+            }
         }
     }
 
@@ -213,18 +197,14 @@ abstract class TestCase extends BaseTestCase
      */
     private function isPermissionError($response): bool
     {
+        if ($response->status() === 403 && $response instanceof JsonResponse) {
+            $errMessage = $response->getData(true)['error']['message'] ?? '';
+            return $errMessage === 'You do not have permission to perform the requested action.';
+        }
+
         return $response->status() === 302
-            && (
-                (
-                    $response->headers->get('Location') === url('/')
-                    && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
-                )
-                ||
-                (
-                    $response instanceof JsonResponse &&
-                    $response->json(['error' => 'You do not have permission to perform the requested action.'])
-                )
-            );
+            && $response->headers->get('Location') === url('/')
+            && str_starts_with(session()->pull('error', ''), 'You do not have permission to access');
     }
 
     /**
@@ -278,8 +258,8 @@ abstract class TestCase extends BaseTestCase
         $detailsToCheck = ['type' => $type];
 
         if ($entity) {
-            $detailsToCheck['entity_type'] = $entity->getMorphClass();
-            $detailsToCheck['entity_id'] = $entity->id;
+            $detailsToCheck['loggable_type'] = $entity->getMorphClass();
+            $detailsToCheck['loggable_id'] = $entity->id;
         }
 
         if ($detail) {
@@ -288,4 +268,42 @@ abstract class TestCase extends BaseTestCase
 
         $this->assertDatabaseHas('activities', $detailsToCheck);
     }
+
+    /**
+     * Assert the database has the given data for an entity type.
+     */
+    protected function assertDatabaseHasEntityData(string $type, array $data = []): self
+    {
+        $entityFields = array_intersect_key($data, array_flip(Entity::$commonFields));
+        $extraFields = array_diff_key($data, $entityFields);
+        $extraTable = $type === 'page' ? 'entity_page_data' : 'entity_container_data';
+        $entityFields['type'] = $type;
+
+        $this->assertThat(
+            $this->getTable('entities'),
+            new HasInDatabase($this->getConnection(null, 'entities'), $entityFields)
+        );
+
+        if (!empty($extraFields)) {
+            $id = $entityFields['id'] ?? DB::table($this->getTable('entities'))
+                ->where($entityFields)->orderByDesc('id')->first()->id ?? null;
+            if (is_null($id)) {
+                throw new Exception('Failed to find entity id for asserting database data');
+            }
+
+            if ($type !== 'page') {
+                $extraFields['entity_id'] = $id;
+                $extraFields['entity_type'] = $type;
+            } else {
+                $extraFields['page_id'] = $id;
+            }
+
+            $this->assertThat(
+                $this->getTable($extraTable),
+                new HasInDatabase($this->getConnection(null, $extraTable), $extraFields)
+            );
+        }
+
+        return $this;
+    }
 }