You are here

AcquiaLiftAPI.test in Acquia Lift Connector 7

Same filename and directory in other branches
  1. 7.2 tests/AcquiaLiftAPI.test

Unit tests for Acquia Lift module.

File

tests/AcquiaLiftAPI.test
View source
<?php

/**
 * @file
 * Unit tests for Acquia Lift module.
 */
class AcquiaLiftTest extends DrupalUnitTestCase {
  public static function getInfo() {
    return array(
      'name' => t('Acquia Lift Unit Tests'),
      'description' => t('Unit tests for AcquiaLiftAPI methods.'),
      'group' => t('Personalize'),
    );
  }
  protected function setUp() {
    require_once dirname(__FILE__) . '/../includes/acquia_lift.classes.inc';
    require_once dirname(__FILE__) . '/acquia_lift.test_classes.inc';
    parent::setUp();
  }

  /**
   * @var AcquiaLiftTestLogger
   */
  protected $logger = NULL;

  /**
   * @var DummyAcquiaLiftHttpClient
   */
  protected $httpClient = NULL;

  /**
   * The string to use as the runtime API key.
   *
   * @var string
   */
  protected $liftAPIKey = 'api-key-123';

  /**
   * The string to use as the admin API key.
   *
   * @var string
   */
  protected $liftAdminKey = 'admin-key-123';

  /**
   * The string to use as the owner code.
   *
   * @var string
   */
  protected $liftOwnerCode = 'Some_valid-owner123-code';

