Merge pull request #6703 from tobiasd/2019.03-CHANGELOG
[friendica.git/.git] / tests / DatabaseTest.php
1 <?php
2 /**
3  * DatabaseTest class.
4  */
5
6 namespace Friendica\Test;
7
8 use Friendica\Core\Config\Cache;
9 use Friendica\Database\DBA;
10 use Friendica\Factory;
11 use Friendica\Util\BasePath;
12 use Friendica\Util\Profiler;
13 use PHPUnit\DbUnit\DataSet\YamlDataSet;
14 use PHPUnit\DbUnit\TestCaseTrait;
15 use PHPUnit_Extensions_Database_DB_IDatabaseConnection;
16
17 require_once __DIR__ . '/../boot.php';
18
19 /**
20  * Abstract class used by tests that need a database.
21  */
22 abstract class DatabaseTest extends MockedTest
23 {
24         use TestCaseTrait;
25
26         /**
27          * Get database connection.
28          *
29          * This function is executed before each test in order to get a database connection that can be used by tests.
30          * If no prior connection is available, it tries to create one using the USER, PASS and DB environment variables.
31          *
32          * If it could not connect to the database, the test is skipped.
33          *
34          * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection
35          * @see https://phpunit.de/manual/5.7/en/database.html
36          */
37         protected function getConnection()
38         {
39                 if (!getenv('MYSQL_DATABASE')) {
40                         $this->markTestSkipped('Please set the MYSQL_* environment variables to your test database credentials.');
41                 }
42
43                 $basePath = BasePath::create(dirname(__DIR__));
44                 $configLoader = new Cache\ConfigCacheLoader($basePath);
45                 $config = Factory\ConfigFactory::createCache($configLoader);
46
47                 $profiler = \Mockery::mock(Profiler::class);
48
49                 DBA::connect(
50                         $basePath,
51                         $config,
52                         $profiler,
53                         getenv('MYSQL_HOST'),
54                         getenv('MYSQL_USERNAME'),
55                         getenv('MYSQL_PASSWORD'),
56                         getenv('MYSQL_DATABASE'));
57
58                 if (!DBA::connected()) {
59                         $this->markTestSkipped('Could not connect to the database.');
60                 }
61
62                 return $this->createDefaultDBConnection(DBA::getConnection(), getenv('MYSQL_DATABASE'));
63         }
64
65         /**
66          * Get dataset to populate the database with.
67          * @return YamlDataSet
68          * @see https://phpunit.de/manual/5.7/en/database.html
69          */
70         protected function getDataSet()
71         {
72                 return new YamlDataSet(__DIR__ . '/datasets/api.yml');
73         }
74 }