You are here

userpoints.test in User Points 7.2

Contains test classes for userpoints module.

File

userpoints.test
View source
<?php

// Author: Jacob Redding
// additional tests added by Zhao ning (nzhao, user/96328)

/**
 * @file
 * Contains test classes for userpoints module.
 */

/**
 * Userpoints base test class with various helper functions.
 */
class UserpointsBaseTestCase extends DrupalWebTestCase {

  /**
   * Add points through the admin form.
   *
   * @param $points
   *   Amount of points to add.
   * @param $user
   *   User object for which to grant points for.
   * @param $total
   *   Amount of points the user should have after the points have been added.
   *   If not NULL, the confirmation string is checked and so is
   *   userpoints_get_current_points().
   *
   * @return
   *   The most recent transaction id, assuming that this belongs to this
   *   transaction.
   */
  function addPoints($points, $user, $total = NULL, $additional = array()) {
    $edit = array(
      'txn_user' => $user->name,
      'points' => $points,
    ) + $additional;
    $this
      ->drupalPost('admin/config/people/userpoints/add', $edit, t('Save'));
    if ($total !== NULL) {
      $categories = userpoints_get_categories();
      $tid = userpoints_get_default_tid();
      $category = $categories[$tid];
      $this
        ->assertText(t('@name just earned @points points and now has @total points in the @category category.', array(
        '@name' => $user->name,
        '@points' => $points,
        '@total' => $total,
        '@category' => $category,
      )), t('Correct confirmation message displayed.'));
      $this
        ->assertEqual($total, userpoints_get_current_points($user->uid, $tid), t('User has the correct total amount of points.'));
    }
    return db_query('SELECT MAX(txn_id) FROM {userpoints_txn} WHERE uid = :uid', array(
      ':uid' => $user->uid,
    ))
      ->fetchField();
  }

  /**
   * Verify the current and optionally max points in a specific category.
   *
   * @param $uid
   *   User uid for the user that needs to be tested.
   * @param $current
   *   The amount of points the user is currently supposed to have.
   * @param $max
   *   The amount of max points of the user. Only tested if not NULL.
   * @param $tid
   *   The category that needs to be checked. Default is used is none is
   *   provided.
   */
  function verifyPoints($uid, $current, $max = NULL, $tid = NULL) {

    // Check if a term id is passed as a parameter.
    if (!$tid) {

      // It is not, so get the default term id.
      $tid = userpoints_get_default_tid();
    }
    $api_current = userpoints_get_current_points($uid, $tid);
    $this
      ->assertEqual($current, $api_current, t('Current points for tid %tid are correct (expected: %expected, actual: %actual).', array(
      '%expected' => $current,
      '%actual' => $api_current,
      '%tid' => $tid,
    )));
    if ($max !== NULL) {

      // Hijack static cache, delete this item from it.
      $max_cache =& drupal_static('userpoints_get_max_points', array());
      unset($max_cache[$uid][$tid]);
      $api_max = userpoints_get_max_points($uid, $tid);
      $this
        ->assertEqual($max, $api_max, t('Max points for tid %tid are correct (expected: %expected, actual: %actual).', array(
        '%expected' => $max,
        '%actual' => $api_max,
        '%tid' => $tid,
      )));
    }
  }

}

/**
 * API Tests.
 */
class UserpointsAPITestCase extends UserpointsBaseTestCase {
  private $admin_user;
  private $non_admin_user;

  /**
   * Implements getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => t('Userpoints API'),
      'description' => t('Tests the core API for proper inserts & updates to the database tables,
			  moderation, expiration, as well as permission checks'),
      'group' => t('Userpoints'),
    );
  }

  /**
   * Install userpoints module and create users.
   */
  function setUp() {
    parent::setUp('userpoints');

    // Create an administrator account.
    $this->admin_user = $this
      ->drupalCreateUser(array(
      'administer userpoints',
    ));

    // Create a standard Drupal account and log in as that person.
    $this->non_admin_user = $this
      ->drupalCreateUser();
    $this
      ->drupalLogin($this->non_admin_user);
  }

  /**
   * Returns the user points of a specific transaction.
   *
   * @param $uid
   *   User uid for which the points should be selected.
   * @param $points
   *   Optionaly define which transaction should be loaded by specifying the
   *   points.
   * @param $sum
   *   If TRUE, calculate the sum of all matching transaction rows.
   * @return
   *   Amount of points according to the arguments.
   */
  function getTxnPoints($uid, $points = NULL, $sum = FALSE) {
    $query = db_select('userpoints_txn', 'p');
    if ($sum) {
      $query
        ->addExpression('SUM(points)');
    }
    else {
      $query
        ->addField('p', 'points');
    }
    $query
      ->condition('uid', $uid);
    if ($points) {
      $query
        ->condition('points', $points);
    }
    return (int) $query
      ->execute()
      ->fetchField();
  }

  /**
   * Returns the user points.
   *
   * @param $uid
   *   User uid for which the points should be selected.
   * @param $points
   *   Optionaly define which transaction should be loaded by specifying the
   *   points.
   * @param $sum
   *   If TRUE, calculate the sum of all matching transaction rows.
   * @return
   *   Amount of points according to the arguments.
   */
  function getPoints($uid, $points = NULL, $sum = FALSE) {
    $query = db_select('userpoints', 'p');
    if ($sum) {
      $query
        ->addExpression('SUM(points)');
    }
    else {
      $query
        ->addField('p', 'points');
    }
    $query
      ->condition('uid', $uid);
    if ($points) {
      $query
        ->condition('points', $points);
    }
    return (int) $query
      ->execute()
      ->fetchField();
  }
  function testExpiration() {
    $points = rand(1, 100);
    $sum_points = 0;

    // Create various time tests.
    $times['valid']['time'] = rand(1, 10000);
    $times['valid']['string'] = '(expirydate = random number)';
    $times['expire']['time'] = REQUEST_TIME;
    $times['expire']['string'] = '(expirydate = today)';
    $times['null']['time'] = NULL;
    $times['null']['string'] = '(expirydate = NULL)';
    $bad_time = 'test string';

    // First lets check to make sure it is blocking bad times.
    try {
      userpoints_grant_points('bad_time', $points, 'userpoints', $this->non_admin_user->uid)
        ->setExpiryDate($bad_time)
        ->save();
      $this
        ->fail(t('API succesfully blocked an entry with a string as the expiry date'));
    } catch (UserpointsInvalidArgumentException $e) {
      $this
        ->pass(t('API succesfully blocked an entry with a string as the expiry date'));
    }
    foreach ($times as $key => $time) {
      $transaction = userpoints_grant_points($key, $points, 'userpoints', $this->non_admin_user->uid)
        ->setExpiryDate($time['time']);
      $transaction
        ->save();
      $this
        ->assertTrue((bool) $transaction
        ->getTxnId(), t($time['string'] . " API responded with a successful grant of points"));

      // Check the database to ensure the points were properly saved.
      $sql = "SELECT points FROM {userpoints_txn} WHERE uid = :uid AND points = :points AND expirydate = :date";
      $db_points = (int) db_query($sql, array(
        ':uid' => $this->non_admin_user->uid,
        ':points' => $points,
        ':date' => (int) $time['time'],
      ))
        ->fetchField();
      $this
        ->assertEqual($db_points, $points, t($time['string'] . "Successfully verified points in the txn table."));
      $sum_points += $points;

      // Check update point to userpoints table.
      $this
        ->assertEqual($this
        ->getPoints($this->non_admin_user->uid), $sum_points, t($time['string'] . "Successfully verified that the summary table was updated"));
    }

    // Clear the slate again.
    db_truncate('userpoints')
      ->execute();
    db_truncate('userpoints_txn')
      ->execute();

    // Set a default expire time.
    variable_set(USERPOINTS_EXPIREON_DATE, REQUEST_TIME + 5000);

    // Add two different points in, one to post immediately another to expire in the future.
    $keep_points = rand(1, 100);
    $expire_points = rand(1, 100);
    $transaction = userpoints_grant_points('must_expire', $expire_points, 'userpoints', $this->non_admin_user->uid)
      ->setExpiryDate(REQUEST_TIME - 100);
    $transaction
      ->save();
    $this
      ->assertTrue((bool) $transaction
      ->getTxnId(), t("API succesfully added points for expiration"));
    $transaction = userpoints_grant_points('must_not_expire', $keep_points, 'userpoints', $this->non_admin_user->uid)
      ->setExpiryDate(REQUEST_TIME + 10000);
    $transaction
      ->save();
    $this
      ->assertTrue((bool) $transaction
      ->getTxnId(), t("API succesfully added points for expiration"));

    // Load timestamp of the first transaction.
    $time_stamp = db_query('SELECT time_stamp FROM {userpoints_txn} WHERE operation = :op', array(
      ':op' => 'must_expire',
    ))
      ->fetchField();

    // Call cron to check expiration.
    drupal_cron_run();

    // Check the user points removed or not if the point was expiration.
    $this
      ->assertEqual($this
      ->getTxnPoints($this->non_admin_user->uid, NULL, TRUE), $keep_points, t("Successfully removed expired points from the txn table."));
    $this
      ->assertEqual($this
      ->getPoints($this->non_admin_user->uid), $keep_points, t("Successfully removed expired points from the summary table."));

    // Load the expiry transaction from the database and verify that it does
    // not expire.
    $expired_time = db_query('SELECT expirydate FROM {userpoints_txn} WHERE operation = :expiry', array(
      ':expiry' => 'expiry',
    ))
      ->fetchField();
    $this
      ->assertEqual($expired_time, 0, t('Expiry userpoints transaction does not expire.'));

    // Load expired transaction and verify that time_stamp was not updated.
    $updated_time_stamp = db_query('SELECT time_stamp FROM {userpoints_txn} WHERE expired = 1')
      ->fetchField();
    $this
      ->assertEqual($time_stamp, $updated_time_stamp, t('Time stamp of expired transaction was not changed.'));
  }

  /**
   * Changes the default expiration date in the administrative settings
   * and then checks to ensure that it is saved/returned correctly.
   */
  function testDefaultExpireDate() {

    // Login as an admin.
    $this
      ->drupalLogin($this->admin_user);

    // Use a date in the future.
    $date = REQUEST_TIME + 100000;
    $date_array = array(
      'month' => date('n', $date),
      'day' => date('d', $date),
      'year' => date('Y', $date),
    );

    // save settings.
    $edit = array(
      'userpoints_expireon_date[month]' => $date_array['month'],
      'userpoints_expireon_date[day]' => $date_array['day'],
      'userpoints_expireon_date[year]' => $date_array['year'],
    );
    $this
      ->drupalPost('admin/config/people/userpoints/settings', $edit, 'Save configuration');

    // Check database.
    $database_date = variable_get('userpoints_expireon_date', FALSE);
    $this
      ->assertEqual($database_date['day'], $date_array['day']);
    $this
      ->assertEqual($database_date['month'], $date_array['month']);
    $this
      ->assertEqual($database_date['year'], $date_array['year']);

    // Check API.
    $expiry_date = userpoints_get_default_expiry_date();
    $this
      ->assertEqual($expiry_date, userpoints_date_to_timestamp($date_array));
  }

  /**
   * Test the default term id.
   */
  function testGetDefaultTid() {
    $vid = userpoints_get_vid();
    $term_name = $this
      ->randomName(10);
    $desc = $this
      ->randomName(10);

    // create a new term.
    $term = (object) array(
      'name' => $term_name,
      'description' => $desc,
      'vid' => $vid,
    );
    taxonomy_term_save($term);

    // login as admin userpoints
    $this->admin_user = $this
      ->drupalCreateUser(array(
      'administer userpoints',
    ));
    $this
      ->drupalLogin($this->admin_user);

    // save settings.
    $edit = array(
      'userpoints_category_default_tid' => $term->tid,
    );
    $this
      ->drupalPost('admin/config/people/userpoints/settings', $edit, 'Save configuration');

    // Check database.
    $this
      ->assertEqual(variable_get('userpoints_category_default_tid', FALSE), $term->tid);

    // check API.
    $tid = userpoints_get_default_tid();
    $this
      ->assertEqual($tid, $term->tid);

    // Check database.
    $this
      ->assertTrue(variable_get('userpoints_category_default_vid', FALSE) != FALSE, t("Successfully verified the vocab ID in the database."));

    // Check API.
    $vid = userpoints_get_vid();
    $this
      ->assertTrue(is_numeric($vid), t("Successfully retrieved default vid %d.", array(
      '%d' => $vid,
    )));
  }

