### EarlyBootstrapTestCase::setUp() Example Source: https://docs.backdropcms.org/api/backdrop/core%21modules%21simpletest%21tests%21boot.test/function/EarlyBootstrapTestCase%3A%3AsetUp/1 This is an example of how to use the `setUp()` method within a test case. It calls the parent `setUp()` method, passing module names as arguments to enable them for the test. ```php function setUp() { parent::setUp('boot_test_1', 'boot_test_2'); } ``` -------------------------------- ### NodeQueryAlter::setUp() Example Source: https://docs.backdropcms.org/api/backdrop/core%21modules%21node%21tests%21node.test/function/NodeQueryAlter%3A%3AsetUp/1 This snippet demonstrates the setup process for a Backdrop CMS test, including installing modules, creating content, and setting up users with specific permissions. It's used to prepare the testing environment. ```php function setUp() { parent::setUp('node_access_test'); node_access_rebuild(); // Create some content. $this->backdropCreateNode(); $this->backdropCreateNode(); $this->backdropCreateNode(); $this->backdropCreateNode(); // Create user with simple node access permission. The 'node test view' // permission is implemented and granted by the node_access_test module. $this->accessUser = $this->backdropCreateUser(array('access content overview', 'access content', 'node test view')); $this->noAccessUser = $this->backdropCreateUser(array('access content overview', 'access content')); $this->noAccessUser2 = $this->backdropCreateUser(array('access content overview', 'access content')); } ``` -------------------------------- ### BackdropSystemListingCompatibleTestCase::setUp() Example Source: https://docs.backdropcms.org/api/backdrop/core%21profiles%21testing%21modules%21backdrop_system_listing_compatible_test%21backdrop_system_listing_compatible_test.test/function/BackdropSystemListingCompatibleTestCase%3A%3AsetUp/1 This snippet demonstrates how to use the setUp() method to prepare a Backdrop site for testing. It specifically enables the 'backdrop_system_listing_compatible_test' module during the setup process, overriding the default parent setup. ```php function setUp() { // Attempt to install a module in Testing profile, while this test runs with // a different profile. parent::setUp(array('backdrop_system_listing_compatible_test')); } ``` -------------------------------- ### Create Radios with Individual Descriptions Source: https://docs.backdropcms.org/form_api This example shows how to set individual descriptions for each radio option. This is useful for providing specific context or explanations for each choice. ```php 'radios', '#title' => $node->nid ? t('Published state') : t('Publish action'), '#options' => array( NODE_PUBLISHED => $node->nid ? t('Published') : t('Publish now'), NODE_NOT_PUBLISHED => $node->nid ? t('Draft') : t('Save as draft'), ), '#default_value' => $status, ); $form['options']['status'][NODE_PUBLISHED]['#description'] = t('Site visitors will be able to access this content.'); $form['options']['status'][NODE_NOT_PUBLISHED]['#description'] = t('Only the content creator or site administrators will be able to access this content.'); ?> ``` -------------------------------- ### Form Element Build Callback Source: https://docs.backdropcms.org/form_api Use #after_build to specify functions that run after a form or element is built. This example shows setting a default value and description for a textfield. ```php 'textfield', '#title' => t('Public file system path'), '#default_value' => variable_get('file_public_path', conf_path() . '/files'), '#maxlength' => 255, '#description' => t('A local file system path where public files will be stored. This directory must exist and be writable by Backdrop. This directory must be relative to the Backdrop installation directory and be accessible over the web.'), '#after_build' => array('system_check_directory'), ); ?> ``` -------------------------------- ### Basic Machine Name Element Source: https://docs.backdropcms.org/form_api Example of a basic machine_name form element for a vocabulary. It sets a default value and a maximum length, and specifies an 'exists' callback for validation. ```php 'machine_name', '#default_value' => $vocabulary->machine_name, '#maxlength' => 21, '#machine_name' => array( 'exists' => 'menu_edit_menu_name_exists', ), ); ?> ``` -------------------------------- ### Configurable Machine Name Element for Menu Source: https://docs.backdropcms.org/form_api An advanced example of a machine_name element for a menu. It customizes the title, description, maximum length, and the machine name configuration, including source, label, replacement pattern, and replacement character. It also demonstrates disabling the element based on existing conditions. ```php 'machine_name', '#title' => t('Menu name'), '#default_value' => $menu['menu_name'], '#maxlength' => MENU_MAX_MENU_NAME_LENGTH_UI, '#description' => t('A unique name to construct the URL for the menu. It must only contain lowercase letters, numbers and hyphens.'), '#machine_name' => array( 'exists' => 'menu_edit_menu_name_exists', 'source' => array('title'), 'label' => t('URL path'), 'replace_pattern' => '[^a-z0-9-]+', 'replace' => '-', ), // A menu's machine name cannot be changed. '#disabled' => !empty($menu['old_name']) || isset($system_menus[$menu['menu_name']]), ); ?> ``` -------------------------------- ### Configure AJAX Progress Indicator in Backdrop Form Source: https://docs.backdropcms.org/form_api This example demonstrates how to configure the AJAX progress indicator for a form element. It sets the progress type to 'bar' and specifies a message, while also defining an effect for the AJAX response. ```php implode('_', $element['#parents']) . '_remove_button', '#type' => 'submit', '#value' => t('Remove'), '#validate' => array(), '#submit' => array('file_managed_file_submit'), '#limit_validation_errors' => array($element['#parents']), '#ajax' => $ajax_settings, '#weight' => -5, ); ?> ``` -------------------------------- ### Install Backdrop CMS with Guided Setup Source: https://docs.backdropcms.org/documentation/advanced-installation Initiate the guided installation process for Backdrop CMS from the command line. ```bash bee install ``` -------------------------------- ### FileExampleTest Setup Source: https://docs.backdropcms.org/api/backdrop/modules%21examples%21file_example%21tests%21file_example.test/class/FileExampleTest/1?object_type=&order=object_type&sort=asc&title=&title_1= Sets up the test environment by creating a privileged user with specific permissions and logging them in. It also enables the 'file_example' module. ```php class FileExampleTest extends BackdropWebTestCase { protected $priviledgedUser; /** * {@inheritdoc} */ public function setUp() { parent::setUp(array('file_example')); $this->priviledgedUser = $this->backdropCreateUser(array('use file example')); $this->backdropLogin($this->priviledgedUser); } /** * Test the basic File Example UI. * * - Create a directory to work with * - Foreach scheme create and read files using each of the three methods. */ public function testFileExampleBasic() { $expected_text = array( t('Write managed file') => t('Saved managed file'), t('Write unmanaged file') => t('Saved file as'), t('Unmanaged using PHP') => t('Saved file as'), ); // For each of the three buttons == three write types. $buttons = array( t('Write managed file'), t('Write unmanaged file'), t('Unmanaged using PHP'), ); foreach ($buttons as $button) { // For each scheme supported by Backdrop + the session:// wrapper. $schemes = array('public', 'private', 'temporary', 'session'); foreach ($schemes as $scheme) { // Create a directory for use. $dirname = $scheme . '://' . $this->randomName(10); // Directory does not yet exist; assert that. $edit = array( 'directory_name' => $dirname, ); $this->backdropPost('examples/file_example/fileapi', $edit, t('Check to see if directory exists')); $this->assertRaw(t('Directory %dirname does not exist', array('%dirname' => $dirname)), 'Verify that directory does not exist.'); $this->backdropPost('examples/file_example/fileapi', $edit, t('Create directory')); $this->assertRaw(t('Directory %dirname is ready for use', array('%dirname' => $dirname))); $this->backdropPost('examples/file_example/fileapi', $edit, t('Check to see if directory exists')); $this->assertRaw(t('Directory %dirname exists', array('%dirname' => $dirname)), 'Verify that directory now does exist.'); // Create a file in the directory we created. $content = $this->randomName(30); $filename = $dirname . '/' . $this->randomName(30) . '.txt'; // Assert that the file we're about to create does not yet exist. $edit = array( 'fileops_file' => $filename, ); $this->backdropPost('examples/file_example/fileapi', $edit, t('Check to see if file exists')); $this->assertRaw(t('The file %filename does not exist', array('%filename' => $filename)), 'Verify that file does not yet exist.'); debug( t('Processing button=%button, scheme=%scheme, dir=%dirname, file=%filename', array( '%button' => $button, '%scheme' => $scheme, '%filename' => $filename, '%dirname' => $dirname, ) ) ); $edit = array( 'write_contents' => $content, 'destination' => $filename, ); $this->backdropPost('examples/file_example/fileapi', $edit, $button); $this->assertText($expected_text[$button]); // Capture the name of the output file, as it might have changed due // to file renaming. $element = $this->xpath('//span[@id="uri"]'); $output_filename = (string) $element[0]; debug($output_filename, 'Name of output file'); // Click the link provided that is an easy way to get the data for // checking and make sure that the data we put in is what we get out. if (!in_array($scheme, array('private', 'temporary'))) { $this->clickLink(t('this URL')); $this->assertText($content); } // Verify that the file exists. $edit = array( 'fileops_file' => $filename, ); $this->backdropPost('examples/file_example/fileapi', $edit, t('Check to see if file exists')); $this->assertRaw(t('The file %filename exists', array('%filename' => $filename)), 'Verify that file now exists.'); // Now read the file that got written above and verify that we can use // the writing tools. $edit = array( 'fileops_file' => $output_filename, ); $this->backdropPost('examples/file_example/fileapi', $edit, t('Read the file and store it locally')); $this->assertText(t('The file was read and copied')); $edit = array( 'fileops_file' => $filename, ); $this->backdropPost('examples/file_example/fileapi', $edit, t('Delete file')); $this->assertText(t('Successfully deleted')); $this->backdropPost('examples/file_example/fileapi', $edit, t('Check to see if file exists')); $this->assertRaw(t('The file %filename does not exist', array('%filename' => $filename)), 'Verify file has been deleted.'); } } } } ``` -------------------------------- ### Configure Managed File Element with Custom Value Callback Source: https://docs.backdropcms.org/form_api Example of configuring a 'managed_file' form element, including setting a custom #value_callback. This snippet demonstrates extending element information and defining upload locations and validators. ```php 'managed_file', '#default_value' => isset($items[$delta]) ? $items[$delta] : $defaults, '#upload_location' => file_field_widget_uri($field, $instance), '#upload_validators' => file_field_widget_upload_validators($field, $instance), '#value_callback' => 'file_field_widget_value', '#process' => array_merge($element_info['#process'], array('file_field_widget_process')), // Allows this field to return an array instead of a single value. '#extended' => TRUE, ); ... function file_field_widget_value($element, $input = FALSE, $form_state) { if ($input) { // Checkboxes lose their value when empty. // If the display field is present make sure its unchecked value is saved. $field = field_widget_field($element, $form_state); if (empty($input['display'])) { $input['display'] = $field['settings']['display_field'] ? 0 : 1; } } ?> ``` -------------------------------- ### FilterCRUDTestCase::setUp() Example Source: https://docs.backdropcms.org/api/backdrop/core%21modules%21filter%21tests%21filter.test/function/FilterCRUDTestCase%3A%3AsetUp/1 This is an example of how to use the `setUp()` method within a test case. It calls the parent `setUp()` method, passing 'filter_test' as an argument to ensure the filter module is installed for the test. ```php function setUp() { parent::setUp('filter_test'); } ``` -------------------------------- ### ImageExampleTestCase::setUp() - Enable Modules and Create User Source: https://docs.backdropcms.org/api/backdrop/modules%21examples%21image_example%21tests%21image_example.test/function/ImageExampleTestCase%3A%3AsetUp/1 Overrides the parent setUp method to enable the 'image_example' module and create a test user with specific administrative permissions. Use this to set up the testing environment for image-related functionalities. ```php public function setUp() { parent::setUp('image_example'); // Create user with permission to administer image styles. $this->webUser = $this->backdropCreateUser(array('administer image styles', 'administer blocks')); } ``` -------------------------------- ### Create a File Upload Element Source: https://docs.backdropcms.org/form_api Formats a file upload field. The browser will automatically add `enctype="multipart/form-data"`. This example sets the title to be invisible and specifies a weight. ```php 'files[' . implode('_', $element['#parents']) . ']', '#type' => 'file', '#title' => t('Choose a file'), '#title_display' => 'invisible', '#size' => 22, '#theme_wrappers' => array(), '#weight' => -10, ); ?> ``` -------------------------------- ### Set Form Submission Method Source: https://docs.backdropcms.org/form_api Use #method to specify the HTTP method (GET or POST) for form submission. Defaults to POST. ```php ``` -------------------------------- ### Get Database Installer Object Source: https://docs.backdropcms.org/api/backdrop/core%21includes%21install.inc/1?order=title&sort=desc Loads the appropriate driver file for database installation tasks and returns a DatabaseTasks object. This object is used to perform driver-specific setup and checks on the database. ```php function db_installer_object($driver) { Database::loadDriverFile($driver, array('install.inc')); } ``` -------------------------------- ### ActionExampleTestCase::setUp() - Setup for Action Example Module Source: https://docs.backdropcms.org/api/backdrop/modules%21examples%21action_example%21tests%21action_example.test/function/ActionExampleTestCase%3A%3AsetUp/1 This method sets up the Backdrop site for the action_example module test. It calls the parent setUp method, passing 'action_example' to enable the module. ```php public function setUp() { parent::setUp('action_example'); } ``` -------------------------------- ### Database Example Unit Test Class Source: https://docs.backdropcms.org/api/backdrop/modules%21examples%21database_example%21tests%21database_example.test/class/DatabaseExampleUnitTestCase/1 Defines a unit test class for the Database Example module, extending BackdropWebTestCase. Includes setup and test methods for installation, UI, and API operations. ```php class DatabaseExampleUnitTestCase extends BackdropWebTestCase { /** * {@inheritdoc} */ public function setUp() { parent::setUp('database_example'); } /** * Tests the default module installation, two entries in the database table. */ public function testInstall() { $result = database_example_entry_load(); $this->assertEqual(count($result), 2, 'Found two entries in the table after installing the module.'); } /** * Tests the UI. */ public function testUI() { // Test the basic list. $this->backdropGet('examples/database_example'); $this->assertPattern("/John[td\/<>\w]+Doe/", "Text 'John Doe' found in table"); // Test the add tab. // Add the new entry. $this->backdropPost('examples/database_example/add', array( 'name' => 'Some', 'surname' => 'Anonymous', 'age' => 33, ), t('Add') ); cache('page')->flush(); // Now find the new entry. $this->backdropGet('examples/database_example'); $this->assertPattern("/Some[td\/<>\w]+Anonymous/", "Text 'Some Anonymous' found in table"); // Try the update tab. // Find out the pid of our "anonymous" guy. $result = database_example_entry_load(array('surname' => 'Anonymous')); $this->backdropGet("examples/database_example"); $this->assertEqual(count($result), 1, 'Found one entry in the table with surname = "Anonymous".'); $entry = $result[0]; unset($entry->uid); $entry->name = 'NewFirstName'; $this->backdropPost('examples/database_example/update', (array) $entry, t('Update')); cache('page')->flush(); // Now find the new entry. $this->backdropGet('examples/database_example'); $this->assertPattern("/NewFirstName[td\/<>\w]+Anonymous/", "Text 'NewFirstName Anonymous' found in table"); // Try the advanced tab. $this->backdropGet('examples/database_example/advanced'); $rows = $this->xpath("//*[contains(@class, 'l-content')]/table[1]/tbody/tr"); $this->assertEqual(count($rows), 1, "One row found in advanced view"); $this->assertFieldByXPath("//*[contains(@class, 'l-content')]/table[1]/tbody/tr/td[4]", "Roe", "Name 'Roe' Exists in advanced list"); } /** * Tests several combinations, adding entries, updating and deleting. */ public function testAPIExamples() { // Create a new entry. $entry = array( 'name' => 'James', 'surname' => 'Doe', 'age' => 23, ); database_example_entry_insert($entry); // Save another entry. $entry = array( 'name' => 'Jane', 'surname' => 'NotDoe', 'age' => 19, ); database_example_entry_insert($entry); // Verify that 4 records are found in the database. $result = database_example_entry_load(); $this->assertEqual(count($result), 4, 'Found a total of four entries in the table after creating two additional entries.'); // Verify 2 of these records have 'Doe' as surname. $result = database_example_entry_load(array('surname' => 'Doe')); $this->assertEqual(count($result), 2, 'Found two entries in the table with surname = "Doe".'); // Now find our not-Doe entry. $result = database_example_entry_load(array('surname' => 'NotDoe')); $this->assertEqual(count($result), 1, 'Found one entry in the table with surname "NotDoe'); // Our NotDoe will be changed to "NowDoe". $entry = $result[0]; $entry->surname = "NowDoe"; database_example_entry_update((array) $entry); $result = database_example_entry_load(array('surname' => 'NowDoe')); $this->assertEqual(count($result), 1, "Found renamed 'NowDoe' surname"); // Read only John Doe entry. $result = database_example_entry_load(array('name' => 'John', 'surname' => 'Doe')); $this->assertEqual(count($result), 1, 'Found one entry for John Doe.'); // Get the entry. $entry = (array) end($result); // Change the age to 45 and update the entry in the database. $entry['age'] = 45; database_example_entry_update((array) $entry); // Find entries with age equal to 45 where the surname is NowDoe. $result = database_example_entry_load(array('surname' => 'NowDoe')); $this->assertEqual(count($result), 1, 'Found one entry with surname = Nowdoe.'); // Verify it is Jane NowDoe. $entry = (array) end($result); $this->assertEqual($entry['name'], 'Jane', 'The name Jane has been found in the database'); $this->assertEqual($entry['surname'], 'NowDoe', 'The surname NowDoe has been found in the database'); // Delete the entry. database_example_entry_delete($entry); // Verify that now there are only 3 records. $result = database_example_entry_load(); $this->assertEqual(count($result), 3, 'Found only three records.'); } } ``` -------------------------------- ### Define Head Tag Elements in Backdrop CMS Source: https://docs.backdropcms.org/form_api Example of defining meta tags for character set and generator information using the '#type' => 'head_tag' property. Ensure the Content-Type meta tag is output first for security. ```php 'head_tag',     '#tag' => 'meta',     '#attributes' => array(       'charset' => 'utf-8',     ),     // Security: This always has to be output first.     '#weight' => -1000,   );   // Show Backdrop and the major version number in the META GENERATOR tag.   // Get the major version.   list($version, ) = explode('.', BACKDROP_VERSION);   $elements['system_meta_generator'] = array(     '#type' => 'head_tag',     '#tag' => 'meta',     '#attributes' => array(       'name' => 'Generator',       'content' => 'Backdrop CMS ' . $version . ' (https://backdropcms.org)',     ),   );   // Also send the generator in the HTTP header.   $elements['system_meta_generator']['#attached']['backdrop_add_http_header'][] = array('X-Generator', $elements['system_meta_generator']['#attributes']['content']);   return $elements; } ?> ``` -------------------------------- ### Handle Already Installed Error Source: https://docs.backdropcms.org/api/backdrop/core%21includes%21install.core.inc/1 Returns a themed list of items guiding the user when Backdrop has already been installed, offering options to start over, change database settings, or view the existing site. ```php function install_already_done_error() { global $base_url; backdrop_set_title(st('Backdrop already installed')); $items = array(); $items[] = st('To start over, you must empty your existing database.'); $settings_php = st('To install to a different database, edit the settings.php file located in the root folder of this site.'); if (conf_path() !== '.') { $settings_php = st('To install to a different database, edit the settings.php file corresponding to this site within the sites directory.'); } $items[] = $settings_php; $items[] = st('To upgrade an existing installation, proceed to the update script.', array('@base-url' => $base_url)); $items[] = st('View your existing site.', array('@base-url' => $base_url)); return theme('item_list', array('items' => $items)); } ``` -------------------------------- ### SimpleTestExampleTestCase Setup and Node Creation Source: https://docs.backdropcms.org/api/backdrop/modules%21examples%21simpletest_example%21tests%21simpletest_example.test/class/SimpleTestExampleTestCase/1 Sets up the test environment by enabling modules and logging in a privileged user. It then demonstrates creating a 'simpletest_example' node and asserting its successful creation. ```php class SimpleTestExampleTestCase extends BackdropWebTestCase { protected $privilegedUser; /** * Set up the test environment. * * This method is called once per test method, before the test is executed. * * If you need a different test environment, then you should create another * test class which overloads BackdropWebTestCase::setUp() differently. * * @see BackdropWebTestCase::setUp() */ public function setUp() { // We call parent::setUp() with the list of modules we want to enable. // This can be an array or just a list of arguments. parent::setUp('simpletest_example'); // Create and log in our user. The user has the arbitrary privilege // 'extra special edit simpletest_example' which is provided by // our module to grant access. $this->privilegedUser = $this->backdropCreateUser(array('create simpletest_example content', 'extra special edit any simpletest_example')); $this->backdropLogin($this->privilegedUser); } /** * Create a simpletest_example node using the node form. */ public function testSimpleTestExampleCreate() { // Create node to edit. $edit = array(); $edit['title'] = $this->randomName(8); $edit["body[und][0][value]"] = $this->randomName(16); $this->backdropPost('node/add/simpletest-example', $edit, t('Save')); $this->assertText(t('SimpleTest Example Node Type @title has been created.', array('@title' => $edit['title']))); } /** * Create a simpletest_example node and then see if our user can edit it. */ public function testSimpleTestExampleEdit() { $settings = array( 'type' => 'simpletest_example', 'title' => $this->randomName(32), 'body' => array(LANGUAGE_NONE => array(array($this->randomName(64)))), ); $node = $this->backdropCreateNode($settings); // For debugging, we might output the node structure with $this->verbose() // It would only be output if the testing settings had 'verbose' set. $this->verbose('Node created: ' . var_export($node, TRUE)); // We'll run this test normally, but not on the testbot, as it would // indicate that the examples module was failing tests. if (!$this->runningOnTestbot()) { // The debug() statement will output information into the test results. // It can also be used in Backdrop anywhere in code and will come out // as a backdrop_set_message(). debug('We are not running on the PIFR testing server, so will go ahead and catch the failure.'); $this->backdropGet("node/{$node->nid}/edit"); // Make sure we don't get a 401 unauthorized response: $this->assertResponse(200, 'User is allowed to edit the content.'); // Looking for title text in the page to determine whether we were // successful opening edit form. $this->assertText(t("@title", array('@title' => $settings['title'])), "Found title in edit form"); } } /** * Detect if we're running on PIFR testbot. * * Skip intentional failure in that case. It happens that on the testbot the * site under test is in a directory named 'checkout' or 'site_under_test'. * * @return bool * TRUE if running on testbot. */ public function runningOnTestbot() { return (file_exists("../checkout") || file_exists("../site_under_test")); } } ``` -------------------------------- ### setUp() - Enable Modules and Create User Source: https://docs.backdropcms.org/api/backdrop/modules%21examples%21block_example%21tests%21block_example.test/function/BlockExampleTestCase%3A%3AsetUp/1 Overrides the parent setUp method to enable the 'block_example' and 'search' modules. It then creates a web user with permissions to administer blocks, search content, access contextual links, and administer layouts, which are necessary for the block example tests. ```php public function setUp() { parent::setUp('block_example', 'search'); // Create user. Search content permission granted for the search block to // be shown. $this->webUser = $this->backdropCreateUser( array( 'administer blocks', 'search content', 'access contextual links', 'administer layouts', ) ); } ``` -------------------------------- ### Get Database Installer Object Source: https://docs.backdropcms.org/api/backdrop/core%21includes%21install.inc/1?order=title&sort=asc Loads the necessary driver file for database installation tasks and returns the corresponding database tasks object. This object is used to perform various checks and setup operations on the database. ```php function db_installer_object($driver) { Database::loadDriverFile($driver, array('install.inc')); ``` -------------------------------- ### FileExampleTest Class Setup Source: https://docs.backdropcms.org/api/backdrop/modules%21examples%21file_example%21tests%21file_example.test/class/FileExampleTest/1?object_type=&order=summary&sort=desc&title=&title_1= Sets up the test environment by enabling the file_example module and logging in a privileged user. ```php class FileExampleTest extends BackdropWebTestCase { protected $priviledgedUser; /** * {@inheritdoc} */ public function setUp() { parent::setUp(array('file_example')); $this->priviledgedUser = $this->backdropCreateUser(array('use file example')); $this->backdropLogin($this->priviledgedUser); } /** * Test the basic File Example UI. * * - Create a directory to work with * - Foreach scheme create and read files using each of the three methods. */ public function testFileExampleBasic() { $expected_text = array( t('Write managed file') => t('Saved managed file'), t('Write unmanaged file') => t('Saved file as'), t('Unmanaged using PHP') => t('Saved file as'), ); // For each of the three buttons == three write types. $buttons = array( t('Write managed file'), t('Write unmanaged file'), t('Unmanaged using PHP'), ); foreach ($buttons as $button) { // For each scheme supported by Backdrop + the session:// wrapper. $schemes = array('public', 'private', 'temporary', 'session'); foreach ($schemes as $scheme) { // Create a directory for use. $dirname = $scheme . '://' . $this->randomName(10); // Directory does not yet exist; assert that. $edit = array( 'directory_name' => $dirname, ); $this->backdropPost('examples/file_example/fileapi', $edit, t('Check to see if directory exists')); $this->assertRaw(t('Directory %dirname does not exist', array('%dirname' => $dirname)), 'Verify that directory does not exist.'); $this->backdropPost('examples/file_example/fileapi', $edit, t('Create directory')); $this->assertRaw(t('Directory %dirname is ready for use', array('%dirname' => $dirname))); $this->backdropPost('examples/file_example/fileapi', $edit, t('Check to see if directory exists')); $this->assertRaw(t('Directory %dirname exists', array('%dirname' => $dirname)), 'Verify that directory now does exist.'); // Create a file in the directory we created. $content = $this->randomName(30); $filename = $dirname . '/' . $this->randomName(30) . '.txt'; // Assert that the file we're about to create does not yet exist. $edit = array( 'fileops_file' => $filename, ); $this->backdropPost('examples/file_example/fileapi', $edit, t('Check to see if file exists')); $this->assertRaw(t('The file %filename does not exist', array('%filename' => $filename)), 'Verify that file does not yet exist.'); debug( t('Processing button=%button, scheme=%scheme, dir=%dirname, file=%filename', array( '%button' => $button, '%scheme' => $scheme, '%filename' => $filename, '%dirname' => $dirname, ) ) ); $edit = array( 'write_contents' => $content, 'destination' => $filename, ); $this->backdropPost('examples/file_example/fileapi', $edit, $button); $this->assertText($expected_text[$button]); // Capture the name of the output file, as it might have changed due // to file renaming. $element = $this->xpath('//span[@id="uri"]'); $output_filename = (string) $element[0]; debug($output_filename, 'Name of output file'); // Click the link provided that is an easy way to get the data for // checking and make sure that the data we put in is what we get out. if (!in_array($scheme, array('private', 'temporary'))) { $this->clickLink(t('this URL')); $this->assertText($content); } // Verify that the file exists. $edit = array( 'fileops_file' => $filename, ); $this->backdropPost('examples/file_example/fileapi', $edit, t('Check to see if file exists')); $this->assertRaw(t('The file %filename exists', array('%filename' => $filename)), 'Verify that file now exists.'); // Now read the file that got written above and verify that we can use // the writing tools. $edit = array( 'fileops_file' => $output_filename, ); $this->backdropPost('examples/file_example/fileapi', $edit, t('Read the file and store it locally')); $this->assertText(t('The file was read and copied')); $edit = array( 'fileops_file' => $filename, ); $this->backdropPost('examples/file_example/fileapi', $edit, t('Delete file')); $this->assertText(t('Successfully deleted')); $this->backdropPost('examples/file_example/fileapi', $edit, t('Check to see if file exists')); $this->assertRaw(t('The file %filename does not exist', array('%filename' => $filename)), 'Verify file has been deleted.'); } } } } ``` -------------------------------- ### EntityAPITestCase::setUp() Example Source: https://docs.backdropcms.org/api/backdrop/core%21modules%21entity%21tests%21entity.test/function/EntityAPITestCase%3A%3AsetUp/1 This function overrides the parent setUp method to install the 'entity' and 'entity_test' modules for the duration of the test. It ensures the necessary modules are enabled before tests run. ```php function setUp() { parent::setUp('entity', 'entity_test'); } ``` -------------------------------- ### DatabaseExampleUnitTestCase::setUp() Source: https://docs.backdropcms.org/api/backdrop/modules%21examples%21database_example%21tests%21database_example.test/function/DatabaseExampleUnitTestCase%3A%3AsetUp/1 Sets up the Backdrop site for tests, enabling the 'database_example' module. This method overrides the parent setUp method to include specific module setup for the test. ```php public function setUp() { parent::setUp('database_example'); } ``` -------------------------------- ### Get Installation Profile Name Source: https://docs.backdropcms.org/api/backdrop/core%21includes%21drupal.inc/1?order=title&sort=desc Gets the name of the currently active installation profile. This function is deprecated and replaced by backdrop_get_profile(). ```APIDOC ## drupal_get_profile() ### Description Gets the name of the currently active installation profile. ### @deprecated since 1.0.0 @see backdrop_get_profile() ### Returns (string) - The name of the installation profile. ``` -------------------------------- ### Get Current Installation Profile - backdrop_get_profile() Source: https://docs.backdropcms.org/api/backdrop/core%21includes%21common.inc/function/backdrop_get_profile/1 Use this function to get the name of the active installation profile. It handles both installation-time and post-installation scenarios. ```php function backdrop_get_profile() { global $install_state; if (isset($install_state['parameters']['profile'])) { $profile = $install_state['parameters']['profile']; } else { try { $profile = config_get('system.core', 'install_profile'); } catch (ConfigException $e) { } } if (empty($profile)) { $profile = 'standard'; } return $profile; } ``` -------------------------------- ### File Example Test Class Setup Source: https://docs.backdropcms.org/api/backdrop/modules%21examples%21file_example%21tests%21file_example.test/class/FileExampleTest/1?object_type=&order=title&sort=asc&title=&title_1= Sets up the test environment by enabling the file_example module, creating a privileged user, and logging in. ```php class FileExampleTest extends BackdropWebTestCase { protected $priviledgedUser; /** * {@inheritdoc} */ public function setUp() { parent::setUp(array('file_example')); $this->priviledgedUser = $this->backdropCreateUser(array('use file example')); $this->backdropLogin($this->priviledgedUser); } /** * Test the basic File Example UI. * * - Create a directory to work with * - Foreach scheme create and read files using each of the three methods. */ public function testFileExampleBasic() { $expected_text = array( t('Write managed file') => t('Saved managed file'), t('Write unmanaged file') => t('Saved file as'), t('Unmanaged using PHP') => t('Saved file as'), ); // For each of the three buttons == three write types. $buttons = array( t('Write managed file'), t('Write unmanaged file'), t('Unmanaged using PHP'), ); foreach ($buttons as $button) { // For each scheme supported by Backdrop + the session:// wrapper. $schemes = array('public', 'private', 'temporary', 'session'); foreach ($schemes as $scheme) { // Create a directory for use. $dirname = $scheme . '://' . $this->randomName(10); // Directory does not yet exist; assert that. $edit = array( 'directory_name' => $dirname, ); $this->backdropPost('examples/file_example/fileapi', $edit, t('Check to see if directory exists')); $this->assertRaw(t('Directory %dirname does not exist', array('%dirname' => $dirname)), 'Verify that directory does not exist.'); $this->backdropPost('examples/file_example/fileapi', $edit, t('Create directory')); $this->assertRaw(t('Directory %dirname is ready for use', array('%dirname' => $dirname))); $this->backdropPost('examples/file_example/fileapi', $edit, t('Check to see if directory exists')); $this->assertRaw(t('Directory %dirname exists', array('%dirname' => $dirname)), 'Verify that directory now does exist.'); // Create a file in the directory we created. $content = $this->randomName(30); $filename = $dirname . '/' . $this->randomName(30) . '.txt'; // Assert that the file we're about to create does not yet exist. $edit = array( 'fileops_file' => $filename, ); $this->backdropPost('examples/file_example/fileapi', $edit, t('Check to see if file exists')); $this->assertRaw(t('The file %filename does not exist', array('%filename' => $filename)), 'Verify that file does not yet exist.'); debug( t('Processing button=%button, scheme=%scheme, dir=%dirname, file=%filename', array( '%button' => $button, '%scheme' => $scheme, '%filename' => $filename, '%dirname' => $dirname, ) ) ); $edit = array( 'write_contents' => $content, 'destination' => $filename, ); $this->backdropPost('examples/file_example/fileapi', $edit, $button); $this->assertText($expected_text[$button]); // Capture the name of the output file, as it might have changed due // to file renaming. $element = $this->xpath('//span[@id="uri"]'); $output_filename = (string) $element[0]; debug($output_filename, 'Name of output file'); // Click the link provided that is an easy way to get the data for // checking and make sure that the data we put in is what we get out. if (!in_array($scheme, array('private', 'temporary'))) { $this->clickLink(t('this URL')); $this->assertText($content); } // Verify that the file exists. $edit = array( 'fileops_file' => $filename, ); $this->backdropPost('examples/file_example/fileapi', $edit, t('Check to see if file exists')); $this->assertRaw(t('The file %filename exists', array('%filename' => $filename)), 'Verify that file now exists.'); // Now read the file that got written above and verify that we can use // the writing tools. $edit = array( 'fileops_file' => $output_filename, ); $this->backdropPost('examples/file_example/fileapi', $edit, t('Read the file and store it locally')); $this->assertText(t('The file was read and copied')); $edit = array( 'fileops_file' => $filename, ); $this->backdropPost('examples/file_example/fileapi', $edit, t('Delete file')); $this->assertText(t('Successfully deleted')); $this->backdropPost('examples/file_example/fileapi', $edit, t('Check to see if file exists')); $this->assertRaw(t('The file %filename does not exist', array('%filename' => $filename)), 'Verify file has been deleted.'); ``` -------------------------------- ### UserEditRebuildTestCase::setUp() - Example Source: https://docs.backdropcms.org/api/backdrop/core%21modules%21user%21tests%21user.test/function/UserEditRebuildTestCase%3A%3AsetUp/1 This is an example of how to use the setUp() method within UserEditRebuildTestCase. It calls the parent setUp() method and enables the 'user_form_test' module for the duration of the test. ```php function setUp() { parent::setUp('user_form_test'); } ``` -------------------------------- ### ActionExampleTestCase::setUp() Source: https://docs.backdropcms.org/api/backdrop/modules%21examples%21action_example%21tests%21action_example.test/function/ActionExampleTestCase%3A%3AsetUp/1 Sets up a Backdrop site for running functional and integration tests. It generates a random database prefix, installs Backdrop with a specified profile, and then installs any additional modules required by the test. After installation, caches are flushed and configuration values are reset to match the parent site's environment. ```APIDOC ## public function ActionExampleTestCase::setUp ### Description Sets up a Backdrop site for running functional and integration tests. Generates a random database prefix and installs Backdrop with the specified installation profile in BackdropWebTestCase::$profile into the prefixed database. Afterwards, installs any additional modules specified by the test. After installation all caches are flushed and several configuration values are reset to the values of the parent site executing the test, since the default values may be incompatible with the environment in which tests are being executed. ### Parameters **...** : List of modules to enable for the duration of the test. This can be either a single array or a variable number of string arguments. ### Return value **bool** : TRUE if set up completes, FALSE if an error occurred. Overrides BackdropWebTestCase::setUp ### See also BackdropWebTestCase::prepareDatabasePrefix() BackdropWebTestCase::changeDatabasePrefix() BackdropWebTestCase::prepareEnvironment() ### File modules/examples/action_example/tests/action_example.test, line 17 ### Class ActionExampleTestCase Default test case for the action_example module. ### Code ```php public function setUp() { parent::setUp('action_example'); } ``` ``` -------------------------------- ### PHP - SystemBlockTestCase::setUp() Example Source: https://docs.backdropcms.org/api/backdrop/core%21modules%21system%21tests%21system.test/function/SystemBlockTestCase%3A%3AsetUp/1 This snippet demonstrates how to set up a test environment by calling the parent setUp method with the 'block' module enabled, and then creating and logging in an administrative user. ```php function setUp() { parent::setUp('block'); // Create and login user $admin_user = $this->backdropCreateUser(array('administer site configuration', 'access administration pages')); $this->backdropLogin($admin_user); } ``` -------------------------------- ### UserCreateTestCase::setUp() Example Source: https://docs.backdropcms.org/api/backdrop/core%21modules%21user%21tests%21user.test/function/UserCreateTestCase%3A%3AsetUp/1 This is an example of how to use the setUp() function within a test case. It calls the parent setUp() method and enables the 'views' module for the test. ```php function setUp() { parent::setUp(array('views')); } ``` -------------------------------- ### JsExampleTestCase::setUp() Example Source: https://docs.backdropcms.org/api/backdrop/modules%21examples%21js_example%21tests%21js_example.test/function/JsExampleTestCase%3A%3AsetUp/1 This is an example of the setUp() method within JsExampleTestCase. It calls the parent setUp() method, passing 'js_example' as an argument to enable the js_example module for the test. ```php public function setUp() { parent::setUp('js_example'); } ```