Drupal 8: Functional tests with SQLite databases

Submitted by Peter Majmesku on Sat, 02/17/2018 - 23:56

Using a SQlite database makes testing faster than with a DBMS like MySQL. Because the database is contained in just 1 file. Make sure that Drupal is not using your default database connection from the settings.php file. 

A simple solution is to check the HTTP_USER_AGRENT. E.g.:

if ($_SERVER['HTTP_USER_AGENT'] !== 'Drupal command line') {

  
$databases['default']['default'] = array (
    
'database' => 'MY-DATABASE',
    
'username' => 'root',
    
'password' => 'root',
    
'prefix' => '',
    
'host' => '127.0.0.1',
    
'port' => '',
    
'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
    
'driver' => 'mysql',
    
'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
  );

In your phpunit.xml file specify your SQLite database connection (the file do not must exist before):

<env name="SIMPLETEST_DB" value="sqlite://localhost/sites/default/files/db.sqlite"/> 

Otherwise you get errors like this:

Exception: PDOException: SQLSTATE[HY000] [2002] Connection refused

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.