  /**
   * Tests getting a AcquiaLiftAPI instance with invalid and valid credentials.
   */
  function testGetInstance() {
    try {
      $lift_api = AcquiaLiftAPI::getInstance(array(
        'api_key' => 'asdf',
      ));
      $this
        ->fail('Should never reach here.');
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftCredsException);
      $this
        ->assertEqual('Acquia Lift account info is not complete.', $e
        ->getMessage());
      try {
        $lift_api = AcquiaLiftAPI::getInstance(array(
          'api_key' => 'asdf',
          'admin_key' => 'fasfasfs',
          'owner_code' => 'OHAI LOL',
        ));
        $this
          ->fail('Should never reach here.');
      } catch (Exception $e) {
        $this
          ->assertTrue($e instanceof AcquiaLiftCredsException);
        $this
          ->assertEqual('Acquia Lift owner code is invalid.', $e
          ->getMessage());
        try {

          // Here we pass valid creds.
          $lift_api = AcquiaLiftAPI::getInstance(array(
            'api_key' => $this->liftAPIKey,
            'admin_key' => $this->liftAdminKey,
            'owner_code' => $this->liftOwnerCode,
          ));
          $lift_api
            ->setLogger(new AcquiaLiftTestLogger());
        } catch (Exception $e) {
          $this
            ->fail('Exception thrown when none expected.');
        }
        $this
          ->assertEqual($this->liftAPIKey, $lift_api
          ->getApiKey());
      }
    }
    AcquiaLiftAPI::reset();
  }

  /**
   * Tests getting a AcquiaLiftAPI instance that uses the default API url.
   */
  function testGetInstanceWithAPIUrl() {
    AcquiaLiftAPI::reset();
    try {

      // We don't pass an API url so it should use the default.
      $lift_api = AcquiaLiftAPI::getInstance(array(
        'api_key' => $this->liftAPIKey,
        'admin_key' => $this->liftAdminKey,
        'owner_code' => $this->liftOwnerCode,
      ));
      $lift_api
        ->setLogger(new AcquiaLiftTestLogger());
    } catch (Exception $e) {
      $this
        ->fail('Exception thrown when none expected.');
    }
    global $is_https;
    $url_scheme = $is_https ? 'https://' : 'http://';

    // Check that the URL is as expected.
    $this
      ->assertEqual($url_scheme . AcquiaLiftAPI::API_URL, $lift_api
      ->getApiUrl());
    AcquiaLiftAPI::reset();

    // Test passing an invalid URL.
    try {
      $lift_api = AcquiaLiftAPI::getInstance(array(
        'api_key' => $this->liftAPIKey,
        'admin_key' => $this->liftAdminKey,
        'owner_code' => $this->liftOwnerCode,
        'api_url' => 'some\\invalid\\url',
      ));
      $this
        ->fail('Should never reach here.');
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftCredsException);
      $this
        ->assertEqual('Acquia Lift API URL is not a valid URL.', $e
        ->getMessage());
    }

    // Test passing a valid URL with no scheme.
    $lift_api = AcquiaLiftAPI::getInstance(array(
      'api_key' => $this->liftAPIKey,
      'admin_key' => $this->liftAdminKey,
      'owner_code' => $this->liftOwnerCode,
      'api_url' => 'test-api.example.com',
    ));

    // The scheme will match whatever the current scheme is.
    global $is_https;
    $url_scheme = $is_https ? 'https://' : 'http://';

    // Check that the URL is as expected.
    $this
      ->assertEqual($url_scheme . 'test-api.example.com', $lift_api
      ->getApiUrl());
    AcquiaLiftAPI::reset();

    // Test passing a valid URL with the scheme specified.
    $lift_api = AcquiaLiftAPI::getInstance(array(
      'api_key' => $this->liftAPIKey,
      'admin_key' => $this->liftAdminKey,
      'owner_code' => $this->liftOwnerCode,
      'api_url' => 'https://test-api.example.com',
    ));

    // Check that the URL is as expected.
    $this
      ->assertEqual('https://test-api.example.com', $lift_api
      ->getApiUrl());
    AcquiaLiftAPI::reset();
  }

  /**
   * Test AcquiaLiftAPI->pingTest()
   */
  public function testPingTest() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $ping_test = $lift_api
      ->pingTest();
    $this
      ->assertTrue($ping_test);
    $expected = array(
      array(
        'type' => 'get',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/list-agents?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
      array(
        'type' => 'post',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/ping-test-agent/expire?apikey={$lift_api->getApiKey()}",
        'headers' => array(
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );
    $this
      ->assertAPIRequests($expected);

    // Now test with a broken connection.
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    $ping_test = $lift_api
      ->pingTest();
    $this
      ->assertFALSE($ping_test);
    $this
      ->assertAPIRequests($expected);
  }

  /**
   * Test AcquiaLiftAPI->savePoint()
   */
  public function testSavePoint() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some-test-agent';
    $pointName = 'Some Test Point';
    $lift_api
      ->savePoint($agentName, $pointName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'put',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$agentName}/points/{$pointName}?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Content-Type' => 'application/json; charset=utf-8',
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => array(),
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::INFO,
        'message' => "The point {$pointName} was pushed to the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->savePoint($agentName, $pointName);
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => "Could not save the point {$pointName} to the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();
  }

  /**
   * Test AcquiaLiftAPI->saveDecision()
   */
  public function testSaveDecision() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some-test-agent';
    $pointName = 'Some Test Point';
    $decisionName = 'Some Test Decision';
    $lift_api
      ->saveDecision($agentName, $pointName, $decisionName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'put',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$agentName}/points/{$pointName}/decisions/{$decisionName}?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Content-Type' => 'application/json; charset=utf-8',
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::INFO,
        'message' => "The decision {$decisionName} for point {$pointName} was pushed to the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();
    $lift_api
      ->saveDecision($agentName, $pointName, $decisionName, array(
      'key' => 'data',
    ));

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'put',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$agentName}/points/{$pointName}/decisions/{$decisionName}?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Content-Type' => 'application/json; charset=utf-8',
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => array(
          'key' => 'data',
        ),
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::INFO,
        'message' => "The decision {$decisionName} for point {$pointName} was pushed to the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->saveDecision($agentName, $pointName, $decisionName, array(
        'key' => 'data',
      ));
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => "Could not save decision {$decisionName} for point {$pointName} to the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();
  }

  /**
   * Test AcquiaLiftAPI->saveChoice()
   */
  public function testSaveChoice() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some-test-agent';
    $pointName = 'Some Test Point';
    $decisionName = 'Some Test Decision';
    $choiceName = 'Some Test Choice';
    $lift_api
      ->saveChoice($agentName, $pointName, $decisionName, $choiceName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'put',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$agentName}/points/{$pointName}/decisions/{$decisionName}/choices/{$choiceName}?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Content-Type' => 'application/json; charset=utf-8',
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::INFO,
        'message' => "The decision choice {$decisionName}: {$choiceName} for point {$pointName} was pushed to the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();
    $lift_api
      ->saveChoice($agentName, $pointName, $decisionName, $choiceName, array(
      'key' => 'data',
    ));

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'put',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$agentName}/points/{$pointName}/decisions/{$decisionName}/choices/{$choiceName}?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Content-Type' => 'application/json; charset=utf-8',
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => array(
          'key' => 'data',
        ),
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::INFO,
        'message' => "The decision choice {$decisionName}: {$choiceName} for point {$pointName} was pushed to the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->saveChoice($agentName, $pointName, $decisionName, $choiceName, array(
        'key' => 'data',
      ));
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => "Could not save decision choice {$decisionName}: {$choiceName} for point {$pointName} to the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();
  }

  /**
   * Test AcquiaLiftAPI->deletePoint()
   */
  public function testDeletePoint() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some-test-agent';
    $pointName = 'Some Test Point';
    $lift_api
      ->deletePoint($agentName, $pointName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'delete',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$agentName}/points/{$pointName}?apikey={$lift_api->getAdminKey()}",
        'headers' => NULL,
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::INFO,
        'message' => "The decision point {$pointName} was deleted from the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->deletePoint($agentName, $pointName);
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => "Could not delete decision point {$pointName} from the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->deleteDecision()
   */
  public function testDeleteDecision() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some-test-agent';
    $pointName = 'Some Test Point';
    $decisionName = 'Some Test Decision';
    $lift_api
      ->deleteDecision($agentName, $pointName, $decisionName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'delete',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$agentName}/points/{$pointName}/decisions/{$decisionName}?apikey={$lift_api->getAdminKey()}",
        'headers' => NULL,
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::INFO,
        'message' => "The decision {$decisionName} for point {$pointName} was deleted from the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->deleteDecision($agentName, $pointName, $decisionName);
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => "Could not delete decision {$decisionName} for point {$pointName} from the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->deleteChoice()
   */
  public function testDeleteChoice() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some-test-agent';
    $pointName = 'Some Test Point';
    $decisionName = 'Some Test Decision';
    $choiceName = 'Some Test Choice';
    $lift_api
      ->deleteChoice($agentName, $pointName, $decisionName, $choiceName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'delete',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$agentName}/points/{$pointName}/decisions/{$decisionName}/choices/{$choiceName}?apikey={$lift_api->getAdminKey()}",
        'headers' => NULL,
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::INFO,
        'message' => "The decision choice {$decisionName}: {$choiceName} for point {$pointName} was deleted from the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->deleteChoice($agentName, $pointName, $decisionName, $choiceName);
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => "Could not delete decision choice {$decisionName}: {$choiceName} for point {$pointName} from the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->saveGoal()
   */
  public function testSaveGoal() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some-test-agent';
    $goalName = 'Some Test Point';
    $data = array(
      'key' => 'value',
    );
    $lift_api
      ->saveGoal($agentName, $goalName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'put',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$agentName}/goals/{$goalName}?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Content-Type' => 'application/json; charset=utf-8',
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::INFO,
        'message' => "The goal {$goalName} was pushed to the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);

    // Try to pass data structure
    $lift_api
      ->saveGoal($agentName, $goalName, $data);
    $requests = array(
      array(
        'type' => 'put',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$agentName}/goals/{$goalName}?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Content-Type' => 'application/json; charset=utf-8',
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => $data,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::INFO,
        'message' => "The goal {$goalName} was pushed to the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->saveGoal($agentName, $goalName, $data);
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => "Could not save the goal {$goalName} to the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->deleteGoal()
   */
  public function testDeleteGoal() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some-test-agent';
    $goalName = 'goal-1';
    $lift_api
      ->deleteGoal($agentName, $goalName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'delete',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$agentName}/goals/{$goalName}?apikey={$lift_api->getAdminKey()}",
        'headers' => NULL,
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::INFO,
        'message' => "The goal {$goalName} was deleted from the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->deleteGoal($agentName, $goalName);
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => "Could not delete the goal {$goalName} from the Acquia Lift campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->getAgent()
   */
  public function testGetAgent() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $machineName = 'some_machine_name';
    $lift_api
      ->getAgent($machineName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'get',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$machineName}?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests and logs.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->getAgent($machineName);
      $this
        ->fail('Should not reach here');
    } catch (AcquiaLiftException $e) {
    }

    // Confirm the expected requests and logs.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->getGoalsForAgent()
   */
  public function testGetGoalsForAgent() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some_machine_name';
    $lift_api
      ->getGoalsForAgent($agentName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'get',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$agentName}/goals?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests and logs.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->getGoalsForAgent($agentName);
      $this
        ->fail('Should not reach here');
    } catch (AcquiaLiftException $e) {
    }

    // Confirm the expected requests and logs.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->getPointsForAgent()
   */
  public function testGetPointsForAgent() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some_machine_name';
    $lift_api
      ->getPointsForAgent($agentName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'get',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$agentName}/points?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests and logs.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->getPointsForAgent($agentName);
      $this
        ->fail('Should not reach here');
    } catch (AcquiaLiftException $e) {
    }

    // Confirm the expected requests and logs.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->getDecisionsForPoint()
   */
  public function testGetDecisionsForPoint() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some_machine_name';
    $pointName = 'some_point_name';
    $lift_api
      ->getDecisionsForPoint($agentName, $pointName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'get',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$agentName}/points/{$pointName}/decisions?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests and logs.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->getDecisionsForPoint($agentName, $pointName);
      $this
        ->fail('Should not reach here');
    } catch (AcquiaLiftException $e) {
    }

    // Confirm the expected requests and logs.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->getChoicesForDecision()
   */
  public function testGetChoicesForDecision() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some_machine_name';
    $pointName = 'some_point_name';
    $decisionName = 'some_decision_name';
    $lift_api
      ->getChoicesForDecision($agentName, $pointName, $decisionName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'get',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$agentName}/points/{$pointName}/decisions/{$decisionName}/choices?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests and logs.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->getChoicesForDecision($agentName, $pointName, $decisionName);
      $this
        ->fail('Should not reach here');
    } catch (AcquiaLiftException $e) {
    }

    // Confirm the expected requests and logs.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->getExistingAgents()
   */
  public function testGetExistingAgents() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $lift_api
      ->getExistingAgents();

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'get',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/list-agents?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests and logs.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->getExistingAgents();
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests and logs.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => 'Error retrieving agent list from Acquia Lift',
      ),
    );
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->getTransformOptions()
   */
  public function testGetTransformOptions() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $lift_api
      ->getTransformOptions();

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'get',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/transforms-options?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->getTransformOptions();
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => 'Error retrieving list of transforms options',
      ),
    );
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->saveAutoTargetingRule()
   */
  public function testSaveAutoTargetingRule() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some-agent-name';
    $autoFeatures = array(
      'first',
      'second',
      'third',
    );
    $lift_api
      ->saveAutoTargetingRule($agentName, $autoFeatures);
    $processedAutoFeatures = array();
    foreach ($autoFeatures as $key => $feature) {
      $processedAutoFeatures[$key] = '#' . $feature;
    }

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'post',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/transform-rule?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Content-Type' => 'application/json; charset=utf-8',
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => array(
          'code' => $agentName . '-auto-targeting',
          'status' => 1,
          'agents' => array(
            $agentName,
          ),
          'when' => array(),
          'apply' => array(
            'feature' => implode(',', $processedAutoFeatures),
          ),
        ),
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::INFO,
        'message' => "The targeting rule for campaign {$agentName} was saved successfully",
      ),
    );
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->saveAutoTargetingRule($agentName, $autoFeatures);
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => "The targeting rule could not be saved for campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->testHasAutoTargetingRule()
   */
  public function testHasAutoTargetingRule() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some-agent-name';
    $result = $lift_api
      ->hasAutoTargetingRule($agentName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'get',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/transforms-list?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);

    // Confirm that we received a boolean false as the result.
    $this
      ->assertTrue($result === FALSE);
    $logs = array();
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    $msg = 'Problem retrieving auto-targeting rules';
    try {
      $lift_api
        ->hasAutoTargetingRule($agentName);
      $this
        ->fail("Should not reach here");
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
      $this
        ->assertEqual($msg, $e
        ->getMessage());
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => $msg,
      ),
    );
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->getPotentialTargetingValues()
   */
  public function testGetPotentialTargetingValues() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some-agent-name';
    $lift_api
      ->getPotentialTargetingValues($agentName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'get',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/-/potential-targeting?agent={$agentName}&include-current=true&apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->getPotentialTargetingValues($agentName);
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => 'Problem retrieving potential targeting values',
      ),
    );
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->saveFixedTargetingMapping()
   */
  public function testSaveFixedTargetingMapping() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some-agent-name';
    $pointName = 'some-point-name';
    $map = array(
      'key' => 'data',
    );
    $lift_api
      ->saveFixedTargetingMapping($agentName, $pointName, $map);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'put',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/agent-api/{$agentName}/points/{$pointName}/fixed-targeting?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Content-Type' => 'application/json; charset=utf-8',
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => $map,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::INFO,
        'message' => "The fixed targeting mapping for point {$pointName} was successfully saved for campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->saveFixedTargetingMapping($agentName, $pointName, $map);
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => "The fixed targeting mapping for point {$pointName} could not be saved for campaign {$agentName}",
      ),
    );
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->getTargetingImpactReport()
   * @todo test with 'point' value
   */
  public function testGetTargetingImpactReport() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some-agent-name';
    $dateStr = date('Y-m-d');
    $lift_api
      ->getTargetingImpactReport($agentName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'get',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/{$agentName}/report/targeting-features/{$dateStr}?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
    $startDate = '2014-01-01';
    $endDate = '2014-01-02';
    $lift_api
      ->getTargetingImpactReport($agentName, $startDate, $endDate);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'get',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/{$agentName}/report/targeting-features/{$startDate}/{$endDate}?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->getTargetingImpactReport($agentName, $startDate, $endDate);
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => 'Problem retrieving targeting impact report.',
      ),
    );
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->getAgentStatusReport()
   */
  public function testGetAgentStatusReport() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentNamesArray = array(
      'some-agent-name',
      'some-another-name',
    );
    $agentNames = 'some-agent-name,some-another-name';
    $dayNumber = 10;
    $lift_api
      ->getAgentStatusReport($agentNamesArray, $dayNumber);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'get',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/report/status?codes={$agentNames}&days={$dayNumber}&apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->getAgentStatusReport($agentNamesArray, $dayNumber);
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => 'Problem retrieving status report.',
      ),
    );
    $this
      ->assertLogs($logs);
  }

  /**
   * Test AcquiaLiftAPI->getConfidenceReport()
   */
  public function testGetConfidenceReport() {
    $default_confidence = 0.95;
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $test_request = array(
      'type' => 'get',
      'headers' => array(
        'Accept' => 'application/json',
      ),
      'options' => array(),
      'body' => NULL,
    );
    $agentName = 'some-agent-name';
    $params = array();
    $params[] = $agentName;

    // Confirm the expected requests were made.
    $dateStr = date('Y-m-d');
    $test_request['uri'] = "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/{$agentName}/report/confidence/{$dateStr}?features=(none)&apikey={$lift_api->getAdminKey()}&confidence-measure={$default_confidence}&aggregated-over-dates=true";
    $this
      ->assertConfidenceReportAPI($params, $test_request, $lift_api);

    // Test date range.
    $startDate = '2014-01-01';
    $endDate = '2014-01-02';
    $params[] = $startDate;
    $params[] = $endDate;
    $test_request['uri'] = "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/{$agentName}/report/confidence/{$startDate}/{$endDate}?features=(none)&apikey={$lift_api->getAdminKey()}&confidence-measure={$default_confidence}&aggregated-over-dates=true";
    $this
      ->assertConfidenceReportAPI($params, $test_request, $lift_api);

    // Test sending point name.
    $point_name = 'decision_point';
    $test_request['headers']['x-mpath-point'] = $point_name;
    $params[] = $point_name;
    $this
      ->assertConfidenceReportAPI($params, $test_request, $lift_api);

    // Send features.
    $features = array(
      'feature1',
      'feature2',
    );
    $features_str = implode(',', $features);
    $params[] = array(
      'features' => $features,
    );
    $test_request['uri'] = "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/{$agentName}/report/confidence/{$startDate}/{$endDate}?features={$features_str}&apikey={$lift_api->getAdminKey()}&confidence-measure={$default_confidence}&aggregated-over-dates=true";
    $this
      ->assertConfidenceReportAPI($params, $test_request, $lift_api);

    // Send confidence measure.
    $confidence_measure = 0.99;
    $params[4]['confidence-measure'] = $confidence_measure;
    $test_request['uri'] = "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/{$agentName}/report/confidence/{$startDate}/{$endDate}?features={$features_str}&apikey={$lift_api->getAdminKey()}&confidence-measure={$confidence_measure}&aggregated-over-dates=true";
    $this
      ->assertConfidenceReportAPI($params, $test_request, $lift_api);

    // Get detail report.
    $params[4]['aggregated-over-dates'] = FALSE;
    $test_request['uri'] = "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/{$agentName}/report/confidence/{$startDate}/{$endDate}?features={$features_str}&apikey={$lift_api->getAdminKey()}&confidence-measure={$confidence_measure}&aggregated-over-dates=false";
    $this
      ->assertConfidenceReportAPI($params, $test_request, $lift_api);

    // Get a detail report with a specific goal.
    $params[4]['goal'] = 'some_goal';
    $test_request['uri'] = "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/{$agentName}/report/confidence/{$startDate}/{$endDate}?features={$features_str}&apikey={$lift_api->getAdminKey()}&confidence-measure={$confidence_measure}&aggregated-over-dates=false&goal=some_goal";
    $this
      ->assertConfidenceReportAPI($params, $test_request, $lift_api);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    $this
      ->assertConfidenceReportAPI($params, $test_request, $lift_api);
  }

  /**
   * Test AcquiaLiftAPI->getRawLearningReport()
   * @todo test with 'point' value
   */
  public function testGetRawLearningReport() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some-agent-name';
    $dateStr = date('Y-m-d');
    $lift_api
      ->getRawLearningReport($agentName);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'get',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/{$agentName}/report/learning/{$dateStr}?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
    $startDate = '2014-01-01';
    $endDate = '2014-01-02';
    $lift_api
      ->getRawLearningReport($agentName, $startDate, $endDate);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'get',
        'uri' => "{$lift_api->getApiUrl()}/{$lift_api->getOwnerCode()}/{$agentName}/report/learning/{$startDate}/{$endDate}?apikey={$lift_api->getAdminKey()}",
        'headers' => array(
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array();
    $this
      ->assertLogs($logs);
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->getRawLearningReport($agentName, $startDate, $endDate);
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => 'Problem retrieving learning report.',
      ),
    );
    $this
      ->assertLogs($logs);
  }
  function testSaveAgent() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agentName = 'some-test-agent';
    $lift_api
      ->saveAgent($agentName, 'Some Test Agent', 'adaptive', 'enabled');

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'put',
        'uri' => "http://api.lift.acquia.com/{$this->liftOwnerCode}/agent-api/{$agentName}?apikey={$this->liftAdminKey}",
        'headers' => array(
          'Content-Type' => 'application/json; charset=utf-8',
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => array(
          'name' => 'Some Test Agent',
          'selection-mode' => 'adaptive',
          'status' => 'enabled',
          'control-rate' => 0.1,
          'explore-rate' => 0.2,
          'decision-stickiness' => 'session',
        ),
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    DummyAcquiaLiftHttpClient::clearLoggedRequests();

    // Confirm the expected messages were logged.
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::INFO,
        'message' => "The campaign {$agentName} was pushed to Acquia Lift",
      ),
    );
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();

    // Make sure we can use a Personalize status code.
    $this
      ->assertAPIRequests(array());
    $lift_api
      ->saveAgent($agentName, 'Some Test Agent', 'adaptive', PERSONALIZE_STATUS_RUNNING);

    // The requests and logs should be the same.
    $this
      ->assertAPIRequests($requests);
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();
    $this
      ->assertAPIRequests(array());
    $lift_api
      ->saveAgent($agentName, 'Some Test Agent', 'adaptive', 'enabled', 0.1, 0.4);

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'put',
        'uri' => "http://api.lift.acquia.com/{$this->liftOwnerCode}/agent-api/{$agentName}?apikey={$this->liftAdminKey}",
        'headers' => array(
          'Content-Type' => 'application/json; charset=utf-8',
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => array(
          'name' => 'Some Test Agent',
          'selection-mode' => 'adaptive',
          'status' => 'enabled',
          'control-rate' => 0.1,
          'explore-rate' => 0.4,
          'decision-stickiness' => 'session',
        ),
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();

    // Save an agent without sticky decisions
    $lift_api
      ->saveAgent($agentName, 'Some Test Agent', 'adaptive', 'enabled', 0.1, 0.4, 0);
    $requests[0]['body']['decision-stickiness'] = 'none';

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();

    // Try with something nonsensical for the decision mode.
    $lift_api
      ->saveAgent($agentName, 'Some Test Agent', 'narf', 'enabled', 0.1, 0.4, 0);

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();

    // Now try with a broken http client.
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->saveAgent('some-test-agent', 'Some Test Agent', 'adaptive', 'enabled', 0.1, 0.4, 0);
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // The same requests should be made.
    $this
      ->assertAPIRequests($requests);

    // Confirm the expected error message was logged.
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => "The campaign {$agentName} could not be pushed to Acquia Lift",
      ),
    );
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();
  }
  function testGetAgents() {
    $lift_api = AcquiaLiftAPI::getInstance(array(
      'api_key' => 'asdf',
      'admin_key' => 'fasfasfs',
      'owner_code' => 'Some_valid-owner123-code',
    ));

    // Pass some dummy agent data to our dummy http client and
    // confirm that we get it back via the getExistingAgents()
    // method on the the AcquiaLiftAPI class.
    $agents = array();
    $agent_codes = array(
      'first-agent',
      'second-agent',
    );
    foreach ($agent_codes as $code) {
      $agent = new stdClass();
      $agent->code = $code;
      $agent->decisions = array();
      $agent->goals = array();
      $agents[] = $agent;
    }
    $lift_api
      ->setHttpClient(new DummyAcquiaLiftHttpClient(FALSE, array(
      'agents' => $agents,
    )));
    $lift_api
      ->setLogger(new AcquiaLiftTestLogger());
    $agents = $lift_api
      ->getExistingAgents();
    $this
      ->assertEqual($agent_codes, array_keys($agents));

    // Simulate no agents being returned by the service.
    $lift_api
      ->setHttpClient(new DummyAcquiaLiftHttpClient(FALSE));
    $agents = $lift_api
      ->getExistingAgents();
    $this
      ->assertTrue(empty($agents));

    // Now try with a broken httpclient (simulating a 500 response from the service).
    $lift_api
      ->setHttpClient(new DummyAcquiaLiftHttpClient(TRUE));
    try {
      $agents = $lift_api
        ->getExistingAgents();
      $this
        ->fail('Should never reach here');
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
      $this
        ->assertEqual('Error retrieving agent list from Acquia Lift', $e
        ->getMessage());
    }
  }
  function testGetPossibleValues() {
    $lift_api = AcquiaLiftAPI::getInstance(array(
      'api_key' => 'asdf',
      'admin_key' => 'fasfasfs',
      'owner_code' => 'Some_valid-owner123-code',
    ));
    $lift_api
      ->setLogger(new AcquiaLiftTestLogger());

    // Pass some dummy feature codes to our dummy http client.
    $features = array(
      array(
        'code' => '(none)',
        'name' => '(Any Visitor)',
      ),
      array(
        'code' => 'first-mutex: Some Value',
        'name' => 'Some Friendly Name',
        'typeName' => 'First Mutex',
      ),
      array(
        'code' => 'first-mutex: Other Value',
        'name' => 'Other Friendly Name',
        'typeName' => 'First Mutex',
      ),
      array(
        'code' => 'first-non-mutex:: Some Nonmutex Value',
        'name' => 'Some Friendly Nonmutex Name',
        'typeName' => 'First Non-Mutex',
      ),
      array(
        'code' => 'first-non-mutex:: Other Nonmutex Value',
        'name' => 'Other Friendly Nonmutex Name',
        'typeName' => 'First Non-Mutex',
      ),
    );
    $lift_api
      ->setHttpClient(new DummyAcquiaLiftHttpClient(FALSE, array(
      'features' => $features,
    )));
    $possible_values = $lift_api
      ->getPossibleValues('some-agent', ':', '::');
    $expected = array(
      'first-mutex' => array(
        'value type' => 'predefined',
        'mutex' => TRUE,
        'friendly name' => 'First Mutex',
        'values' => array(
          'Some Value' => 'Some Friendly Name',
          'Other Value' => 'Other Friendly Name',
        ),
      ),
      'first-non-mutex' => array(
        'value type' => 'predefined',
        'mutex' => FALSE,
        'friendly name' => 'First Non-Mutex',
        'values' => array(
          'Some Nonmutex Value' => 'Some Friendly Nonmutex Name',
          'Other Nonmutex Value' => 'Other Friendly Nonmutex Name',
        ),
      ),
    );
    $this
      ->assertEqual($expected, $possible_values);

    // If the mutex vs non-mutex separators were ever to change, the getPossibleValues()
    // method should still work fine.
    $features = array(
      array(
        'code' => '(none)',
        'name' => '(Any Visitor)',
      ),
      array(
        'code' => 'first-mutex:: Some Value',
        'name' => 'Some Friendly Name',
        'typeName' => 'First Mutex',
      ),
      array(
        'code' => 'first-mutex:: Other Value',
        'name' => 'Other Friendly Name',
        'typeName' => 'First Mutex',
      ),
      array(
        'code' => 'first-non-mutex: Some Nonmutex Value',
        'name' => 'Some Friendly Nonmutex Name',
        'typeName' => 'First Non-Mutex',
      ),
      array(
        'code' => 'first-non-mutex: Other Nonmutex Value',
        'name' => 'Other Friendly Nonmutex Name',
        'typeName' => 'First Non-Mutex',
      ),
    );
    $lift_api
      ->setHttpClient(new DummyAcquiaLiftHttpClient(FALSE, array(
      'features' => $features,
    )));

    // We switch around the mutex and non-mutex separators so it can handle this change.
    $possible_values = $lift_api
      ->getPossibleValues('some-agent', '::', ':');

    // We still expect the exact same set of values to be returned.
    $this
      ->assertEqual($expected, $possible_values);
  }

  /**
   * Test the testGetCallsForPreviousMonth() method.
   */
  public function testGetCallsForPreviousMonth() {
    $lift_api = $this
      ->getAcquiaLiftAPI();

    // Make sure we're starting off when a clean request log in our dummy
    // http client.
    DummyAcquiaLiftHttpClient::clearLoggedRequests();
    $timestamps = array(
      // Timestamp representing March 12th 2014
      1394652611 => array(
        'start' => '2014-02-01',
        'end' => '2014-02-28',
      ),
      // Timestamp representing January 2nd 2014
      1388695528 => array(
        'start' => '2013-12-01',
        'end' => '2013-12-31',
      ),
      // Timestamp representing December 31st 2013
      1388522626 => array(
        'start' => '2013-11-01',
        'end' => '2013-11-30',
      ),
      // Timestamp representing October 9th 2013
      1381348094 => array(
        'start' => '2013-09-01',
        'end' => '2013-09-30',
      ),
    );
    foreach ($timestamps as $timestamp => $expected_dates) {
      $count = $lift_api
        ->getCallsForPreviousMonth($timestamp);

      // Define the requests we expect to have been made to our dummy http
      // client for this operation.
      $requests = array(
        array(
          'type' => 'get',
          'uri' => "http://api.lift.acquia.com/{$this->liftOwnerCode}/-/report/system-usage/{$expected_dates['start']}/{$expected_dates['end']}?apikey={$this->liftAdminKey}",
          'headers' => array(
            'Accept' => 'application/json',
          ),
          'options' => array(),
          'body' => NULL,
        ),
      );

      // Confirm the expected requests were made.
      $this
        ->assertAPIRequests($requests);
    }
  }

  /**
   * Test the testGetCallsForPreviousMonth() method.
   */
  public function testGetCallsForMonthToDate() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $timestamps = array(
      // Timestamp representing March 12th 2014
      1394652611 => array(
        'start' => '2014-03-01',
        'end' => '2014-03-12',
      ),
      // Timestamp representing January 2nd 2014
      1388695528 => array(
        'start' => '2014-01-01',
        'end' => '2014-01-02',
      ),
      // Timestamp representing December 31st 2013
      1388522626 => array(
        'start' => '2013-12-01',
        'end' => '2013-12-31',
      ),
    );
    foreach ($timestamps as $timestamp => $expected_dates) {
      $count = $lift_api
        ->getCallsForMonthToDate($timestamp);

      // Define the requests we expect to have been made to our dummy http
      // client for this operation.
      $requests = array(
        array(
          'type' => 'get',
          'uri' => "http://api.lift.acquia.com/{$this->liftOwnerCode}/-/report/system-usage/{$expected_dates['start']}/{$expected_dates['end']}?apikey={$this->liftAdminKey}",
          'headers' => array(
            'Accept' => 'application/json',
          ),
          'options' => array(),
          'body' => NULL,
        ),
      );

      // Confirm the expected requests were made.
      $this
        ->assertAPIRequests($requests);
    }
  }
  public function testResetAgentData() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    $agent_name = 'my-test-agent';
    try {
      $lift_api
        ->resetAgentData($agent_name);
    } catch (Exception $e) {
      $this
        ->fail('Exception thrown when none expected');
    }

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'delete',
        'uri' => "http://api.lift.acquia.com/{$this->liftOwnerCode}/{$agent_name}/data?apikey={$this->liftAdminKey}",
        'headers' => NULL,
        'options' => array(),
        'body' => NULL,
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);

    // Confirm the expected messages were logged.
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::INFO,
        'message' => "The data for Acquia Lift campaign {$agent_name} was reset",
      ),
    );
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();

    // Now try with a broken http client.
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->resetAgentData($agent_name);
    } catch (Exception $e) {
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);

    // Confirm the expected messages were logged.
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => "Could not reset data for Acquia Lift campaign {$agent_name}",
      ),
    );
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();
  }
  function testEnsureUniqueAgentName() {
    $lift_api = AcquiaLiftAPI::getInstance(array(
      'api_key' => 'asdf',
      'admin_key' => 'fasfasfs',
      'owner_code' => 'Some_valid-owner123-code',
    ));

    // Pass some dummy agent data to our dummy http client.
    $agents = array();
    $agent_codes = array(
      'first-agent',
      'first-agent-0',
      'first-agent-1',
      'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx',
      'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv-0',
      'abcdefghijklmnopqrstuvwxyzabcdef',
      'abcdefghijklmnopqrstuvwxyzabcd-0',
      'abcdefghijklmnopqrstuvwxyzabcd-1',
      'abcdefghijklmnopqrstuvwxyzabcd-2',
      'abcdefghijklmnopqrstuvwxyzabcd-3',
      'abcdefghijklmnopqrstuvwxyzabcd-4',
      'abcdefghijklmnopqrstuvwxyzabcd-5',
      'abcdefghijklmnopqrstuvwxyzabcd-6',
      'abcdefghijklmnopqrstuvwxyzabcd-7',
      'abcdefghijklmnopqrstuvwxyzabcd-8',
      'abcdefghijklmnopqrstuvwxyzabcd-9',
    );
    foreach ($agent_codes as $code) {
      $agent = new stdClass();
      $agent->code = $code;
      $agent->decisions = array();
      $agent->goals = array();
      $agents[] = $agent;
    }
    $lift_api
      ->setHttpClient(new DummyAcquiaLiftHttpClient(FALSE, array(
      'agents' => $agents,
    )));
    $lift_api
      ->setLogger(new AcquiaLiftTestLogger());

    // Try to get a unique name based on 'first-agent'
    $new_name = $lift_api
      ->ensureUniqueAgentName($agent_codes[0], 64);
    $this
      ->assertEqual('first-agent-2', $new_name);

    // Try to get a unique name based on a long string.
    $new_name = $lift_api
      ->ensureUniqueAgentName('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz', 64);
    $this
      ->assertEqual('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv-1', $new_name);

    // Now try with a max length restriction that is shorter than the one
    // for Acquia Lift
    $new_name = $lift_api
      ->ensureUniqueAgentName('abcdefghijklmnopqrstuvwxyzabcde1f', 32);
    $this
      ->assertEqual('abcdefghijklmnopqrstuvwxyzabcde1', $new_name);
    $new_name = $lift_api
      ->ensureUniqueAgentName('abcdefghijklmnopqrstuvwxyzabcdef', 32);
    $this
      ->assertEqual('abcdefghijklmnopqrstuvwxyzabc-10', $new_name);
  }
  function testUpdateAgentStatus() {
    $lift_api = $this
      ->getAcquiaLiftAPI();
    DummyAcquiaLiftHttpClient::clearLoggedRequests();
    $agent_name = 'my-test-agent';

    // The updating the status to a non-existent status code string.
    try {
      $lift_api
        ->updateAgentStatus($agent_name, 'some-non-existent-status-code');
      $this
        ->fail('Exception not thrown as expected');
    } catch (Exception $e) {
      $this
        ->pass('Exception thrown as expected');
    }

    // Now try with a non-existent numeric code.
    try {
      $lift_api
        ->updateAgentStatus($agent_name, 33);
      $this
        ->fail('Exception not thrown as expected');
    } catch (Exception $e) {
      $this
        ->pass('Exception thrown as expected');
    }

    // Now try with a string code that exists in Lift.
    try {
      $lift_api
        ->updateAgentStatus($agent_name, AcquiaLiftAPI::PAUSED_STATUS);
    } catch (Exception $e) {
      $this
        ->fail('Exception thrown when none expected');
    }

    // Define the requests we expect to have been made to our dummy http
    // client for this operation.
    $requests = array(
      array(
        'type' => 'put',
        'uri' => "http://api.lift.acquia.com/{$this->liftOwnerCode}/agent-api/{$agent_name}?apikey={$this->liftAdminKey}",
        'headers' => array(
          'Content-Type' => 'application/json; charset=utf-8',
          'Accept' => 'application/json',
        ),
        'options' => array(),
        'body' => array(
          'status' => AcquiaLiftAPI::PAUSED_STATUS,
        ),
      ),
    );

    // Confirm the expected requests were made.
    $this
      ->assertAPIRequests($requests);

    // Confirm the expected messages were logged.
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::INFO,
        'message' => "The new status of campaign {$agent_name} was pushed to Acquia Lift",
      ),
    );
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();

    // Now try with a numeric code that exists in Personalize.
    try {
      $lift_api
        ->updateAgentStatus($agent_name, PERSONALIZE_STATUS_PAUSED);
    } catch (Exception $e) {
      $this
        ->fail('Exception thrown when none expected');
    }

    // The request made and the logs should be identical.
    $this
      ->assertAPIRequests($requests);
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();

    // Now try with a broken http client.
    $lift_api = $this
      ->getAcquiaLiftAPI(TRUE);
    try {
      $lift_api
        ->updateAgentStatus($agent_name, PERSONALIZE_STATUS_PAUSED);
      $this
        ->fail('Exception not thrown as expected');
    } catch (Exception $e) {
      $this
        ->pass('Exception thrown as expected');
    }
    $this
      ->assertAPIRequests($requests);
    $logs = array(
      array(
        'level' => PersonalizeLogLevel::ERROR,
        'message' => "The new status of campaign {$agent_name} could not be pushed to Acquia Lift",
      ),
    );
    $this
      ->assertLogs($logs);
    $this->logger
      ->clearLogs();
  }

  /**
   * Returns a AcquiaLiftAPI instance that can be used to test methods.
   *
   * @param bool $broken
   *   Whether the HTTP client used by the API class should be broken, simulating
   *   500 responses from Acquia Lift.
   * @return AcquiaLiftAPI
   *   A AcquiaLiftAPI instance.
   */
  protected function getAcquiaLiftAPI($broken = FALSE) {
    $lift_api = AcquiaLiftAPI::getInstance(array(
      'api_key' => $this->liftAPIKey,
      'admin_key' => $this->liftAdminKey,
      'owner_code' => $this->liftOwnerCode,
    ));

    // Create a dummy http client for the Acquia Lift API to use. All
    // requests to it will be logged and retrievable for checking later.
    $this->httpClient = new DummyAcquiaLiftHttpClient($broken);
    $lift_api
      ->setHttpClient($this->httpClient);
    if ($this->logger === NULL) {

      // Create a dummy logger instance which will maintain a log in memory
      // that we can retrieve for checking later.
      $this->logger = new AcquiaLiftTestLogger();
    }
    else {
      $this->logger
        ->clearLogs();
    }
    $lift_api
      ->setLogger($this->logger);
    return $lift_api;
  }

  /**
   * Helper function to call the confidence report endpoint and verify the API
   * request.
   *
   * @param $params
   *   The indexed parameter array to pass to the api call.
   * @param $request
   *   The expected request values.
   * @param $lift_api
   *   (Optional) the lift api instance to use for tests.
   */
  protected function assertConfidenceReportAPI($params, $request, $lift_api) {
    $logs = array();
    if (empty($lift_api)) {
      $lift_api = $this
        ->getAcquiaLiftAPI();
    }
    try {
      call_user_func_array(array(
        $lift_api,
        'getConfidenceReport',
      ), $params);
    } catch (Exception $e) {
      $logs = array(
        array(
          'level' => PersonalizeLogLevel::ERROR,
          'message' => 'Problem retrieving confidence report.',
        ),
      );
      $this
        ->assertTrue($e instanceof AcquiaLiftException);
    }
    $this
      ->assertAPIRequests(array(
      $request,
    ));
    $this
      ->assertLogs($logs);
  }

  /**
   * Asserts that the expected requests were made to the http client.
   *
   * @param $expected_requests
   */
  protected function assertAPIRequests($expected_requests) {
    $logged_requests = DummyAcquiaLiftHttpClient::getLoggedRequests();
    $this
      ->assertEqual($expected_requests, $logged_requests);
    DummyAcquiaLiftHttpClient::clearLoggedRequests();
  }

  /**
   * Asserts that the expected messages were logged to the logger.
   *
   * @param $expected_logs
   */
  protected function assertLogs($expected_logs) {
    $logs = $this->logger
      ->getLogs();
    $this
      ->assertEqual($expected_logs, $logs);
    $this->logger
      ->clearLogs();
  }

}

Classes

Namesort descending Description
AcquiaLiftTest @file Unit tests for Acquia Lift module.