You are here

class UbercartCartLinksTestCase in Ubercart 7.3

Same name and namespace in other branches
  1. 6.2 uc_cart_links/uc_cart_links.test \UbercartCartLinksTestCase

SimpleTests for Ubercart Cart Links.

Hierarchy

Expanded class hierarchy of UbercartCartLinksTestCase

File

uc_cart_links/tests/uc_cart_links.test, line 11
Ubercart Cart Links Tests.

View source
class UbercartCartLinksTestCase extends UbercartTestHelper {
  public static function getInfo() {
    return array(
      'name' => 'Cart Links',
      'description' => 'Test Cart Links.',
      'group' => 'Ubercart',
    );
  }

  /**
   * Overrides DrupalWebTestCase::setUp().
   */
  protected function setUp($modules = array(), $permissions = array()) {
    parent::setUp(array(
      'uc_cart_links',
      'uc_attribute',
    ), array(
      'administer cart links',
      'view cart links report',
      'access administration pages',
    ));
  }

  /**
   * Tests access to admin settings page and tests default values.
   */
  public function testCartLinksUISettingsPage() {

    // Access settings page by anonymous user.
    $this
      ->drupalGet('admin/store/settings/cart-links');
    $this
      ->assertText(t('Access denied'));
    $this
      ->assertText(t('You are not authorized to access this page.'));

    // Access settings page by privileged user.
    $this
      ->drupalLogin($this->adminUser);
    $this
      ->drupalGet('admin/store/settings/cart-links');
    $this
      ->assertText(t('View the help page to learn how to create Cart Links.'), t('Settings page found.'));
    $this
      ->assertFieldByName('uc_cart_links_add_show', 0, t('Display Cart Links product action messages is off.'));
    $this
      ->assertFieldByName('uc_cart_links_track', 1, t('Track clicks is on.'));
    $this
      ->assertFieldByName('uc_cart_links_empty', 1, t('Allow Cart Links to empty carts is on.'));
    $this
      ->assertFieldByName('uc_cart_links_messages', '', t('Cart Links messages  is empty.'));
    $this
      ->assertFieldByName('uc_cart_links_restrictions', '', t('Cart Links restrictions is empty.'));

    // Test presence of and contents of Help page.
    $this
      ->clickLink(t('View the help page'));
    $this
      ->assertText('http://www.example.com/cart/add/<cart_link_content>', t('Help text found.'));
  }

  /**
   * Tests Cart Links on a page under a variety of conditions.
   */
  public function testCartLinksBasicFunctionality() {

    // Create product.
    $products[] = $this
      ->createCartLinksProduct(FALSE);

    // Create a product class.
    $products[] = $this
      ->createCartLinksProduct(FALSE);

    // later ...
    // Create some valid Cart Links for these products.
    $link_array = $this
      ->createValidCartLinks($products);
    $cart_links = $link_array['links'];
    $link_data = $link_array['data'];

    // Need to test incorrect links as well:
    // - links which add invalid attributes.
    // - links which omit required attributes.
    // Create a page containing these links.
    $page = $this
      ->createCartLinksPage($cart_links);

    //
    // Test clicking on links.
    //
    foreach ($cart_links as $key => $test_link) {
      $this
        ->drupalGet('node/' . $page->nid);

      // Look for link on page.
      $this
        ->assertLink(t('Cart Link #@link', array(
        '@link' => $key,
      )), 0, t('Cart Link #@link found on page.', array(
        '@link' => $key,
      )));

      // Note we strip the leading / from the link for the testbot ...
      $this
        ->assertLinkByHref(t('@link', array(
        '@link' => substr($test_link, 1),
      )), 0, t('Cart Link @link found on page.', array(
        '@link' => $test_link,
      )));

      // Click on link.
      $this
        ->clickLink(t('Cart Link #@link', array(
        '@link' => $key,
      )));

      // Check for notice that item was added (this notice is set ON
      // by default, see admin/store/settings/cart).
      $this
        ->assertText(t('@title added to your shopping cart.', array(
        '@title' => $link_data[$key]['title'],
      )), t('Product @title added to cart.', array(
        '@title' => $link_data[$key]['title'],
      )));

      // Check contents of cart.
      $this
        ->drupalGet('cart');
      $this
        ->assertText($link_data[$key]['title'], t('Product title correct in cart.'));
      $this
        ->assertFieldByName('items[0][qty]', $link_data[$key]['qty'], t('Product quantity correct in cart.'));

      // Check for correct attribute name(s) in cart.
      foreach ($link_data[$key]['attributes'] as $label => $attribute) {
        $this
          ->assertText($label . ':', t('Attribute @label correct in cart.', array(
          '@label' => $label,
        )));
        foreach ($attribute as $option) {

          // Check for correct option name(s) in cart.
          $this
            ->assertText($option, t('Option @name correct in cart.', array(
            '@name' => $option,
          )));
        }
      }

      // Use the same link, but this time append an '_s' to turn
      // off message display for this product.
      $this
        ->drupalGet($test_link . '_s');

      // Default add-to-cart message is different when adding a duplicate item.
      $this
        ->assertNoText(t('Your item(s) have been updated.'), t('Default add-to-cart message suppressed.'));

      // Empty cart (press remove button).
      $this
        ->drupalPost('cart', array(), t('Remove'));
      $this
        ->assertText('There are no products in your shopping cart.');
    }
  }

  /**
   * Tests Cart Links product action messages.
   */
  public function testCartLinksProductActionMessage() {

    // Create product.
    $products[] = $this
      ->createCartLinksProduct(FALSE);

    // Create a product class.
    $products[] = $this
      ->createCartLinksProduct(FALSE);

    // later ...
    // Create some valid Cart Links for these products.
    $link_array = $this
      ->createValidCartLinks($products);
    $cart_links = $link_array['links'];
    $link_data = $link_array['data'];

    // Create a page containing these links.
    $page = $this
      ->createCartLinksPage($cart_links);
    $this
      ->drupalLogin($this->adminUser);

    //
    // Test product action message display.
    //
    // Turn on display of product action message.
    $this
      ->setCartLinksUIProductActionMessage(TRUE);

    // Go to page with Cart Links.
    $this
      ->drupalGet('node/' . $page->nid);

    // Pick one of the links at random.
    $test_link = array_rand($cart_links);
    $this
      ->clickLink(t('Cart Link #@link', array(
      '@link' => $test_link,
    )));
    $this
      ->assertText(t('Cart Link product action: @link', array(
      '@link' => substr($cart_links[$test_link], 10),
    )), t('Cart Link product action message found.'));

    // Empty cart (press remove button).
    $this
      ->drupalPost('cart', array(), t('Remove'));
    $this
      ->assertText('There are no products in your shopping cart.');

    // Turn off display of product action message.
    $this
      ->setCartLinksUIProductActionMessage(FALSE);

    // Go to page with Cart Links.
    $this
      ->drupalGet('node/' . $page->nid);

    // Pick one of the links at random.
    $test_link = array_rand($cart_links);
    $this
      ->clickLink(t('Cart Link #@link', array(
      '@link' => $test_link,
    )));
    $this
      ->assertNoText(t('Cart Link product action: @link', array(
      '@link' => substr($cart_links[$test_link], 10),
    )), t('Cart Link product action message not present.'));
    $this
      ->drupalLogout();
  }

  /**
   * Tests Cart Links cart empty action.
   */
  public function testCartLinksAllowEmptying() {

    // Create product.
    $products[] = $this
      ->createCartLinksProduct(FALSE);

    // Create a product class.
    $products[] = $this
      ->createCartLinksProduct(FALSE);

    // later ...
    // Create some valid Cart Links for these products.
    $link_array = $this
      ->createValidCartLinks($products);
    $cart_links = $link_array['links'];
    $link_data = $link_array['data'];

    // Create a page containing these links.
    $page = $this
      ->createCartLinksPage($cart_links);
    $this
      ->drupalLogin($this->adminUser);

    //
    // Test empty cart action.
    //
    // Allow links to empty cart.
    $this
      ->setCartLinksUIAllowEmptying(TRUE);

    // Go to page with Cart Links.
    $this
      ->drupalGet('node/' . $page->nid);

    // Pick one of the links at random and add it to the cart.
    $test_link_0 = array_rand($cart_links);
    $this
      ->clickLink(t('Cart Link #@link', array(
      '@link' => $test_link_0,
    )));

    // Pick another link at random and prepend an 'e-' so it will empty cart.
    $in_cart = $cart_links[$test_link_0];

    // (Don't want to use the same link.)
    unset($cart_links[$test_link_0]);
    $test_link = array_rand($cart_links);
    $this
      ->drupalGet(str_replace('add/p', 'add/e-p', $cart_links[$test_link]));
    $this
      ->assertText(t('The current contents of your shopping cart will be lost. Are you sure you want to continue?'), t('Empty cart confirmation page found.'));

    // Allow.
    $this
      ->drupalPost(NULL, array(), t('Confirm'));

    // Verify the cart doesn't have the first item and does have the second item.
    $this
      ->drupalGet('cart');
    $this
      ->assertText($link_data[$test_link]['title'], t('Product title correct in cart.'));
    $this
      ->assertNoText($link_data[$test_link_0]['title'], t('Cart was emptied by Cart Link.'));

    // Still have something ($test_link) in the cart.
    // Forbid links to empty cart.
    $this
      ->setCartLinksUIAllowEmptying(FALSE);

    // Re-use $test_link_0 and prepend an 'e-' so it will (try to) empty cart.
    $this
      ->drupalGet(str_replace('add/p', 'add/e-p', $in_cart));

    // Verify the cart has both items - cart wasn't emptied.
    $this
      ->drupalGet('cart');
    $this
      ->assertText($link_data[$test_link_0]['title'], t('Cart was not emptied by Cart Link.'));
    $this
      ->assertText($link_data[$test_link]['title'], t('Cart was not emptied by Cart Link.'));
    $this
      ->drupalLogout();
  }

  /**
   * Tests Cart Links restrictions.
   */
  public function testCartLinksRestrictions() {

    // Create product.
    $products[] = $this
      ->createCartLinksProduct(FALSE);

    // Create a product class.
    $products[] = $this
      ->createCartLinksProduct(FALSE);

    // later ...
    // Create some valid Cart Links for these products.
    $link_array = $this
      ->createValidCartLinks($products);
    $cart_links = $link_array['links'];
    $link_data = $link_array['data'];

    // Create a page containing these links.
    $page = $this
      ->createCartLinksPage($cart_links);
    $this
      ->drupalLogin($this->adminUser);

    //
    // Test Cart Links restrictions.
    //
    // Go to page with Cart Links.
    $this
      ->drupalGet('node/' . $page->nid);

    // Pick one of the links at random and restrict it.
    $test_link_0 = array_rand($cart_links);

    // Only this link is allowed - strip '/cart/add/' from beginning
    $this
      ->setCartLinksUIRestrictions(substr($cart_links[$test_link_0], 10));

    // Attempt to click link - should pass.
    $this
      ->drupalGet('node/' . $page->nid);
    $this
      ->clickLink(t('Cart Link #@link', array(
      '@link' => $test_link_0,
    )));

    // Check for notice that item was added (this notice is set ON
    // by default, see admin/store/settings/cart).
    $this
      ->assertText(t('@title added to your shopping cart.', array(
      '@title' => $link_data[$test_link_0]['title'],
    )), t('Product @title added to cart.', array(
      '@title' => $link_data[$test_link_0]['title'],
    )));

    // Pick another link at random, as long as it is different from first.
    $in_cart = $cart_links[$test_link_0];
    unset($cart_links[$test_link_0]);
    $test_link = array_rand($cart_links);

    // Attempt to click it.
    // It should fail and redirect to the home page (default).
    $this
      ->drupalGet('node/' . $page->nid);
    $this
      ->clickLink(t('Cart Link #@link', array(
      '@link' => $test_link,
    )));
    $this
      ->assertText(t('Welcome to Drupal'));
    $this
      ->assertText(t('No front page content has been created yet.'), t('Redirected to front page for link not in restrictions.'));

    // Now create a special redirect page for bad links.
    $redirect_page = $this
      ->drupalCreateNode(array(
      'body' => array(
        LANGUAGE_NONE => array(
          array(
            'value' => 'ERROR: Invalid Cart Link!',
          ),
        ),
      ),
    ));

    // Set redirect link.
    $this
      ->setCartLinksUIRedirect('node/' . $redirect_page->nid);

    // Attempt to click same restricted link as above.
    // It should fail again but this time redirect to $redirect_page.
    $this
      ->drupalGet('node/' . $page->nid);
    $this
      ->clickLink(t('Cart Link #@link', array(
      '@link' => $test_link,
    )));
    $this
      ->assertText(t('ERROR: Invalid Cart Link!'), t('Redirected to error page for link not in restrictions.'));

    // Remove restrictions, try to add again - it should pass.
    $this
      ->setCartLinksUIRestrictions('');
    $this
      ->drupalGet('node/' . $page->nid);
    $this
      ->clickLink(t('Cart Link #@link', array(
      '@link' => $test_link,
    )));
    $this
      ->assertText(t('@title added to your shopping cart.', array(
      '@title' => $link_data[$test_link]['title'],
    )), t('Product @title added to cart.', array(
      '@title' => $link_data[$test_link]['title'],
    )));
    $this
      ->drupalLogout();
  }

  /**
   * Tests Cart Links messages.
   *
   * To stop the default "xxx was added to your shopping cart" message for
   * a product, use the argument "_s". For example /cart/add/p23_s
   * "_s" is an argument to the "p" action, and suppresses the message for this
   * product only.  Other products added by other actions in the Cart Link
   * will still show the message.  e.g. /cart/add/p23_s-p15 will show a message
   * for product 15 but not for product 23.
   *
   * To insert your own message, first define your message in the Cart Links
   * messages panel on the Cart Links settings page, by entering for example
   * "99|My message text". Then use the action "-m99" (a dash, not an
   * underscore) to add the message. For example, /cart/add/p23-m99
   *
   * Note that just specifying "-m99" will display both your message 99 and the
   * default message, unless you have turned off the default message with "_s".
   *
   * For additional messages, add additional actions, e.g. "-m99-m1337".
   */
  public function testCartLinksMessages() {

    // Create product.
    $products[] = $this
      ->createCartLinksProduct(FALSE);

    // Create a product class.
    $products[] = $this
      ->createCartLinksProduct(FALSE);

    // later ...
    // Create some valid Cart Links for these products.
    $link_array = $this
      ->createValidCartLinks($products);
    $cart_links = $link_array['links'];
    $link_data = $link_array['data'];

    // Create a page containing these links.
    $page = $this
      ->createCartLinksPage($cart_links);

    // Need to be admin to define messages.
    $this
      ->drupalLogin($this->adminUser);

    // Define some messages.
    $messages = array();
    for ($i = 0; $i < 15; $i++) {
      $key = mt_rand(1, 999);
      $messages[$key] = $key . '|' . $this
        ->randomName(32);
    }
    $this
      ->setCartLinksUIMessages($messages);

    //
    // Test message display.
    //
    // Go to page with Cart Links.
    $this
      ->drupalGet('node/' . $page->nid);

    // Pick one link at random and append an '-m<#>' to display a message.
    $test_link = array_rand($cart_links);
    $message_key = array_rand($messages);
    $message_text = explode('|', $messages[$message_key]);
    $this
      ->drupalGet($cart_links[$test_link] . '-m' . $message_key);
    $this
      ->assertText(t('@message', array(
      '@message' => $message_text[1],
    )), t('Message @key displayed.', array(
      '@key' => $message_key,
    )));

    // Empty cart (press remove button).
    $this
      ->drupalPost('cart', array(), t('Remove'));
    $this
      ->assertText('There are no products in your shopping cart.');
    $this
      ->drupalLogout();
  }

