class BackdropWebTestCase extends BackdropTestCase {
protected $profile = 'standard';
protected $url;
protected $curlHandle;
protected $headers;
protected $content;
protected $plainTextContent;
protected $backdropSettings;
protected $elements = NULL;
protected $loggedInUser = FALSE;
protected $cookieFile = NULL;
protected $cookies = array();
protected $additionalCurlOptions = array();
protected $originalUser = NULL;
protected $originalSettings = NULL;
protected $originalProfile;
protected $originalCleanUrl;
protected $originalShutdownCallbacks = array();
protected $session_name = NULL;
protected $session_id = NULL;
protected $generatedTestFiles = array();
protected $maximumRedirects = 5;
protected $redirect_count;
public $public_files_directory;
public $private_files_directory;
public $temp_files_directory;
protected $originalLanguage;
protected $originalLanguageUrl;
function __construct($test_id = NULL) {
parent::__construct($test_id);
$this->skipClasses[__CLASS__] = TRUE;
}
function backdropGetNodeByTitle($title, $reset = FALSE) {
$nodes = node_load_multiple(array(), array('title' => $title), $reset);
$returned_node = reset($nodes);
return $returned_node;
}
protected function backdropCreateNode($settings = array()) {
$settings += array(
'body' => array(LANGUAGE_NONE => array(array())),
'title' => $this->randomName(8),
'comment' => 2,
'changed' => REQUEST_TIME,
'moderate' => 0,
'promote' => 0,
'revision' => 1,
'log' => '',
'status' => 1,
'sticky' => 0,
'type' => 'page',
'revisions' => NULL,
'langcode' => LANGUAGE_NONE,
);
if (isset($settings['created']) && !isset($settings['date'])) {
$settings['date'] = format_date($settings['created'], 'custom', 'Y-m-d H:i:s O');
}
if (!isset($settings['uid'])) {
if ($this->loggedInUser) {
$settings['uid'] = $this->loggedInUser->uid;
}
else {
global $user;
$settings['uid'] = $user->uid;
}
}
$body = array(
'value' => $this->randomName(32),
'format' => filter_default_format(),
);
$settings['body'][$settings['langcode']][0] += $body;
$node = new Node($settings);
$node->save();
db_update('node_revision')
->fields(array('uid' => $node->uid))
->condition('vid', $node->vid)
->execute();
return $node;
}
protected function backdropCreateContentType($settings = array()) {
do {
$name = strtolower($this->randomName(8));
} while (node_type_get_type($name));
$defaults = array(
'type' => $name,
'name' => $name,
'base' => 'node_content',
'description' => '',
'help' => '',
'title_label' => 'Title',
'has_title' => 1,
'is_new' => TRUE,
);
$forced = array(
'orig_type' => '',
'old_type' => '',
'module' => 'node',
'custom' => 1,
'modified' => 1,
'locked' => 0,
);
$type = $forced + $settings + $defaults;
$type = (object) $type;
$saved_type = node_type_save($type);
menu_rebuild();
node_add_body_field($type);
$this->assertEqual($saved_type, SAVED_NEW, t('Created content type %type.', array('%type' => $type->type)));
$this->checkPermissions(array(), TRUE);
return $type;
}
protected function backdropGetTestFiles($type, $size = NULL) {
$files = array();
$possible_types = array('binary', 'html', 'image', 'svg', 'javascript', 'php', 'sql', 'text');
if (in_array($type, $possible_types)) {
if (!in_array($type, $this->generatedTestFiles)) {
switch ($type) {
case 'binary':
$lines = array(64, 1024);
$count = 0;
foreach ($lines as $line) {
simpletest_generate_file('binary-' . $count++, 64, $line, 'binary');
}
$this->generatedTestFiles[] = 'binary';
break;
case 'text':
$lines = array(16, 256, 1024, 2048, 20480);
$count = 0;
foreach ($lines as $line) {
simpletest_generate_file('text-' . $count++, 64, $line, 'text');
}
$this->generatedTestFiles[] = 'text';
break;
default:
$original = backdrop_get_path('module', 'simpletest') . '/files';
$files = file_scan_directory($original, '/' . $type . '-.*/');
foreach ($files as $file) {
file_unmanaged_copy($file->uri, config_get('system.core', 'file_public_path'));
}
$this->generatedTestFiles[] = $type;
break;
}
}
$files = file_scan_directory('public://', '/' . $type . '\-.*/');
if ($size !== NULL) {
foreach ($files as $file) {
$stats = stat($file->uri);
if ($stats['size'] != $size) {
unset($files[$file->uri]);
}
}
}
}
usort($files, array($this, 'backdropCompareFiles'));
return $files;
}
protected function backdropCompareFiles($file1, $file2) {
$compare_size = filesize($file1->uri) - filesize($file2->uri);
if ($compare_size) {
return $compare_size;
}
else {
return strnatcmp($file1->name, $file2->name);
}
}
protected function backdropCreateUser(array $permissions = array()) {
$role_name = FALSE;
if ($permissions) {
$role_name = $this->backdropCreateRole($permissions);
if (!$role_name) {
return FALSE;
}
}
$edit = array();
$edit['name'] = $this->randomName();
$edit['mail'] = $edit['name'] . '@example.com';
$edit['pass'] = user_password();
$edit['status'] = 1;
if ($role_name) {
$edit['roles'] = array($role_name);
}
$account = entity_create('user', $edit);
$account->save();
$this->assertTrue(!empty($account->uid), t('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), t('User login'));
if (empty($account->uid)) {
return FALSE;
}
$account->pass_raw = $edit['pass'];
return $account;
}
protected function backdropCreateRole(array $permissions, $name = NULL) {
if (!$name) {
$name = $this->randomName();
}
if (!$this->checkPermissions($permissions)) {
return FALSE;
}
$role = new stdClass();
$role->name = $name;
$role->label = $name;
user_role_save($role);
user_role_grant_permissions($role->name, $permissions);
$role = user_role_load($role->name);
$this->assertTrue(isset($role->name), t('Created role of name: @name', array('@name' => $name)), t('Role'));
if ($role && !empty($role->name)) {
$this->assertTrue(count($role->permissions) == count($permissions), t('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), t('Role'));
return $role->name;
}
else {
return FALSE;
}
}
protected function checkPermissions(array $permissions, $reset = FALSE) {
$available = &backdrop_static(__FUNCTION__);
if (!isset($available) || $reset) {
$available = array_keys(module_invoke_all('permission'));
}
$valid = TRUE;
foreach ($permissions as $permission) {
if (!in_array($permission, $available)) {
$this->fail(t('Invalid permission %permission.', array('%permission' => $permission)), t('Role'));
$valid = FALSE;
}
}
return $valid;
}
protected function backdropLogin(User $account, $by_email = FALSE) {
global $user;
if ($this->loggedInUser) {
$this->backdropLogout();
}
elseif ($user->uid) {
$this->backdropLogout();
}
$edit = array(
'name' => $by_email ? $account->mail : $account->name,
'pass' => $account->pass_raw
);
$this->backdropPost('user/login', $edit, t('Log in'));
$result = $this->xpath('/html/body[contains(@class, "logged-in")]');
$pass = $this->assertEqual(count($result), 1, t('User %name successfully logged in.', array('%name' => $account->name)), t('User login'));
if ($pass) {
$this->loggedInUser = $account;
}
}
protected function backdropGetToken($value = '') {
return backdrop_hmac_base64($value, $this->session_id . backdrop_get_private_key() . backdrop_get_hash_salt());
}
protected function backdropLogout() {
$this->backdropGet('user/logout');
$this->backdropGet('user');
$pass = $this->assertField('name', t('Username field found.'), t('Logout'));
$pass = $pass && $this->assertField('pass', t('Password field found.'), t('Logout'));
if ($pass) {
$this->loggedInUser = FALSE;
}
}
protected function changeDatabasePrefix() {
if (empty($this->databasePrefix)) {
$this->prepareDatabasePrefix();
if (empty($this->databasePrefix)) {
return;
}
}
$connection_info = Database::getConnectionInfo('default');
Database::renameConnection('default', 'simpletest_original_default');
foreach ($connection_info as $target => $value) {
$connection_info[$target]['prefix'] = array(
'default' => $value['prefix']['default'] . $this->databasePrefix,
);
}
Database::addConnectionInfo('default', 'default', $connection_info['default']);
$this->setupDatabasePrefix = TRUE;
}
protected function prepareEnvironment() {
global $user, $language, $language_url, $settings, $config_directories;
$site_config = config('system.core');
$this->originalLanguage = $language;
$this->originalLanguageUrl = $language_url;
$this->originalConfigDirectories = $config_directories;
$this->originalFileDirectory = $site_config->get('file_public_path');
$this->verboseDirectoryUrl = file_create_url($this->originalFileDirectory . '/simpletest/verbose');
$this->originalProfile = backdrop_get_profile();
$this->originalCleanUrl = $site_config->get('clean_url');
$this->originalUser = $user;
$this->originalSettings = $settings;
$language_url = $language = (object) array(
'langcode' => 'en',
'name' => 'English',
'enabled' => 1,
'weight' => 0,
);
$callbacks = &backdrop_register_shutdown_function();
$this->originalShutdownCallbacks = $callbacks;
$callbacks = array();
$this->public_files_directory = $this->originalFileDirectory . '/simpletest/' . $this->fileDirectoryName;
$this->private_files_directory = $this->public_files_directory . '/private';
$this->temp_files_directory = $this->private_files_directory . '/temp';
file_prepare_directory($this->public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
file_prepare_directory($this->private_files_directory, FILE_CREATE_DIRECTORY);
file_prepare_directory($this->temp_files_directory, FILE_CREATE_DIRECTORY);
$this->generatedTestFiles = array();
$config_base_path = 'files/simpletest/' . $this->fileDirectoryName . '/config_';
$config_directories['active'] = $config_base_path . 'active';
$config_directories['staging'] = $config_base_path . 'staging';
ini_set('log_errors', 1);
ini_set('error_log', $this->public_files_directory . '/error.log');
$test_info = &$GLOBALS['backdrop_test_info'];
$test_info['test_run_id'] = $this->databasePrefix;
$test_info['in_child_site'] = FALSE;
$settings['backdrop_drupal_compatibility'] = FALSE;
$this->setupEnvironment = TRUE;
}
protected function useCache() {
$config_cache_dir = $this->originalFileDirectory . '/simpletest/simpletest_cache_' . $this->profile;
if (is_dir($config_cache_dir)) {
$prefix = 'simpletest_cache_' . $this->profile . '_';
$tables = db_query("SHOW TABLES LIKE :prefix", array(':prefix' => db_like($prefix) . '%'))->fetchCol();
foreach ($tables as $table_prefix) {
$table = substr($table_prefix, strlen($prefix));
db_query('CREATE TABLE ' . $this->databasePrefix . $table . ' LIKE ' . $table_prefix);
db_query('INSERT ' . $this->databasePrefix . $table . ' SELECT * FROM ' . $table_prefix);
}
$this->recursiveCopy($config_cache_dir, $this->public_files_directory);
return TRUE;
}
return FALSE;
}
private function recursiveCopy($src, $dst) {
$dir = opendir($src);
if (!file_exists($dst)) {
mkdir($dst);
}
while (FALSE !== ($file = readdir($dir))) {
if ($file != '.' && $file != '..' && $file != '.htaccess') {
if (is_dir($src . '/' . $file)) {
$this->recursiveCopy($src . '/' . $file, $dst . '/' . $file);
}
else {
copy($src . '/' . $file, $dst . '/' . $file);
}
}
}
closedir($dir);
}
protected function setUp() {
global $user, $language, $language_url, $conf;
$this->prepareDatabasePrefix();
$this->prepareEnvironment();
if (!$this->setupEnvironment) {
return FALSE;
}
$conf = array();
backdrop_static_reset();
$this->changeDatabasePrefix();
if (!$this->setupDatabasePrefix) {
return FALSE;
}
$use_cache = $this->useCache();
if (!$use_cache) {
config_get_config_storage('active')->initializeStorage();
config_get_config_storage('staging')->initializeStorage();
}
config_install_default_config('system');
config_set('system.core', 'install_profile', $this->profile);
if (!$use_cache) {
include_once BACKDROP_ROOT . '/core/includes/install.inc';
backdrop_install_system();
$core_config = config('system.core');
$core_config->set('file_default_scheme', 'public');
$core_config->set('file_public_path', $this->public_files_directory);
$core_config->set('file_private_path', $this->private_files_directory);
$core_config->set('file_temporary_path', $this->temp_files_directory);
$core_config->save();
backdrop_static_reset('backdrop_get_schema_versions');
config_set('system.core', 'install_profile', $this->profile);
$profile_details = install_profile_info($this->profile, 'en');
module_enable($profile_details['dependencies'], FALSE);
$install_profile_module_exists = db_query("SELECT 1 FROM {system} WHERE type = 'module' AND name = :name", array(':name' => $this->profile))->fetchField();
if ($install_profile_module_exists) {
module_enable(array($this->profile), FALSE);
}
}
else {
$core_config = config('system.core');
$core_config->set('file_default_scheme', 'public');
$core_config->set('file_public_path', $this->public_files_directory);
$core_config->set('file_private_path', $this->private_files_directory);
$core_config->set('file_temporary_path', $this->temp_files_directory);
$core_config->save();
}
config_set('simpletest.settings', 'parent_profile', $this->originalProfile);
$modules = func_get_args();
if (isset($modules[0]) && is_array($modules[0])) {
$modules = $modules[0];
}
if ($modules) {
$success = module_enable($modules, TRUE);
$this->assertTrue($success, t('Enabled modules: %modules', array('%modules' => implode(', ', $modules))));
}
$this->resetAll();
backdrop_save_session(FALSE);
$user = user_load(1);
state_set('install_task', 'done');
config_set('system.core', 'clean_url', $this->originalCleanUrl);
config_set('system.core', 'site_mail', 'simpletest@example.com');
config_set('system.date', 'date_default_timezone', date_default_timezone_get());
backdrop_static_reset('url');
unset($conf['language_default']);
$language_url = $language = language_default();
config_set('system.mail', 'default-system', 'TestingMailSystem');
$dashboard_config = config('dashboard.settings');
if (!$dashboard_config->isNew()) {
$dashboard_config->set('news_feed_url', FALSE);
$dashboard_config->save();
}
backdrop_cron_run();
backdrop_set_time_limit($this->timeLimit);
$this->setup = TRUE;
return TRUE;
}
protected function resetAll() {
backdrop_static_reset();
module_list(TRUE);
backdrop_get_schema(NULL, TRUE);
backdrop_flush_all_caches();
$this->refreshVariables();
$this->checkPermissions(array(), TRUE);
}
protected function refreshVariables() {
global $conf;
cache('bootstrap')->delete('variables');
$conf = variable_initialize();
backdrop_static_reset('states');
backdrop_static_reset('config');
}
protected function tearDown() {
global $user, $language, $language_url, $settings, $config_directories;
simpletest_log_read($this->testId, $this->databasePrefix, get_class($this), TRUE);
$emailCount = count(state_get('test_email_collector', array()));
if ($emailCount) {
$message = format_plural($emailCount, '1 email was sent during this test.', '@count emails were sent during this test.');
$this->pass($message, t('Email'));
}
backdrop_static_reset();
file_unmanaged_delete_recursive($this->originalFileDirectory . '/simpletest/' . $this->fileDirectoryName);
$connection_info = Database::getConnectionInfo('default');
$tables = db_find_tables($connection_info['default']['prefix']['default'] . '%');
if (empty($tables)) {
$this->fail('Failed to find test tables to drop.');
}
$prefix_length = strlen($connection_info['default']['prefix']['default']);
foreach ($tables as $table) {
if (db_drop_table(substr($table, $prefix_length))) {
unset($tables[$table]);
}
}
if (!empty($tables)) {
$this->fail('Failed to drop all prefixed tables.');
}
$close = \PHP_VERSION_ID < 80000;
Database::removeConnection('default', $close);
Database::renameConnection('simpletest_original_default', 'default');
db_delete('simpletest_prefix')
->condition('test_id', $this->testId)
->condition('prefix', $this->databasePrefix)
->execute();
$config_directories = $this->originalConfigDirectories;
$settings = $this->originalSettings;
$callbacks = &backdrop_register_shutdown_function();
$callbacks = $this->originalShutdownCallbacks;
$user = $this->originalUser;
backdrop_save_session(TRUE);
$this->loggedInUser = FALSE;
$this->additionalCurlOptions = array();
module_list(TRUE);
module_implements_reset();
$this->refreshVariables();
$language = $this->originalLanguage;
$language_url = $this->originalLanguageUrl;
$this->curlClose();
$this->cookies = array();
}
protected function curlInitialize() {
global $base_url;
if (!isset($this->curlHandle)) {
$this->curlHandle = curl_init();
if (empty($this->cookieFile)) {
$this->cookieFile = $this->public_files_directory . '/cookie.jar';
}
$curl_options = array(
CURLOPT_COOKIEJAR => $this->cookieFile,
CURLOPT_URL => $base_url,
CURLOPT_FOLLOWLOCATION => FALSE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYPEER => FALSE, CURLOPT_SSL_VERIFYHOST => FALSE, CURLOPT_HEADERFUNCTION => array(&$this, 'curlHeaderCallback'),
CURLOPT_USERAGENT => $this->databasePrefix,
);
if (isset($this->httpauth_credentials)) {
$curl_options[CURLOPT_HTTPAUTH] = $this->httpauth_method;
$curl_options[CURLOPT_USERPWD] = $this->httpauth_credentials;
}
$result = curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
if (!$result) {
throw new Exception('One or more cURL options could not be set.');
}
$this->session_name = session_name();
}
if (preg_match('/simpletest\d+/', $this->databasePrefix, $matches)) {
curl_setopt($this->curlHandle, CURLOPT_USERAGENT, backdrop_generate_test_ua($matches[0]));
}
}
protected function curlExec($curl_options, $redirect = FALSE) {
$this->curlInitialize();
if (!empty($curl_options[CURLOPT_URL]) && strpos($curl_options[CURLOPT_URL], '#')) {
$original_url = $curl_options[CURLOPT_URL];
$curl_options[CURLOPT_URL] = strtok($curl_options[CURLOPT_URL], '#');
}
$url = empty($curl_options[CURLOPT_URL]) ? curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL) : $curl_options[CURLOPT_URL];
if (!empty($curl_options[CURLOPT_POST])) {
$curl_options[CURLOPT_HTTPHEADER][] = 'Expect:';
}
curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
if (!$redirect) {
$this->session_id = NULL;
$this->headers = array();
$this->redirect_count = 0;
}
$content = curl_exec($this->curlHandle);
$status = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
if (in_array($status, array(300, 301, 302, 303, 305, 307)) && $this->redirect_count < $this->maximumRedirects) {
if ($this->backdropGetHeader('location')) {
$this->redirect_count++;
$curl_options = array();
$curl_options[CURLOPT_URL] = $this->backdropGetHeader('location');
$curl_options[CURLOPT_HTTPGET] = TRUE;
return $this->curlExec($curl_options, TRUE);
}
}
$this->backdropSetContent($content, isset($original_url) ? $original_url : curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL));
$message_vars = array(
'!method' => !empty($curl_options[CURLOPT_NOBODY]) ? 'HEAD' : (empty($curl_options[CURLOPT_POSTFIELDS]) ? 'GET' : 'POST'),
'@url' => isset($original_url) ? $original_url : $url,
'@status' => $status,
'!length' => format_size(strlen($this->backdropGetContent()))
);
$message = t('!method @url returned @status (!length).', $message_vars);
$this->assertTrue($this->backdropGetContent() !== FALSE, $message, t('Browser'));
return $this->backdropGetContent();
}
protected function curlHeaderCallback($curlHandler, $header) {
if ($header[0] == ' ' || $header[0] == "\t") {
$this->headers[] = array_pop($this->headers) . ' ' . trim($header);
}
else {
$this->headers[] = $header;
}
if (preg_match('/^X-Backdrop-Assertion-[0-9]+: (.*)$/', trim($header), $matches)) {
call_user_func_array(array(&$this, 'error'), unserialize(urldecode($matches[1])));
}
if (preg_match('/^Set-Cookie: ([^=]+)=(.+)/', $header, $matches)) {
$name = $matches[1];
$parts = array_map('trim', explode(';', $matches[2]));
$value = array_shift($parts);
$this->cookies[$name] = array('value' => $value, 'secure' => in_array('secure', $parts));
if ($name == $this->session_name) {
if ($value != 'deleted') {
$this->session_id = $value;
}
else {
$this->session_id = NULL;
}
}
}
return strlen($header);
}
protected function curlClose() {
if (isset($this->curlHandle)) {
curl_close($this->curlHandle);
unset($this->curlHandle);
}
}
protected function parse() {
if (!$this->elements) {
$htmlDom = new DOMDocument();
@$htmlDom->loadHTML('<?xml encoding="UTF-8">' . $this->backdropGetContent());
if ($htmlDom) {
$this->pass(t('Valid HTML found on "@path"', array('@path' => $this->getUrl())), t('Browser'));
$this->elements = simplexml_import_dom($htmlDom);
}
}
if (!$this->elements) {
$this->fail(t('Parsed page successfully.'), t('Browser'));
}
return $this->elements;
}
protected function backdropGet($path, array $options = array(), array $headers = array()) {
$options['absolute'] = TRUE;
$out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers));
$this->refreshVariables();
if ($new = $this->checkForMetaRefresh()) {
$out = $new;
}
$this->verbose('GET request to: ' . $path .
'<hr />Ending URL: ' . $this->getUrl() .
'<hr />' . $out);
return $out;
}
protected function backdropGetAJAX($path, array $options = array(), array $headers = array()) {
$headers[] = 'X-Requested-With: XMLHttpRequest';
$headers[] = 'Accept: application/vnd.backdrop-ajax, */*; q=0.01';
return backdrop_json_decode($this->backdropGet($path, $options, $headers));
}
protected function backdropPost($path, $edit, $submit, array $options = array(), array $headers = array(), $form_html_id = NULL, $extra_post = NULL) {
$submit_matches = FALSE;
$ajax = is_array($submit);
if (isset($path)) {
$this->backdropGet($path, $options);
}
if ($this->parse()) {
$edit_save = $edit;
$xpath = "//form";
if (!empty($form_html_id)) {
$xpath .= "[@id='" . $form_html_id . "']";
}
$forms = $this->xpath($xpath);
foreach ($forms as $form) {
$edit = $edit_save;
$post = array();
$upload = array();
$submit_matches = $this->handleForm($post, $edit, $upload, $ajax ? NULL : $submit, $form);
$action = isset($form['action']) ? $this->getAbsoluteUrl((string) $form['action']) : $this->getUrl();
if ($ajax) {
$action = $this->getAbsoluteUrl(!empty($submit['path']) ? $submit['path'] : 'system/ajax');
$submit_matches = TRUE;
}
if (!$edit && ($submit_matches || !isset($submit))) {
$post_array = $post;
if ($upload) {
foreach ($upload as $key => $file) {
$file = backdrop_realpath($file);
if ($file && is_file($file)) {
$post[$key] = curl_file_create($file);
}
}
}
else {
foreach ($post as $key => $value) {
$post[$key] = urlencode($key) . '=' . urlencode($value);
}
$post = implode('&', $post) . $extra_post;
}
$out = $this->curlExec(array(CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers));
$this->refreshVariables();
if ($new = $this->checkForMetaRefresh()) {
$out = $new;
}
$this->verbose('POST request to: ' . $path .
'<hr />Ending URL: ' . ($this->getUrl()) .
'<hr />Fields: ' . highlight_string('<?php ' . var_export($post_array, TRUE), TRUE) .
'<hr />' . $out);
return $out;
}
}
foreach ($edit as $name => $value) {
$this->fail(t('Failed to set field @name to @value', array('@name' => $name, '@value' => $value)));
}
if (!$ajax && isset($submit)) {
$this->assertTrue($submit_matches, t('Found the @submit button', array('@submit' => $submit)));
}
$this->fail(t('Found the requested form fields at @path', array('@path' => $path)));
}
return FALSE;
}
protected function backdropPostAJAX($path, $edit, $triggering_element, $ajax_path = NULL, array $options = array(), array $headers = array(), $form_html_id = NULL, $ajax_settings = NULL) {
if (isset($path)) {
$this->backdropGet($path, $options);
}
$content = $this->content;
$backdrop_settings = $this->backdropSettings;
if (!isset($ajax_settings)) {
if (is_array($triggering_element)) {
$xpath = '//*[@name="' . key($triggering_element) . '" and @value="' . current($triggering_element) . '"]';
}
else {
$xpath = '//*[@name="' . $triggering_element . '"]';
}
if (isset($form_html_id)) {
$xpath = '//form[@id="' . $form_html_id . '"]' . $xpath;
}
$element = $this->xpath($xpath);
$element_id = (string) $element[0]['id'];
$ajax_settings = $backdrop_settings['ajax'][$element_id];
}
$extra_post = '';
if (isset($ajax_settings['submit'])) {
foreach ($ajax_settings['submit'] as $key => $value) {
$extra_post .= '&' . urlencode($key) . '=' . urlencode($value);
}
}
foreach ($this->xpath('//*[@id]') as $element) {
$id = (string) $element['id'];
$extra_post .= '&' . urlencode('ajax_html_ids[]') . '=' . urlencode($id);
}
if (isset($backdrop_settings['ajaxPageState'])) {
$extra_post .= '&' . urlencode('ajax_page_state[theme]') . '=' . urlencode($backdrop_settings['ajaxPageState']['theme']);
$extra_post .= '&' . urlencode('ajax_page_state[theme_token]') . '=' . urlencode($backdrop_settings['ajaxPageState']['theme_token']);
foreach ($backdrop_settings['ajaxPageState']['css'] as $key => $value) {
$extra_post .= '&' . urlencode("ajax_page_state[css][$key]") . '=1';
}
foreach ($backdrop_settings['ajaxPageState']['js'] as $key => $value) {
$extra_post .= '&' . urlencode("ajax_page_state[js][$key]") . '=1';
}
}
if (!isset($ajax_path)) {
$ajax_path = isset($ajax_settings['url']) ? $ajax_settings['url'] : 'system/ajax';
}
$headers[] = 'X-Requested-With: XMLHttpRequest';
$headers[] = 'Accept: application/vnd.backdrop-ajax, */*; q=0.01';
$return = backdrop_json_decode($this->backdropPost(NULL, $edit, array('path' => $ajax_path, 'triggering_element' => $triggering_element), $options, $headers, $form_html_id, $extra_post));
$this->assertIdentical($this->backdropGetHeader('X-Backdrop-Ajax-Token'), '1', 'Ajax response header found.');
if (!empty($ajax_settings) && !empty($return)) {
$ajax_settings += array(
'method' => 'replaceWith',
);
$dom = new DOMDocument();
@$dom->loadHTML($content);
$xpath = new DOMXPath($dom);
foreach ($return as $command) {
switch ($command['command']) {
case 'settings':
$backdrop_settings = backdrop_array_merge_deep($backdrop_settings, $command['settings']);
break;
case 'insert':
$wrapperNode = NULL;
if (!isset($command['selector'])) {
$wrapperNode = $xpath->query('//*[@id="' . $ajax_settings['wrapper'] . '"]')->item(0);
}
elseif (in_array($command['selector'], array('head', 'body'))) {
$wrapperNode = $xpath->query('//' . $command['selector'])->item(0);
}
if ($wrapperNode) {
$newDom = new DOMDocument();
$newDom->loadHTML('<div>' . $command['data'] . '</div>');
$newNode = @$dom->importNode($newDom->documentElement->firstChild->firstChild, TRUE);
$method = isset($command['method']) ? $command['method'] : $ajax_settings['method'];
switch ($method) {
case 'replaceWith':
$wrapperNode->parentNode->replaceChild($newNode, $wrapperNode);
break;
case 'append':
$wrapperNode->appendChild($newNode);
break;
case 'prepend':
$wrapperNode->insertBefore($newNode, $wrapperNode->firstChild);
break;
case 'before':
$wrapperNode->parentNode->insertBefore($newNode, $wrapperNode);
break;
case 'after':
$wrapperNode->parentNode->insertBefore($newNode, $wrapperNode->nextSibling);
break;
case 'html':
foreach ($wrapperNode->childNodes as $childNode) {
$wrapperNode->removeChild($childNode);
}
$wrapperNode->appendChild($newNode);
break;
}
}
break;
case 'updateBuildId':
$buildId = $xpath->query('//input[@name="form_build_id" and @value="' . $command['old'] . '"]')->item(0);
if ($buildId) {
$buildId->setAttribute('value', $command['new']);
}
break;
case 'remove':
break;
case 'changed':
break;
case 'css':
break;
case 'data':
break;
case 'restripe':
break;
case 'addCss':
break;
}
}
$content = $dom->saveHTML();
}
$this->backdropSetContent($content);
$this->backdropSetSettings($backdrop_settings);
$verbose = 'AJAX POST request to: ' . $path;
$verbose .= '<br />AJAX callback path: ' . $ajax_path;
$verbose .= '<hr />Ending URL: ' . $this->getUrl();
$verbose .= '<hr />' . $this->content;
$this->verbose($verbose);
return $return;
}
protected function cronRun() {
$this->backdropGet($GLOBALS['base_url'] . '/core/cron.php', array('external' => TRUE, 'query' => array('cron_key' => state_get('cron_key'))));
}
protected function checkForMetaRefresh() {
if (strpos($this->backdropGetContent(), '<meta ') && $this->parse()) {
$refresh = $this->xpath('//meta[@http-equiv="Refresh"]');
if (!empty($refresh)) {
if (preg_match('/\d+;\s*URL=(?P<url>.*)/i', $refresh[0]['content'], $match)) {
return $this->backdropGet($this->getAbsoluteUrl(decode_entities($match['url'])));
}
}
}
return FALSE;
}
protected function backdropHead($path, array $options = array(), array $headers = array()) {
$options['absolute'] = TRUE;
$out = $this->curlExec(array(CURLOPT_NOBODY => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_HTTPHEADER => $headers));
$this->refreshVariables(); return $out;
}
protected function handleForm(&$post, &$edit, &$upload, $submit, $form) {
$elements = $form->xpath('.//input[not(@disabled)]|.//textarea[not(@disabled)]|.//select[not(@disabled)]');
$submit_matches = FALSE;
foreach ($elements as $element) {
$name = (string) $element['name'];
$type = isset($element['type']) ? (string) $element['type'] : $element->getName();
$value = isset($element['value']) ? (string) $element['value'] : '';
$done = FALSE;
if (isset($edit[$name])) {
switch ($type) {
case 'color':
case 'email':
case 'hidden':
case 'number':
case 'range':
case 'text':
case 'tel':
case 'date':
case 'time':
case 'textarea':
case 'url':
case 'password':
case 'search':
$post[$name] = $edit[$name];
unset($edit[$name]);
break;
case 'radio':
if ($edit[$name] == $value) {
$post[$name] = $edit[$name];
unset($edit[$name]);
}
break;
case 'checkbox':
if ($edit[$name] === FALSE) {
unset($edit[$name]);
continue 2;
}
else {
unset($edit[$name]);
$post[$name] = $value;
}
break;
case 'select':
$new_value = $edit[$name];
$options = $this->getAllOptions($element);
if (is_array($new_value)) {
if (!empty($new_value)) {
$index = 0;
$key = preg_replace('/\[\]$/', '', $name);
foreach ($options as $option) {
$option_value = (string) $option['value'];
if (in_array($option_value, $new_value)) {
$post[$key . '[' . $index++ . ']'] = $option_value;
$done = TRUE;
unset($edit[$name]);
}
}
}
else {
$done = TRUE;
unset($edit[$name]);
}
}
else {
foreach ($options as $option) {
if ($new_value == $option['value']) {
$post[$name] = $new_value;
unset($edit[$name]);
$done = TRUE;
break;
}
}
}
break;
case 'file':
$upload[$name] = $edit[$name];
unset($edit[$name]);
break;
}
}
if (!isset($post[$name]) && !$done) {
switch ($type) {
case 'textarea':
$post[$name] = (string) $element;
break;
case 'select':
$single = empty($element['multiple']);
$first = TRUE;
$index = 0;
$key = preg_replace('/\[\]$/', '', $name);
$options = $this->getAllOptions($element);
foreach ($options as $option) {
if ($option['selected'] || ($first && $single)) {
$first = FALSE;
if ($single) {
$post[$name] = (string) $option['value'];
}
else {
$post[$key . '[' . $index++ . ']'] = (string) $option['value'];
}
}
}
break;
case 'file':
break;
case 'submit':
case 'image':
if (isset($submit) && $submit == $value) {
$post[$name] = $value;
$submit_matches = TRUE;
}
break;
case 'radio':
case 'checkbox':
if (!isset($element['checked'])) {
break;
}
$post[$name] = $value;
break;
default:
$post[$name] = $value;
}
}
}
return $submit_matches;
}
protected function buildXPathQuery($xpath, array $args = array()) {
foreach ($args as $placeholder => $value) {
if (is_string($value)) {
$parts = explode('"', $value);
foreach ($parts as &$part) {
$part = '"' . $part . '"';
}
$value = count($parts) > 1 ? 'concat(' . implode(', \'"\', ', $parts) . ')' : $parts[0];
}
$xpath = preg_replace('/' . preg_quote($placeholder) . '\b/', $value, $xpath);
}
return $xpath;
}
protected function xpath($xpath, array $arguments = array()) {
if ($this->parse()) {
$xpath = $this->buildXPathQuery($xpath, $arguments);
$result = $this->elements->xpath($xpath);
return $result ? $result : array();
}
else {
return FALSE;
}
}
protected function getAllOptions(SimpleXMLElement $element) {
$options = array();
foreach ($element->option as $option) {
$options[] = $option;
}
if (isset($element->optgroup)) {
foreach ($element->optgroup as $group) {
$options = array_merge($options, $this->getAllOptions($group));
}
}
return $options;
}
protected function assertLink($label, $index = 0, $message = '', $group = 'Other') {
$links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
$message = ($message ? $message : t('Link with label %label found.', array('%label' => $label)));
return $this->assert(isset($links[$index]), $message, $group);
}
protected function assertNoLink($label, $message = '', $group = 'Other') {
$links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
$message = ($message ? $message : t('Link with label %label not found.', array('%label' => $label)));
return $this->assert(empty($links), $message, $group);
}
protected function assertLinkByHref($href, $index = 0, $message = '', $group = 'Other') {
$links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
$message = ($message ? $message : t('Link containing href %href found.', array('%href' => $href)));
return $this->assert(isset($links[$index]), $message, $group);
}
protected function assertNoLinkByHref($href, $message = '', $group = 'Other') {
$links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
$message = ($message ? $message : t('No link containing href %href found.', array('%href' => $href)));
return $this->assert(empty($links), $message, $group);
}
protected function clickLink($label, $index = 0) {
$url_before = $this->getUrl();
$urls = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
if (isset($urls[$index])) {
$url_target = $this->getAbsoluteUrl($urls[$index]['href']);
$this->pass(t('Clicked link %label (@url_target) from @url_before', array('%label' => $label, '@url_target' => $url_target, '@url_before' => $url_before)), 'Browser');
return $this->backdropGet($url_target);
}
$this->fail(t('Link %label does not exist on @url_before', array('%label' => $label, '@url_before' => $url_before)), 'Browser');
return FALSE;
}
protected function getAbsoluteUrl($path) {
global $base_url, $base_path;
$parts = parse_url($path);
if (empty($parts['host'])) {
$path = (string) $path;
$length = strlen($base_path);
if (substr($path, 0, $length) === $base_path) {
$path = substr($path, $length);
}
if (strlen($path) && $path[0] !== '/') {
$path = '/' . $path;
}
$path = $base_url . $path;
}
return $path;
}
protected function getUrl() {
return $this->url;
}
protected function backdropGetHeaders($all_requests = FALSE) {
$request = 0;
$headers = array($request => array());
foreach ($this->headers as $header) {
$header = trim($header);
if ($header === '') {
$request++;
}
else {
if (strpos($header, 'HTTP/') === 0) {
$name = ':status';
$value = $header;
}
else {
list($name, $value) = explode(':', $header, 2);
$name = strtolower($name);
}
if (isset($headers[$request][$name])) {
$headers[$request][$name] .= ',' . trim($value);
}
else {
$headers[$request][$name] = trim($value);
}
}
}
if (!$all_requests) {
$headers = array_pop($headers);
}
return $headers;
}
protected function backdropGetHeader($name, $all_requests = FALSE) {
$name = strtolower($name);
$header = FALSE;
if ($all_requests) {
foreach (array_reverse($this->backdropGetHeaders(TRUE)) as $headers) {
if (isset($headers[$name])) {
$header = $headers[$name];
break;
}
}
}
else {
$headers = $this->backdropGetHeaders();
if (isset($headers[$name])) {
$header = $headers[$name];
}
}
return $header;
}
protected function backdropGetContent() {
return $this->content;
}
protected function backdropGetSettings() {
return $this->backdropSettings;
}
protected function backdropGetMails($filter = array()) {
$captured_emails = state_get('test_email_collector', array());
$filtered_emails = array();
foreach ($captured_emails as $message) {
foreach ($filter as $key => $value) {
if (!isset($message[$key]) || $message[$key] != $value) {
continue 2;
}
}
$filtered_emails[] = $message;
}
return $filtered_emails;
}
protected function backdropSetContent($content, $url = 'internal:') {
$this->content = $content;
$this->url = $url;
$this->plainTextContent = FALSE;
$this->elements = FALSE;
$this->backdropSettings = array();
if (preg_match('/window.Backdrop[ ]?=[ ]?{settings:[ ]?(.*)}/', $content, $matches)) {
$this->backdropSettings = backdrop_json_decode($matches[1]);
}
}
protected function backdropSetSettings($settings) {
$this->backdropSettings = $settings;
}
protected function assertUrl($path, array $options = array(), $message = '', $group = 'Other') {
if (!$message) {
$message = t('Current URL is @url.', array(
'@url' => var_export(url($path, $options), TRUE),
));
}
$options['absolute'] = TRUE;
return $this->assertEqual($this->getUrl(), url($path, $options), $message, $group);
}
protected function assertRaw($raw, $message = '', $group = 'Other') {
if (!$message) {
$message = t('Raw "@raw" found', array('@raw' => $raw));
}
return $this->assert(strpos($this->backdropGetContent(), (string) $raw) !== FALSE, $message, $group);
}
protected function assertNoRaw($raw, $message = '', $group = 'Other') {
if (!$message) {
$message = t('Raw "@raw" not found', array('@raw' => $raw));
}
return $this->assert(strpos($this->backdropGetContent(), (string) $raw) === FALSE, $message, $group);
}
protected function assertText($text, $message = '', $group = 'Other') {
return $this->assertTextHelper($text, $message, $group, FALSE);
}
protected function assertNoText($text, $message = '', $group = 'Other') {
return $this->assertTextHelper($text, $message, $group, TRUE);
}
protected function assertTextHelper($text, $message, $group, $not_exists) {
if ($this->plainTextContent === FALSE) {
$this->plainTextContent = filter_xss($this->backdropGetContent(), array());
}
if (!$message) {
$message = !$not_exists ? t('"@text" found', array('@text' => $text)) : t('"@text" not found', array('@text' => $text));
}
return $this->assert($not_exists == (strpos($this->plainTextContent, $text) === FALSE), $message, $group);
}
protected function assertUniqueText($text, $message = '', $group = 'Other') {
return $this->assertUniqueTextHelper($text, $message, $group, TRUE);
}
protected function assertNoUniqueText($text, $message = '', $group = 'Other') {
return $this->assertUniqueTextHelper($text, $message, $group, FALSE);
}
protected function assertUniqueTextHelper($text, $message, $group, $be_unique) {
if ($this->plainTextContent === FALSE) {
$this->plainTextContent = filter_xss($this->backdropGetContent(), array());
}
if (!$message) {
$message = '"' . $text . '"' . ($be_unique ? ' found only once' : ' found more than once');
}
$first_occurrence = strpos($this->plainTextContent, $text);
if ($first_occurrence === FALSE) {
return $this->assert(FALSE, $message, $group);
}
$offset = $first_occurrence + strlen($text);
$second_occurrence = strpos($this->plainTextContent, $text, $offset);
return $this->assert($be_unique == ($second_occurrence === FALSE), $message, $group);
}
protected function assertPattern($pattern, $message = '', $group = 'Other') {
if (!$message) {
$message = t('Pattern "@pattern" found', array('@pattern' => $pattern));
}
return $this->assert((bool) preg_match($pattern, $this->backdropGetContent()), $message, $group);
}
protected function assertNoPattern($pattern, $message = '', $group = 'Other') {
if (!$message) {
$message = t('Pattern "@pattern" not found', array('@pattern' => $pattern));
}
return $this->assert(!preg_match($pattern, $this->backdropGetContent()), $message, $group);
}
protected function assertTitle($title, $message = '', $group = 'Other') {
$actual = (string) current($this->xpath('//title'));
if (!$message) {
$message = t('Page title @actual is equal to @expected.', array(
'@actual' => var_export($actual, TRUE),
'@expected' => var_export($title, TRUE),
));
}
return $this->assertEqual($actual, $title, $message, $group);
}
protected function assertNoTitle($title, $message = '', $group = 'Other') {
$actual = (string) current($this->xpath('//title'));
if (!$message) {
$message = t('Page title @actual is not equal to @unexpected.', array(
'@actual' => var_export($actual, TRUE),
'@unexpected' => var_export($title, TRUE),
));
}
return $this->assertNotEqual($actual, $title, $message, $group);
}
protected function assertThemeOutput($callback, array $variables, $expected, $message = '', $group = 'Other') {
$output = theme($callback, $variables);
$this->verbose('Variables:<pre>' . check_plain(var_export($variables, TRUE)) . '</pre>'
. '<hr />Result:<pre>' . check_plain(var_export($output, TRUE)) . '</pre>'
. '<hr />Expected:<pre>' . check_plain(var_export($expected, TRUE)) . '</pre>'
. '<hr />' . $output
);
if (!$message) {
$message = '%callback rendered correctly.';
}
$message = format_string($message, array('%callback' => 'theme_' . $callback . '()'));
return $this->assertIdentical($output, $expected, $message, $group);
}
protected function assertFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
$fields = $this->xpath($xpath);
$found = TRUE;
if (isset($value)) {
$found = FALSE;
if ($fields) {
foreach ($fields as $field) {
if (isset($field['value']) && $field['value'] == $value) {
$found = TRUE;
}
elseif (isset($field->option)) {
if ($this->getSelectedItem($field) == $value) {
$found = TRUE;
}
else {
$items = $this->getAllOptions($field);
if (!empty($items) && $items[0]['value'] == $value) {
$found = TRUE;
}
}
}
elseif ((string) $field == $value) {
$found = TRUE;
}
}
}
}
return $this->assertTrue($fields && $found, $message, $group);
}
protected function getSelectedItem(SimpleXMLElement $element) {
foreach ($element->children() as $item) {
if (isset($item['selected'])) {
return $item['value'];
}
elseif ($item->getName() == 'optgroup') {
if ($value = $this->getSelectedItem($item)) {
return $value;
}
}
}
return FALSE;
}
protected function assertNoFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
$fields = $this->xpath($xpath);
$found = TRUE;
if (isset($value)) {
$found = FALSE;
if ($fields) {
foreach ($fields as $field) {
if ($field['value'] == $value) {
$found = TRUE;
}
}
}
}
return $this->assertFalse($fields && $found, $message, $group);
}
protected function assertFieldByName($name, $value = NULL, $message = NULL) {
if (!isset($message)) {
if (!isset($value)) {
$message = t('Found field with name @name', array(
'@name' => var_export($name, TRUE),
));
}
else {
$message = t('Found field with name @name and value @value', array(
'@name' => var_export($name, TRUE),
'@value' => var_export($value, TRUE),
));
}
}
return $this->assertFieldByXPath($this->constructFieldXpath('name', $name), $value, $message, t('Browser'));
}
protected function assertNoFieldByName($name, $value = '', $message = '') {
return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $name), $value, $message ? $message : t('Did not find field by name @name', array('@name' => $name)), t('Browser'));
}
protected function assertFieldById($id, $value = '', $message = '') {
return $this->assertFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Found field by id @id', array('@id' => $id)), t('Browser'));
}
protected function assertNoFieldById($id, $value = '', $message = '') {
return $this->assertNoFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Did not find field by id @id', array('@id' => $id)), t('Browser'));
}
protected function assertFieldChecked($id, $message = '') {
$elements = $this->xpath('//input[@id=:id]', array(':id' => $id));
return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['checked']), $message ? $message : t('Checkbox field @id is checked.', array('@id' => $id)), t('Browser'));
}
protected function assertNoFieldChecked($id, $message = '') {
$elements = $this->xpath('//input[@id=:id]', array(':id' => $id));
return $this->assertTrue(isset($elements[0]) && empty($elements[0]['checked']), $message ? $message : t('Checkbox field @id is not checked.', array('@id' => $id)), t('Browser'));
}
protected function assertOption($id, $option, $message = '') {
$options = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
return $this->assertTrue(isset($options[0]), $message ? $message : t('Option @option for field @id exists.', array('@option' => $option, '@id' => $id)), t('Browser'));
}
protected function assertNoOption($id, $option, $message = '') {
$selects = $this->xpath('//select[@id=:id]', array(':id' => $id));
$options = $this->xpath('//select[@id=:id]/option[@value=:option]', array(':id' => $id, ':option' => $option));
return $this->assertTrue(isset($selects[0]) && !isset($options[0]), $message ? $message : t('Option @option for field @id does not exist.', array('@option' => $option, '@id' => $id)), t('Browser'));
}
protected function assertOptionSelected($id, $option, $message = '') {
$elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['selected']), $message ? $message : t('Option @option for field @id is selected.', array('@option' => $option, '@id' => $id)), t('Browser'));
}
protected function assertNoOptionSelected($id, $option, $message = '') {
$elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
return $this->assertTrue(isset($elements[0]) && empty($elements[0]['selected']), $message ? $message : t('Option @option for field @id is not selected.', array('@option' => $option, '@id' => $id)), t('Browser'));
}
protected function assertField($field, $message = '', $group = 'Other') {
return $this->assertFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), NULL, $message, $group);
}
protected function assertNoField($field, $message = '', $group = 'Other') {
return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), NULL, $message, $group);
}
protected function assertNoDuplicateIds($message = '', $group = 'Other', $ids_to_skip = array()) {
$status = TRUE;
foreach ($this->xpath('//*[@id]') as $element) {
$id = (string) $element['id'];
if (isset($seen_ids[$id]) && !in_array($id, $ids_to_skip)) {
$this->fail(t('The HTML ID %id is unique.', array('%id' => $id)), $group);
$status = FALSE;
}
$seen_ids[$id] = TRUE;
}
return $this->assert($status, $message, $group);
}
protected function constructFieldXpath($attribute, $value) {
$xpath = '//textarea[@' . $attribute . '=:value]|//input[@' . $attribute . '=:value]|//select[@' . $attribute . '=:value]';
return $this->buildXPathQuery($xpath, array(':value' => $value));
}
protected function assertResponse($code, $message = '') {
$curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
$match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
return $this->assertTrue($match, $message ? $message : t('HTTP response expected !code, actual !curl_code', array('!code' => $code, '!curl_code' => $curl_code)), t('Browser'));
}
protected function assertNoResponse($code, $message = '') {
$curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
$match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
return $this->assertFalse($match, $message ? $message : t('HTTP response not expected !code, actual !curl_code', array('!code' => $code, '!curl_code' => $curl_code)), t('Browser'));
}
protected function assertMail($name, $value = '', $message = '') {
$captured_emails = state_get('test_email_collector', array());
$email = end($captured_emails);
return $this->assertTrue($email && isset($email[$name]) && $email[$name] == $value, $message, t('Email'));
}
protected function assertMailString($field_name, $string, $email_depth) {
$mails = $this->backdropGetMails();
$string_found = FALSE;
for ($i = sizeof($mails) -1; $i >= sizeof($mails) - $email_depth && $i >= 0; $i--) {
$mail = $mails[$i];
$normalized_mail = preg_replace('/\s+/', ' ', $mail[$field_name]);
$normalized_string = preg_replace('/\s+/', ' ', $string);
$string_found = (FALSE !== strpos($normalized_mail, $normalized_string));
if ($string_found) {
break;
}
}
return $this->assertTrue($string_found, t('Expected text found in @field of email message: "@expected".', array('@field' => $field_name, '@expected' => $string)));
}
protected function assertMailPattern($field_name, $regex, $message) {
$mails = $this->backdropGetMails();
$mail = end($mails);
$regex_found = preg_match("/$regex/", $mail[$field_name]);
return $this->assertTrue($regex_found, t('Expected text found in @field of email message: "@expected".', array('@field' => $field_name, '@expected' => $regex)));
}
protected function verboseEmail($count = 1) {
$mails = $this->backdropGetMails();
for ($i = sizeof($mails) -1; $i >= sizeof($mails) - $count && $i >= 0; $i--) {
$mail = $mails[$i];
$this->verbose(t('Email:') . '<pre>' . print_r($mail, TRUE) . '</pre>');
}
}
protected function assertWatchdogMessage($watchdog_message, array $variables, $message) {
$status = (bool) db_query_range("SELECT 1 FROM {watchdog} WHERE message = :message AND variables = :variables", 0, 1, array(
':message' => $watchdog_message,
':variables' => serialize($variables),
))->fetchField();
return $this->assert($status, format_string('@message', array('@message' => $message)));
}
protected function clearWatchdog() {
db_truncate('watchdog')->execute();
}
}