Skip to content

Instantly share code, notes, and snippets.

@jackrabbithanna
Last active October 23, 2020 23:20
Show Gist options
  • Save jackrabbithanna/a627d24a3da48eed5e988986ab413031 to your computer and use it in GitHub Desktop.
Save jackrabbithanna/a627d24a3da48eed5e988986ab413031 to your computer and use it in GitHub Desktop.
<?php
namespace Drupal\Tests\civicrm_tests\FunctionalJavascript;
use Behat\Mink\Element\NodeElement;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
use Drupal\Core\Database\Database;
/**
* Base class for CiviCRM Functional Javascript Tests
*/
class CivicrmFunctionalJavascriptBase extends WebDriverTestBase {
/**
* The modules to load to run the test.
*
* @var array
*/
public static $modules = [
'system',
'breakpoint',
'user',
'toolbar',
'admin_toolbar',
'libraries',
'civicrm',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'seven';
/**
* CiviCRM settings passed in from the phpunit.xml
*
* @var array
*/
public $civicrm_environment_settings = [];
/**
* @var array
*/
public $drupal_admin_permissions = [
'access administration pages',
'administer site configuration',
'view the administration theme',
'access site reports',
];
public $civicrm_admin_permissions = [
'administer CiviCRM',
'access CiviCRM',
'access AJAX API',
'access all custom data',
];
/**
* Add a single module to the list to install in setUp()
*
* @param $module_name
*/
protected function addInstallModule($module_name) {
if (!in_array($module_name, self::$modules)) {
self::$modules[] = $module_name;
}
}
/**
* Add an array of modules to the list to be installed in setUp()
*
* @param $modules
*/
protected function addInstallModules($modules) {
if (is_array($modules)) {
foreach ($modules as $module_name) {
$this->addInstallModule($module_name);
}
}
}
/**
* Function to nuke every cache I can find
*
* @throws \Exception
*/
protected function cacheNuker() {
// Clear cached metadata.
\Civi::service('settings_manager')->flush();
\CRM_Core_Config::clearDBCache();
// cleanup caches CRM-8739
$config = \CRM_Core_Config::singleton(TRUE, TRUE);
$config->cleanupCaches(1);
\Civi::cache('session')->clear(); // This doesn't make a lot of sense to me, but it maintains pre-existing behavior.
\CRM_Utils_System::flushCache();
\CRM_Core_Resources::singleton()->resetCacheCode();
$parameters['extensionsURL'] = $this->civicrm_environment_settings['settings']['extensionsURL'];
$parameters['extensionsDir'] = $this->civicrm_environment_settings['settings']['extensionsDir'];
$extension_system = new \CRM_Extension_System($parameters);
$extension_system->setSingleton($extension_system);
$extension_system->getCache()->flush();
$config = \CRM_Core_Config::singleton(TRUE, TRUE);
$config->cleanupPermissions();
drupal_flush_all_caches();
\CRM_Core_Invoke::rebuildMenuAndCaches(TRUE);
// clear asset builder folder
\Civi::service('asset_builder')->clear(FALSE);
}
/**
* Clear Drupal and CiviCRM caches via user login to their pages and clicking the clear caches buttons
*
* @throws \Drupal\Core\Entity\EntityStorageException
*/
protected function clearDrupalCivicrmCachesAdminUI() {
$this->clearDrupalCachesViaAdminUI();
$this->clearCivicrmCachesViaAdminUI();
}
/**
* CiviCRM programmatic cache nuking
*/
protected function clearAllCivicrmCaches() {
// Clear cached metadata.
\Civi::service('settings_manager')->flush();
\CRM_Core_Config::clearDBCache();
// cleanup caches CRM-8739
$config = \CRM_Core_Config::singleton(TRUE, TRUE);
$config->cleanupCaches(1);
\Civi::cache('session')->clear(); // This doesn't make a lot of sense to me, but it maintains pre-existing behavior.
\CRM_Utils_System::flushCache();
\CRM_Core_Resources::singleton()->resetCacheCode();
$parameters['extensionsURL'] = $this->civicrm_environment_settings['settings']['extensionsURL'];
$parameters['extensionsDir'] = $this->civicrm_environment_settings['settings']['extensionsDir'];
$extension_system = new \CRM_Extension_System($parameters);
$extension_system->setSingleton($extension_system);
$extension_system->getCache()->flush();
$config = \CRM_Core_Config::singleton(TRUE, TRUE);
$config->cleanupPermissions();
\CRM_Core_Invoke::rebuildMenuAndCaches(TRUE);
// clear asset builder folder
\Civi::service('asset_builder')->clear(FALSE);
}
/**
* Programmatically clear all Drupal caches
*/
public function clearAllDrupalCaches() {
drupal_flush_all_caches();
}
/**
* Set one CiviCRM setting
*
* @param $setting_key
* @param $setting_value
*
* @throws \CiviCRM_API3_Exception
* @throws \Drupal\Core\Entity\EntityStorageException
*/
protected function setCivicrmSettings($settings, $clear_cache = TRUE) {
if (!empty($settings)) {
foreach ($settings as $setting_key => $setting_value)
$result = civicrm_api3('Setting', 'create', [
$setting_key => $setting_value,
]);
// update to more specific cache clearing TBD
//$this->cacheNuker();
if (!empty($clear_cache)) {
\Civi::service('settings_manager')->flush();
$config = \CRM_Core_Config::singleton(TRUE, TRUE);
}
}
}
/**
* Get CiviCRM specific environment variables from phpunit.xml and set settings through API
*
* @throws \CiviCRM_API3_Exception
* @throws \Drupal\Core\Entity\EntityStorageException
*/
protected function setCivicrmEnvironmentSettings() {
// fetch CiviCRM settings from phpunit.xml environment variables
$this->civicrm_environment_settings['settings']['extensionsDir'] = getenv('CIVICRM_EXTENSIONS_DIRECTORY');
$this->civicrm_environment_settings['settings']['extensionsURL'] = getenv('CIVICRM_EXTENSIONS_URL');
$this->civicrm_environment_settings['settings']['userFrameworkResourceURL'] = getenv('CIVICRM_USER_FRAMEWORK_RESOURCE_URL');
$this->civicrm_environment_settings['settings']['assetCache'] = 0;
$this->civicrm_environment_settings['settings']['verifySSL'] = 0;
foreach ($this->civicrm_environment_settings['settings'] as $setting_key => $setting_value) {
if (!empty($setting_value)) {
$result = civicrm_api3('Setting', 'create', [
$setting_key => $setting_value,
]);
}
}
$this->civicrm_environment_settings['civicrm.root']['url'] = getenv('CIVICRM_CRM_ROOT_URL');
$this->civicrm_environment_settings['civicrm.root']['path'] = getenv('CIVICRM_CRM_ROOT_PATH');
$this->civicrm_environment_settings['cms.root']['url'] = getenv('CIVICRM_CMS_ROOT_URL');
$this->civicrm_environment_settings['cms.root']['path'] = getenv('CIVICRM_CMS_ROOT_PATH');
if (!empty($this->civicrm_environment_settings['cms.root']['path']) && file_exists($this->civicrm_environment_settings['cms.root']['path'] . \Drupal::service('kernel')->getSitePath() . '/civicrm.settings.php')) {
$civicrm_paths['civicrm.root']['url'] = !empty($this->civicrm_environment_settings['civicrm.root']['url']) ? $this->civicrm_environment_settings['civicrm.root']['url'] : '';
$civicrm_paths['civicrm.root']['path'] = !empty($this->civicrm_environment_settings['civicrm.root']['path']) ? $this->civicrm_environment_settings['civicrm.root']['path'] : '';
$civicrm_paths['cms.root']['url'] = !empty($this->civicrm_environment_settings['cms.root']['url']) ? $this->civicrm_environment_settings['cms.root']['url'] : '';
$civicrm_paths['cms.root']['path'] = !empty($this->civicrm_environment_settings['cms.root']['path']) ? $this->civicrm_environment_settings['cms.root']['path'] : '';
$civicrm_paths_tokens = '
$civicrm_paths["civicrm.root"] = array(
"url" => "' . $civicrm_paths['civicrm.root']['url'] . '",
"path" => "' . $civicrm_paths['civicrm.root']['path'] . '",
);
$civicrm_paths["cms.root"] = array(
"url" => "' . $civicrm_paths['cms.root']['url'] . '",
"path" => "' . $civicrm_paths['cms.root']['path'] . '",
);
$civicrm_paths["civicrm.files"] = array(
"url" => "' . $this->civicrm_environment_settings['cms.root']['url'] . \Drupal::service('kernel')->getSitePath() . '/files/civicrm/",
"path" => "' . $this->civicrm_environment_settings['cms.root']['path'] . \Drupal::service('kernel')->getSitePath() . '/files/civicrm/",
);
';
$file_result = file_put_contents ($this->civicrm_environment_settings['cms.root']['path'] . \Drupal::service('kernel')->getSitePath() . '/civicrm.settings.php', $civicrm_paths_tokens, FILE_APPEND);
/*
if ($file_result !== FALSE) {
fwrite(STDERR, "\nDrupal site path2: " . print_r(\Drupal::service('kernel')->getSitePath(), TRUE) . "\n");
}
*/
}
global $civicrm_paths;
if (!empty($this->civicrm_environment_settings['civicrm.root']['url'])) {
$civicrm_paths['civicrm.root']['url'] = $this->civicrm_environment_settings['civicrm.root']['url'];
}
if (!empty($this->civicrm_environment_settings['civicrm.root']['path'])) {
$civicrm_paths['civicrm.root']['path'] = $this->civicrm_environment_settings['civicrm.root']['path'];
}
if (!empty($this->civicrm_environment_settings['cms.root']['url'])) {
$civicrm_paths['cms.root']['url'] = $this->civicrm_environment_settings['cms.root']['url'];
}
if (!empty($this->civicrm_environment_settings['cms.root']['path'])) {
$civicrm_paths['cms.root']['path'] = $this->civicrm_environment_settings['cms.root']['path'];
}
//$this->cacheNuker();
$config = \CRM_Core_Config::singleton(TRUE, TRUE);
}
/**
* Override of UserCreationTrait checkPermissions()
*
* this throws an error if the fail() call runs, if try to create admin user with permission provided by CiviCRM Extension installed in test run
*
* @param array $permissions
*
* @return bool
*/
protected function checkPermissions(array $permissions) {
$available = array_keys(\Drupal::service('user.permissions')
->getPermissions());
$valid = TRUE;
/*
foreach ($permissions as $permission) {
if (!in_array($permission, $available)) {
$this
->fail(new FormattableMarkup('Invalid permission %permission.', [
'%permission' => $permission,
]), 'Role');
$valid = FALSE;
}
}*/
return $valid;
}
/**
* Install CiviCRM Extensions programmatically
*
* @param $civicrm_extension_keys
*
* @throws \CRM_Extension_Exception
* @throws \Drupal\Core\Entity\EntityStorageException
*/
protected function installCivicrmExtensions($civicrm_extension_keys) {
if (!empty($civicrm_extension_keys)) {
if (!is_array($civicrm_extension_keys)) {
$civicrm_extension_keys = [$civicrm_extension_keys];
}
foreach ($civicrm_extension_keys as $key) {
$parameters['extensionsURL'] = $this->civicrm_environment_settings['settings']['extensionsURL'];
$parameters['extensionsDir'] = $this->civicrm_environment_settings['settings']['extensionsDir'];
$extension_system = new \CRM_Extension_System($parameters);
$extension_system->getCache()->flush();
$manager = $extension_system->getManager();
$manager->install($manager->findInstallRequirements([$key]));
$extension_system->setSingleton($extension_system);
$extension_system->getCache()->flush();
$config = \CRM_Core_Config::singleton();
$config->clearModuleList();
$this->clearAllDrupalCaches();
$extension_upgrader = new \CRM_Extension_Upgrades();
if ($extension_upgrader->hasPending()) {
$upgrade_queue = $extension_upgrader->createQueue();
if (!empty($upgrade_queue)) {
$queueRunner = new \CRM_Queue_Runner([
'title' => ts('CiviCRM Upgrade Tasks'),
'queue' => $upgrade_queue,
]);
$queueResult = $queueRunner->runAll();
// Clear cached metadata.
\Civi::service('settings_manager')->flush();
// cleanup caches CRM-8739
$config = \CRM_Core_Config::singleton();
$config->cleanupCaches(1);
// Rebuild all triggers and re-enable logging if needed
$logging = new \CRM_Logging_Schema();
$logging->fixSchemaDifferences();
}
}
}
}
}
/**
* Shoreditch extension installation plus setting customCSSURL CiviCRM setting to use it's css file
*
* @throws \CRM_Extension_Exception
* @throws \CiviCRM_API3_Exception
* @throws \Drupal\Core\Entity\EntityStorageException
*/
protected function installShoreditchExtension() {
$this->installCivicrmExtensions('org.civicrm.shoreditch');
$this->setCivicrmSettings(['customCSSURL' => $this->civicrm_environment_settings['settings']['extensionsURL'] . 'org.civicrm.shoreditch/css/custom-civicrm.css',]);
}
/**
* Clear all caches via 'admin/config/development/performance' button
*
* @throws \Drupal\Core\Entity\EntityStorageException
*/
protected function clearDrupalCachesViaAdminUI() {
$admin_user = $this->drupalCreateUser([
'administer site configuration',
'access administration pages',
]);
$this->drupalLogin($admin_user);
$this->drupalGet('admin/config/development/performance');
$session = $this->getSession();
$page = $session->getPage();
$button = $page->findButton('Clear all caches');
$button->click();
$this->drupalLogout();
}
/**
* Clear CiviCRM Caches via Admin UI
*
* @throws \Drupal\Core\Entity\EntityStorageException
*/
protected function clearCivicrmCachesViaAdminUI() {
$admin_user = $this->drupalCreateUser([
'administer CiviCRM',
'access CiviCRM',
]);
$this->drupalLogin($admin_user);
$this->drupalGet('civicrm/admin/setting/updateConfigBackend', ['query' => ['reset' => 1]]);
$session = $this->getSession();
$page = $session->getPage();
$button = $page->findButton('Cleanup Caches');
$button->click();
$this->drupalLogout();
}
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->setCivicrmEnvironmentSettings();
/*$config = \CRM_Core_Config::singleton();
$parameters = [];
$parameters['extensionsDir'] = \CRM_Utils_Array::value('extensionsDir', $parameters, $config->extensionsDir);
$parameters['extensionsURL'] = \CRM_Utils_Array::value('extensionsURL', $parameters, $config->extensionsURL);
$parameters['resourceBase'] = \CRM_Utils_Array::value('resourceBase', $parameters, $config->resourceBase);
$parameters['uploadDir'] = \CRM_Utils_Array::value('uploadDir', $parameters, $config->uploadDir);
$parameters['userFrameworkBaseURL'] = \CRM_Utils_Array::value('userFrameworkBaseURL', $parameters, $config->userFrameworkBaseURL);
fwrite(STDERR, "\nConfig parameters: " . print_r($parameters, TRUE) . "\n"); */
}
/**
* {@inheritdoc}
*/
protected function tearDown() {
$conn = Database::getConnection('default', 'civicrm_test');
$database = $conn->getConnectionOptions()['database'];
$conn->query("SET FOREIGN_KEY_CHECKS = 0");
$tables = $conn->query('SHOW TABLES')->fetchAll();
foreach ($tables as $table_result) {
$table = $table_result->{"Tables_in_$database"};
$conn->query("DROP TABLE $table");
}
$conn->query("SET FOREIGN_KEY_CHECKS = 1");
$conn->destroy();
parent::tearDown();
}
/**
* Removes any non-visible elements from the passed array.
*
* @param \Behat\Mink\Element\NodeElement[] $elements
* An array of node elements.
*
* @return \Behat\Mink\Element\NodeElement[]
*/
protected function filterVisibleElements(array $elements) {
$elements = array_filter($elements, function (NodeElement $element) {
return $element->isVisible();
});
return $elements;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment