]> BookStack Code Mirror - system-cli/blob - tests/TestCase.php
Added test case for mysql usage with special chars
[system-cli] / tests / TestCase.php
1 <?php
2
3 namespace Tests;
4
5 use Symfony\Component\Console\Application;
6 use Symfony\Component\Console\Tester\CommandTester;
7
8 class TestCase extends \PHPUnit\Framework\TestCase
9 {
10     /**
11      * Reset the current working directory to the application directory.
12      */
13     protected function resetCurrentDirectory(): void
14     {
15         chdir(dirname(__DIR__));
16     }
17
18     protected function getTestDataDirectory(): string
19     {
20         return dirname(__DIR__) . DIRECTORY_SEPARATOR . 'test-data';
21     }
22
23     protected function getEmptyTestDir(): string
24     {
25         $dir = $this->getTestDataDirectory() . DIRECTORY_SEPARATOR . bin2hex(random_bytes(10));
26         mkdir($dir);
27         return $dir;
28     }
29
30     protected function deleteDirectory(string $dir): void
31     {
32         // For safety, only delete directories within our test data dir.
33         if (!str_starts_with($dir, $this->getTestDataDirectory())) {
34             return;
35         }
36
37         $files = array_diff(scandir($dir), ['.', '..']);
38
39         foreach ($files as $file) {
40             (is_dir("$dir/$file")) ? $this->deleteDirectory("$dir/$file") : unlink("$dir/$file");
41         }
42
43         rmdir($dir);
44     }
45
46     protected function getApp(): Application
47     {
48         return require dirname(__DIR__) . '/src/app.php';
49     }
50
51     protected function runCommand(string $command, array $args = [], array $inputs = [], array $env = []): CommandResult
52     {
53         $app = $this->getApp();
54         $command = $app->find($command);
55
56         $err = null;
57         $commandTester = new CommandTester($command);
58
59         if (!empty($inputs)) {
60             $commandTester->setInputs($inputs);
61         }
62
63         foreach ($env as $name => $value) {
64             $_SERVER[$name] = $value;
65         }
66
67         try {
68             $commandTester->execute($args);
69         } catch (\Exception $exception) {
70             $err = $exception;
71         }
72
73         foreach ($env as $name => $value) {
74             unset($_SERVER[$name]);
75         }
76
77         return new CommandResult($commandTester, $err);
78     }
79
80     /**
81      * Create a clone of a BookStack install folder, then pass that path
82      * and run the given callback.
83      * Destroys the folder afterwards.
84      */
85     protected function withOwnBookStackFolder(callable $callback)
86     {
87         $path = '/var/www/bookstack-' . md5(random_bytes(5));
88         exec("cp -r /var/www/bookstack $path");
89         chdir($path);
90         $callback($path);
91         exec("rm -rf $path");
92     }
93 }