  /**
   * Tests Cart Links tracking.
   */
  public function testCartLinksTracking() {

    // Create product.
    $products[] = $this
      ->createCartLinksProduct(FALSE);

    // Create a product class.
    $products[] = $this
      ->createCartLinksProduct(FALSE);

    // later ...
    // Create some valid Cart Links for these products.
    $link_array = $this
      ->createValidCartLinks($products);
    $cart_links = $link_array['links'];
    $link_data = $link_array['data'];

    // Create a page containing these links.
    $page = $this
      ->createCartLinksPage($cart_links);
    $this
      ->drupalLogin($this->adminUser);

    //
    // Test Cart Links tracking.
    //
    // Go to page with Cart Links.
    $this
      ->drupalGet('node/' . $page->nid);

    // Create three tracking IDs.
    $tracking = array();
    for ($i = 0; $i < 3; $i++) {
      $tracking[$this
        ->randomName(16)] = 0;
    }

    // Click a number of links to create some statistics.
    for ($i = 0; $i < 50; $i++) {

      // Pick one link at random and append an '-i<tracking ID>'.
      $test_link = array_rand($cart_links);

      // Assign one of the tracking IDs.
      $tracking_id = array_rand($tracking);
      $this
        ->drupalGet($cart_links[$test_link] . '-i' . $tracking_id);

      // Keep a record of how many links were assigned this key.
      $tracking[$tracking_id] += 1;
    }

    // Check report to see these clicks have been recorded correctly.
    $this
      ->drupalGet('admin/store/reports/cart-links');
    $total = 0;
    foreach ($tracking as $id => $clicks) {
      $total += $clicks;
      $this
        ->assertRaw(t('<td>@id</td><td>@clicks</td>', array(
        '@id' => $id,
        '@clicks' => $clicks,
      )), t('Tracking ID @id received @clicks clicks.', array(
        '@id' => $id,
        '@clicks' => $clicks,
      )));
    }
    $this
      ->assertEqual($total, 50, t('Fifty clicks recorded.'));
    $this
      ->drupalLogout();
  }

  /****************************************************************************
   * Utility Functions                                                        *
   ****************************************************************************/

  /**
   * Sets checkbox to display Cart Links product action messages.
   *
   * Must be logged in with 'administer cart links' permission.
   *
   * @param $state
   *   TRUE to display product action messages, FALSE to not display.
   *   Defaults to FALSE.
   */
  protected function setCartLinksUIProductActionMessage($state = FALSE) {
    $this
      ->drupalPost('admin/store/settings/cart-links', array(
      'uc_cart_links_add_show' => $state,
    ), t('Save configuration'));
    $this
      ->assertFieldByName('uc_cart_links_add_show', $state, t('Display Cart Links product action messages is @state.', array(
      '@state' => $state ? 'TRUE' : 'FALSE',
    )));
  }

  /**
   * Sets checkbox to track Cart Links clicks.
   *
   * Must be logged in with 'administer cart links' permission.
   *
   * @param $state
   *   TRUE to display product action messages, FALSE to not display.
   *   Defaults to TRUE.
   */
  protected function setCartLinksUITrackClicks($state = TRUE) {
    $this
      ->drupalPost('admin/store/settings/cart-links', array(
      'uc_cart_links_track' => 0,
    ), t('Save configuration'));
    $this
      ->assertFieldByName('uc_cart_links_track', $state ? 1 : 0, t('Track clicks is @state.', array(
      '@state' => $state ? 'TRUE' : 'FALSE',
    )));
  }

  /**
   * Sets checkbox to allow Cart Links to empty cart.
   *
   * Must be logged in with 'administer cart links' permission.
   *
   * @param $state
   *   TRUE to display product action messages, FALSE to not display.
   *   Defaults to TRUE.
   */
  protected function setCartLinksUIAllowEmptying($state = TRUE) {
    $this
      ->drupalPost('admin/store/settings/cart-links', array(
      'uc_cart_links_empty' => $state,
    ), t('Save configuration'));
    $this
      ->assertFieldByName('uc_cart_links_empty', $state, t('Allow Cart Links to empty carts is @state.', array(
      '@state' => $state ? 'TRUE' : 'FALSE',
    )));
  }

  /**
   * Sets messages that can be referenced by a link.
   *
   * Must be logged in with 'administer cart links' permission.
   *
   * @param $messages
   *   String containing user input from a textarea, one message per line.
   *   Messages have numeric key and text value, separated by '|'.
   */
  protected function setCartLinksUIMessages($messages = '') {
    $message_string = implode("\n", $messages);
    $this
      ->drupalPost('admin/store/settings/cart-links', array(
      'uc_cart_links_messages' => $message_string,
    ), t('Save configuration'));
    $this
      ->assertFieldByName('uc_cart_links_messages', $message_string, t('Cart Links messages contains "@messages".', array(
      '@messages' => $message_string,
    )));
  }

  /**
   * Sets allowed Cart Links.
   *
   * Must be logged in with 'administer cart links' permission.
   *
   * @param $restrictions
   *   String containing user input from a textarea, one restriction per line.
   *   Restrictions are valid Cart Links - i.e. relative URLs.
   */
  protected function setCartLinksUIRestrictions($restrictions = '') {
    $this
      ->drupalPost('admin/store/settings/cart-links', array(
      'uc_cart_links_restrictions' => $restrictions,
    ), t('Save configuration'));
    $this
      ->assertFieldByName('uc_cart_links_restrictions', $restrictions, t('Cart Links restrictions contains "@restrictions".', array(
      '@restrictions' => $restrictions,
    )));
  }

  /**
   * Sets redirect destination page for invalid Cart Links.
   *
   * Must be logged in with 'administer cart links' permission.
   *
   * @param $url
   *   Relative URL of the destination page for the redirect.  Omit leading '/'.
   */
  protected function setCartLinksUIRedirect($url = '') {
    $this
      ->drupalPost('admin/store/settings/cart-links', array(
      'uc_cart_links_invalid_page' => $url,
    ), t('Save configuration'));
    $this
      ->assertFieldByName('uc_cart_links_invalid_page', $url, t('Cart Links invalid page URL contains "@url".', array(
      '@url' => $url,
    )));
  }

  /**
   * Create a page with Cart Links in the body.
   *
   * @param $links
   *   Array of Cart Links to appear on page.
   */
  protected function createCartLinksPage($links = array()) {
    if (!empty($links)) {
      $i = 0;
      foreach ($links as $link) {
        $body['links'][] = array(
          'title' => t('Cart Link #@num', array(
            '@num' => $i++,
          )),
          'href' => $link,
        );
      }
    }
    $page = array(
      'type' => 'page',
      // This is default anyway ...
      'body' => array(
        LANGUAGE_NONE => array(
          array(
            'value' => isset($body) ? theme('links', $body) : $this
              ->randomName(128),
            'format' => filter_default_format(),
          ),
        ),
      ),
    );
    return $this
      ->drupalCreateNode($page);
  }

  /**
   * Creates a product with all attribute types and options.
   *
   * @param $product_class
   *   Defaults to FALSE to create a normal product, set to TRUE to
   *   create a product class instead.
   */
  protected function createCartLinksProduct($product_class = FALSE) {

    // Create a product.
    if ($product_class) {
      $product = $this
        ->createProductClass();
    }
    else {
      $product = $this
        ->createProduct();
    }

    // Create some attributes.
    for ($i = 0; $i < 5; $i++) {
      $attribute = UbercartAttributeTestCase::createAttribute();
      $attributes[$attribute->aid] = $attribute;
    }

    // Add some options, organizing them by aid and oid.
    $attribute_aids = array_keys($attributes);
    $all_options = array();
    foreach ($attribute_aids as $aid) {
      for ($i = 0; $i < 3; $i++) {
        $option = UbercartAttributeTestCase::createAttributeOption(array(
          'aid' => $aid,
        ));
        $all_options[$option->aid][$option->oid] = $option;
      }
    }

    // array('required' => TRUE)
    // Get the options.
    $attribute = uc_attribute_load($attribute->aid);

    // Load every attribute we got.
    $attributes_with_options = uc_attribute_load_multiple();

    // Pick 5 keys to check at random.
    $aids = drupal_map_assoc(array_rand($attributes, 3));

    // Load the attributes back.
    $loaded_attributes = uc_attribute_load_multiple($aids);

    // TODO: add attributes of all 4 types.
    // TODO: create both required and not required attributes.
    // Add the selected attributes to the product.
    foreach ($loaded_attributes as $loaded_attribute) {
      uc_attribute_subject_save($loaded_attribute, 'product', $product->nid, TRUE);
    }
    return $product;
  }

