diff --git a/src/Codeception/Module/DrupalUser.php b/src/Codeception/Module/DrupalUser.php index e81e384..a54c234 100644 --- a/src/Codeception/Module/DrupalUser.php +++ b/src/Codeception/Module/DrupalUser.php @@ -3,8 +3,10 @@ namespace Codeception\Module; use Codeception\Module; +use Drupal\Core\Config\StorageInterface; use Drupal\Core\Entity\EntityStorageInterface; use Drupal\user\Entity\User; +use Codeception\Util\Drush; use Faker\Factory; /** @@ -42,12 +44,22 @@ class DrupalUser extends Module { */ protected $users; + /** + * Flag to note whether the CLI should be used for user actions. + * + * @var bool + */ + protected $useCli = FALSE; + /** * Default module configuration. * * @var array */ protected $config = [ + 'alias' => '', + 'driver' => NULL, + 'drush' => 'drush', 'default_role' => 'authenticated', 'cleanup_entities' => [], 'cleanup_test' => TRUE, @@ -55,6 +67,19 @@ class DrupalUser extends Module { 'cleanup_suite' => TRUE, ]; + /** + * {@inheritdoc} + */ + public function _beforeSuite($settings = []) { // @codingStandardsIgnoreLine + $this->driver = null; + if (!$this->hasModule($this->_getConfig('driver'))) { + $this->useCli = TRUE; + } + else { + $this->driver = $this->getModule($this->_getConfig('driver')); + } + } + /** * {@inheritdoc} */ @@ -109,7 +134,8 @@ public function createUserWithRoles(array $roles = [], $password = FALSE) { $this->users[] = $user->id(); } catch (\Exception $e) { - $this->fail('Could not create user with roles' . implode(', ', $roles)); + $message = sprintf('Could not create user with roles: %s. Error: %s', implode(', ', $roles), $e->getMessage()); + $this->fail($message); } return $user; @@ -124,15 +150,24 @@ public function createUserWithRoles(array $roles = [], $password = FALSE) { public function logInAs($username) { /** @var \Drupal\user\Entity\User $user */ try { - // Load the user. - $account = user_load_by_name($username); + if ($this->useCli) { + // Load the user. + $account = user_load_by_name($username); - if (FALSE === $account ) { - throw new \Exception(); - } + if (FALSE === $account ) { + throw new \Exception(); + } - // Login with the user. - user_login_finalize($account); + // Login with the user. + user_login_finalize($account); + } + else { + $alias = $this->_getConfig('alias') ? $this->_getConfig('alias') . ' ' : ''; + $output = Drush::runDrush($alias. 'uli --name=' . $username, $this->_getConfig('drush'), $this->_getConfig('working_directory')); + $gen_url = str_replace(PHP_EOL, '', $output); + $url = substr($gen_url, strpos($gen_url, '/user/reset')); + $this->driver->amOnPage($url); + } } catch (\Exception $e) { $this->fail('Coud not login with username ' . $username);