  /**
   * Test user permissions
   */
  function testUserpermissions() {
    $this->non_admin_username = 'test';
    $points = 10;

    // check permission with admin user.
    $this->admin_user = $this
      ->drupalCreateUser(array(
      'administer userpoints',
    ));
    $this
      ->drupalLogin($this->admin_user);

    // check access page.
    $this
      ->drupalGet('admin/config/people/userpoints');
    $content = $this
      ->drupalGetContent();
    $content = strstr($content, 'Access denied');
    $this
      ->assertTrue($content == FALSE, t("Successful navigated to the page modify points"));

    // check modify points.
    $this
      ->addPoints($points, $this->admin_user);

    // Check database.
    $this
      ->assertEqual($this
      ->getTxnPoints($this->admin_user->uid, $points), $points, t("Successful verified that points were added into database."));

    // logout and change user.
    $this
      ->drupalLogout();

    // check permission with view user.
    $view_user = $this
      ->drupalCreateUser(array(
      'view userpoints',
    ));
    $this
      ->drupalLogin($view_user);

    // check access page.
    $this
      ->drupalGet('admin/config/people/userpoints');
    $this
      ->assertResponse(403, t("Successful verified that a user without admin userpoints permissions can not access the admin interface."));
  }

  /**
   * Test user userpoints transactions permissions
   *
   * Creates users with different permissions on userpoints transactions, and
   * check both, own and other users accounts access to the userpoints
   * transaction history.
   */
  function testUserTransactionPermissions() {

    // Sets default points and creates default test users.
    $points = 10;
    $view_own_transactions_user = $this
      ->DrupalCreateUser(array(
      'view own userpoints transactions',
    ));
    $view_all_transactions_user = $this
      ->DrupalCreateUser(array(
      'view userpoints transactions',
    ));

    // Login with the admin user.
    $this
      ->drupalLogin($this->admin_user);

    // Add points to every user created.
    $this
      ->addPoints($points, $this->non_admin_user);
    $this
      ->addPoints($points, $view_own_transactions_user);
    $this
      ->addPoints($points, $view_all_transactions_user);

    // Login with no permissions.
    $this
      ->drupalLogin($this->non_admin_user);

    // Checking own account.
    $this
      ->drupalGet('myuserpoints');
    $this
      ->assertResponse(403, t("Successful verified that a user without view own userpoints transactions permission can not access to myuserpoints."));

    // Checking against other's user account.
    $this
      ->drupalGet('user/' . $view_all_transactions_user->uid . '/points');
    $this
      ->assertResponse(403, t("Successful verified that a user without view own userpoints transactions permission can not access to others user points transactions."));

    // Login as view own userpoints transactions.
    $this
      ->drupalLogin($view_own_transactions_user);

    // Checking own account.
    $this
      ->drupalGet('myuserpoints');
    $this
      ->assertResponse(200, t("Successful verified that a user with view own userpoints transactions permission can access to myuserpoints."));
    $this
      ->drupalGet('user');

    // Checking against other's user account.
    $this
      ->drupalGet('user/' . $view_all_transactions_user->uid . '/points');
    $this
      ->assertResponse(403, t("Successful verified that a user with view own userpoints transactions permission can not access to others user points transactions."));

    // Login as view userpoints transactions.
    $this
      ->drupalLogin($view_all_transactions_user);

    // Checking own account.
    $this
      ->drupalGet('myuserpoints');
    $this
      ->assertResponse(200, t("Successful verified that a user with view userpoints transactions can access to myuserpoints."));
    $this
      ->drupalGet('user');

    // Checking against other's user account.
    $this
      ->drupalGet('user/' . $this->non_admin_user->uid . '/points');
    $this
      ->assertResponse(200, t("Successful verified that a user with view userpoints transactions permission can access to others user points transactions."));
  }

  /**
   * Test user transactions links permissions on users profile.
   *
   * Creates users with different permissions on userpoints, userpoints
   * transactions and access user profiles, and check both, own and other
   * users accounts access to the userpoints transaction history links.
   */
  function testUserTransactionLinksPermissions() {

    // Sets default points and creates default test users
    $points = 10;
    $view_own_transactions_links_user = $this
      ->DrupalCreateUser(array(
      'access user profiles',
      'view own userpoints',
      'view own userpoints transactions',
    ));
    $view_all_transactions_links_user = $this
      ->DrupalCreateUser(array(
      'access user profiles',
      'view userpoints',
      'view userpoints transactions',
    ));

    // Login with the admin user.
    $this
      ->drupalLogin($this->admin_user);

    // Add points to every user created.
    $this
      ->addPoints($points, $this->non_admin_user);
    $this
      ->addPoints($points, $view_own_transactions_links_user);
    $this
      ->addPoints($points, $view_all_transactions_links_user);

    // Login with no permissions.
    $this
      ->drupalLogin($this->non_admin_user);

    // Checking own user account.
    $this
      ->drupalGet('user');
    $this
      ->assertNoLink(t('View !points transactions', userpoints_translation()), t("Successful verified that a user without view own userpoints transactions permission can not access to view points transaction link."));

    // Login as access user profiles, view own userpoints, view own userpoints transactions.
    $this
      ->drupalLogin($view_own_transactions_links_user);

    // Checking own user account.
    $this
      ->drupalGet('user');
    $this
      ->assertLink(t('View !points transactions', userpoints_translation()), 0, t("Successful verified that a user with view own userpoints transactions permission and view own userpoints permission can access to view own points transaction link."));

    // Checking others user accounts.
    $this
      ->drupalGet('user/' . $view_all_transactions_links_user->uid);
    $this
      ->assertNoLink(t('View !points transactions', userpoints_translation()), t("Successful verified that a user with view own userpoints transactions permission and view own userpoints permission can not access to view points transaction link from other user."));

    // Login as access user profiles, view userpoints, view userpoints transactions.
    $this
      ->drupalLogin($view_all_transactions_links_user);

    // Checking own user account.
    $this
      ->drupalGet('user');
    $this
      ->assertLink(t('View !points transactions', userpoints_translation()), 0, t("Successful verified that a user with view userpoints transactions permission and view userpoints permission can access to view points transaction link."));

    // Checking others user accounts.
    $this
      ->drupalGet('user/' . $view_own_transactions_links_user->uid);
    $this
      ->assertLink(t('View !points transactions', userpoints_translation()), 0, t("Successful verified that a user with view userpoints transactions permission and view userpoints permission can access to view points transaction link from other user."));
  }

}

/**
 * Administration UI tests
 */
class UserpointsAdminTestCase extends UserpointsBaseTestCase {
  private $admin_user;
  private $non_admin_user;

  /**
   * Implements getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => t('Userpoints Admin'),
      'description' => t('Test various userpoints administration forms and listings.'),
      'group' => t('Userpoints'),
    );
  }

  /**
   * Install userpoints module and create users.
   */
  function setUp() {
    parent::setUp('userpoints');

    // Create an administrator account and log in with that.
    $this->admin_user = $this
      ->drupalCreateUser(array(
      'administer userpoints',
    ));
    $this
      ->drupalLogin($this->admin_user);
  }
  function testAddEditPoints() {
    $user = $this
      ->drupalCreateUser();
    $categories = userpoints_get_categories();
    $tid = userpoints_get_default_tid();
    $category = $categories[$tid];

    // Grant some points with admin user.
    $txn_id = $this
      ->addPoints(10, $user, NULL, array(
      'moderate' => 1,
    ));
    $this
      ->assertText(t('@user just earned @points points, pending administrator approval.', array(
      '@user' => $user->name,
      '@points' => 10,
    )));

    // Go to the listing page, verify that the user is not shown yet, as the
    // points are still pending.
    $row = $this
      ->xpath('//table/tbody/tr');
    $this
      ->assertTrue(empty($row));

    // Go to the transaction listing page, verify that the transaction is shown.
    $this
      ->clickLink(t('Transactions'));
    $row = $this
      ->xpath('//table/tbody/tr');
    $transaction = userpoints_transaction_load($txn_id);

    //$this->assertEqual(strip_tags((string)$row[0]->td[0]), $user->name, t('User correctly displayed.'));
    $this
      ->assertEqual((string) $row[0]->td[1], 10, t('Points correctly displayed.'));
    $this
      ->assertEqual((string) $row[0]->td[2], format_date($transaction->time_stamp, 'small'), t('Date correctly displayed.'));
    $this
      ->assertEqual((string) $row[0]->td[3], 'admin', t('Reason correctly displayed.'));
    $this
      ->assertEqual((string) $row[0]->td[4], t('Pending'), t('Status correctly displayed.'));
    $this
      ->clickLink(t('edit'));

    // Verify default values.
    $this
      ->assertFieldByName('points', 10, t('Points default value is correct.'));
    $value = $this
      ->xpath("//input[@name=:name and @disabled=:disabled]/@value", array(
      ':name' => 'txn_user',
      ':disabled' => 'disabled',
    ));
    $this
      ->assertEqual($value[0]['value'], $user->name, t('User field has the correct value and is disabled.'));
    $this
      ->assertFieldByName('approver', $this->admin_user->name);
    $edit = array(
      'points' => 7,
      'operation' => $this
        ->randomName(),
      'description' => $this
        ->randomName(),
      'reference' => $this
        ->randomName(),
      'status' => UserpointsTransaction::STATUS_APPROVED,
    );
    $this
      ->drupalPost(NULL, $edit, t('Save'));

    // Verify that the transaction has been updated.
    $this
      ->assertEqual(7, userpoints_get_current_points($user->uid));
    $row = $this
      ->xpath('//table/tbody/tr');
    $transaction = userpoints_transaction_load($transaction->txn_id);

    //$this->assertEqual(strip_tags((string)$row[0]->td[0]), $user->name, t('User correctly displayed.'));
    $this
      ->assertEqual((string) $row[0]->td[1], 7, t('Points correctly displayed.'));
    $this
      ->assertEqual((string) $row[0]->td[2], format_date($transaction->time_stamp, 'small'), t('Date correctly displayed.'));
    $this
      ->assertEqual((string) $row[0]->td[3], $edit['description'], t('Reason correctly displayed.'));
    $this
      ->assertEqual((string) $row[0]->td[4], t('Approved'), t('Status correctly displayed.'));

    // Go to the listing page, verify that the total points have been updated.
    $this
      ->clickLink(t('Totals'));
    $row = $this
      ->xpath('//table/tbody/tr');

    //$this->assertEqual(strip_tags((string)$row[0]->td[0]), t('@name (details)', array('@name' => $user->name)), t('User name with details link displayed.'));
    $this
      ->assertEqual((string) $row[0]->td[1], 7, t('Points correctly displayed.'));

    // View transaction details.
    $this
      ->clickLink(t('Transactions'));
    $this
      ->clickLink('view');
  }

}