  /**
   * Creates Cart Links pointing to the given product(s).
   *
   * Links containing many combinations of attributes and options wil be
   * returned. Return value is an associative array containing two keys:
   *   -links: An array of the actual links we're building.
   *   -data: An array of metadata about the Cart Links so we won't have to try
   *   to re-construct this information by parsing the link at a later time.
   *
   * The 'links' and 'data' sub-arrays are both indexed by the keys used in
   * the $products array that is passed in as an argument, so these keys may
   * be used to lookup the link and metadata for a specific product.
   *
   * @param $products
   *   An array of products.
   *
   * @return
   *   Array containing Cart Links and link metadata.
   */
  protected function createValidCartLinks($products = array()) {
    foreach ($products as $key => $product) {
      $nid = $product->nid;
      $title = $product->title;
      $qty = mt_rand(1, 19);

      // $link_data will hold meta information about the Cart Links
      // so we won't have to try to re-construct this information by
      // parsing the link at a later time.
      $link_data[$key] = array(
        'nid' => $nid,
        'title' => $title,
        'qty' => $qty,
        'attributes' => array(),
      );

      // $cart_links will hold the actual links we're building.
      // $cart_links and $link_data share the same keys.
      $cart_links[$key] = '/cart/add/p' . $nid . '_q' . $qty;

      // Loop over attributes, append all attribute/option combos to links.
      $attributes = uc_product_get_attributes($nid);
      foreach ($attributes as $attribute) {

        // If this is textfield, radio, or select option, then
        // only 1 option allowed.  If checkbox, multiple are allowed.
        switch ($attribute->display) {
          case 0:

            // textfield
            $value = $this
              ->randomName(12);

            // Textfield
            $link_data[$key]['attributes'][$attribute->label][] = $value;
            $cart_links[$key] .= '_a' . $attribute->aid . 'o' . $value;
            break;
          case 1:

          // select
          case 2:

            // radios
            $option = $attribute->options[array_rand($attribute->options)];
            $link_data[$key]['attributes'][$attribute->label][] = $option->name;
            $cart_links[$key] .= '_a' . $attribute->aid . 'o' . $option->oid;
            break;
          case 3:

            // checkboxes
            foreach ($attribute->options as $option) {
              $link_data[$key]['attributes'][$attribute->label][] = $option->name;
              $cart_links[$key] .= '_a' . $attribute->aid . 'o' . $option->oid;
            }
            break;
        }
      }
    }
    return array(
      'links' => $cart_links,
      'data' => $link_data,
    );
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DrupalTestCase::$assertions protected property Assertions thrown in that test case.
DrupalTestCase::$databasePrefix protected property The database prefix of this test run.
DrupalTestCase::$originalFileDirectory protected property The original file directory, before it was changed for testing purposes.
DrupalTestCase::$results public property Current results of this test case.
DrupalTestCase::$setup protected property Flag to indicate whether the test has been set up.
DrupalTestCase::$setupDatabasePrefix protected property
DrupalTestCase::$setupEnvironment protected property
DrupalTestCase::$skipClasses protected property This class is skipped when looking for the source of an assertion.
DrupalTestCase::$testId protected property The test run ID.
DrupalTestCase::$timeLimit protected property Time limit for the test.
DrupalTestCase::$useSetupInstallationCache public property Whether to cache the installation part of the setUp() method.
DrupalTestCase::$useSetupModulesCache public property Whether to cache the modules installation part of the setUp() method.
DrupalTestCase::$verboseDirectoryUrl protected property URL to the verbose output file directory.
DrupalTestCase::assert protected function Internal helper: stores the assert.
DrupalTestCase::assertEqual protected function Check to see if two values are equal.
DrupalTestCase::assertFalse protected function Check to see if a value is false (an empty string, 0, NULL, or FALSE).
DrupalTestCase::assertIdentical protected function Check to see if two values are identical.
DrupalTestCase::assertNotEqual protected function Check to see if two values are not equal.
DrupalTestCase::assertNotIdentical protected function Check to see if two values are not identical.
DrupalTestCase::assertNotNull protected function Check to see if a value is not NULL.
DrupalTestCase::assertNull protected function Check to see if a value is NULL.
DrupalTestCase::assertTrue protected function Check to see if a value is not false (not an empty string, 0, NULL, or FALSE).
DrupalTestCase::deleteAssert public static function Delete an assertion record by message ID.
DrupalTestCase::error protected function Fire an error assertion. 1
DrupalTestCase::errorHandler public function Handle errors during test runs. 1
DrupalTestCase::exceptionHandler protected function Handle exceptions.
DrupalTestCase::fail protected function Fire an assertion that is always negative.
DrupalTestCase::generatePermutations public static function Converts a list of possible parameters into a stack of permutations.
DrupalTestCase::getAssertionCall protected function Cycles through backtrace until the first non-assertion method is found.
DrupalTestCase::getDatabaseConnection public static function Returns the database connection to the site running Simpletest.
DrupalTestCase::insertAssert public static function Store an assertion from outside the testing context.
DrupalTestCase::pass protected function Fire an assertion that is always positive.
DrupalTestCase::randomName public static function Generates a random string containing letters and numbers.
DrupalTestCase::randomString public static function Generates a random string of ASCII characters of codes 32 to 126.
DrupalTestCase::run public function Run all tests in this class.
DrupalTestCase::verbose protected function Logs a verbose message in a text file.
DrupalWebTestCase::$additionalCurlOptions protected property Additional cURL options.
DrupalWebTestCase::$content protected property The content of the page currently loaded in the internal browser.
DrupalWebTestCase::$cookieFile protected property The current cookie file used by cURL.
DrupalWebTestCase::$cookies protected property The cookies of the page currently loaded in the internal browser.
DrupalWebTestCase::$curlHandle protected property The handle of the current cURL connection.
DrupalWebTestCase::$drupalSettings protected property The value of the Drupal.settings JavaScript variable for the page currently loaded in the internal browser.
DrupalWebTestCase::$elements protected property The parsed version of the page.
DrupalWebTestCase::$generatedTestFiles protected property Whether the files were copied to the test files directory.
DrupalWebTestCase::$headers protected property The headers of the page currently loaded in the internal browser.
DrupalWebTestCase::$httpauth_credentials protected property HTTP authentication credentials (<username>:<password>).
DrupalWebTestCase::$httpauth_method protected property HTTP authentication method
DrupalWebTestCase::$loggedInUser protected property The current user logged in using the internal browser.
DrupalWebTestCase::$originalShutdownCallbacks protected property The original shutdown handlers array, before it was cleaned for testing purposes.
DrupalWebTestCase::$originalUser protected property The original user, before it was changed to a clean uid = 1 for testing purposes.
DrupalWebTestCase::$plainTextContent protected property The content of the page currently loaded in the internal browser (plain text version).
DrupalWebTestCase::$profile protected property The profile to install as a basis for testing. 20
DrupalWebTestCase::$redirect_count protected property The number of redirects followed during the handling of a request.
DrupalWebTestCase::$session_id protected property The current session ID, if available.
DrupalWebTestCase::$session_name protected property The current session name, if available.
DrupalWebTestCase::$url protected property The URL currently loaded in the internal browser.
DrupalWebTestCase::assertField protected function Asserts that a field exists with the given name or ID.
DrupalWebTestCase::assertFieldById protected function Asserts that a field exists in the current page with the given ID and value.
DrupalWebTestCase::assertFieldByName protected function Asserts that a field exists in the current page with the given name and value.
DrupalWebTestCase::assertFieldByXPath protected function Asserts that a field exists in the current page by the given XPath.
DrupalWebTestCase::assertFieldChecked protected function Asserts that a checkbox field in the current page is checked.
DrupalWebTestCase::assertLink protected function Pass if a link with the specified label is found, and optional with the specified index.
DrupalWebTestCase::assertLinkByHref protected function Pass if a link containing a given href (part) is found.
DrupalWebTestCase::assertMail protected function Asserts that the most recently sent e-mail message has the given value.
DrupalWebTestCase::assertMailPattern protected function Asserts that the most recently sent e-mail message has the pattern in it.
DrupalWebTestCase::assertMailString protected function Asserts that the most recently sent e-mail message has the string in it.
DrupalWebTestCase::assertNoDuplicateIds protected function Asserts that each HTML ID is used for just a single element.
DrupalWebTestCase::assertNoField protected function Asserts that a field does not exist with the given name or ID.
DrupalWebTestCase::assertNoFieldById protected function Asserts that a field does not exist with the given ID and value.
DrupalWebTestCase::assertNoFieldByName protected function Asserts that a field does not exist with the given name and value.
DrupalWebTestCase::assertNoFieldByXPath protected function Asserts that a field doesn't exist or its value doesn't match, by XPath.
DrupalWebTestCase::assertNoFieldChecked protected function Asserts that a checkbox field in the current page is not checked.
DrupalWebTestCase::assertNoLink protected function Pass if a link with the specified label is not found.
DrupalWebTestCase::assertNoLinkByHref protected function Pass if a link containing a given href (part) is not found.
DrupalWebTestCase::assertNoOptionSelected protected function Asserts that a select option in the current page is not checked.
DrupalWebTestCase::assertNoPattern protected function Will trigger a pass if the perl regex pattern is not present in raw content.
DrupalWebTestCase::assertNoRaw protected function Pass if the raw text is NOT found on the loaded page, fail otherwise. Raw text refers to the raw HTML that the page generated.
DrupalWebTestCase::assertNoResponse protected function Asserts the page did not return the specified response code.
DrupalWebTestCase::assertNoText protected function Pass if the text is NOT found on the text version of the page. The text version is the equivalent of what a user would see when viewing through a web browser. In other words the HTML has been filtered out of the contents.
DrupalWebTestCase::assertNoTitle protected function Pass if the page title is not the given string.
DrupalWebTestCase::assertNoUniqueText protected function Pass if the text is found MORE THAN ONCE on the text version of the page.
DrupalWebTestCase::assertOptionSelected protected function Asserts that a select option in the current page is checked.
DrupalWebTestCase::assertPattern protected function Will trigger a pass if the Perl regex pattern is found in the raw content.
DrupalWebTestCase::assertRaw protected function Pass if the raw text IS found on the loaded page, fail otherwise. Raw text refers to the raw HTML that the page generated.
DrupalWebTestCase::assertResponse protected function Asserts the page responds with the specified response code.
DrupalWebTestCase::assertText protected function Pass if the text IS found on the text version of the page. The text version is the equivalent of what a user would see when viewing through a web browser. In other words the HTML has been filtered out of the contents.
DrupalWebTestCase::assertTextHelper protected function Helper for assertText and assertNoText.
DrupalWebTestCase::assertThemeOutput protected function Asserts themed output.
DrupalWebTestCase::assertTitle protected function Pass if the page title is the given string.
DrupalWebTestCase::assertUniqueText protected function Pass if the text is found ONLY ONCE on the text version of the page.
DrupalWebTestCase::assertUniqueTextHelper protected function Helper for assertUniqueText and assertNoUniqueText.
DrupalWebTestCase::assertUrl protected function Pass if the internal browser's URL matches the given path.
DrupalWebTestCase::buildXPathQuery protected function Builds an XPath query.
DrupalWebTestCase::changeDatabasePrefix protected function Changes the database connection to the prefixed one.
DrupalWebTestCase::checkForMetaRefresh protected function Check for meta refresh tag and if found call drupalGet() recursively. This function looks for the http-equiv attribute to be set to "Refresh" and is case-sensitive.
DrupalWebTestCase::checkPermissions protected function Check to make sure that the array of permissions are valid.
DrupalWebTestCase::clickLink protected function Follows a link by name.
DrupalWebTestCase::constructFieldXpath protected function Helper function: construct an XPath for the given set of attributes and value.
DrupalWebTestCase::copySetupCache protected function Copy the setup cache from/to another table and files directory.
DrupalWebTestCase::cronRun protected function Runs cron in the Drupal installed by Simpletest.
DrupalWebTestCase::curlClose protected function Close the cURL handler and unset the handler.
DrupalWebTestCase::curlExec protected function Initializes and executes a cURL request.
DrupalWebTestCase::curlHeaderCallback protected function Reads headers and registers errors received from the tested site.
DrupalWebTestCase::curlInitialize protected function Initializes the cURL connection.
DrupalWebTestCase::drupalCompareFiles protected function Compare two files based on size and file name.
DrupalWebTestCase::drupalCreateContentType protected function Creates a custom content type based on default settings.
DrupalWebTestCase::drupalCreateNode protected function Creates a node based on default settings.
DrupalWebTestCase::drupalCreateRole protected function Creates a role with specified permissions.
DrupalWebTestCase::drupalCreateUser protected function Create a user with a given set of permissions.
DrupalWebTestCase::drupalGet protected function Retrieves a Drupal path or an absolute path.
DrupalWebTestCase::drupalGetAJAX protected function Retrieve a Drupal path or an absolute path and JSON decode the result.
DrupalWebTestCase::drupalGetContent protected function Gets the current raw HTML of requested page.
DrupalWebTestCase::drupalGetHeader protected function Gets the value of an HTTP response header. If multiple requests were required to retrieve the page, only the headers from the last request will be checked by default. However, if TRUE is passed as the second argument, all requests will be processed…
DrupalWebTestCase::drupalGetHeaders protected function Gets the HTTP response headers of the requested page. Normally we are only interested in the headers returned by the last request. However, if a page is redirected or HTTP authentication is in use, multiple requests will be required to retrieve the…
DrupalWebTestCase::drupalGetMails protected function Gets an array containing all e-mails sent during this test case.
DrupalWebTestCase::drupalGetNodeByTitle function Get a node from the database based on its title.
DrupalWebTestCase::drupalGetSettings protected function Gets the value of the Drupal.settings JavaScript variable for the currently loaded page.
DrupalWebTestCase::drupalGetTestFiles protected function Get a list files that can be used in tests.
DrupalWebTestCase::drupalGetToken protected function Generate a token for the currently logged in user.
DrupalWebTestCase::drupalHead protected function Retrieves only the headers for a Drupal path or an absolute path.
DrupalWebTestCase::drupalLogin protected function Log in a user with the internal browser.
DrupalWebTestCase::drupalLogout protected function
DrupalWebTestCase::drupalPost protected function Execute a POST request on a Drupal page. It will be done as usual POST request with SimpleBrowser.
DrupalWebTestCase::drupalPostAJAX protected function Execute an Ajax submission.
DrupalWebTestCase::drupalSetContent protected function Sets the raw HTML content. This can be useful when a page has been fetched outside of the internal browser and assertions need to be made on the returned page.
DrupalWebTestCase::drupalSetSettings protected function Sets the value of the Drupal.settings JavaScript variable for the currently loaded page.
DrupalWebTestCase::getAbsoluteUrl protected function Takes a path and returns an absolute path.
DrupalWebTestCase::getAllOptions protected function Get all option elements, including nested options, in a select.
DrupalWebTestCase::getSelectedItem protected function Get the selected value from a select field.
DrupalWebTestCase::getSetupCacheKey protected function Returns the cache key used for the setup caching.
DrupalWebTestCase::getUrl protected function Get the current URL from the cURL handler.
DrupalWebTestCase::handleForm protected function Handle form input related to drupalPost(). Ensure that the specified fields exist and attempt to create POST data in the correct manner for the particular field type.
DrupalWebTestCase::loadSetupCache protected function Copies the cached tables and files for a cached installation setup.
DrupalWebTestCase::parse protected function Parse content returned from curlExec using DOM and SimpleXML.
DrupalWebTestCase::preloadRegistry protected function Preload the registry from the testing site.
DrupalWebTestCase::prepareDatabasePrefix protected function Generates a database prefix for running tests.
DrupalWebTestCase::prepareEnvironment protected function Prepares the current environment for running the test.
DrupalWebTestCase::recursiveDirectoryCopy protected function Recursively copy one directory to another.
DrupalWebTestCase::refreshVariables protected function Refresh the in-memory set of variables. Useful after a page request is made that changes a variable in a different thread. 1
DrupalWebTestCase::resetAll protected function Reset all data structures after having enabled new modules.
DrupalWebTestCase::storeSetupCache protected function Store the installation setup to a cache.
DrupalWebTestCase::tearDown protected function Delete created files and temporary files directory, delete the tables created by setUp(), and reset the database prefix. 6
DrupalWebTestCase::verboseEmail protected function Outputs to verbose the most recent $count emails sent.
DrupalWebTestCase::xpath protected function Perform an xpath search on the contents of the internal browser. The search is relative to the root element (HTML tag normally) of the page.
DrupalWebTestCase::__construct function Constructor for DrupalWebTestCase. Overrides DrupalTestCase::__construct 1
UbercartCartLinksTestCase::createCartLinksPage protected function Create a page with Cart Links in the body.
UbercartCartLinksTestCase::createCartLinksProduct protected function Creates a product with all attribute types and options.
UbercartCartLinksTestCase::createValidCartLinks protected function Creates Cart Links pointing to the given product(s).
UbercartCartLinksTestCase::getInfo public static function
UbercartCartLinksTestCase::setCartLinksUIAllowEmptying protected function Sets checkbox to allow Cart Links to empty cart.
UbercartCartLinksTestCase::setCartLinksUIMessages protected function Sets messages that can be referenced by a link.
UbercartCartLinksTestCase::setCartLinksUIProductActionMessage protected function Sets checkbox to display Cart Links product action messages.
UbercartCartLinksTestCase::setCartLinksUIRedirect protected function Sets redirect destination page for invalid Cart Links.
UbercartCartLinksTestCase::setCartLinksUIRestrictions protected function Sets allowed Cart Links.
UbercartCartLinksTestCase::setCartLinksUITrackClicks protected function Sets checkbox to track Cart Links clicks.
UbercartCartLinksTestCase::setUp protected function Overrides DrupalWebTestCase::setUp(). Overrides UbercartTestHelper::setUp
UbercartCartLinksTestCase::testCartLinksAllowEmptying public function Tests Cart Links cart empty action.
UbercartCartLinksTestCase::testCartLinksBasicFunctionality public function Tests Cart Links on a page under a variety of conditions.
UbercartCartLinksTestCase::testCartLinksMessages public function Tests Cart Links messages.
UbercartCartLinksTestCase::testCartLinksProductActionMessage public function Tests Cart Links product action messages.
UbercartCartLinksTestCase::testCartLinksRestrictions public function Tests Cart Links restrictions.
UbercartCartLinksTestCase::testCartLinksTracking public function Tests Cart Links tracking.
UbercartCartLinksTestCase::testCartLinksUISettingsPage public function Tests access to admin settings page and tests default values.
UbercartTestHelper::$adminUser protected property User with privileges to do everything.
UbercartTestHelper::$customer protected property Authenticated but unprivileged user.
UbercartTestHelper::$product protected property Test product.
UbercartTestHelper::assertAjaxHelper protected function Helper function to test for text in a drupal ajax response.
UbercartTestHelper::assertAjaxRaw protected function Assert that the specified text is present in the raw drupal ajax response.
UbercartTestHelper::assertAjaxText protected function Assert that the specified text is present in the plain text version of the html that would be inserted into the page if this ajax response were executed.
UbercartTestHelper::assertNoAjaxRaw protected function Assert that the specified text is not present in the raw drupal ajax response.
UbercartTestHelper::assertNoAjaxText protected function Assert that the specified text is not present in the plain text version of the html that would be inserted into the page if this ajax response were executed.
UbercartTestHelper::checkout protected function Executes the checkout process.
UbercartTestHelper::createProduct protected function Creates a new product.
UbercartTestHelper::createProductClass protected function Creates a new product class.
UbercartTestHelper::findMail protected function Assert that an email was sent with a specific subject line.
UbercartTestHelper::populateCheckoutForm protected function Helper function to fill-in required fields on the checkout page.
UbercartTestHelper::ucPostAJAX protected function Extends drupalPostAjax() to replace additional content on the page after an ajax submission.