/**
 * API Tests.
 */
class UserpointsGrantPointsTestCase extends UserpointsBaseTestCase {
  private $admin_user;
  private $non_admin_user;

  /**
   * Implements getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => t('Userpoints grant points'),
      'description' => t('Tests the core API for proper inserts & updates to the database tables.'),
      'group' => t('Userpoints'),
    );
  }

  /**
   * Install userpoints module and create users.
   */
  function setUp() {
    parent::setUp('userpoints');

    // Create an administrator account.
    $this->admin_user = $this
      ->drupalCreateUser(array(
      'administer userpoints',
    ));

    // Create a standard Drupal account and log in as that person.
    $this->non_admin_user = $this
      ->drupalCreateUser();
    $this
      ->drupalLogin($this->non_admin_user);
  }

  /**
   * Test basic usage of the API to create and update transactions.
   */
  function testGrantPoints() {

    // Most basic usage, with automated saving.
    userpoints_grant_points('test', 10, 'userpoints', $this->non_admin_user->uid)
      ->save();
    $this
      ->verifyPoints($this->non_admin_user->uid, 10, 10);

    // Negative points, use of save().
    userpoints_grant_points('test', -5, 'userpoints', $this->non_admin_user->uid)
      ->save();
    $this
      ->verifyPoints($this->non_admin_user->uid, 5, 10);

    // Verify that pending points are not added to the total.
    $transaction = userpoints_grant_points('test', 7, 'userpoints', $this->non_admin_user->uid)
      ->pending();
    $transaction
      ->save();
    $this
      ->verifyPoints($this->non_admin_user->uid, 5, 10);

    // Make sure that loaded transactions can be updated, and after marked as
    // approved, the points are correct.
    $transaction = userpoints_transaction_load($transaction
      ->getTxnId());
    $transaction
      ->approve()
      ->save();
    $this
      ->verifyPoints($this->non_admin_user->uid, 12, 12);
    try {

      // Approved transaction must not be changed.
      $transaction
        ->setPoints(123)
        ->save();
      $this
        ->fail(t('Changing a approved transaction was not denied.'));
    } catch (UserpointsChangeException $e) {
      $this
        ->pass(t('Changing a approved transaction was denied.'));
    }
    $transaction = userpoints_grant_points('test', 19, 'userpoints', $this->non_admin_user->uid)
      ->pending();
    $transaction
      ->save();
    $this
      ->verifyPoints($this->non_admin_user->uid, 12, 12);

    // Transactions can be declined.
    $transaction
      ->decline()
      ->save();
    $this
      ->verifyPoints($this->non_admin_user->uid, 12, 12);
    try {

      // Declined transaction must not be changed.
      $transaction
        ->setPoints(123)
        ->save();
      $this
        ->fail(t('Changing a declined transaction was not denied.'));
    } catch (UserpointsChangeException $e) {
      $this
        ->pass(t('Changing a declined transaction was denied.'));
    }
  }

}

/**
 * Tests for fields integration.
 */
class UserpointsFieldsTestCase extends UserpointsBaseTestCase {

  /**
   * Implements getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => t('Userpoints fields.'),
      'description' => t('Tests integration with fields.'),
      'group' => t('Userpoints'),
    );
  }

  /**
   * Implements setUp().
   */
  function setUp() {
    parent::setUp('userpoints');
  }
  function testSingleField() {

    // Create an administrator account.
    $admin = $this
      ->drupalCreateUser(array(
      'administer userpoints',
    ));
    $this
      ->drupalLogin($admin);

    // Create a new field.
    $edit = array(
      'fields[_add_new_field][label]' => $this
        ->randomName(),
      'fields[_add_new_field][field_name]' => $name = strtolower($this
        ->randomName()),
      'fields[_add_new_field][type]' => 'text',
      'fields[_add_new_field][widget_type]' => 'text_textfield',
    );
    $this
      ->drupalPost('admin/config/people/userpoints/types/userpoints/fields', $edit, t('Save'));
    $this
      ->drupalPost(NULL, array(), t('Save field settings'));
    $this
      ->drupalPost(NULL, array(), t('Save settings'));

    // Create transaction.
    $message = array(
      'txn_user' => $admin->name,
      'points' => 10,
      'field_' . $name . '[' . LANGUAGE_NONE . '][0][value]' => $this
        ->randomName(50),
    );
    $this
      ->drupalPost('admin/config/people/userpoints/add', $message, t('Save'));

    // Check message.
    $this
      ->drupalGet('myuserpoints');
    $this
      ->clickLink(t('view'));
    $this
      ->assertText($message['field_' . $name . '[' . LANGUAGE_NONE . '][0][value]'], t('Content of new field is displayed.'));
  }

}

/**
 * Tests for update 7200: bundles.
 */
class UserpointsUpdate7200TestCase extends UpdatePathTestCase {

  /**
   * Implements getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => 'Userpoints update 7200',
      'description' => 'Assert that database update 7200 works',
      'group' => 'Userpoints',
    );
  }

  /**
   * Implements setUp().
   */
  public function setUp() {
    $this->databaseDumpFiles = array(
      drupal_get_path('module', 'simpletest') . '/tests/upgrade/drupal-7.bare.standard_all.database.php.gz',
      drupal_get_path('module', 'userpoints') . '/tests/userpoints.filled.database.php',
    );
    parent::setUp();

    // Shamelessly taken from botcha module.
    spl_autoload_register('drupal_autoload_class');
    spl_autoload_register('drupal_autoload_interface');
    registry_rebuild();
  }

  /**
   * Assert successful update.
   */
  public function testUpdate() {
    $update = $this
      ->performUpgrade();
    $this
      ->assertTrue($update);
    $this
      ->drupalGet('admin/config/people/userpoints/types');
    $this
      ->assertRaw(t('Default'));
  }

}

/**
 * Tests for update 7200: bundles. Alternate.
 */
class UserpointsUpdate7200AlternateTestCase extends UpdatePathTestCase {

  /**
   * Implements getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => 'Userpoints update 7200 (alternate)',
      'description' => 'Assert that database update 7200 works. This uses a different database dump.',
      'group' => 'Userpoints',
    );
  }

  /**
   * Implements setUp().
   */
  public function setUp() {
    $this->databaseDumpFiles = array(
      drupal_get_path('module', 'userpoints') . '/tests/userpoints.filled.database.all.php.gz',
    );
    parent::setUp();

    // Shamelessly taken from botcha module.
    spl_autoload_register('drupal_autoload_class');
    spl_autoload_register('drupal_autoload_interface');
    registry_rebuild();
  }

  /**
   * Assert successful update.
   */
  public function testUpdate() {
    $update = $this
      ->performUpgrade();
    $this
      ->assertTrue($update);
    $this
      ->drupalGet('admin/config/people/userpoints/types');
    $this
      ->assertRaw(t('Default'));
  }

}

Classes

Namesort descending Description
UserpointsAdminTestCase Administration UI tests
UserpointsAPITestCase API Tests.
UserpointsBaseTestCase Userpoints base test class with various helper functions.
UserpointsFieldsTestCase Tests for fields integration.
UserpointsGrantPointsTestCase API Tests.
UserpointsUpdate7200AlternateTestCase Tests for update 7200: bundles. Alternate.
UserpointsUpdate7200TestCase Tests for update 7200: bundles.