function tearDown()
 {
     // Uninstall the openXDeliveryLog plugin
     TestEnv::uninstallPluginPackage('openXDeliveryLimitations', false);
     // Clean up the testing environment
     TestEnv::restoreEnv();
 }
 function test_backupTables()
 {
     $GLOBALS['_MAX']['CONF']['pluginPaths']['repo'] = $GLOBALS['_MAX']['CONF']['pluginPaths']['repo'] . '|' . MAX_PATH . $this->testpathData . 'plugins_repo/';
     $zipFile = $this->testpathData . 'plugins_repo/' . 'testPluginPackage_v3.zip';
     $plugin = $this->testpathData . 'plugins_repo/' . 'testPluginPackage.zip';
     if (file_exists($zipFile) && !unlink($zipFile)) {
         $this->fail('error unlinking ' . $zipFile);
         return false;
     }
     if (!copy(MAX_PATH . $zipFile, MAX_PATH . $plugin)) {
         $this->fail('error copying ' . $zipFile);
         return false;
     }
     if (!file_exists(MAX_PATH . $plugin)) {
         $this->fail('file does not exist ' . $plugin);
         return false;
     }
     TestEnv::installPluginPackage('testPluginPackage', false);
     $prefix = $GLOBALS['_MAX']['CONF']['table']['prefix'];
     $oExport = new OX_PluginExport();
     $oExport->init('testPluginPackage');
     $aTables = OA_DB_Table::listOATablesCaseSensitive('testplugin_table');
     $this->assertEqual(count($aTables), 1);
     $this->assertEqual($aTables[0], $prefix . 'testplugin_table');
     $this->assertTrue($oExport->backupTables('testPluginPackage'));
     $aTables = OA_DB_Table::listOATablesCaseSensitive('testplugin_table');
     $this->assertEqual(count($aTables), 2);
     $this->assertEqual($aTables[0], $prefix . 'testplugin_table');
     $this->assertPattern('/' . $prefix . 'testplugin_table_' . date('Ymd') . '_[\\d]{6}/', $aTables[1]);
     TestEnv::uninstallPluginPackage('testPluginPackage', false);
     TestEnv::restoreConfig();
     TestEnv::restoreEnv();
 }
 function test_runScript()
 {
     $GLOBALS['_MAX']['CONF']['table']['prefix'] = $this->prefix;
     $oUpgrade = new OA_Upgrade();
     $oUpgrade->initDatabaseConnection();
     $oDbh =& $oUpgrade->oDbh;
     $oTable = new OA_DB_Table();
     $testfile = MAX_PATH . "/etc/changes/tests/data/schema_tables_core_dashboard.xml";
     $oTable->init($testfile);
     $table = 'preference';
     $aExistingTables = OA_DB_Table::listOATablesCaseSensitive();
     if (in_array($this->prefix . $table, $aExistingTables)) {
         $this->assertTrue($oTable->dropTable($this->prefix . $table), 'error dropping ' . $this->prefix . $table);
     }
     $this->assertTrue($oTable->createTable($table), 'error creating ' . $this->prefix . $table);
     $aExistingTables = OA_DB_Table::listOATablesCaseSensitive();
     $this->assertTrue(in_array($this->prefix . $table, $aExistingTables), $this->prefix . $table . ' table not found');
     $this->assertTrue($oUpgrade->runScript('postscript_openads_upgrade_2.3.36-beta-rc1.php'));
     $aExistingColumns = $oDbh->manager->listTableFields($this->prefix . $table);
     $aColumns = array('ad_clicks_sum', 'ad_views_sum', 'ad_clicks_per_second', 'ad_views_per_second', 'ad_cs_data_last_sent', 'ad_cs_data_last_sent', 'ad_cs_data_last_received');
     foreach ($aColumns as $column) {
         $this->assertFalse(in_array($column, $aExistingColumns, $column . ' found in column list'));
     }
     TestEnv::restoreConfig();
     TestEnv::restoreEnv();
 }
 /**
  * Method to test the getZonesAllocationsByAgencyAndCampaignPriority method.
  *
  * Requirements:
  * Test 1: Test with no data, and ensure no data returned.
  * Test 2: Test with sample data, and ensure the correct data is returned.
  */
 function testGetZonesAllocationsByAgencyAndCampaignPriority()
 {
     $oMaxDalMaintenance = new OA_Dal_Maintenance_Priority();
     list($agencyId1, $agencyId2) = $this->_generateData($priority = 5);
     $priority--;
     // always bigger priority is summed up
     // Test 1
     $result = $oMaxDalMaintenance->getZonesAllocationsByAgencyAndCampaignPriority($agencyId2, $priority);
     $this->assertEqual(0, count($result));
     // Test 2
     $aResult = $oMaxDalMaintenance->getZonesAllocationsByAgencyAndCampaignPriority($agencyId1, $priority);
     $this->assertEqual(1, count($aResult));
     $this->assertEqual(7, $aResult[$this->idZone1]);
     TestEnv::restoreEnv();
 }
 /**
  * Method to test the getAgencyCampaignsDeliveriesToDate method.
  *
  * Requirements:
  * Test 1: Test correct results are returned with no data.
  * Test 2: Test correct results are returned with single data entry.
  * Test 3: Test correct results are returned with multiple data entries.
  */
 function testGetAgencyEcpmRemnantCampaignsDeliveriesToDate()
 {
     TestEnv::restoreEnv();
     $priority = DataObjects_Campaigns::PRIORITY_ECPM;
     $oMaxDalMaintenance = new OA_Dal_Maintenance_Priority();
     list($agencyId1, $agencyId2) = $this->_commonTest($oMaxDalMaintenance, $priority);
     // Check that there are no results for agency 1 (when checking ecpm deliveries)
     $result = $oMaxDalMaintenance->getAgencyEcpmRemnantCampaignsDeliveriesToDate($agencyId1);
     $this->assertTrue(is_array($result));
     $this->assertEqual(count($result), 0);
     // Check that results for agency 2 are the same (when checking ecpm deliveries)
     $result = $oMaxDalMaintenance->getAgencyEcpmRemnantCampaignsDeliveriesToDate($agencyId2);
     $this->_testResult($result);
     DataGenerator::cleanUp();
 }
 /**
  * Method to test the setMaintenancePriorityLastRunInfo method.
  *
  * Requirements:
  * Test 1: Test with no data in the database, ensure data is correctly stored.
  * Test 2: Test with previous test data in the database, ensure data is correctly stored.
  */
 function testSetMaintenancePriorityLastRunInfo()
 {
     // Test relies on transaction numbers, so ensure fresh database used
     TestEnv::restoreEnv('dropTmpTables');
     $conf = $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $oMaxDalMaintenance = new OA_Dal_Maintenance_Priority();
     // Test 1
     $oStartDate = new Date('2005-06-21 15:00:01');
     $oEndDate = new Date('2005-06-21 15:01:01');
     $oUpdatedTo = new Date('2005-06-21 15:59:59');
     $result = $oMaxDalMaintenance->setMaintenancePriorityLastRunInfo($oStartDate, $oEndDate, $oUpdatedTo, DAL_PRIORITY_UPDATE_ECPM);
     $this->assertEqual($result, 1);
     $query = "\n            SELECT\n                start_run,\n                end_run,\n                operation_interval,\n                duration,\n                run_type,\n                updated_to\n            FROM\n                " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['log_maintenance_priority'], true) . "\n            WHERE\n                log_maintenance_priority_id = 1";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $this->assertEqual($aRow['start_run'], '2005-06-21 15:00:01');
     $this->assertEqual($aRow['end_run'], '2005-06-21 15:01:01');
     $this->assertEqual($aRow['operation_interval'], $conf['maintenance']['operationInterval']);
     $this->assertEqual($aRow['duration'], 60);
     $this->assertEqual($aRow['run_type'], DAL_PRIORITY_UPDATE_ECPM);
     $this->assertEqual($aRow['updated_to'], '2005-06-21 15:59:59');
     // Test 2
     $oStartDate = new Date('2005-06-21 16:00:01');
     $oEndDate = new Date('2005-06-21 16:01:06');
     $oUpdatedTo = new Date('2005-06-21 16:59:59');
     $result = $oMaxDalMaintenance->setMaintenancePriorityLastRunInfo($oStartDate, $oEndDate, $oUpdatedTo, DAL_PRIORITY_UPDATE_PRIORITY_COMPENSATION);
     $this->assertEqual($result, 1);
     $query = "\n            SELECT\n                start_run,\n                end_run,\n                operation_interval,\n                duration,\n                run_type,\n                updated_to\n            FROM\n                " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['log_maintenance_priority'], true) . "\n            WHERE\n                log_maintenance_priority_id = 1";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $this->assertEqual($aRow['start_run'], '2005-06-21 15:00:01');
     $this->assertEqual($aRow['end_run'], '2005-06-21 15:01:01');
     $this->assertEqual($aRow['operation_interval'], $conf['maintenance']['operationInterval']);
     $this->assertEqual($aRow['duration'], 60);
     $this->assertEqual($aRow['run_type'], DAL_PRIORITY_UPDATE_ECPM);
     $this->assertEqual($aRow['updated_to'], '2005-06-21 15:59:59');
     $query = "\n            SELECT\n                start_run,\n                end_run,\n                operation_interval,\n                duration,\n                run_type,\n                updated_to\n            FROM\n                " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['log_maintenance_priority'], true) . "\n            WHERE\n                log_maintenance_priority_id = 2";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $this->assertEqual($aRow['start_run'], '2005-06-21 16:00:01');
     $this->assertEqual($aRow['end_run'], '2005-06-21 16:01:06');
     $this->assertEqual($aRow['operation_interval'], $conf['maintenance']['operationInterval']);
     $this->assertEqual($aRow['duration'], 65);
     $this->assertEqual($aRow['run_type'], DAL_PRIORITY_UPDATE_PRIORITY_COMPENSATION);
     $this->assertEqual($aRow['updated_to'], '2005-06-21 16:59:59');
     DataGenerator::cleanUp(array('log_maintenance_priority'));
 }
 /**
  * A method to test the getCampaigns method.
  */
 function testGetCampaigns()
 {
     /**
      * @TODO Locate where clean up doesn't happen before this test, and fix!
      */
     TestEnv::restoreEnv();
     $da = new OA_Dal_Maintenance_Priority();
     $this->_generateStatsOne();
     // Test 1 getCampaigns method.
     $ret = $da->getCampaigns();
     $this->assertTrue(is_array($ret));
     $this->assertTrue(count($ret) == 5);
     $campaign = $ret[0];
     $this->assertIsA($campaign, 'OX_Maintenance_Priority_Campaign');
     $this->assertEqual($campaign->id, 1);
     $this->assertEqual($campaign->impressionTargetTotal, 0);
     $this->assertEqual($campaign->clickTargetTotal, 400);
     $this->assertEqual($campaign->conversionTargetTotal, 0);
     $this->assertEqual($campaign->impressionTargetDaily, 0);
     $this->assertEqual($campaign->clickTargetDaily, 0);
     $this->assertEqual($campaign->conversionTargetDaily, 0);
     $this->assertEqual($campaign->priority, 3);
     // Test 2 getCampaignData method.
     $campaign = $da->getCampaignData(1);
     $this->assertTrue(is_array($campaign));
     $this->assertTrue(count($campaign) == 5);
     $this->assertTrue(array_key_exists('advertiser_id', $campaign));
     $this->assertTrue(array_key_exists('placement_id', $campaign));
     $this->assertTrue(array_key_exists('name', $campaign));
     $this->assertTrue(array_key_exists('status', $campaign));
     $this->assertTrue(array_key_exists('num_children', $campaign));
     // Test 3 getCampaignStats method.
     $ret = $da->getCampaignStats(1);
     $this->assertTrue(is_array($ret));
     $this->assertTrue(count($ret) == 9);
     $this->assertTrue(array_key_exists('advertiser_id', $ret));
     $this->assertTrue(array_key_exists('placement_id', $ret));
     $this->assertTrue(array_key_exists('name', $ret));
     $this->assertTrue(array_key_exists('status', $ret));
     $this->assertTrue(array_key_exists('num_children', $ret));
     $this->assertTrue(array_key_exists('sum_requests', $ret));
     $this->assertTrue(array_key_exists('sum_views', $ret));
     $this->assertTrue(array_key_exists('sum_clicks', $ret));
     $this->assertTrue(array_key_exists('sum_conversions', $ret));
     DataGenerator::cleanUp();
 }
 /**
  * Tests the saveSummary() method.
  *
  * Requirements:
  * Test 1: Test with no data.
  * Test 2: Test a single day summarisation.
  * Test 3: Test multi-day summarisation.
  */
 function testSaveSummary()
 {
     $aConf =& $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $oFactory = new OX_Dal_Maintenance_Statistics_Factory();
     $oDalMaintenanceStatistics = $oFactory->factory();
     // Test 1
     $start = new Date('2004-06-06 12:00:00');
     $end = new Date('2004-06-06 12:29:59');
     $aActionTypes = array('types' => array(0 => 'request', 1 => 'impression', 2 => 'click'), 'connections' => array(1 => MAX_CONNECTION_AD_IMPRESSION, 2 => MAX_CONNECTION_AD_CLICK));
     $oDalMaintenanceStatistics->saveSummary($start, $end, $aActionTypes, 'data_intermediate_ad', 'data_summary_ad_hourly');
     $query = "\n            SELECT\n                COUNT(*) AS number\n            FROM\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_summary_ad_hourly'], true);
     $aRow = $oDbh->queryRow($query);
     $this->assertEqual($aRow['number'], 0);
     // Test 2
     // Insert the test data
     $this->_insertTestSaveSummaryPlacement();
     $this->_insertTestSaveSummaryAd();
     $this->_insertTestSaveSummaryZone();
     $query = "\n            INSERT INTO\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_intermediate_ad'], true) . "\n                (\n                    date_time, operation_interval, operation_interval_id, interval_start, interval_end,\n                    ad_id, creative_id, zone_id, impressions, clicks, conversions, total_basket_value, total_num_items\n                )\n            VALUES\n                (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
     $aTypes = array('timestamp', 'integer', 'integer', 'timestamp', 'timestamp', 'integer', 'integer', 'integer', 'integer', 'integer', 'integer', 'integer', 'integer');
     $st = $oDbh->prepare($query, $aTypes, MDB2_PREPARE_MANIP);
     $aData = array('2004-06-06 18:00:00', 30, 36, '2004-06-06 18:00:00', '2004-06-06 18:29:59', 1, 1, 1, 1, 1, 1, 1, 0);
     $rows = $st->execute($aData);
     $aData = array('2004-06-06 18:00:00', 30, 36, '2004-06-06 18:00:00', '2004-06-06 18:29:59', 1, 2, 1, 1, 1, 1, 1, 0);
     $rows = $st->execute($aData);
     $aData = array('2004-06-06 18:00:00', 30, 36, '2004-06-06 18:00:00', '2004-06-06 18:29:59', 1, 2, 1, 1, 1, 1, 1, 0);
     $rows = $st->execute($aData);
     $aData = array('2004-06-06 18:00:00', 30, 36, '2004-06-06 18:00:00', '2004-06-06 18:29:59', 2, 1, 1, 1, 1, 0, 0, 0);
     $rows = $st->execute($aData);
     $aData = array('2004-06-06 18:00:00', 30, 36, '2004-06-06 18:00:00', '2004-06-06 18:29:59', 3, 1, 2, 1, 1, 0, 0, 0);
     $rows = $st->execute($aData);
     $aData = array('2004-06-06 18:00:00', 30, 36, '2004-06-06 18:00:00', '2004-06-06 18:29:59', 4, 1, 3, 1, 1, 5, 0, 0);
     $rows = $st->execute($aData);
     $aData = array('2004-06-06 18:00:00', 30, 36, '2004-06-06 18:00:00', '2004-06-06 18:29:59', 4, 1, 4, 1, 1, 5, 0, 0);
     $rows = $st->execute($aData);
     $aData = array('2004-06-06 18:00:00', 30, 36, '2004-06-06 18:00:00', '2004-06-06 18:29:59', 4, 1, 5, 1, 1, 5, 100, 1);
     $rows = $st->execute($aData);
     $aData = array('2004-06-06 18:00:00', 30, 36, '2004-06-06 18:00:00', '2004-06-06 18:29:59', 4, 1, 6, 1, 1, 5, 100, 3);
     $rows = $st->execute($aData);
     // Test
     $start = new Date('2004-06-06 18:00:00');
     $end = new Date('2004-06-06 18:29:59');
     $oDalMaintenanceStatistics->saveSummary($start, $end, $aActionTypes, 'data_intermediate_ad', 'data_summary_ad_hourly');
     $query = "\n            SELECT\n                COUNT(*) AS number\n            FROM\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_summary_ad_hourly'], true);
     $aRow = $oDbh->queryRow($query);
     $this->assertEqual($aRow['number'], 8);
     $query = "\n            SELECT\n                *\n            FROM\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_summary_ad_hourly'], true) . "\n            WHERE\n                ad_id = 1\n                AND creative_id = 1";
     $aRow = $oDbh->queryRow($query);
     $this->assertEqual($aRow['date_time'], '2004-06-06 18:00:00');
     $this->assertEqual($aRow['zone_id'], 1);
     $this->assertEqual($aRow['impressions'], 1);
     $this->assertEqual($aRow['clicks'], 1);
     $this->assertEqual($aRow['conversions'], 1);
     $this->assertEqual($aRow['total_basket_value'], 1);
     $this->assertEqual($aRow['total_revenue'], 5);
     $query = "\n            SELECT\n                *\n            FROM\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_summary_ad_hourly'], true) . "\n            WHERE\n                ad_id = 1\n                AND creative_id = 2";
     $aRow = $oDbh->queryRow($query);
     $this->assertEqual($aRow['date_time'], '2004-06-06 18:00:00');
     $this->assertEqual($aRow['zone_id'], 1);
     $this->assertEqual($aRow['impressions'], 2);
     $this->assertEqual($aRow['clicks'], 2);
     $this->assertEqual($aRow['conversions'], 2);
     $this->assertEqual($aRow['total_basket_value'], 2);
     $this->assertEqual($aRow['total_revenue'], 10);
     $query = "\n            SELECT\n                *\n            FROM\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_summary_ad_hourly'], true) . "\n            WHERE\n                ad_id = 2";
     $aRow = $oDbh->queryRow($query);
     $this->assertEqual($aRow['date_time'], '2004-06-06 18:00:00');
     $this->assertEqual($aRow['creative_id'], 1);
     $this->assertEqual($aRow['zone_id'], 1);
     $this->assertEqual($aRow['impressions'], 1);
     $this->assertEqual($aRow['clicks'], 1);
     $this->assertEqual($aRow['conversions'], 0);
     $this->assertEqual($aRow['total_basket_value'], 0);
     $this->assertEqual($aRow['total_revenue'], 2);
     $query = "\n            SELECT\n                *\n            FROM\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_summary_ad_hourly'], true) . "\n            WHERE\n                ad_id = 3";
     $aRow = $oDbh->queryRow($query);
     $this->assertEqual($aRow['date_time'], '2004-06-06 18:00:00');
     $this->assertEqual($aRow['creative_id'], 1);
     $this->assertEqual($aRow['zone_id'], 2);
     $this->assertEqual($aRow['impressions'], 1);
     $this->assertEqual($aRow['clicks'], 1);
     $this->assertEqual($aRow['conversions'], 0);
     $this->assertEqual($aRow['total_basket_value'], 0);
     $this->assertEqual($aRow['total_revenue'], 0);
     $query = "\n            SELECT\n                *\n            FROM\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_summary_ad_hourly'], true) . "\n            WHERE\n                ad_id = 4\n            ORDER BY\n                zone_id";
     $rc = $oDbh->query($query);
     $this->assertEqual($rc->numRows(), 4);
     $aRow = $rc->fetchRow();
     $this->assertEqual($aRow['date_time'], '2004-06-06 18:00:00');
     $this->assertEqual($aRow['creative_id'], 1);
     $this->assertEqual($aRow['zone_id'], 3);
     $this->assertEqual($aRow['impressions'], 1);
     $this->assertEqual($aRow['clicks'], 1);
     $this->assertEqual($aRow['conversions'], 5);
     $this->assertEqual($aRow['total_basket_value'], 0);
     $this->assertEqual($aRow['total_revenue'], 20);
     $aRow = $rc->fetchRow();
     $this->assertEqual($aRow['date_time'], '2004-06-06 18:00:00');
     $this->assertEqual($aRow['creative_id'], 1);
     $this->assertEqual($aRow['zone_id'], 4);
     $this->assertEqual($aRow['impressions'], 1);
     $this->assertEqual($aRow['clicks'], 1);
     $this->assertEqual($aRow['conversions'], 5);
     $this->assertEqual($aRow['total_basket_value'], 0);
     $this->assertEqual($aRow['total_revenue'], 20);
     $aRow = $rc->fetchRow();
     $this->assertEqual($aRow['date_time'], '2004-06-06 18:00:00');
     $this->assertEqual($aRow['creative_id'], 1);
     $this->assertEqual($aRow['zone_id'], 5);
     $this->assertEqual($aRow['impressions'], 1);
     $this->assertEqual($aRow['clicks'], 1);
     $this->assertEqual($aRow['conversions'], 5);
     $this->assertEqual($aRow['total_basket_value'], 100);
     $this->assertEqual($aRow['total_revenue'], 20);
     $aRow = $rc->fetchRow();
     $this->assertEqual($aRow['date_time'], '2004-06-06 18:00:00');
     $this->assertEqual($aRow['creative_id'], 1);
     $this->assertEqual($aRow['zone_id'], 6);
     $this->assertEqual($aRow['impressions'], 1);
     $this->assertEqual($aRow['clicks'], 1);
     $this->assertEqual($aRow['conversions'], 5);
     $this->assertEqual($aRow['total_basket_value'], 100);
     $this->assertEqual($aRow['total_revenue'], 20);
     TestEnv::restoreEnv();
     // Test 3
     // Insert the test data
     $this->_insertTestSaveSummaryPlacement();
     $this->_insertTestSaveSummaryAd();
     $this->_insertTestSaveSummaryZone();
     $aData = array('2004-06-06 18:00:00', 30, 36, '2004-06-06 18:00:00', '2004-06-06 18:29:59', 1, 1, 1, 1, 1, 1, 1);
     $rows = $st->execute($aData);
     $aData = array('2004-06-07 18:00:00', 30, 36, '2004-06-07 18:00:00', '2004-06-07 18:29:59', 1, 2, 1, 1, 1, 1, 1);
     $rows = $st->execute($aData);
     $aData = array('2004-06-07 18:00:00', 30, 36, '2004-06-07 18:00:00', '2004-06-07 18:29:59', 1, 2, 1, 1, 1, 1, 1);
     $rows = $st->execute($aData);
     $aData = array('2004-06-08 18:00:00', 30, 36, '2004-06-08 18:00:00', '2004-06-08 18:29:59', 2, 1, 1, 1, 1, 0, 0);
     $rows = $st->execute($aData);
     // Test
     $start = new Date('2004-06-06 18:00:00');
     $end = new Date('2004-06-08 18:29:59');
     $oDalMaintenanceStatistics->saveSummary($start, $end, $aActionTypes, 'data_intermediate_ad', 'data_summary_ad_hourly');
     $query = "\n            SELECT\n                COUNT(*) AS number\n            FROM\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_summary_ad_hourly'], true);
     $aRow = $oDbh->queryRow($query);
     $this->assertEqual($aRow['number'], 3);
     $query = "\n            SELECT\n                *\n            FROM\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_summary_ad_hourly'], true) . "\n            WHERE\n                ad_id = 1\n                AND creative_id = 1";
     $aRow = $oDbh->queryRow($query);
     $this->assertEqual($aRow['date_time'], '2004-06-06 18:00:00');
     $this->assertEqual($aRow['zone_id'], 1);
     $this->assertEqual($aRow['impressions'], 1);
     $this->assertEqual($aRow['clicks'], 1);
     $this->assertEqual($aRow['conversions'], 1);
     $this->assertEqual($aRow['total_basket_value'], 1);
     $this->assertEqual($aRow['total_revenue'], 5);
     $query = "\n            SELECT\n                *\n            FROM\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_summary_ad_hourly'], true) . "\n            WHERE\n                ad_id = 1\n                AND creative_id = 2";
     $aRow = $oDbh->queryRow($query);
     $this->assertEqual($aRow['date_time'], '2004-06-07 18:00:00');
     $this->assertEqual($aRow['zone_id'], 1);
     $this->assertEqual($aRow['impressions'], 2);
     $this->assertEqual($aRow['clicks'], 2);
     $this->assertEqual($aRow['conversions'], 2);
     $this->assertEqual($aRow['total_basket_value'], 2);
     $this->assertEqual($aRow['total_revenue'], 10);
     $query = "\n            SELECT\n                *\n            FROM\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_summary_ad_hourly'], true) . "\n            WHERE\n                ad_id = 2";
     $aRow = $oDbh->queryRow($query);
     $this->assertEqual($aRow['date_time'], '2004-06-08 18:00:00');
     $this->assertEqual($aRow['creative_id'], 1);
     $this->assertEqual($aRow['zone_id'], 1);
     $this->assertEqual($aRow['impressions'], 1);
     $this->assertEqual($aRow['clicks'], 1);
     $this->assertEqual($aRow['conversions'], 0);
     $this->assertEqual($aRow['total_basket_value'], 0);
     $this->assertEqual($aRow['total_revenue'], 2);
     TestEnv::restoreEnv();
     TestEnv::restoreConfig();
 }
 /**
  * Tests creating/dropping all of the MPE temporary tables.
  *
  * Requirements:
  * Test 1: Test that all MPE temporary tables can be created and dropped.
  */
 function testAllMaintenanceStatisticsTables()
 {
     $tmpTables = array('tmp_ad_impression', 'tmp_ad_click', 'tmp_tracker_impression_ad_impression_connection', 'tmp_tracker_impression_ad_click_connection', 'tmp_ad_connection');
     // Test 1
     $conf =& $GLOBALS['_MAX']['CONF'];
     $conf['table']['prefix'] = '';
     $oDbh =& OA_DB::singleton();
     foreach ($tmpTables as $tableName) {
         $query = "SELECT * FROM {$tableName}";
         OA::disableErrorHandling();
         $result = $oDbh->query($query);
         OA::enableErrorHandling();
         $this->assertEqual(strtolower(get_class($result)), 'mdb2_error');
     }
     $oTable =& OA_DB_Table_Statistics::singleton();
     foreach ($tmpTables as $tableName) {
         $oTable->createTable($tableName);
     }
     $aExistingTables = OA_DB_Table::listOATablesCaseSensitive();
     foreach ($tmpTables as $tableName) {
         // Test that the table has been created
         $query = "SELECT * FROM {$tableName}";
         $result = $oDbh->query($query);
         $this->assertTrue($result);
         // Test that the table can be dropped
         // Use a different query to overcome MDB2 query buffering
         $query = "SELECT foo FROM {$tableName}";
         OA::disableErrorHandling();
         $result = $oDbh->query($query);
         OA::enableErrorHandling();
         $this->assertEqual(strtolower(get_class($result)), 'mdb2_error');
     }
     // Restore the testing environment
     TestEnv::restoreEnv();
 }
 /**
  * this test calls backup method then immediately rollsback
  * emulating an upgrade error without interrupt (can recover in same session)
  *
  */
 function test_BackupAndRollback_restoreAutoIncrement()
 {
     $oDB_Upgrade = $this->_newDBUpgradeObject();
     $oDB_Upgrade->oAuditor->auditId = 5;
     $oDB_Upgrade->oAuditor->setKeyParams(array('schema_name' => 'tables_core', 'version' => '920', 'timing' => 0));
     $this->_createTestTableAutoInc($oDB_Upgrade->oSchema->db);
     $oDB_Upgrade->aChanges['affected_tables']['constructive'] = array('table1_autoinc');
     OA_DB::setCaseSensitive();
     $aTbl_def_orig = $oDB_Upgrade->oSchema->getDefinitionFromDatabase(array($this->prefix . 'table1_autoinc'));
     OA_DB::disableCaseSensitive();
     $this->assertTrue($oDB_Upgrade->_backup(), '_backup failed');
     $this->assertTrue($oDB_Upgrade->prepRollbackByAuditId(5, $version, $schema), 'prep rollback failed');
     $this->assertIsA($oDB_Upgrade->aRestoreTables, 'array', 'aRestoreTables not an array');
     $this->assertTrue(array_key_exists('table1_autoinc', $oDB_Upgrade->aRestoreTables['tables_core']['920']), 'table not found in aRestoreTables');
     $this->assertTrue(array_key_exists('tablename_backup', $oDB_Upgrade->aRestoreTables['tables_core']['920']['table1_autoinc'][0]), 'backup table name not found for table1_autoinc');
     $this->assertTrue(array_key_exists('table_backup_schema', $oDB_Upgrade->aRestoreTables['tables_core']['920']['table1_autoinc'][0]), 'definition array not found for table1_autoinc');
     $oDB_Upgrade->aDBTables = $oDB_Upgrade->_listTables();
     $table_bak = $oDB_Upgrade->aRestoreTables['tables_core']['920']['table1_autoinc'][0]['tablename_backup'];
     $this->assertTrue($this->_tableExists($table_bak, $oDB_Upgrade->aDBTables), 'backup table not found in database');
     //OA_DB::setQuoteIdentifier();
     OA_DB::setCaseSensitive();
     $aTbl_def_bak = $oDB_Upgrade->oSchema->getDefinitionFromDatabase(array($this->prefix . $table_bak));
     OA_DB::disableCaseSensitive();
     //OA_DB::disabledQuoteIdentifier();
     $aTbl_def_orig = $aTbl_def_orig['tables'][$this->prefix . 'table1_autoinc'];
     $aTbl_def_bak = $aTbl_def_bak['tables'][$this->prefix . $table_bak];
     foreach ($aTbl_def_orig['fields'] as $name => $aType) {
         $this->assertTrue(array_key_exists($name, $aTbl_def_bak['fields']), 'field missing from backup table');
     }
     $oDB_Upgrade->oSchema->db->manager->dropTable($this->prefix . 'table1_autoinc');
     $oDB_Upgrade->aDBTables = $oDB_Upgrade->_listTables();
     $this->assertFalse($this->_tableExists('table1_autoinc', $oDB_Upgrade->aDBTables), 'could not drop test table');
     $this->assertTrue($oDB_Upgrade->rollback(), 'rollback failed');
     $oDB_Upgrade->aDBTables = $oDB_Upgrade->_listTables();
     $this->assertTrue($this->_tableExists('table1_autoinc', $oDB_Upgrade->aDBTables), 'test table was not restored');
     OA_DB::setCaseSensitive();
     $aTbl_def_rest = $oDB_Upgrade->oSchema->getDefinitionFromDatabase(array($this->prefix . 'table1_autoinc'));
     OA_DB::disableCaseSensitive();
     $aTbl_def_rest = $aTbl_def_rest['tables']['table1_autoinc'];
     // also test field definition properties?
     $aDiffs = $oDB_Upgrade->oSchema->compareDefinitions($aTbl_def_orig, $aTbl_def_rest);
     $this->assertEqual(count($aDiffs) == 0, 'differences found in restored table');
     $this->assertFalse($this->_tableExists($table_bak, $oDB_Upgrade->aDBTables), 'backup table was not removed');
     TestEnv::restoreConfig();
     TestEnv::restoreEnv();
 }
Ejemplo n.º 11
0
 /**
  * tests an upgrade package containing two schema upgrades
  *
  */
 function test_upgradeSchemas()
 {
     $this->_deleteTestAppVarRecord('tables_core', '');
     $this->assertEqual($this->_getTestAppVarValue('tables_core', ''), '', '');
     $this->_createTestAppVarRecord('tables_core', '997');
     $this->assertEqual($this->_getTestAppVarValue('tables_core', '997'), '997', '');
     $this->_createTestAppVarRecord('oa_version', '2.3.00');
     $oUpgrade->versionInitialSchema['tables_core'] = 997;
     $oUpgrade->versionInitialApplication = '2.3.00';
     $oUpgrade = new OA_Upgrade();
     $oUpgrade->upgradePath = MAX_PATH . '/lib/OA/Upgrade/tests/data/';
     $oUpgrade->oDBUpgrader->path_changes = $oUpgrade->upgradePath;
     $oUpgrade->oDBUpgrader->path_schema = $oUpgrade->upgradePath;
     $input_file = 'openads_upgrade_2.3.00_to_2.3.02_beta.xml';
     $oUpgrade->initDatabaseConnection();
     $oUpgrade->_parseUpgradePackageFile($oUpgrade->upgradePath . $input_file);
     $this->assertTrue($oUpgrade->upgradeSchemas(), 'upgradeSchemas');
     $this->_checkTablesUpgraded($oUpgrade);
     $this->assertEqual($this->_getTestAppVarValue('tables_core', '999'), '999', '');
     // remove the fake application variable records
     $this->_deleteTestAppVarRecordAllNames('oa_version');
     $this->_deleteTestAppVarRecordAllNames('tables_core');
     TestEnv::restoreConfig();
     TestEnv::restoreEnv();
 }
 /**
  * A method to test the main run() method.
  */
 function testRun()
 {
     $aConf =& $GLOBALS['_MAX']['CONF'];
     $aConf['maintenance']['operationInterval'] = 60;
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oFactory = new OX_Dal_Maintenance_Statistics_Factory();
     $oDalMaintenanceStatsticsClassName = $oFactory->deriveClassName();
     // Test 1: Run, with the migration required but with no plugins installed
     $oNowDate = new Date('2008-08-28 09:01:00');
     $oServiceLocator->register('now', $oNowDate);
     $oMaintenanceStatistics = new OX_Maintenance_Statistics();
     $oMaintenanceStatistics->updateIntermediate = true;
     $oMaintenanceStatistics->oLastDateIntermediate = new Date('2008-08-28 07:59:59');
     $oMaintenanceStatistics->oUpdateIntermediateToDate = new Date('2008-08-28 08:59:59');
     Mock::generatePartial($oDalMaintenanceStatsticsClassName, 'MockOX_Dal_Maintenance_Statistics_Test_1', array('summariseBucketsRaw', 'summariseBucketsRawSupplementary', 'summariseBucketsAggregate', 'migrateRawRequests', 'migrateRawImpressions', 'migrateRawClicks'));
     $oDal = new MockOX_Dal_Maintenance_Statistics_Test_1($this);
     $oDal->expectNever('summariseBucketsRaw');
     $oDal->expectNever('summariseBucketsRawSupplementary');
     $oDal->expectNever('summariseBucketsAggregate');
     $oDal->expectNever('migrateRawRequests');
     $oDal->expectNever('migrateRawImpressions');
     $oDal->expectNever('migrateRawClicks');
     $oDal->OX_Dal_Maintenance_Statistics();
     $oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal);
     $oSummariseIntermediate = new OX_Maintenance_Statistics_Task_MigrateBucketData();
     $oSummariseIntermediate->run();
     $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
     $oDal->tally();
     // Create the "application_variable" table required for installing the plugin
     $oTables =& OA_DB_Table_Core::singleton();
     $oTables->createTable('application_variable');
     // Setup the default OpenX delivery logging plugin for the next test
     TestEnv::installPluginPackage('openXDeliveryLog', false);
     // Test 2: Run, with plugins installed, but with the migration not required
     $oNowDate = new Date('2008-08-28 09:01:00');
     $oServiceLocator->register('now', $oNowDate);
     $oMaintenanceStatistics = new OX_Maintenance_Statistics();
     $oMaintenanceStatistics->updateIntermediate = false;
     $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics);
     Mock::generatePartial($oDalMaintenanceStatsticsClassName, 'MockOX_Dal_Maintenance_Statistics_Test_2', array('summariseBucketsRaw', 'summariseBucketsRawSupplementary', 'summariseBucketsAggregate', 'migrateRawRequests', 'migrateRawImpressions', 'migrateRawClicks'));
     $oDal = new MockOX_Dal_Maintenance_Statistics_Test_2($this);
     $oDal->expectNever('summariseBucketsRaw');
     $oDal->expectNever('summariseBucketsRawSupplementary');
     $oDal->expectNever('summariseBucketsAggregate');
     $oDal->expectNever('migrateRawRequests');
     $oDal->expectNever('migrateRawImpressions');
     $oDal->expectNever('migrateRawClicks');
     $oDal->OX_Dal_Maintenance_Statistics();
     $oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal);
     $oSummariseIntermediate = new OX_Maintenance_Statistics_Task_MigrateBucketData();
     $oSummariseIntermediate->run();
     $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
     $oDal->tally();
     // Test 3: Run, with plugins installed and with the migration required for a single
     //         operation interval
     $oNowDate = new Date('2008-08-28 09:01:00');
     $oServiceLocator->register('now', $oNowDate);
     $oMaintenanceStatistics = new OX_Maintenance_Statistics();
     $oMaintenanceStatistics->updateIntermediate = true;
     $oMaintenanceStatistics->oLastDateIntermediate = new Date('2008-08-28 07:59:59');
     $oMaintenanceStatistics->oUpdateIntermediateToDate = new Date('2008-08-28 08:59:59');
     $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics);
     Mock::generatePartial($oDalMaintenanceStatsticsClassName, 'MockOX_Dal_Maintenance_Statistics_Test_3', array('summariseBucketsRaw', 'summariseBucketsRawSupplementary', 'summariseBucketsAggregate', 'migrateRawRequests', 'migrateRawImpressions', 'migrateRawClicks'));
     $oDal = new MockOX_Dal_Maintenance_Statistics_Test_3($this);
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogConversion', 'logConversion');
     $oStartDate = new Date('2008-08-28 07:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 09:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectOnce('summariseBucketsRaw', array($aConf['table']['prefix'] . 'data_intermediate_ad_connection', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogConversion', 'logConversionVariable');
     $oStartDate = new Date('2008-08-28 07:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 09:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectOnce('summariseBucketsRawSupplementary', array($aConf['table']['prefix'] . 'data_intermediate_ad_variable_value', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $aMap = array();
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogClick', 'logClick');
     $aMap[get_class($oComponent)] = $oComponent->getStatisticsMigration();
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogImpression', 'logImpression');
     $aMap[get_class($oComponent)] = $oComponent->getStatisticsMigration();
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogRequest', 'logRequest');
     $aMap[get_class($oComponent)] = $oComponent->getStatisticsMigration();
     $oStartDate = new Date('2008-08-28 07:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 09:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectOnce('summariseBucketsAggregate', array($aConf['table']['prefix'] . 'data_intermediate_ad', $aMap, array('start' => $oStartDate, 'end' => $oEndDate), array('operation_interval' => '60', 'operation_interval_id' => OX_OperationInterval::convertDateToOperationIntervalID($oStartDate), 'interval_start' => "'2008-08-28 08:00:00'", 'interval_end' => "'2008-08-28 08:59:59'", 'creative_id' => 0, 'updated' => "'2008-08-28 09:01:00'")));
     $oDal->expectNever('migrateRawRequests');
     $oDal->expectNever('migrateRawImpressions');
     $oDal->expectNever('migrateRawClicks');
     $oDal->OX_Dal_Maintenance_Statistics();
     $oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal);
     $oSummariseIntermediate = new OX_Maintenance_Statistics_Task_MigrateBucketData();
     $oSummariseIntermediate->run();
     $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
     $oDal->tally();
     // Test 4: Run, with plugins installed and with the migration required for a single
     //         operation interval + migration of raw data set to occur
     $doApplication_variable = OA_Dal::factoryDO('application_variable');
     $doApplication_variable->name = 'mse_process_raw';
     $doApplication_variable->value = '1';
     $doApplication_variable->insert();
     $oNowDate = new Date('2008-08-28 09:01:00');
     $oServiceLocator->register('now', $oNowDate);
     $oMaintenanceStatistics = new OX_Maintenance_Statistics();
     $oMaintenanceStatistics->updateIntermediate = true;
     $oMaintenanceStatistics->oLastDateIntermediate = new Date('2008-08-28 07:59:59');
     $oMaintenanceStatistics->oUpdateIntermediateToDate = new Date('2008-08-28 08:59:59');
     $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics);
     Mock::generatePartial($oDalMaintenanceStatsticsClassName, 'MockOX_Dal_Maintenance_Statistics_Test_4', array('summariseBucketsRaw', 'summariseBucketsRawSupplementary', 'summariseBucketsAggregate', 'migrateRawRequests', 'migrateRawImpressions', 'migrateRawClicks'));
     $oDal = new MockOX_Dal_Maintenance_Statistics_Test_4($this);
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogConversion', 'logConversion');
     $oStartDate = new Date('2008-08-28 07:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 09:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectOnce('summariseBucketsRaw', array($aConf['table']['prefix'] . 'data_intermediate_ad_connection', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogConversion', 'logConversionVariable');
     $oStartDate = new Date('2008-08-28 07:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 09:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectOnce('summariseBucketsRawSupplementary', array($aConf['table']['prefix'] . 'data_intermediate_ad_variable_value', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $aMap = array();
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogClick', 'logClick');
     $aMap[get_class($oComponent)] = $oComponent->getStatisticsMigration();
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogImpression', 'logImpression');
     $aMap[get_class($oComponent)] = $oComponent->getStatisticsMigration();
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogRequest', 'logRequest');
     $aMap[get_class($oComponent)] = $oComponent->getStatisticsMigration();
     $oStartDate = new Date('2008-08-28 07:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 09:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectOnce('summariseBucketsAggregate', array($aConf['table']['prefix'] . 'data_intermediate_ad', $aMap, array('start' => $oStartDate, 'end' => $oEndDate), array('operation_interval' => '60', 'operation_interval_id' => OX_OperationInterval::convertDateToOperationIntervalID($oStartDate), 'interval_start' => "'2008-08-28 08:00:00'", 'interval_end' => "'2008-08-28 08:59:59'", 'creative_id' => 0, 'updated' => "'2008-08-28 09:01:00'")));
     $oDal->expectOnce('migrateRawRequests', array($oStartDate, $oEndDate));
     $oDal->expectOnce('migrateRawImpressions', array($oStartDate, $oEndDate));
     $oDal->expectOnce('migrateRawClicks', array($oStartDate, $oEndDate));
     $oDal->OX_Dal_Maintenance_Statistics();
     $oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal);
     $oSummariseIntermediate = new OX_Maintenance_Statistics_Task_MigrateBucketData();
     $oSummariseIntermediate->run();
     $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
     $oDal->tally();
     $doApplication_variable = OA_Dal::factoryDO('application_variable');
     $doApplication_variable->name = 'mse_process_raw';
     $doApplication_variable->value = '1';
     $doApplication_variable->find();
     $rows = $doApplication_variable->getRowCount();
     $this->assertEqual($rows, 0);
     // Test 5: Run, with plugins installed and with the migration required for multiple
     //         operation intervals
     $oNowDate = new Date('2008-08-28 11:01:00');
     $oServiceLocator->register('now', $oNowDate);
     $oMaintenanceStatistics = new OX_Maintenance_Statistics();
     $oMaintenanceStatistics->updateIntermediate = true;
     $oMaintenanceStatistics->oLastDateIntermediate = new Date('2008-08-28 07:59:59');
     $oMaintenanceStatistics->oUpdateIntermediateToDate = new Date('2008-08-28 10:59:59');
     $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics);
     Mock::generatePartial($oDalMaintenanceStatsticsClassName, 'MockOX_Dal_Maintenance_Statistics_Test_5', array('summariseBucketsRaw', 'summariseBucketsRawSupplementary', 'summariseBucketsAggregate', 'migrateRawRequests', 'migrateRawImpressions', 'migrateRawClicks'));
     $oDal = new MockOX_Dal_Maintenance_Statistics_Test_5($this);
     $oDal->expectCallCount('summariseBucketsRaw', 3);
     $oDal->expectCallCount('summariseBucketsRawSupplementary', 3);
     $oDal->expectCallCount('summariseBucketsAggregate', 3);
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogConversion', 'logConversion');
     $oStartDate = new Date('2008-08-28 07:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 09:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(0, 'summariseBucketsRaw', array($aConf['table']['prefix'] . 'data_intermediate_ad_connection', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oStartDate = new Date('2008-08-28 08:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 10:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(1, 'summariseBucketsRaw', array($aConf['table']['prefix'] . 'data_intermediate_ad_connection', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oStartDate = new Date('2008-08-28 09:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 11:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(2, 'summariseBucketsRaw', array($aConf['table']['prefix'] . 'data_intermediate_ad_connection', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogConversion', 'logConversionVariable');
     $oStartDate = new Date('2008-08-28 07:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 09:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(0, 'summariseBucketsRawSupplementary', array($aConf['table']['prefix'] . 'data_intermediate_ad_variable_value', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oStartDate = new Date('2008-08-28 08:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 10:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(1, 'summariseBucketsRawSupplementary', array($aConf['table']['prefix'] . 'data_intermediate_ad_variable_value', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oStartDate = new Date('2008-08-28 09:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 11:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(2, 'summariseBucketsRawSupplementary', array($aConf['table']['prefix'] . 'data_intermediate_ad_variable_value', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $aMap = array();
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogClick', 'logClick');
     $aMap[get_class($oComponent)] = $oComponent->getStatisticsMigration();
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogImpression', 'logImpression');
     $aMap[get_class($oComponent)] = $oComponent->getStatisticsMigration();
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogRequest', 'logRequest');
     $aMap[get_class($oComponent)] = $oComponent->getStatisticsMigration();
     $oStartDate = new Date('2008-08-28 07:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 09:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(0, 'summariseBucketsAggregate', array($aConf['table']['prefix'] . 'data_intermediate_ad', $aMap, array('start' => $oStartDate, 'end' => $oEndDate), array('operation_interval' => '60', 'operation_interval_id' => OX_OperationInterval::convertDateToOperationIntervalID($oStartDate), 'interval_start' => "'2008-08-28 08:00:00'", 'interval_end' => "'2008-08-28 08:59:59'", 'creative_id' => 0, 'updated' => "'2008-08-28 11:01:00'")));
     $oStartDate = new Date('2008-08-28 08:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 10:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(1, 'summariseBucketsAggregate', array($aConf['table']['prefix'] . 'data_intermediate_ad', $aMap, array('start' => $oStartDate, 'end' => $oEndDate), array('operation_interval' => '60', 'operation_interval_id' => OX_OperationInterval::convertDateToOperationIntervalID($oStartDate), 'interval_start' => "'2008-08-28 09:00:00'", 'interval_end' => "'2008-08-28 09:59:59'", 'creative_id' => 0, 'updated' => "'2008-08-28 11:01:00'")));
     $oStartDate = new Date('2008-08-28 09:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 11:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(2, 'summariseBucketsAggregate', array($aConf['table']['prefix'] . 'data_intermediate_ad', $aMap, array('start' => $oStartDate, 'end' => $oEndDate), array('operation_interval' => '60', 'operation_interval_id' => OX_OperationInterval::convertDateToOperationIntervalID($oStartDate), 'interval_start' => "'2008-08-28 10:00:00'", 'interval_end' => "'2008-08-28 10:59:59'", 'creative_id' => 0, 'updated' => "'2008-08-28 11:01:00'")));
     $oDal->expectNever('migrateRawRequests');
     $oDal->expectNever('migrateRawImpressions');
     $oDal->expectNever('migrateRawClicks');
     $oDal->OX_Dal_Maintenance_Statistics();
     $oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal);
     $oSummariseIntermediate = new OX_Maintenance_Statistics_Task_MigrateBucketData();
     $oSummariseIntermediate->run();
     $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
     $oDal->tally();
     // Test 6: Run, with plugins installed and with the migration required for multiple
     //         operation intervals + migration of raw data set to occur
     $doApplication_variable = OA_Dal::factoryDO('application_variable');
     $doApplication_variable->name = 'mse_process_raw';
     $doApplication_variable->value = '1';
     $doApplication_variable->insert();
     $oNowDate = new Date('2008-08-28 11:01:00');
     $oServiceLocator->register('now', $oNowDate);
     $oMaintenanceStatistics = new OX_Maintenance_Statistics();
     $oMaintenanceStatistics->updateIntermediate = true;
     $oMaintenanceStatistics->oLastDateIntermediate = new Date('2008-08-28 07:59:59');
     $oMaintenanceStatistics->oUpdateIntermediateToDate = new Date('2008-08-28 10:59:59');
     $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics);
     Mock::generatePartial($oDalMaintenanceStatsticsClassName, 'MockOX_Dal_Maintenance_Statistics_Test_6', array('summariseBucketsRaw', 'summariseBucketsRawSupplementary', 'summariseBucketsAggregate', 'migrateRawRequests', 'migrateRawImpressions', 'migrateRawClicks'));
     $oDal = new MockOX_Dal_Maintenance_Statistics_Test_6($this);
     $oDal->expectCallCount('summariseBucketsRaw', 3);
     $oDal->expectCallCount('summariseBucketsRawSupplementary', 3);
     $oDal->expectCallCount('summariseBucketsAggregate', 3);
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogConversion', 'logConversion');
     $oStartDate = new Date('2008-08-28 07:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 09:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(0, 'summariseBucketsRaw', array($aConf['table']['prefix'] . 'data_intermediate_ad_connection', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oStartDate = new Date('2008-08-28 08:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 10:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(1, 'summariseBucketsRaw', array($aConf['table']['prefix'] . 'data_intermediate_ad_connection', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oStartDate = new Date('2008-08-28 09:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 11:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(2, 'summariseBucketsRaw', array($aConf['table']['prefix'] . 'data_intermediate_ad_connection', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogConversion', 'logConversionVariable');
     $oStartDate = new Date('2008-08-28 07:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 09:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(0, 'summariseBucketsRawSupplementary', array($aConf['table']['prefix'] . 'data_intermediate_ad_variable_value', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oStartDate = new Date('2008-08-28 08:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 10:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(1, 'summariseBucketsRawSupplementary', array($aConf['table']['prefix'] . 'data_intermediate_ad_variable_value', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $oStartDate = new Date('2008-08-28 09:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 11:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(2, 'summariseBucketsRawSupplementary', array($aConf['table']['prefix'] . 'data_intermediate_ad_variable_value', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
     $aMap = array();
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogClick', 'logClick');
     $aMap[get_class($oComponent)] = $oComponent->getStatisticsMigration();
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogImpression', 'logImpression');
     $aMap[get_class($oComponent)] = $oComponent->getStatisticsMigration();
     $oComponent =& OX_Component::factory('deliveryLog', 'oxLogRequest', 'logRequest');
     $aMap[get_class($oComponent)] = $oComponent->getStatisticsMigration();
     $oStartDate = new Date('2008-08-28 07:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 09:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(0, 'summariseBucketsAggregate', array($aConf['table']['prefix'] . 'data_intermediate_ad', $aMap, array('start' => $oStartDate, 'end' => $oEndDate), array('operation_interval' => '60', 'operation_interval_id' => OX_OperationInterval::convertDateToOperationIntervalID($oStartDate), 'interval_start' => "'2008-08-28 08:00:00'", 'interval_end' => "'2008-08-28 08:59:59'", 'creative_id' => 0, 'updated' => "'2008-08-28 11:01:00'")));
     $oStartDate = new Date('2008-08-28 08:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 10:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(1, 'summariseBucketsAggregate', array($aConf['table']['prefix'] . 'data_intermediate_ad', $aMap, array('start' => $oStartDate, 'end' => $oEndDate), array('operation_interval' => '60', 'operation_interval_id' => OX_OperationInterval::convertDateToOperationIntervalID($oStartDate), 'interval_start' => "'2008-08-28 09:00:00'", 'interval_end' => "'2008-08-28 09:59:59'", 'creative_id' => 0, 'updated' => "'2008-08-28 11:01:00'")));
     $oStartDate = new Date('2008-08-28 09:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 11:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(2, 'summariseBucketsAggregate', array($aConf['table']['prefix'] . 'data_intermediate_ad', $aMap, array('start' => $oStartDate, 'end' => $oEndDate), array('operation_interval' => '60', 'operation_interval_id' => OX_OperationInterval::convertDateToOperationIntervalID($oStartDate), 'interval_start' => "'2008-08-28 10:00:00'", 'interval_end' => "'2008-08-28 10:59:59'", 'creative_id' => 0, 'updated' => "'2008-08-28 11:01:00'")));
     $oStartDate = new Date('2008-08-28 07:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 09:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(0, 'migrateRawRequests', array($oStartDate, $oEndDate));
     $oDal->expectAt(0, 'migrateRawImpressions', array($oStartDate, $oEndDate));
     $oDal->expectAt(0, 'migrateRawClicks', array($oStartDate, $oEndDate));
     $oStartDate = new Date('2008-08-28 08:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 10:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(1, 'migrateRawRequests', array($oStartDate, $oEndDate));
     $oDal->expectAt(1, 'migrateRawImpressions', array($oStartDate, $oEndDate));
     $oDal->expectAt(1, 'migrateRawClicks', array($oStartDate, $oEndDate));
     $oStartDate = new Date('2008-08-28 09:59:59');
     $oStartDate->addSeconds(1);
     $oEndDate = new Date('2008-08-28 11:00:00');
     $oEndDate->subtractSeconds(1);
     $oDal->expectAt(2, 'migrateRawRequests', array($oStartDate, $oEndDate));
     $oDal->expectAt(2, 'migrateRawImpressions', array($oStartDate, $oEndDate));
     $oDal->expectAt(2, 'migrateRawClicks', array($oStartDate, $oEndDate));
     $oDal->OX_Dal_Maintenance_Statistics();
     $oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal);
     $oSummariseIntermediate = new OX_Maintenance_Statistics_Task_MigrateBucketData();
     $oSummariseIntermediate->run();
     $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
     $oDal->tally();
     $doApplication_variable = OA_Dal::factoryDO('application_variable');
     $doApplication_variable->name = 'mse_process_raw';
     $doApplication_variable->value = '1';
     $doApplication_variable->find();
     $rows = $doApplication_variable->getRowCount();
     $this->assertEqual($rows, 0);
     // Uninstall the installed plugins
     TestEnv::uninstallPluginPackage('openXDeliveryLog', false);
     // Reset the testing environment
     TestEnv::restoreEnv();
 }
Ejemplo n.º 13
0
 /**
  * Tests that an e-mail advising a placement has been activated is able to
  * be generated correctly.
  *
  */
 function testPrepareActivateDeactivatePlacementEmail()
 {
     $adminContact = 'Andrew Hill';
     $adminName = 'OpenX Limited';
     $adminMail = '*****@*****.**';
     $adminCompany = 'Admin company name';
     $adminAccountId = 100;
     $agencyName = 'Agency Ltd.';
     $agencyContact = 'Mr. Foo Bar Agency';
     $agencyMail = '*****@*****.**';
     $advertiserName = 'Foo Client';
     $advertiserMail = '*****@*****.**';
     $advertiserUsername = '******';
     $aConf =& $GLOBALS['_MAX']['CONF'];
     $aConf['webpath']['admin'] = 'example.com';
     $aConf['email']['fromAddress'] = $adminMail;
     $aConf['email']['fromName'] = $adminName;
     $aConf['email']['fromCompany'] = $adminCompany;
     $aConf['email']['useManagerDetails'] = true;
     $aConf['email']['logOutgoing'] = true;
     Mock::generatePartial('OA_Email', 'PartialMockOA_Email', array('sendMail'));
     $oEmail = new PartialMockOA_Email();
     $oEmail->setReturnValue('sendMail', true);
     unset($GLOBALS['_MAX']['PREF']);
     // Prepare an admin user
     // Create the admin account
     $doAccounts = OA_Dal::factoryDO('accounts');
     $doAccounts->account_name = 'System Administrator';
     $doAccounts->account_type = OA_ACCOUNT_ADMIN;
     $adminAccountId = DataGenerator::generateOne($doAccounts);
     // Setup the admin account id
     $doAppVar = OA_Dal::factoryDO('application_variable');
     $doAppVar->name = 'admin_account_id';
     $doAppVar->value = $adminAccountId;
     // Create a user
     $doAdminUser = OA_Dal::factoryDO('users');
     $doAdminUser->contact_name = $adminContact;
     $doAdminUser->email_address = $adminMail;
     $doAdminUser->username = $adminName;
     $doAdminUser->password = md5('password');
     $doAdminUser->language = 'en';
     $doAdminUser->default_account_id = $adminAccountId;
     $adminUserId = DataGenerator::generateOne($doAdminUser);
     $doAdminUser = OA_Dal::staticGetDO('users', $adminUserId);
     $aAdminUser = $doAdminUser->toArray();
     // Create admin account-user association
     $doAUA = OA_Dal::factoryDO('account_user_assoc');
     $doAUA->account_id = $adminAccountId;
     $doAUA->user_id = $adminUserId;
     $doAUA->insert();
     $doAgency = OA_Dal::factoryDO('agency');
     $doAgency->name = $agencyName;
     $doAgency->contact = $agencyContact;
     $doAgency->email = $agencyMail;
     $agencyId = DataGenerator::generateOne($doAgency);
     $doAgency = OA_Dal::staticGetDO('agency', $agencyId);
     //get('agencyid', $agencyId);
     $agencyAccountId = $doAgency->account_id;
     // Prepare an agency user
     $doUser = OA_Dal::factoryDO('users');
     $doUser->contact_name = $agencyContact;
     $doUser->email_address = $agencyMail;
     $doUser->username = $agencyName;
     $doUser->language = 'en';
     $agencyUserId = DataGenerator::generateOne($doUser);
     $doAgencyUser = OA_Dal::staticGetDO('users', $agencyUserId);
     $aAgencyUser = $doAgencyUser->toArray();
     $oUserAccess = new OA_Admin_UI_UserAccess();
     // Agency user
     $oUserAccess->linkUserToAccount($agencyUserId, $doAgency->account_id, array(), array());
     // Generate an advertiser owned by the agency
     $doClients = OA_Dal::factoryDO('clients');
     $doClients->agencyid = $agencyId;
     $doClients->clientname = $advertiserName;
     $doClients->email = '*****@*****.**';
     $advertiserId1 = DataGenerator::generateOne($doClients);
     $doClients = OA_Dal::staticGetDO('clients', 'clientid', $advertiserId1);
     $advertiserAccountId = $doClients->account_id;
     // Create an advertiser user
     $doUser = OA_Dal::factoryDO('users');
     $doUser->contact_name = $advertiserName;
     $doUser->email_address = $advertiserMail;
     $doUser->username = $advertiserUsername;
     $doUser->language = 'en';
     $userId = DataGenerator::generateOne($doUser);
     $doAdvertiserUser = OA_Dal::staticGetDO('users', $userId);
     $aAdvertiserUser = $doAdvertiserUser->toArray();
     // Link the advertiser user
     $oUserAccess->linkUserToAccount($userId, $doClients->account_id, array(), array());
     // Create a campaign
     $doPlacements = OA_Dal::factoryDO('campaigns');
     $doPlacements->clientid = $advertiserId1;
     $doPlacements->campaignname = 'Default Campaign';
     $placementId = DataGenerator::generateOne($doPlacements);
     // Prepare banners
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $placementId;
     $doBanners->description = 'Test Banner';
     $doBanners->url = '';
     $bannerId1 = DataGenerator::generateOne($doBanners);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $placementId;
     $doBanners->description = 'Test Banner';
     $doBanners->url = 'http://www.fornax.net/';
     $bannerId2 = DataGenerator::generateOne($doBanners);
     // Two copy should be sent (different emails addresses)
     // One copy to the user and another one to the Advertiser
     $result = $oEmail->sendCampaignActivatedDeactivatedEmail($placementId);
     $this->assertEqual($result, 2);
     $doUserLog = OA_Dal::factoryDO('userlog');
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 2);
     $this->assertEqual($aUserLog[0]['action'], phpAds_actionActivationMailed);
     // Turn off email logging and send mail again
     $aConf['email']['logOutgoing'] = false;
     $result = $oEmail->sendCampaignActivatedDeactivatedEmail($placementId);
     $this->assertEqual($result, 2);
     // No new entries in user log
     $doUserLog = OA_Dal::factoryDO('userlog');
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 2);
     // Set email logging back to true
     $aConf['email']['logOutgoing'] = true;
     $aResult = $oEmail->prepareCampaignActivatedDeactivatedEmail($aAdvertiserUser, $placementId);
     // Check the contents of the generated email are correct
     $expectedSubject = 'Campaign activated: Foo Client';
     $expectedContents = "Dear {$aAdvertiserUser['contact_name']},\n\n";
     $expectedContents .= 'Your campaign shown below has been activated because' . "\n";
     $expectedContents .= 'the campaign activation date has been reached.' . "\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "=======================================================\n\n";
     $expectedContents .= " Banner  [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner  [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "\n";
     $expectedContents .= "Regards,\n   {$agencyContact}, {$agencyName}";
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Check for a campaign that should be deactivated
     $expectedSubject = 'Campaign deactivated: Foo Client';
     $expectedContents = "Dear {$aAdvertiserUser['contact_name']},\n\n";
     $expectedContents .= 'Your campaign shown below has been deactivated because:' . "\n";
     $expectedContents .= '  - there are no Impressions remaining.' . "\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "=======================================================\n\n";
     $expectedContents .= " Banner  [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner  [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "\n";
     $expectedContents .= "Regards,\n   {$agencyContact}, {$agencyName}";
     $aResult = $oEmail->prepareCampaignActivatedDeactivatedEmail($aAdvertiserUser, $placementId, OX_CAMPAIGN_DISABLED_IMPRESSIONS);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $aResult = $oEmail->prepareCampaignActivatedDeactivatedEmail($aAdvertiserUser, $placementId, OX_CAMPAIGN_DISABLED_CLICKS);
     $expectedSubject = 'Campaign deactivated: Foo Client';
     $expectedContents = "Dear {$aAdvertiserUser['contact_name']},\n\n";
     $expectedContents .= 'Your campaign shown below has been deactivated because:' . "\n";
     $expectedContents .= '  - there are no Clicks remaining.' . "\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "=======================================================\n\n";
     $expectedContents .= " Banner  [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner  [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "\n";
     $expectedContents .= "Regards,\n   {$agencyContact}, {$agencyName}";
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $aResult = $oEmail->prepareCampaignActivatedDeactivatedEmail($aAdvertiserUser, $placementId, OX_CAMPAIGN_DISABLED_CONVERSIONS);
     $expectedSubject = 'Campaign deactivated: Foo Client';
     $expectedContents = "Dear {$aAdvertiserUser['contact_name']},\n\n";
     $expectedContents .= 'Your campaign shown below has been deactivated because:' . "\n";
     $expectedContents .= '  - there are no Sales remaining.' . "\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "=======================================================\n\n";
     $expectedContents .= " Banner  [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner  [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "\n";
     $expectedContents .= "Regards,\n   {$agencyContact}, {$agencyName}";
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $aResult = $oEmail->prepareCampaignActivatedDeactivatedEmail($aAdvertiserUser, $placementId, OX_CAMPAIGN_DISABLED_DATE);
     $expectedSubject = 'Campaign deactivated: Foo Client';
     $expectedContents = "Dear {$aAdvertiserUser['contact_name']},\n\n";
     $expectedContents .= 'Your campaign shown below has been deactivated because:' . "\n";
     $expectedContents .= '  - the expiration date has been reached.' . "\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "=======================================================\n\n";
     $expectedContents .= " Banner  [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner  [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "\n";
     $expectedContents .= "Regards,\n   {$agencyContact}, {$agencyName}";
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $reason = 0 | OX_CAMPAIGN_DISABLED_IMPRESSIONS | OX_CAMPAIGN_DISABLED_CLICKS | OX_CAMPAIGN_DISABLED_DATE;
     $aResult = $oEmail->prepareCampaignActivatedDeactivatedEmail($aAdvertiserUser, $placementId, $reason);
     $expectedSubject = 'Campaign deactivated: Foo Client';
     $expectedContents = "Dear {$aAdvertiserUser['contact_name']},\n\n";
     $expectedContents .= 'Your campaign shown below has been deactivated because:' . "\n";
     $expectedContents .= '  - there are no Impressions remaining' . "\n";
     $expectedContents .= '  - there are no Clicks remaining' . "\n";
     $expectedContents .= '  - the expiration date has been reached.' . "\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "=======================================================\n\n";
     $expectedContents .= " Banner  [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner  [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "\n";
     $expectedContents .= "Regards,\n   {$agencyContact}, {$agencyName}";
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     TestEnv::restoreEnv();
 }
 /**
  * A method to test the _locateComponents() method.
  */
 function test_locateComponents()
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     // Test 1: There are no deliveryLog group plugins installed, test that
     //         an empty array is returned
     $oSummariseIntermediate = new OX_Maintenance_Statistics_Task_MigrateBucketData();
     $aComponents = $oSummariseIntermediate->_locateComponents();
     $this->assertTrue(is_array($aComponents));
     $this->assertTrue(empty($aComponents));
     // Setup the default OpenX delivery logging plugin for the next test
     TestEnv::installPluginPackage('openXDeliveryLog', false);
     // Test 2: Test with the default OpenX delivery logging plugin installed
     $oSummariseIntermediate = new OX_Maintenance_Statistics_Task_MigrateBucketData();
     $aComponents = $oSummariseIntermediate->_locateComponents();
     $this->assertTrue(is_array($aComponents));
     $this->assertEqual(count($aComponents), 3);
     $dia = $aConf['table']['prefix'] . 'data_intermediate_ad';
     $this->assertTrue(is_array($aComponents[$dia]));
     $this->assertEqual(count($aComponents[$dia]), 3);
     $aComponentClasses = array();
     foreach ($aComponents[$dia] as $oComponent) {
         $aComponentClasses[] = get_class($oComponent);
     }
     $this->assertTrue(in_array('Plugins_DeliveryLog_OxLogRequest_LogRequest', $aComponentClasses));
     $this->assertTrue(in_array('Plugins_DeliveryLog_OxLogImpression_LogImpression', $aComponentClasses));
     $this->assertTrue(in_array('Plugins_DeliveryLog_OxLogClick_LogClick', $aComponentClasses));
     $diac = $aConf['table']['prefix'] . 'data_intermediate_ad_connection';
     $this->assertTrue(is_array($aComponents[$diac]));
     $this->assertEqual(count($aComponents[$diac]), 1);
     $aComponentClasses = array();
     foreach ($aComponents[$diac] as $oComponent) {
         $aComponentClasses[] = get_class($oComponent);
     }
     $this->assertTrue(in_array('Plugins_DeliveryLog_OxLogConversion_LogConversion', $aComponentClasses));
     $diavv = $aConf['table']['prefix'] . 'data_intermediate_ad_variable_value';
     $this->assertTrue(is_array($aComponents[$diavv]));
     $this->assertEqual(count($aComponents[$diavv]), 1);
     $aComponentClasses = array();
     foreach ($aComponents[$diavv] as $oComponent) {
         $aComponentClasses[] = get_class($oComponent);
     }
     $this->assertTrue(in_array('Plugins_DeliveryLog_OxLogConversion_LogConversionVariable', $aComponentClasses));
     /*
     TODO: move this test from core code to the plugin.  only bundled plugins (or the test plugin) can be used in core tests
             // Setup the default OpenX country based impression and click delivery logging plugin for the next test
             TestEnv::installPluginPackage('openXDeliveryLogCountry', false);
             // Test 3: Test with the default OpenX delivery logging plugin and the OpenX country based impression
             //         and click delivery logging plugin installed
             $aComponents = $oSummariseIntermediate->_locateComponents();
             $this->assertTrue(is_array($aComponents));
             $this->assertEqual(count($aComponents), 4);
             $dia = $aConf['table']['prefix'] . 'data_intermediate_ad';
             $this->assertTrue(is_array($aComponents[$dia]));
             $this->assertEqual(count($aComponents[$dia]), 4);
             $aComponentClasses = array();
             foreach ($aComponents[$dia] as $oComponent) {
                 $aComponentClasses[] = get_class($oComponent);
             }
             $this->assertTrue(in_array('Plugins_DeliveryLog_OxLogRequest_LogRequest', $aComponentClasses));
             $this->assertTrue(in_array('Plugins_DeliveryLog_OxLogImpression_LogImpression', $aComponentClasses));
             $this->assertTrue(in_array('Plugins_DeliveryLog_OxLogClick_LogClick', $aComponentClasses));
             $this->assertTrue(in_array('Plugins_DeliveryLog_OxLogImpression_logImpressionBackup', $aComponentClasses));
             $diac = $aConf['table']['prefix'] . 'data_intermediate_ad_connection';
             $this->assertTrue(is_array($aComponents[$diac]));
             $this->assertEqual(count($aComponents[$diac]), 1);
             $aComponentClasses = array();
             foreach ($aComponents[$diac] as $oComponent) {
                 $aComponentClasses[] = get_class($oComponent);
             }
             $this->assertTrue(in_array('Plugins_DeliveryLog_OxLogConversion_LogConversion', $aComponentClasses));
             $diavv = $aConf['table']['prefix'] . 'data_intermediate_ad_variable_value';
             $this->assertTrue(is_array($aComponents[$diavv]));
             $this->assertEqual(count($aComponents[$diavv]), 1);
             $aComponentClasses = array();
             foreach ($aComponents[$diavv] as $oComponent) {
                 $aComponentClasses[] = get_class($oComponent);
             }
             $this->assertTrue(in_array('Plugins_DeliveryLog_OxLogConversion_LogConversionVariable', $aComponentClasses));
             $sc = $aConf['table']['prefix'] . 'stats_country';
             $this->assertTrue(is_array($aComponents[$sc]));
             $this->assertEqual(count($aComponents[$sc]), 2);
             $aComponentClasses = array();
             foreach ($aComponents[$sc] as $oComponent) {
                 $aComponentClasses[] = get_class($oComponent);
             }
             $this->assertTrue(in_array('Plugins_DeliveryLog_OxLogCountry_LogImpressionCountry', $aComponentClasses));
             $this->assertTrue(in_array('Plugins_DeliveryLog_OxLogCountry_LogClickCountry', $aComponentClasses));
             // Uninstall the installed plugins
             TestEnv::uninstallPluginPackage('openXDeliveryLogCountry', false);
     */
     // Uninstall the installed plugins
     TestEnv::uninstallPluginPackage('openXDeliveryLog', false);
     // Reset the testing environment
     TestEnv::restoreEnv();
 }
 /**
  * Method to test the testSetMaintenanceStatisticsRunReport method.
  *
  * Requirements:
  * Test 1: Test two writes to reports.
  */
 function testSetMaintenanceStatisticsRunReport()
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     // Create a new OX_Maintenance_Statistics_Task_LogCompletion object
     $oLogCompletion = new OX_Maintenance_Statistics_Task_LogCompletion();
     // Test 1
     $report = 'Maintenance run has finished :: Maintenance will run again at XYZ.';
     $oLogCompletion->_setMaintenanceStatisticsRunReport($report);
     $query = "\n            SELECT\n                timestamp,\n                usertype,\n                userid,\n                action,\n                object,\n                details\n            FROM\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['userlog'], true) . "\n            WHERE\n                userlogid = 1";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $this->assertEqual($aRow['usertype'], phpAds_userMaintenance);
     $this->assertEqual($aRow['userid'], '0');
     $this->assertEqual($aRow['action'], phpAds_actionBatchStatistics);
     $this->assertEqual($aRow['object'], '0');
     $this->assertEqual($aRow['details'], $report);
     $report = '2nd Maintenance run has finished :: Maintenance will run again at XYZ.';
     $oLogCompletion->_setMaintenanceStatisticsRunReport($report);
     $query = "\n            SELECT\n                timestamp,\n                usertype,\n                userid,\n                action,\n                object,\n                details\n            FROM\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['userlog'], true) . "\n            WHERE\n                userlogid = 2";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $this->assertEqual($aRow['usertype'], phpAds_userMaintenance);
     $this->assertEqual($aRow['userid'], '0');
     $this->assertEqual($aRow['action'], phpAds_actionBatchStatistics);
     $this->assertEqual($aRow['object'], '0');
     $this->assertEqual($aRow['details'], $report);
     TestEnv::restoreEnv();
 }
 /**
  * Method to test the getCampaignDeliveryToDate method.
  *
  * Requirements:
  * Test 1: Test correct results are returned with no data.
  * Test 2: Test correct results are returned with single data entry.
  * Test 3: Test correct results are returned with multiple data entries.
  *
  * @TODO Incomplete test!
  */
 function testGetCampaignDeliveryToDate()
 {
     /**
      * @TODO Locate where clean up doesn't happen before this test, and fix!
      */
     TestEnv::restoreEnv();
     $conf = $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $oMaxDalMaintenance = new OA_Dal_Maintenance_Priority();
     $oNow = new Date();
     // Test 1
     $result = $oMaxDalMaintenance->getCampaignDeliveryToDate(1);
     $this->assertTrue(is_array($result));
     $this->assertEqual(count($result), 0);
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->activate_time = '2005-06-23 00:00:00';
     $doCampaigns->expire_time = '2005-06-25 23:59:59';
     $doCampaigns->priority = '1';
     $doCampaigns->active = 1;
     $doCampaigns->views = 100;
     $doCampaigns->clicks = 200;
     $doCampaigns->conversions = 300;
     $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
     $doCampaigns->updated = $oNow->format('%Y-%m-%d %H:%M:%S');
     $idCampaign = DataGenerator::generateOne($doCampaigns, true);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $idCampaign;
     $doBanners->active = 1;
     $doBanners->status = OA_ENTITY_STATUS_RUNNING;
     $doBanners->acls_updated = $oNow->format('%Y-%m-%d %H:%M:%S');
     $doBanners->updated = $oNow->format('%Y-%m-%d %H:%M:%S');
     $idBanner = DataGenerator::generateOne($doBanners);
     $doInterAd = OA_Dal::factoryDO('data_intermediate_ad');
     $doInterAd->operation_interval = 60;
     $doInterAd->operation_interval_id = 0;
     $doInterAd->ad_id = $idBanner;
     $doInterAd->day = '2005-06-24';
     $doInterAd->creative_id = 0;
     $doInterAd->zone_id = 1;
     $doInterAd->requests = 500;
     $doInterAd->impressions = 475;
     $doInterAd->clicks = 25;
     $doInterAd->conversions = 5;
     $doInterAd->updated = $oNow->format('%Y-%m-%d %H:%M:%S');
     $doInterAd->interval_start = '2005-06-24 10:00:00';
     $doInterAd->interval_end = '2005-06-24 10:59:59';
     $doInterAd->hour = 10;
     $idInterAd = DataGenerator::generateOne($doInterAd);
     $doInterAd->interval_start = '2005-06-24 11:00:00';
     $doInterAd->interval_end = '2005-06-24 11:59:59';
     $doInterAd->hour = 11;
     $idInterAd = DataGenerator::generateOne($doInterAd);
     $result = $oMaxDalMaintenance->getCampaignDeliveryToDate(1);
     $this->assertTrue(is_array($result));
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[0]['placement_id'], 1);
     $this->assertEqual($result[0]['sum_requests'], 1000);
     $this->assertEqual($result[0]['sum_views'], 950);
     $this->assertEqual($result[0]['sum_clicks'], 50);
     $this->assertEqual($result[0]['sum_conversions'], 10);
     // Test 3
     DataGenerator::cleanUp();
 }
 /**
  * A method to test the getCampaigns method.
  */
 function testGetCampaigns()
 {
     /**
      * @TODO Locate where clean up doesn't happen before this test, and fix!
      */
     TestEnv::restoreEnv();
     $da = new OA_Dal_Maintenance_Priority();
     $this->_generateStatsOne();
     // Test 1 getCampaigns method.
     $ret = $da->getCampaigns();
     $this->assertTrue(is_array($ret));
     $this->assertTrue(count($ret) == 5);
     $campaign = $ret[0];
     $this->assertIsA($campaign, 'OX_Maintenance_Priority_Campaign');
     $this->assertEqual($campaign->id, 1);
     $this->assertEqual($campaign->impressionTargetTotal, 0);
     $this->assertEqual($campaign->clickTargetTotal, 400);
     $this->assertEqual($campaign->conversionTargetTotal, 0);
     $this->assertEqual($campaign->impressionTargetDaily, 0);
     $this->assertEqual($campaign->clickTargetDaily, 0);
     $this->assertEqual($campaign->conversionTargetDaily, 0);
     $this->assertEqual($campaign->priority, 3);
     // Test 2 getCampaignData method.
     $campaign = $da->getCampaignData(1);
     $this->assertTrue(is_array($campaign));
     $this->assertTrue(count($campaign) == 5);
     $this->assertTrue(array_key_exists('advertiser_id', $campaign));
     $this->assertTrue(array_key_exists('placement_id', $campaign));
     $this->assertTrue(array_key_exists('name', $campaign));
     $this->assertTrue(array_key_exists('status', $campaign));
     $this->assertTrue(array_key_exists('num_children', $campaign));
     // Test 3 getCampaignStats method.
     $ret = $da->getCampaignStats(1);
     $this->assertTrue(is_array($ret));
     $this->assertTrue(count($ret) == 9);
     $this->assertTrue(array_key_exists('advertiser_id', $ret));
     $this->assertTrue(array_key_exists('placement_id', $ret));
     $this->assertTrue(array_key_exists('name', $ret));
     $this->assertTrue(array_key_exists('status', $ret));
     $this->assertTrue(array_key_exists('num_children', $ret));
     $this->assertTrue(array_key_exists('sum_requests', $ret));
     $this->assertTrue(array_key_exists('sum_views', $ret));
     $this->assertTrue(array_key_exists('sum_clicks', $ret));
     $this->assertTrue(array_key_exists('sum_conversions', $ret));
     // Test 4 getTimezoneForCampaign method
     $oTz = $da->getTimezoneForCampaign(1);
     $this->assertIsA($oTz, 'Date_TimeZone');
     $this->assertEqual($oTz->getID(), 'UTC');
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'timezone';
     $doPreferences->account_type = OA_ACCOUNT_MANAGER;
     $preferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = 3;
     $doAccount_Preference_Assoc->preference_id = $preferenceId;
     $doAccount_Preference_Assoc->value = 'Europe/Rome';
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     $oTz = $da->getTimezoneForCampaign(5);
     $this->assertIsA($oTz, 'Date_TimeZone');
     $this->assertEqual($oTz->getID(), 'Europe/Rome');
     // Test cache
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = 3;
     $doAccount_Preference_Assoc->preference_id = $preferenceId;
     $doAccount_Preference_Assoc->value = 'Europe/Berlin';
     $doAccount_Preference_Assoc->update();
     $oTz = $da->getTimezoneForCampaign(5);
     $this->assertIsA($oTz, 'Date_TimeZone');
     $this->assertEqual($oTz->getID(), 'Europe/Rome');
     DataGenerator::cleanUp();
 }
 /**
  * Method to test the getPreviousAdDeliveryInfo method.
  *
  * Requirements:
  * Test 1:   Test with no Date registered in the service locator, ensure false returned.
  * Test 2:   Test with a Date registered in the service locator, no data in the database,
  *           and ensure no data is returned.
  *
  * Test 3:   Test with ONLY impression data, but NOT in the previous OI, and ensure no
  *           data is returned.
  * Test 4:   Test with ONLY impression data, in the previous OI, and ensure that ONLY
  *           data relating to the impressions is returned.
  * Test 5:   Test with ONLY impression data, in the 2nd previous OI, and ensure that
  *           no data is returned.
  * Test 5a:  Re-test with ONLY impression data, in the 2nd previous OI, but pass in the
  *           ad/zone pair, and ensure that no data is returned.
  *
  * Test 6:   Test with ONLY prioritisation data, but NOT in the previous OI, and
  *           ensure no data is returned.
  * Test 7:   Test with ONLY prioritisation data, in the previous OI, and ensure that
  *           ONLY data relating to the prioritisation is returned.
  * Test 8:   Test with ONLY prioritisation data, in the 2nd previous OI, and ensure no
  *           data is returned.
  * Test 8a:  Re-test with ONLY prioritisation data, in the 2nd previous OI, but pass in
  *           the ad/zone pair, and ensure that ONLY data relating to the prioritisation
  *           is returned.
  *
  * Test 9:   Test with BOTH impressions data NOT in the previous OI, and prioritisation
  *           data NOT in the previous OI, and ensure no data is returned.
  * Test 10:  Test with BOTH impressions data NOT in the previous OI, and prioritisation
  *           data in the previous OI, and ensure ONLY data relating to the prioritisation
  *           is returned.
  * Test 11:  Test with BOTH impressions data NOT in the previous OI, and prioritisation
  *           data in the 2nd previous OI, and ensure no data is returned.
  * Test 11a: Re-test with BOTH impressions data NOT in the previous OI, and prioritisation
  *           data in the 2nd previous OI, but pass in the ad/zone pair, and ensure that
  *           ONLY data relating to the prioritisation is returned.
  *
  * Test 12:  Test with BOTH impressions data in the 2nd previous OI, and prioritisation
  *           data NOT in the previous OI, and ensure no data is returned.
  * Test 13:  Test with BOTH impressions data in the 2nd previous OI, and prioritisation
  *           data in the previous OI, and ensure ONLY data relating to the prioritisation
  *           is returned.
  * Test 14:  Test with BOTH impressions data in the 2nd previous OI, and prioritisation
  *           data in the 2nd previous OI, and ensure no data is returned.
  * Test 14a: Re-test with BOTH impressions data in the 2nd previous OI, and prioritisation
  *           data in the 2nd previous OI, but pass in the ad/zone pair, and ensure that
  *           all data is returned.
  *
  * Test 15:  Test with BOTH impressions data in the previous OI, and prioritisation
  *           data NOT in the previous OI, and ensure that ONLY data relating to the
  *           impressions is returned.
  * Test 16:  Test with BOTH impressions data in the previous OI, and prioritisation
  *           data in the previous OI, and ensure that all data is returned.
  * Test 17:  Test with BOTH impressions data in the previous OI, and prioritisation
  *           data in the 2nd previous OI, and ensure that all data is returned.
  * Test 17a: Re-test with BOTH impressions data in the previous OI, and prioritisation
  *           data in the 2nd previous OI, but pass in the ad/zone pair, and ensure that
  *           all data is returned.
  *
  * Test 18:  Perform a more realistic test, with data for the ads/zones in various
  *           past OIs, and including some ads with multiple prioritisation data
  *           per OI, as well as ads with no prioritisation data in some OIs, and
  *           ensure that the correct values are returned for each one. Test that:
  *           - Only ad/zones that delivered in the previous operation interval,
  *             or were requested to deliver in the previous operation interval,
  *             but didn't (i.e. not in other intervals) are returned in the
  *             results.
  *           - That prioritisation information where just ONE set of data exists
  *             is returned correctly.
  *           - That prioritisation information where multiple sets of INDENTICAL
  *             data exists is returned correctly.
  *           - That prioritisation information where multiple sets of DIFFERENT
  *             data exists is returned correctly.
  *           - That prioritisation information from older sets of data is
  *             returned correctly.
  * Test 18a: Re-test, but also include ad/zone pairs that are in/not in the above
  *           set of data, and ensure that these ad/zone pairs are also included
  *           in the results.
  */
 function testGetPreviousAdDeliveryInfo()
 {
     $conf = $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $oMaxDalMaintenance = new OA_Dal_Maintenance_Priority();
     $aEmptyZoneAdArray = array();
     $aAdParams = array('ad_id' => 1, 'active' => 't', 'type' => 'sql', 'weight' => 1);
     $oAd = new OA_Maintenance_Priority_Ad($aAdParams);
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->addAdvert($oAd);
     $aZoneAdArray = array($oZone->id => $oZone);
     // Test 1
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->remove('now');
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertFalse($result);
     // Test 2
     $oDate = new Date();
     $oServiceLocator->register('now', $oDate);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     // Test 3
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $oNow = new Date();
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 4
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertNull($result[1][1]['required_impressions']);
     $this->assertNull($result[1][1]['requested_impressions']);
     $this->assertNull($result[1][1]['priority_factor']);
     $this->assertNull($result[1][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result[1][1]['impressions'], 1);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 5, 5a
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray);
     $this->assertEqual(count($result), 0);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 6
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0.1, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 7
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertNull($result[1][1]['impressions']);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 8, 8a
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertNull($result[1][1]['impressions']);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 9
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 10
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertNull($result[1][1]['impressions']);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 11, 11a
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertNull($result[1][1]['impressions']);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 12
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 13
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertNull($result[1][1]['impressions']);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 14, 14a
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertEqual($result[1][1]['impressions'], 1);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 15
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertNull($result[1][1]['required_impressions']);
     $this->assertNull($result[1][1]['requested_impressions']);
     $this->assertNull($result[1][1]['priority_factor']);
     $this->assertNull($result[1][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result[1][1]['impressions'], 1);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 16
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertEqual($result[1][1]['impressions'], 1);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 17, 17a
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertEqual($result[1][1]['impressions'], 1);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertEqual($result[1][1]['impressions'], 1);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 18
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 2, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $bannerId2 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 3, 2, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 4, 2, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $bannerId3 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId3, 0, 5, 5, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 100, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 2, 100, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 3, 200, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 4, 200, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId3, 0, 5, 500, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), 4, 0, 5, 500, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $oSpecialDate = new Date($aDates['end']);
     $oSpecialDate->addSeconds(1);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 2, 10, 10, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), 9, 9, 59, 59, 0, 95, 0.995, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 3, 30, 30, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), 0, $aDates['end']->format('%Y-%m-%d %H:30:00'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 3, 30, 30, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $aDates['end']->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 4, 10, 10, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), 0, $aDates['end']->format('%Y-%m-%d %H:30:00'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 4, 20, 20, 0, 0.8, 0.5, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $oSpecialDate = new Date($aDates['end']);
     $oSpecialDate->addSeconds(1);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId3, 5, 200, 200, 0, 0.2, 0.95, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), 0, $aDates['end']->format('%Y-%m-%d %H:30:00'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId3, 5, 100, 100, 0, 0.4, 0.95, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 4);
     $this->assertEqual(count($result[1]), 2);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertNull($result[1][1]['required_impressions']);
     $this->assertNull($result[1][1]['requested_impressions']);
     $this->assertNull($result[1][1]['priority_factor']);
     $this->assertNull($result[1][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result[1][1]['impressions'], 1);
     $this->assertEqual($result[1][2]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][2]['zone_id'], 2);
     $this->assertEqual($result[1][2]['required_impressions'], 10);
     $this->assertEqual($result[1][2]['requested_impressions'], 10);
     $this->assertEqual($result[1][2]['priority_factor'], 0.5);
     $this->assertEqual($result[1][2]['past_zone_traffic_fraction'], 0.99);
     $this->assertEqual($result[1][2]['impressions'], 1);
     $this->assertEqual(count($result[2]), 2);
     $this->assertEqual($result[2][3]['ad_id'], $bannerId2);
     $this->assertEqual($result[2][3]['zone_id'], 3);
     $this->assertEqual($result[2][3]['required_impressions'], 30);
     $this->assertEqual($result[2][3]['requested_impressions'], 30);
     $this->assertEqual($result[2][3]['priority_factor'], 0.4);
     $this->assertEqual($result[2][3]['past_zone_traffic_fraction'], 0.5);
     $this->assertEqual($result[2][3]['impressions'], 2);
     $this->assertEqual($result[2][4]['ad_id'], $bannerId2);
     $this->assertEqual($result[2][4]['zone_id'], 4);
     $this->assertEqual($result[2][4]['required_impressions'], 15);
     $this->assertEqual($result[2][4]['requested_impressions'], 15);
     $this->assertEqual($result[2][4]['priority_factor'], 0.6);
     $this->assertEqual($result[2][4]['past_zone_traffic_fraction'], 0.5);
     $this->assertEqual($result[2][4]['impressions'], 2);
     $this->assertEqual(count($result[3]), 1);
     $this->assertEqual($result[3][5]['ad_id'], $bannerId3);
     $this->assertEqual($result[3][5]['zone_id'], 5);
     $this->assertEqual($result[3][5]['required_impressions'], 150);
     $this->assertEqual($result[3][5]['requested_impressions'], 150);
     $this->assertEqual($result[3][5]['priority_factor'], 0.3);
     $this->assertEqual($result[3][5]['past_zone_traffic_fraction'], 0.95);
     $this->assertEqual($result[3][5]['impressions'], 5);
     $this->assertEqual(count($result[9]), 1);
     $this->assertEqual($result[9][9]['ad_id'], 9);
     $this->assertEqual($result[9][9]['zone_id'], 9);
     $this->assertEqual($result[9][9]['required_impressions'], 59);
     $this->assertEqual($result[9][9]['requested_impressions'], 59);
     $this->assertEqual($result[9][9]['priority_factor'], 95);
     $this->assertEqual($result[9][9]['past_zone_traffic_fraction'], 0.995);
     $this->assertNull($result[9][9]['impressions']);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 18a
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 4));
     $aAdParams = array('ad_id' => 10, 'active' => 't', 'type' => 'sql', 'weight' => 1);
     $oAd = new OA_Maintenance_Priority_Ad($aAdParams);
     $oZone->addAdvert($oAd);
     $aAdParams = array('ad_id' => 11, 'active' => 't', 'type' => 'sql', 'weight' => 1);
     $oAd = new OA_Maintenance_Priority_Ad($aAdParams);
     $oZone->addAdvert($oAd);
     $aZoneAdArray = array($oZone->id => $oZone);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 2, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $bannerId2 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 3, 2, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 4, 2, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $bannerId3 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId3, 0, 5, 5, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 100, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 2, 100, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 3, 200, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 4, 200, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId3, 0, 5, 500, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), 4, 0, 5, 500, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), 10, 0, 4, 1000, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     for ($i = 0; $i <= MINUTES_PER_WEEK / $conf['maintenance']['operationInterval']; $i++) {
         $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     }
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     for ($i = 0; $i <= MINUTES_PER_WEEK / $conf['maintenance']['operationInterval']; $i++) {
         $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     }
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), 11, 0, 4, 2000, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $oSpecialDate = new Date($aDates['end']);
     $oSpecialDate->addSeconds(1);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 2, 10, 10, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), 9, 9, 59, 59, 0, 95, 0.995, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 3, 30, 30, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 3, 30, 30, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $aDates['end']->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 4, 10, 10, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), 0, $aDates['end']->format('%Y-%m-%d %H:30:00'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 4, 20, 20, 0, 0.8, 0.5, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $oSpecialDate = new Date($aDates['end']);
     $oSpecialDate->addSeconds(1);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId3, 5, 200, 200, 0, 0.2, 0.95, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), 0, $aDates['end']->format('%Y-%m-%d %H:30:00'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId3, 5, 100, 100, 0, 0.4, 0.95, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), 10, 4, 1000, 1000, 0, 1, 0.9, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     for ($i = 0; $i <= MINUTES_PER_WEEK / $conf['maintenance']['operationInterval']; $i++) {
         $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     }
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     for ($i = 0; $i <= MINUTES_PER_WEEK / $conf['maintenance']['operationInterval']; $i++) {
         $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     }
     $oSpecialDate = new Date($aDates['end']);
     $oSpecialDate->addSeconds(1);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), 11, 4, 2000, 2000, 0, 1, 0.9, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray);
     $this->assertEqual(count($result), 5);
     $this->assertEqual(count($result[1]), 2);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertNull($result[1][1]['required_impressions']);
     $this->assertNull($result[1][1]['requested_impressions']);
     $this->assertNull($result[1][1]['priority_factor']);
     $this->assertNull($result[1][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result[1][1]['impressions'], 1);
     $this->assertEqual($result[1][2]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][2]['zone_id'], 2);
     $this->assertEqual($result[1][2]['required_impressions'], 10);
     $this->assertEqual($result[1][2]['requested_impressions'], 10);
     $this->assertEqual($result[1][2]['priority_factor'], 0.5);
     $this->assertEqual($result[1][2]['past_zone_traffic_fraction'], 0.99);
     $this->assertEqual($result[1][2]['impressions'], 1);
     $this->assertEqual(count($result[2]), 2);
     $this->assertEqual($result[2][3]['ad_id'], $bannerId2);
     $this->assertEqual($result[2][3]['zone_id'], 3);
     $this->assertEqual($result[2][3]['required_impressions'], 30);
     $this->assertEqual($result[2][3]['requested_impressions'], 30);
     $this->assertEqual($result[2][3]['priority_factor'], 0.4);
     $this->assertEqual($result[2][3]['past_zone_traffic_fraction'], 0.5);
     $this->assertEqual($result[2][3]['impressions'], 2);
     $this->assertEqual($result[2][4]['ad_id'], $bannerId2);
     $this->assertEqual($result[2][4]['zone_id'], 4);
     $this->assertEqual($result[2][4]['required_impressions'], 15);
     $this->assertEqual($result[2][4]['requested_impressions'], 15);
     $this->assertEqual($result[2][4]['priority_factor'], 0.6);
     $this->assertEqual($result[2][4]['past_zone_traffic_fraction'], 0.5);
     $this->assertEqual($result[2][4]['impressions'], 2);
     $this->assertEqual(count($result[3]), 1);
     $this->assertEqual($result[3][5]['ad_id'], $bannerId3);
     $this->assertEqual($result[3][5]['zone_id'], 5);
     $this->assertEqual($result[3][5]['required_impressions'], 150);
     $this->assertEqual($result[3][5]['requested_impressions'], 150);
     $this->assertEqual($result[3][5]['priority_factor'], 0.3);
     $this->assertEqual($result[3][5]['past_zone_traffic_fraction'], 0.95);
     $this->assertEqual($result[3][5]['impressions'], 5);
     $this->assertEqual(count($result[9]), 1);
     $this->assertEqual($result[9][9]['ad_id'], 9);
     $this->assertEqual($result[9][9]['zone_id'], 9);
     $this->assertEqual($result[9][9]['required_impressions'], 59);
     $this->assertEqual($result[9][9]['requested_impressions'], 59);
     $this->assertEqual($result[9][9]['priority_factor'], 95);
     $this->assertEqual($result[9][9]['past_zone_traffic_fraction'], 0.995);
     $this->assertNull($result[9][9]['impressions']);
     $this->assertEqual(count($result[10]), 1);
     $this->assertEqual($result[10][4]['ad_id'], 10);
     $this->assertEqual($result[10][4]['zone_id'], 4);
     $this->assertEqual($result[10][4]['required_impressions'], 1000);
     $this->assertEqual($result[10][4]['requested_impressions'], 1000);
     $this->assertEqual($result[10][4]['priority_factor'], 1);
     $this->assertEqual($result[10][4]['past_zone_traffic_fraction'], 0.9);
     $this->assertEqual($result[10][4]['impressions'], 1000);
     TestEnv::restoreEnv();
 }
 /**
  * Method to test the updatePriorities method.
  *
  * Test 1: Test with no Date registered in the service locator, ensure false returned.
  * Test 2: Test with no data in the database, ensure data is correctly stored.
  * Test 3: Test with previous test data in the database, ensure data is correctly stored.
  * Test 4: Test with an obscene number of items, and ensure that the packet size is
  *         not exceeded (no asserts, test suite will simply fail if unable to work).
  */
 function testUpdatePriorities()
 {
     /**
      * @TODO Locate where clean up doesn't happen before this test, and fix!
      */
     TestEnv::restoreEnv();
     $conf = $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $oMaxDalMaintenance = new OA_Dal_Maintenance_Priority();
     // Insert the data into the ad_zone_assoc table, as an ad is linked to a zone
     $this->_generateTestData();
     // Test 1
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->remove('now');
     $aData = array(array('ads' => array(array('ad_id' => $this->aIds['ad'], 'zone_id' => $this->aIds['zone'], 'required_impressions' => '1000', 'requested_impressions' => '1000', 'priority' => '0.45', 'priority_factor' => null, 'priority_factor_limited' => false, 'past_zone_traffic_fraction' => null))));
     $result = $oMaxDalMaintenance->updatePriorities($aData);
     $this->assertFalse($result);
     // Test 2
     $oDate = new Date();
     $oServiceLocator->register('now', $oDate);
     $result = $oMaxDalMaintenance->updatePriorities($aData);
     $this->assertTrue($result);
     $query = "\n            SELECT\n                ad_id,\n                zone_id,\n                priority\n            FROM\n                " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['ad_zone_assoc'], true) . "\n            WHERE\n                ad_id = {$this->aIds['ad']} AND zone_id = {$this->aIds['zone']}";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $this->assertEqual($aRow['ad_id'], $this->aIds['ad']);
     $this->assertEqual($aRow['zone_id'], $this->aIds['zone']);
     $this->assertEqual($aRow['priority'], 0.45);
     $query = "\n            SELECT\n                operation_interval,\n                operation_interval_id,\n                interval_start,\n                interval_end,\n                ad_id,\n                zone_id,\n                required_impressions,\n                requested_impressions,\n                priority,\n                priority_factor,\n                priority_factor_limited,\n                past_zone_traffic_fraction,\n                created,\n                created_by,\n                expired,\n                expired_by\n            FROM\n                " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['data_summary_ad_zone_assoc'], true) . "\n            WHERE\n                ad_id = {$this->aIds['ad']}";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $currentOperationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $this->assertEqual($aRow['operation_interval'], $conf['maintenance']['operationInterval']);
     $this->assertEqual($aRow['operation_interval_id'], $currentOperationIntervalID);
     $this->assertEqual($aRow['interval_start'], $aDates['start']->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['interval_end'], $aDates['end']->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['ad_id'], $this->aIds['ad']);
     $this->assertEqual($aRow['zone_id'], $this->aIds['zone']);
     $this->assertEqual($aRow['required_impressions'], 1000);
     $this->assertEqual($aRow['requested_impressions'], 1000);
     $this->assertEqual($aRow['priority'], 0.45);
     $this->assertNull($aRow['priority_factor']);
     $this->assertFalse($aRow['priority_factor_limited']);
     $this->assertNull($aRow['past_zone_traffic_fraction']);
     $this->assertEqual($aRow['created'], $oDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['created_by'], 0);
     $this->assertNull($aRow['expired']);
     $this->assertNull($aRow['expired_by']);
     // Test 3
     $aData = array(array('ads' => array(array('ad_id' => $this->aIds['ad'], 'zone_id' => $this->aIds['zone'], 'required_impressions' => 2000, 'requested_impressions' => 2000, 'priority' => 0.9, 'priority_factor' => 0.1, 'priority_factor_limited' => false, 'past_zone_traffic_fraction' => 0.99), array('ad_id' => $this->aIds['ad'] + 1, 'zone_id' => $this->aIds['ad'] + 1, 'required_impressions' => 500, 'requested_impressions' => 500, 'priority' => 0.1, 'priority_factor' => 0.2, 'priority_factor_limited' => true, 'past_zone_traffic_fraction' => 0.45))));
     $oOldDate = new Date();
     $oOldDate->copy($oDate);
     $oDate = new Date();
     $oServiceLocator->register('now', $oDate);
     $result = $oMaxDalMaintenance->updatePriorities($aData);
     $this->assertTrue($result);
     $query = "\n            SELECT\n                ad_id,\n                zone_id,\n                priority\n            FROM\n                " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['ad_zone_assoc'], true) . "\n            WHERE\n                ad_id = {$this->aIds['ad']} AND zone_id = {$this->aIds['zone']}";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $this->assertEqual($aRow['ad_id'], $this->aIds['ad']);
     $this->assertEqual($aRow['zone_id'], $this->aIds['zone']);
     $this->assertEqual($aRow['priority'], 0.9);
     $query = "\n            SELECT\n                operation_interval,\n                operation_interval_id,\n                interval_start,\n                interval_end,\n                ad_id,\n                zone_id,\n                required_impressions,\n                requested_impressions,\n                priority,\n                priority_factor,\n                priority_factor_limited,\n                past_zone_traffic_fraction,\n                created,\n                created_by,\n                expired,\n                expired_by\n            FROM\n                " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['data_summary_ad_zone_assoc'], true) . "\n            WHERE\n                ad_id = {$this->aIds['ad']}\n                AND expired IS NOT NULL";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $currentOperationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oOldDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oOldDate);
     $this->assertEqual($aRow['operation_interval'], $conf['maintenance']['operationInterval']);
     $this->assertEqual($aRow['operation_interval_id'], $currentOperationIntervalID);
     $this->assertEqual($aRow['interval_start'], $aDates['start']->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['interval_end'], $aDates['end']->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['ad_id'], $this->aIds['ad']);
     $this->assertEqual($aRow['zone_id'], $this->aIds['ad']);
     $this->assertEqual($aRow['required_impressions'], 1000);
     $this->assertEqual($aRow['requested_impressions'], 1000);
     $this->assertEqual($aRow['priority'], 0.45);
     $this->assertNull($aRow['priority_factor']);
     $this->assertFalse($aRow['priority_factor_limited']);
     $this->assertNull($aRow['past_zone_traffic_fraction']);
     $this->assertEqual($aRow['created'], $oOldDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['created_by'], 0);
     $this->assertEqual($aRow['expired'], $oDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['expired_by'], 0);
     $query = "\n            SELECT\n                operation_interval,\n                operation_interval_id,\n                interval_start,\n                interval_end,\n                ad_id,\n                zone_id,\n                required_impressions,\n                requested_impressions,\n                priority,\n                priority_factor,\n                priority_factor_limited,\n                past_zone_traffic_fraction,\n                created,\n                created_by,\n                expired,\n                expired_by\n            FROM\n                " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['data_summary_ad_zone_assoc'], true) . "\n            WHERE\n                ad_id = {$this->aIds['ad']}\n                AND expired IS NULL";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $currentOperationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $this->assertEqual($aRow['operation_interval'], $conf['maintenance']['operationInterval']);
     $this->assertEqual($aRow['operation_interval_id'], $currentOperationIntervalID);
     $this->assertEqual($aRow['interval_start'], $aDates['start']->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['interval_end'], $aDates['end']->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['ad_id'], $this->aIds['ad']);
     $this->assertEqual($aRow['zone_id'], $this->aIds['ad']);
     $this->assertEqual($aRow['required_impressions'], 2000);
     $this->assertEqual($aRow['requested_impressions'], 2000);
     $this->assertEqual($aRow['priority'], 0.9);
     $this->assertEqual($aRow['priority_factor'], 0.1);
     $this->assertFalse($aRow['priority_factor_limited']);
     $this->assertEqual($aRow['past_zone_traffic_fraction'], 0.99);
     $this->assertEqual($aRow['created'], $oDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['created_by'], 0);
     $this->assertNull($aRow['expired']);
     $this->assertNull($aRow['expired_by']);
     $query = "\n            SELECT\n                operation_interval,\n                operation_interval_id,\n                interval_start,\n                interval_end,\n                ad_id,\n                zone_id,\n                required_impressions,\n                requested_impressions,\n                priority,\n                priority_factor,\n                priority_factor_limited,\n                past_zone_traffic_fraction,\n                created,\n                created_by,\n                expired,\n                expired_by\n            FROM\n                " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['data_summary_ad_zone_assoc'], true) . "\n            WHERE\n                ad_id = " . ($this->aIds['ad'] + 1);
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $currentOperationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $this->assertEqual($aRow['operation_interval'], $conf['maintenance']['operationInterval']);
     $this->assertEqual($aRow['operation_interval_id'], $currentOperationIntervalID);
     $this->assertEqual($aRow['interval_start'], $aDates['start']->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['interval_end'], $aDates['end']->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['ad_id'], $this->aIds['ad'] + 1);
     $this->assertEqual($aRow['zone_id'], $this->aIds['ad'] + 1);
     $this->assertEqual($aRow['required_impressions'], 500);
     $this->assertEqual($aRow['requested_impressions'], 500);
     $this->assertEqual($aRow['priority'], 0.1);
     $this->assertEqual($aRow['priority_factor'], 0.2);
     $this->assertTrue($aRow['priority_factor_limited']);
     $this->assertEqual($aRow['past_zone_traffic_fraction'], 0.45);
     $this->assertEqual($aRow['created'], $oDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['created_by'], 0);
     $this->assertNull($aRow['expired']);
     $this->assertNull($aRow['expired_by']);
     // Test 4
     $aData = array();
     for ($i = 1; $i < 5000; $i++) {
         $aData[$i] = array('ads' => array(array('ad_id' => $i, 'zone_id' => $i, 'required_impressions' => 2000, 'requested_impressions' => 2000, 'priority' => 0.9, 'priority_factor' => 0.1, 'priority_factor_limited' => false, 'past_zone_traffic_fraction' => 0.99)));
     }
     $oOldDate = new Date();
     $oOldDate->copy($oDate);
     $oDate = new Date();
     $oServiceLocator->register('now', $oDate);
     $result = $oMaxDalMaintenance->updatePriorities($aData);
     TestEnv::restoreEnv('dropTmpTables');
 }
 /**
  * Tests the _getEarliestLoggedDeliveryData() method.
  */
 function test_getEarliestLoggedDeliveryData()
 {
     // Create a reference to the OpenX configuration, and set it to
     // 15 minutes
     $aConf =& $GLOBALS['_MAX']['CONF'];
     $aConf['maintenance']['operationInterval'] = 15;
     // Prepare the OX_Maintenance_Statistics_Task_SetUpdateRequirements class to test with
     $oSetUpdateRequirements = new OX_Maintenance_Statistics_Task_SetUpdateRequirements();
     // Test 1: There are no deliveryLog group plugins installed, test that null is returned
     $oDate = $oSetUpdateRequirements->_getEarliestLoggedDeliveryData(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI);
     $this->assertNull($oDate);
     // Create the "application_variable" table required for installing the plugin
     $oTables =& OA_DB_Table_Core::singleton();
     $oTables->createTable('application_variable');
     // Setup the default OpenX delivery logging plugin for the test
     TestEnv::installPluginPackage('openXDeliveryLog', false);
     // Test 2: There is no delivery data logged, test that null is returned
     $oDate = $oSetUpdateRequirements->_getEarliestLoggedDeliveryData(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI);
     $this->assertNull($oDate);
     // Ask the appropriate default OpenX delivery logging plugin component
     // to log a click
     require_once MAX_PATH . $aConf['pluginPaths']['plugins'] . '/deliveryLog/oxLogClick/logClick.delivery.php';
     $GLOBALS['_MAX']['deliveryData'] = array('interval_start' => '2008-08-12 14:15:00', 'creative_id' => 1, 'zone_id' => 1);
     Plugin_deliveryLog_oxLogClick_logClick_Delivery_logClick();
     // Test 3: Test with just the one click logged, and ensure that the correct
     //         date/time is returned
     $oDate = $oSetUpdateRequirements->_getEarliestLoggedDeliveryData(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI);
     $this->assertEqual($oDate, new Date('2008-08-12 14:14:59'));
     // Ask the appropriate default OpenX delivery logging plugin component
     // to log a later click
     $GLOBALS['_MAX']['deliveryData'] = array('interval_start' => '2008-08-12 14:30:00', 'creative_id' => 1, 'zone_id' => 1);
     Plugin_deliveryLog_oxLogClick_logClick_Delivery_logClick();
     // Test 4: Test with just the two clicks logged, and ensure that the correct
     //         date/time is returned (i.e. unchanged from the last test)
     $oDate = $oSetUpdateRequirements->_getEarliestLoggedDeliveryData(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI);
     $this->assertEqual($oDate, new Date('2008-08-12 14:14:59'));
     // Ask the appropriate default OpenX delivery logging plugin component
     // to log an earlier click
     $GLOBALS['_MAX']['deliveryData'] = array('interval_start' => '2008-08-12 14:00:00', 'creative_id' => 1, 'zone_id' => 1);
     Plugin_deliveryLog_oxLogClick_logClick_Delivery_logClick();
     // Test 5: Test with just the three clicks logged, and ensure that the correct
     //         date/time is returned (i.e. earlier than the last tests)
     $oDate = $oSetUpdateRequirements->_getEarliestLoggedDeliveryData(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI);
     $this->assertEqual($oDate, new Date('2008-08-12 13:59:59'));
     // Ask the appropriate default OpenX delivery logging plugin component
     // to log an earlier impression
     require_once MAX_PATH . $aConf['pluginPaths']['plugins'] . '/deliveryLog/oxLogImpression/logImpression.delivery.php';
     $GLOBALS['_MAX']['deliveryData'] = array('interval_start' => '2008-08-12 13:45:00', 'creative_id' => 1, 'zone_id' => 1);
     Plugin_deliveryLog_oxLogImpression_logImpression_Delivery_logImpression();
     // Test 6: Test with just the three clicks and one impression logged, and
     //         ensure that the correct date/time is returned (i.e. based on
     //         the earliest data, which is the impression).
     $oDate = $oSetUpdateRequirements->_getEarliestLoggedDeliveryData(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI);
     $this->assertEqual($oDate, new Date('2008-08-12 13:44:59'));
     // Test 7: Re-test, but calling for the date/time returned to be based
     //         on the hour boundary, not the operation interval boundary
     $oDate = $oSetUpdateRequirements->_getEarliestLoggedDeliveryData(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR);
     $this->assertEqual($oDate, new Date('2008-08-12 12:59:59'));
     // Uninstall the installed plugin
     TestEnv::uninstallPluginPackage('openXDeliveryLog', false);
     // Reset the testing environment
     TestEnv::restoreEnv();
 }
 /**
  * Method to test the getAllDeliveryLimitationChangedCreatives method.
  *
  * Requirements:
  * Test 0: Test with bad input data, and ensure the method survives.
  * Test 1: Test with no data, and ensure no data are returned.
  * Test 2: Test with an active ad that has not had any delivery limitation changes,
  *         and ensure that no data are returned: DEPRECATED TEST, PostgreSQL DOES
  *         NOT PERMIT THE acls_update FIELD TO HAVE A NULL ENTRY.
  * Test 3: Test with an active ad that has had a delivery limitation change in the
  *         last OI, before the last Priority Compensation run, and ensure that no
  *         data are returned.
  * Test 4: Test with an active ad that has had a delivery limitation change in the
  *         last OI, after the last Priority Compensation run, and ensure that the
  *         correct data are returned.
  * Test 5: Test with an active ad that has had a delivery limitation change in the
  *         current OI, and ensure that the correct data are returned.
  * Test 6: Repeat test 3, but with an inactive ad.
  * Test 7: Repeat test 4, but with an inactive ad.
  * Test 8: Repeat test 5, but with an inactive ad.
  * Test 9: Test with a mixture of ads, and ensure the correct data are returned.
  */
 function testGetAllDeliveryLimitationChangedCreatives()
 {
     TestEnv::restoreEnv('dropTmpTables');
     $conf = $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $oMaxDalMaintenance = new OA_Dal_Maintenance_Priority();
     $oDateNow = new Date('2006-10-04 12:07:01');
     $oDateLastPC = new Date('2006-10-04 11:14:53');
     $aLastRun = array('start_run' => $oDateLastPC, 'now' => $oDateNow);
     // Test 0
     $aResult =& $oMaxDalMaintenance->getAllDeliveryLimitationChangedCreatives(array());
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 0);
     // Test 1
     $aResult =& $oMaxDalMaintenance->getAllDeliveryLimitationChangedCreatives($aLastRun);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 0);
     // Test 3
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doCampaigns->priority = 1;
     $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
     $idCampaign = DataGenerator::generateOne($doCampaigns, true);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $idCampaign;
     $doBanners->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doBanners->status = OA_ENTITY_STATUS_RUNNING;
     $doBanners->acls_updated = '2006-10-04 11:10:00';
     $idBanner = DataGenerator::generateOne($doBanners);
     $aResult =& $oMaxDalMaintenance->getAllDeliveryLimitationChangedCreatives($aLastRun);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 0);
     DataGenerator::cleanUp();
     // Test 4
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doCampaigns->priority = 1;
     $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
     $idCampaign = DataGenerator::generateOne($doCampaigns, true);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $idCampaign;
     $doBanners->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doBanners->status = OA_ENTITY_STATUS_RUNNING;
     $doBanners->acls_updated = '2006-10-04 11:15:00';
     $idBanner = DataGenerator::generateOne($doBanners);
     $aResult =& $oMaxDalMaintenance->getAllDeliveryLimitationChangedCreatives($aLastRun);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 1);
     $this->assertEqual($aResult[$idBanner], '2006-10-04 11:15:00');
     DataGenerator::cleanUp();
     // Test 5
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doCampaigns->priority = 1;
     $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
     $idCampaign = DataGenerator::generateOne($doCampaigns, true);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $idCampaign;
     $doBanners->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doBanners->status = OA_ENTITY_STATUS_RUNNING;
     $doBanners->acls_updated = '2006-10-04 12:15:00';
     $idBanner = DataGenerator::generateOne($doBanners);
     $aResult =& $oMaxDalMaintenance->getAllDeliveryLimitationChangedCreatives($aLastRun);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 1);
     $this->assertEqual($aResult[$idBanner], '2006-10-04 12:15:00');
     DataGenerator::cleanUp();
     // Test 6
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doCampaigns->priority = 1;
     $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
     $idCampaign = DataGenerator::generateOne($doCampaigns, true);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $idCampaign;
     $doBanners->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doBanners->status = OA_ENTITY_STATUS_RUNNING;
     $doBanners->acls_updated = '2006-10-04 11:10:00';
     $idBanner = DataGenerator::generateOne($doBanners);
     $aResult =& $oMaxDalMaintenance->getAllDeliveryLimitationChangedCreatives($aLastRun);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 0);
     DataGenerator::cleanUp();
     // Test 7
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doCampaigns->priority = 1;
     $doCampaigns->activate_time = '2020-01-01 00:00:00';
     $doCampaigns->status = OA_ENTITY_STATUS_AWAITING;
     $idCampaign = DataGenerator::generateOne($doCampaigns, true);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $idCampaign;
     $doBanners->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doBanners->status = OA_ENTITY_STATUS_RUNNING;
     $doBanners->acls_updated = '2006-10-04 11:15:00';
     $idBanner = DataGenerator::generateOne($doBanners);
     $aResult =& $oMaxDalMaintenance->getAllDeliveryLimitationChangedCreatives($aLastRun);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 0);
     DataGenerator::cleanUp();
     // Test 8
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doCampaigns->priority = 1;
     $doCampaigns->activate_time = '2020-01-01 00:00:00';
     $doCampaigns->status = OA_ENTITY_STATUS_AWAITING;
     $idCampaign = DataGenerator::generateOne($doCampaigns, true);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $idCampaign;
     $doBanners->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doBanners->status = OA_ENTITY_STATUS_AWAITING;
     $doBanners->acls_updated = '2006-10-04 12:15:00';
     $idBanner = DataGenerator::generateOne($doBanners);
     $aResult =& $oMaxDalMaintenance->getAllDeliveryLimitationChangedCreatives($aLastRun);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 0);
     DataGenerator::cleanUp();
     // Test 9
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doCampaigns->priority = 1;
     $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
     $aIdCampaignsActive = DataGenerator::generate($doCampaigns, 2, true);
     $doCampaigns->activate_time = '2020-01-01 00:00:00';
     $doCampaigns->status = OA_ENTITY_STATUS_AWAITING;
     $idCampaignInactive = DataGenerator::generateOne($doCampaigns, true);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $aIdCampaignsActive[0];
     $doBanners->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doBanners->status = OA_ENTITY_STATUS_RUNNING;
     $doBanners->acls_updated = '2006-10-04 11:30:00';
     $idBanner1 = DataGenerator::generateOne($doBanners);
     $doBanners->campaignid = $aIdCampaignsActive[0];
     $doBanners->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doBanners->status = OA_ENTITY_STATUS_RUNNING;
     $doBanners->acls_updated = '2006-10-04 10:15:00';
     $idBanner2 = DataGenerator::generateOne($doBanners);
     $doBanners->campaignid = $aIdCampaignsActive[1];
     $doBanners->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doBanners->status = OA_ENTITY_STATUS_AWAITING;
     $doBanners->acls_updated = '2006-10-04 12:06:00';
     $idBanner3 = DataGenerator::generateOne($doBanners);
     $doBanners->campaignid = $aIdCampaignsActive[1];
     $doBanners->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doBanners->status = OA_ENTITY_STATUS_RUNNING;
     $doBanners->acls_updated = '2006-10-04 12:15:00';
     $idBanner4 = DataGenerator::generateOne($doBanners);
     $doBanners->campaignid = $idCampaignInactive;
     $doBanners->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doBanners->status = OA_ENTITY_STATUS_RUNNING;
     $doBanners->acls_updated = '2006-10-04 12:05:00';
     $idBanner5 = DataGenerator::generateOne($doBanners);
     $doBanners->campaignid = $idCampaignInactive;
     $doBanners->updated = $oDateNow->format('%Y-%m-%d %H:%M:%S');
     $doBanners->status = OA_ENTITY_STATUS_RUNNING;
     $doBanners->acls_updated = '2006-10-04 12:01:00';
     $idBanner5 = DataGenerator::generateOne($doBanners);
     $aResult =& $oMaxDalMaintenance->getAllDeliveryLimitationChangedCreatives($aLastRun);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult[$idBanner1], '2006-10-04 11:30:00');
     $this->assertEqual($aResult[$idBanner4], '2006-10-04 12:15:00');
     DataGenerator::cleanUp();
 }
 /**
  * Method to test the getAllZonesWithAllocInv method.
  *
  * Requirements:
  * Test 1: Test with no data, and ensure no data returned.
  * Test 2: Test with sample data, and ensure the correct data is returned.
  *
  * updated in line with OA-120
  * method now returns records only where
  * the ad_id is active and
  * the ad_id belongs to a high priority active campaign
  *
  */
 function testGetAllZonesWithAllocInv()
 {
     $conf = $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $oMaxDalMaintenance = new OA_Dal_Maintenance_Priority();
     // Create the required temporary table for the tests
     $oTable =& OA_DB_Table_Priority::singleton();
     $oTable->createTable('tmp_ad_zone_impression');
     // set up the campaigns and banners
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
     $doCampaigns->priority = '5';
     $campaignId1 = DataGenerator::generateOne($doCampaigns);
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
     $doCampaigns->priority = '-1';
     $campaignId2 = DataGenerator::generateOne($doCampaigns);
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->expire_time = '2000-01-01 23:59:59';
     $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
     $doCampaigns->priority = '5';
     $campaignId3 = DataGenerator::generateOne($doCampaigns);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->status = OA_ENTITY_STATUS_RUNNING;
     $doBanners->campaignid = $campaignId1;
     $bannerId1t = DataGenerator::generateOne($doBanners);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->status = OA_ENTITY_STATUS_EXPIRED;
     $doBanners->campaignid = $campaignId1;
     $bannerId1f = DataGenerator::generateOne($doBanners);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->status = OA_ENTITY_STATUS_RUNNING;
     $doBanners->campaignid = $campaignId2;
     $bannerId2t = DataGenerator::generateOne($doBanners);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->status = OA_ENTITY_STATUS_EXPIRED;
     $doBanners->campaignid = $campaignId2;
     $bannerId2f = DataGenerator::generateOne($doBanners);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->status = OA_ENTITY_STATUS_RUNNING;
     $doBanners->campaignid = $campaignId3;
     $bannerId3t = DataGenerator::generateOne($doBanners);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->status = OA_ENTITY_STATUS_EXPIRED;
     $doBanners->campaignid = $campaignId3;
     $bannerId3f = DataGenerator::generateOne($doBanners);
     // Test 1
     $result =& $oMaxDalMaintenance->getAllZonesWithAllocInv();
     $this->assertEqual(count($result), 0);
     // Test 2
     $query = "\n            INSERT INTO\n                tmp_ad_zone_impression\n                (\n                    ad_id,\n                    zone_id,\n                    required_impressions,\n                    requested_impressions\n                )\n            VALUES\n                (\n                    {$bannerId1t},\n                    1,\n                    2,\n                    3\n                )";
     $rows = $oDbh->exec($query);
     $query = "\n            INSERT INTO\n                tmp_ad_zone_impression\n                (\n                    ad_id,\n                    zone_id,\n                    required_impressions,\n                    requested_impressions\n                )\n            VALUES\n                (\n                    {$bannerId1t},\n                    2,\n                    4,\n                    5\n                )";
     $rows = $oDbh->exec($query);
     $query = "\n            INSERT INTO\n                tmp_ad_zone_impression\n                (\n                    ad_id,\n                    zone_id,\n                    required_impressions,\n                    requested_impressions\n                )\n            VALUES\n                (\n                    {$bannerId1t},\n                    2,\n                    6,\n                    7\n                )";
     $rows = $oDbh->exec($query);
     $query = "\n            INSERT INTO\n                tmp_ad_zone_impression\n                (\n                    ad_id,\n                    zone_id,\n                    required_impressions,\n                    requested_impressions\n                )\n            VALUES\n                (\n                    {$bannerId1f},\n                    1,\n                    2,\n                    3\n                )";
     $rows = $oDbh->exec($query);
     $query = "\n            INSERT INTO\n                tmp_ad_zone_impression\n                (\n                    ad_id,\n                    zone_id,\n                    required_impressions,\n                    requested_impressions\n                )\n            VALUES\n                (\n                    {$bannerId1f},\n                    2,\n                    4,\n                    5\n                )";
     $rows = $oDbh->exec($query);
     $query = "\n            INSERT INTO\n                tmp_ad_zone_impression\n                (\n                    ad_id,\n                    zone_id,\n                    required_impressions,\n                    requested_impressions\n                )\n            VALUES\n                (\n                    {$bannerId1f},\n                    2,\n                    6,\n                    7\n                )";
     $rows = $oDbh->exec($query);
     $query = "\n            INSERT INTO\n                tmp_ad_zone_impression\n                (\n                    ad_id,\n                    zone_id,\n                    required_impressions,\n                    requested_impressions\n                )\n            VALUES\n                (\n                    {$bannerId2t},\n                    1,\n                    2,\n                    3\n                )";
     $rows = $oDbh->exec($query);
     $query = "\n            INSERT INTO\n                tmp_ad_zone_impression\n                (\n                    ad_id,\n                    zone_id,\n                    required_impressions,\n                    requested_impressions\n                )\n            VALUES\n                (\n                    {$bannerId2f},\n                    1,\n                    2,\n                    3\n                )";
     $rows = $oDbh->exec($query);
     $query = "\n            INSERT INTO\n                tmp_ad_zone_impression\n                (\n                    ad_id,\n                    zone_id,\n                    required_impressions,\n                    requested_impressions\n                )\n            VALUES\n                (\n                    {$bannerId3t},\n                    2,\n                    4,\n                    5\n                )";
     $rows = $oDbh->exec($query);
     $query = "\n            INSERT INTO\n                tmp_ad_zone_impression\n                (\n                    ad_id,\n                    zone_id,\n                    required_impressions,\n                    requested_impressions\n                )\n            VALUES\n                (\n                    {$bannerId3f},\n                    2,\n                    4,\n                    5\n                )";
     $rows = $oDbh->exec($query);
     $result =& $oMaxDalMaintenance->getAllZonesWithAllocInv();
     $this->assertEqual(count($result), 3);
     // The last entries have the same zone_id and ad_id. The query used in
     // getAllZonesWithAllocInv doesn't guarantee any order, nor it's useful
     // to add the field to its ORDER BY clause. That's why we sort using PHP
     // by required_impressions
     usort($result, create_function('$a, $b', 'return $a["required_impressions"] - $b["required_impressions"];'));
     $this->assertEqual($result[0]['zone_id'], 1);
     $this->assertEqual($result[0]['ad_id'], $bannerId1t);
     $this->assertEqual($result[0]['required_impressions'], 2);
     $this->assertEqual($result[0]['requested_impressions'], 3);
     $this->assertEqual($result[1]['zone_id'], 2);
     $this->assertEqual($result[1]['ad_id'], $bannerId1t);
     $this->assertEqual($result[1]['required_impressions'], 4);
     $this->assertEqual($result[1]['requested_impressions'], 5);
     $this->assertEqual($result[2]['zone_id'], 2);
     $this->assertEqual($result[2]['ad_id'], $bannerId1t);
     $this->assertEqual($result[2]['required_impressions'], 6);
     $this->assertEqual($result[2]['requested_impressions'], 7);
     TestEnv::restoreEnv();
 }
 /**
  * A method to test the run() method.
  */
 function testRun()
 {
     // Create a reference to the OpenX configuration so that settings
     // can be changed while the tests are running
     $aConf =& $GLOBALS['_MAX']['CONF'];
     // Create the database connection and service locator objects
     $oDbh =& OA_DB::singleton();
     $oServiceLocator =& OA_ServiceLocator::instance();
     // Create the "log_maintenance_statistics" table required for the tests
     $oTables =& OA_DB_Table_Core::singleton();
     $oTables->createTable('log_maintenance_statistics');
     // Create the "controller" OX_Maintenance_Statistics class, and
     // register in the service locator
     $oMaintenanceStatistics = new OX_Maintenance_Statistics();
     $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics);
     // Create a partially mocked instance of the
     // OX_Maintenance_Statistics_Task_SetUpdateRequirements class
     Mock::generatePartial('OX_Maintenance_Statistics_Task_SetUpdateRequirements', 'PartialOX_Maintenance_Statistics_Task_SetUpdateRequirements', array('_getMaintenanceStatisticsLastRunInfo', '_getEarliestLoggedDeliveryData'));
     // Prepare an array of times that the MSE should be run at, to
     // test the effects of different times and data sets
     $aMSERunTimes = array(0 => new Date('2008-08-12 13:00:01'), 1 => new Date('2008-08-12 13:30:01'), 2 => new Date('2008-08-12 14:00:01'));
     // Create an array of valid operation interval values for runnung tests
     $aOperationIntervals = array(30, 60);
     /*-------------------------------------------------------------*/
     /* NO DATA TESTS                                               */
     /*                                                             */
     /* Run tests where with operation intervals of 30 and 60 mins, */
     /* where there is no data in the database, and test that the   */
     /* result is that the MSE will not be run.                     */
     /*-------------------------------------------------------------*/
     foreach ($aMSERunTimes as $key => $oRunDate) {
         // Register the "current" date/time that the MSE is running at
         $oServiceLocator->register('now', $oRunDate);
         foreach ($aOperationIntervals as $operationInterval) {
             // Set the correct operation interval
             $aConf['maintenance']['operationInterval'] = $operationInterval;
             // Prepare the partially mocked instance of the
             // OX_Maintenance_Statistics_Task_SetUpdateRequirements class with
             // the expectations and return values required for the test run
             $oSetUpdateRequirements = new PartialOX_Maintenance_Statistics_Task_SetUpdateRequirements();
             $oSetUpdateRequirements->expectCallCount('_getMaintenanceStatisticsLastRunInfo', 2);
             $oSetUpdateRequirements->expectCallCount('_getEarliestLoggedDeliveryData', 2);
             $oSetUpdateRequirements->expectAt(0, '_getMaintenanceStatisticsLastRunInfo', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI, $oRunDate));
             $oSetUpdateRequirements->setReturnValueAt(0, '_getMaintenanceStatisticsLastRunInfo', null);
             $oSetUpdateRequirements->expectAt(0, '_getEarliestLoggedDeliveryData', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI));
             $oSetUpdateRequirements->setReturnValueAt(0, '_getEarliestLoggedDeliveryData', null);
             $oSetUpdateRequirements->expectAt(1, '_getMaintenanceStatisticsLastRunInfo', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR, $oRunDate));
             $oSetUpdateRequirements->setReturnValueAt(1, '_getMaintenanceStatisticsLastRunInfo', null);
             $oSetUpdateRequirements->expectAt(1, '_getEarliestLoggedDeliveryData', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR));
             $oSetUpdateRequirements->setReturnValueAt(1, '_getEarliestLoggedDeliveryData', null);
             // Create the OX_Maintenance_Statistics_Task_SetUpdateRequirements
             // object and run the task
             $oSetUpdateRequirements->__construct($this);
             $oSetUpdateRequirements->run();
             // Test the results of the task run
             $this->assertFalse($oSetUpdateRequirements->oController->updateIntermediate);
             $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
         }
     }
     /*-------------------------------------------------------------*/
     /* ONLY LOGGED DELIVERY DATA TESTS                             */
     /*                                                             */
     /* Run tests where with operation intervals of 30 and 60 mins, */
     /* where there is only delivery data in the database (i.e. no  */
     /* previous MSE run) and test that the result is that the MSE  */
     /* will be run from the appropriate date/time.                 */
     /*-------------------------------------------------------------*/
     // Set the value that will be returned for the last MSE run
     // update value, based on the earliest logged data, in terms of
     // the operation interval
     $oEarliestLoggedDataDateOI = new Date('2008-08-12 13:29:59');
     // Set the value that will be returned for the last MSE run
     // update value, based on the earliest logged data, in terms of
     // the hour
     $oEarliestLoggedDataDateHour = new Date('2008-08-12 12:59:59');
     foreach ($aMSERunTimes as $key => $oRunDate) {
         // Register the "current" date/time that the MSE is running at
         $oServiceLocator->register('now', $oRunDate);
         foreach ($aOperationIntervals as $operationInterval) {
             // Set the correct operation interval
             $aConf['maintenance']['operationInterval'] = $operationInterval;
             // Prepare the partially mocked instance of the
             // OX_Maintenance_Statistics_Task_SetUpdateRequirements class with
             // the expectations and return values required for the test run
             $oSetUpdateRequirements = new PartialOX_Maintenance_Statistics_Task_SetUpdateRequirements();
             $oSetUpdateRequirements->expectCallCount('_getMaintenanceStatisticsLastRunInfo', 2);
             $oSetUpdateRequirements->expectCallCount('_getEarliestLoggedDeliveryData', 2);
             $oSetUpdateRequirements->expectAt(0, '_getMaintenanceStatisticsLastRunInfo', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI, $oRunDate));
             $oSetUpdateRequirements->setReturnValueAt(0, '_getMaintenanceStatisticsLastRunInfo', null);
             $oSetUpdateRequirements->expectAt(0, '_getEarliestLoggedDeliveryData', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI));
             $oSetUpdateRequirements->setReturnValueAt(0, '_getEarliestLoggedDeliveryData', $oEarliestLoggedDataDateOI);
             $oSetUpdateRequirements->expectAt(1, '_getMaintenanceStatisticsLastRunInfo', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR, $oRunDate));
             $oSetUpdateRequirements->setReturnValueAt(1, '_getMaintenanceStatisticsLastRunInfo', null);
             $oSetUpdateRequirements->expectAt(1, '_getEarliestLoggedDeliveryData', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR));
             $oSetUpdateRequirements->setReturnValueAt(1, '_getEarliestLoggedDeliveryData', $oEarliestLoggedDataDateHour);
             // Create the OX_Maintenance_Statistics_Task_SetUpdateRequirements
             // object and run the task
             $oSetUpdateRequirements->__construct($this);
             $oSetUpdateRequirements->run();
             // Test the results of the task run
             if ($key == 0) {
                 // There is no data logged before "now"; therefore, no udpates will be run
                 $this->assertFalse($oSetUpdateRequirements->oController->updateIntermediate);
                 $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
             } elseif ($key == 1) {
                 // There is logged data before "now", but a complete operation interval
                 // will only have been passed at this stage IF the operation interval is
                 // 30 minutes; in that case, the MSE will update the intermedaite tables;
                 // otherwise, no updates will be run
                 if ($operationInterval == 30) {
                     $this->assertTrue($oSetUpdateRequirements->oController->updateIntermediate);
                     $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
                 } else {
                     $this->assertFalse($oSetUpdateRequirements->oController->updateIntermediate);
                     $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
                 }
             } elseif ($key == 2) {
                 // There is logged data before "now", and a complete operation interval
                 // will have been passed at this stage, and the update boundary is on the
                 // hour, so the MSE will update the intermedaite and final tables
                 $this->assertTrue($oSetUpdateRequirements->oController->updateIntermediate);
                 $this->assertTrue($oSetUpdateRequirements->oController->updateFinal);
             }
         }
     }
     /*-------------------------------------------------------------*/
     /* REAL PAST MSE OI RUN ONLY TESTS                             */
     /*                                                             */
     /* Run tests where with operation intervals of 30 and 60 mins, */
     /* where there the MSE has run previously on the basis of the  */
     /* operation interval, but not for the hour, and test that the */
     /* result is that the MSE will be run from the appropriate     */
     /* date/time.                                                  */
     /*-------------------------------------------------------------*/
     // Set the value that will be returned for the last MSE run
     // update value, based on the the operation interval
     $oLastMSERunOI = new Date('2008-08-12 13:29:59');
     // Set the value that will be returned for the last MSE run
     // update value, based on the earliest logged data, in terms of
     // the hour
     $oEarliestLoggedDataDateHour = new Date('2008-08-12 12:59:59');
     foreach ($aMSERunTimes as $key => $oRunDate) {
         // Register the "current" date/time that the MSE is running at
         $oServiceLocator->register('now', $oRunDate);
         foreach ($aOperationIntervals as $operationInterval) {
             // Set the correct operation interval
             $aConf['maintenance']['operationInterval'] = $operationInterval;
             // Prepare the partially mocked instance of the
             // OX_Maintenance_Statistics_Task_SetUpdateRequirements class with
             // the expectations and return values required for the test run
             $oSetUpdateRequirements = new PartialOX_Maintenance_Statistics_Task_SetUpdateRequirements();
             $oSetUpdateRequirements->expectCallCount('_getMaintenanceStatisticsLastRunInfo', 2);
             $oSetUpdateRequirements->expectCallCount('_getEarliestLoggedDeliveryData', 1);
             $oSetUpdateRequirements->expectAt(0, '_getMaintenanceStatisticsLastRunInfo', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI, $oRunDate));
             $oSetUpdateRequirements->setReturnValueAt(0, '_getMaintenanceStatisticsLastRunInfo', $oLastMSERunOI);
             $oSetUpdateRequirements->expectAt(1, '_getMaintenanceStatisticsLastRunInfo', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR, $oRunDate));
             $oSetUpdateRequirements->setReturnValueAt(1, '_getMaintenanceStatisticsLastRunInfo', null);
             $oSetUpdateRequirements->expectAt(0, '_getEarliestLoggedDeliveryData', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR));
             $oSetUpdateRequirements->setReturnValueAt(0, '_getEarliestLoggedDeliveryData', $oEarliestLoggedDataDateHour);
             // Create the OX_Maintenance_Statistics_Task_SetUpdateRequirements
             // object and run the task
             $oSetUpdateRequirements->__construct($this);
             $oSetUpdateRequirements->run();
             // Test the results of the task run
             if ($key == 0) {
                 // There is no data logged before "now"; therefore, no udpates will be run
                 $this->assertFalse($oSetUpdateRequirements->oController->updateIntermediate);
                 $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
             } elseif ($key == 1) {
                 // There is logged data before "now", but a complete operation interval
                 // will only have been passed at this stage IF the operation interval is
                 // 30 minutes; in that case, the MSE will update the intermedaite tables;
                 // otherwise, no updates will be run
                 if ($operationInterval == 30) {
                     $this->assertTrue($oSetUpdateRequirements->oController->updateIntermediate);
                     $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
                 } else {
                     $this->assertFalse($oSetUpdateRequirements->oController->updateIntermediate);
                     $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
                 }
             } elseif ($key == 2) {
                 // There is logged data before "now", and a complete operation interval
                 // will have been passed at this stage, and the update boundary is on the
                 // hour, so the MSE will update the intermedaite and final tables
                 $this->assertTrue($oSetUpdateRequirements->oController->updateIntermediate);
                 $this->assertTrue($oSetUpdateRequirements->oController->updateFinal);
             }
         }
     }
     /*-------------------------------------------------------------*/
     /* REAL PAST MSE RUN TESTS                                     */
     /*                                                             */
     /* Run tests where with operation intervals of 30 and 60 mins, */
     /* where there the MSE has run previously, and test that the   */
     /* result is that the MSE will be run from the appropriate     */
     /* date/time.                                                  */
     /*-------------------------------------------------------------*/
     // Set the value that will be returned for the last MSE run
     // update value, based on the the operation interval
     $oLastMSERunOI = new Date('2008-08-12 13:29:59');
     // Set the value that will be returned for the last MSE run
     // update value, based on the the hour
     $oLastMSERunHour = new Date('2008-08-12 12:59:59');
     foreach ($aMSERunTimes as $key => $oRunDate) {
         // Register the "current" date/time that the MSE is running at
         $oServiceLocator->register('now', $oRunDate);
         foreach ($aOperationIntervals as $operationInterval) {
             // Set the correct operation interval
             $aConf['maintenance']['operationInterval'] = $operationInterval;
             // Prepare the partially mocked instance of the
             // OX_Maintenance_Statistics_Task_SetUpdateRequirements class with
             // the expectations and return values required for the test run
             $oSetUpdateRequirements = new PartialOX_Maintenance_Statistics_Task_SetUpdateRequirements();
             $oSetUpdateRequirements->expectCallCount('_getMaintenanceStatisticsLastRunInfo', 2);
             $oSetUpdateRequirements->expectCallCount('_getEarliestLoggedDeliveryData', 0);
             $oSetUpdateRequirements->expectAt(0, '_getMaintenanceStatisticsLastRunInfo', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI, $oRunDate));
             $oSetUpdateRequirements->setReturnValueAt(0, '_getMaintenanceStatisticsLastRunInfo', $oLastMSERunOI);
             $oSetUpdateRequirements->expectAt(1, '_getMaintenanceStatisticsLastRunInfo', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR, $oRunDate));
             $oSetUpdateRequirements->setReturnValueAt(1, '_getMaintenanceStatisticsLastRunInfo', $oLastMSERunHour);
             // Create the OX_Maintenance_Statistics_Task_SetUpdateRequirements
             // object and run the task
             $oSetUpdateRequirements->__construct($this);
             $oSetUpdateRequirements->run();
             // Test the results of the task run
             if ($key == 0) {
                 // There is no data logged before "now"; therefore, no udpates will be run
                 $this->assertFalse($oSetUpdateRequirements->oController->updateIntermediate);
                 $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
             } elseif ($key == 1) {
                 // There is logged data before "now", but a complete operation interval
                 // will only have been passed at this stage IF the operation interval is
                 // 30 minutes; in that case, the MSE will update the intermedaite tables;
                 // otherwise, no updates will be run
                 if ($operationInterval == 30) {
                     $this->assertTrue($oSetUpdateRequirements->oController->updateIntermediate);
                     $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
                 } else {
                     $this->assertFalse($oSetUpdateRequirements->oController->updateIntermediate);
                     $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
                 }
             } elseif ($key == 2) {
                 // There is logged data before "now", and a complete operation interval
                 // will have been passed at this stage, and the update boundary is on the
                 // hour, so the MSE will update the intermedaite and final tables
                 $this->assertTrue($oSetUpdateRequirements->oController->updateIntermediate);
                 $this->assertTrue($oSetUpdateRequirements->oController->updateFinal);
             }
         }
     }
     // Reset the testing environment
     TestEnv::restoreEnv();
 }
Ejemplo n.º 24
0
 /**
  * A method to be run after all tests.
  */
 function tearDown()
 {
     // Clean up the testing environment
     TestEnv::restoreEnv();
 }
Ejemplo n.º 25
0
 /**
  * A method to test the getAllDeliveryLimitationsByTypeId() method.
  *
  * Requirements:
  * Test 1:  Test for ad limitations with no data, and ensure null returned
  * Test 2:  Test for channel limitations with no data, and ensure null returned
  * Test 3:  Test with an ad limitation for an ad, but with a different ad id, and
  *          ensure null returned
  * Test 4:  Test with an ad limitation, but with a channel id, and ensure null
  *          returned
  * Test 5:  Test with an ad limitation, but with a bad $type, and ensure null
  *          returned
  * Test 6:  Test with an ad limitation, and ensure values returned
  * Test 7:  Test with a channel limitation, but with an ad id, and ensure null
  *          returned
  * Test 8:  Test with a channel limitation, but with a different channel id, and
  *          ensure null returned
  * Test 9:  Test with a channel limitation, but with a bad $type, and ensure null
  *          returned
  * Test 10: Test with a channel limitation, and ensure values returned
  */
 function testGetAllDeliveryLimitationsByTypeId()
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $oDalMaintenanceCommon = new OA_Dal_Maintenance_Common();
     // Test 1
     $aResult = $oDalMaintenanceCommon->getAllDeliveryLimitationsByTypeId(1, 'ad');
     $this->assertNull($aResult);
     // Test 2
     $aResult = $oDalMaintenanceCommon->getAllDeliveryLimitationsByTypeId(1, 'channel');
     $this->assertNull($aResult);
     $table = $aConf['table']['prefix'] . $aConf['table']['acls'];
     $query = "\n            INSERT INTO\n                " . $oDbh->quoteIdentifier($table, true) . "\n                (\n                    bannerid,\n                    logical,\n                    type,\n                    comparison,\n                    data,\n                    executionorder\n                )\n            VALUES\n                (?, ?, ?, ?, ?, ?)";
     $aTypes = array('integer', 'text', 'text', 'text', 'text', 'integer');
     $st = $oDbh->prepare($query, $aTypes, MDB2_PREPARE_MANIP);
     $aData = array(3, 'and', 'Time:Date', '!=', '2005-05-25', 0);
     $rows = $st->execute($aData);
     $aData = array(3, 'and', 'Geo:Country', '==', 'GB', 1);
     $rows = $st->execute($aData);
     // Test 3
     $aResult = $oDalMaintenanceCommon->getAllDeliveryLimitationsByTypeId(1, 'ad');
     $this->assertNull($aResult);
     // Test 4
     $aResult = $oDalMaintenanceCommon->getAllDeliveryLimitationsByTypeId(1, 'channel');
     $this->assertNull($aResult);
     // Test 5
     $aResult = $oDalMaintenanceCommon->getAllDeliveryLimitationsByTypeId(3, 'foo');
     $this->assertNull($aResult);
     // Test 6
     $aResult = $oDalMaintenanceCommon->getAllDeliveryLimitationsByTypeId(3, 'ad');
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual(count($aResult[0]), 6);
     $this->assertEqual($aResult[0]['ad_id'], 3);
     $this->assertEqual($aResult[0]['logical'], 'and');
     $this->assertEqual($aResult[0]['type'], 'Time:Date');
     $this->assertEqual($aResult[0]['comparison'], '!=');
     $this->assertEqual($aResult[0]['data'], '2005-05-25');
     $this->assertEqual($aResult[0]['executionorder'], 0);
     $this->assertEqual(count($aResult[1]), 6);
     $this->assertEqual($aResult[1]['ad_id'], 3);
     $this->assertEqual($aResult[1]['logical'], 'and');
     $this->assertEqual($aResult[1]['type'], 'Geo:Country');
     $this->assertEqual($aResult[1]['comparison'], '==');
     $this->assertEqual($aResult[1]['data'], 'GB');
     $this->assertEqual($aResult[1]['executionorder'], 1);
     $aCleanupTables = array($aConf['table']['acls']);
     foreach ($aCleanupTables as $table) {
         $query = "DELETE FROM {$aConf['table']['prefix']}{$table}";
         $oDbh->exec($query);
     }
     DataGenerator::resetSequence($aCleanupTables);
     TestEnv::restoreEnv();
     $table = $aConf['table']['prefix'] . $aConf['table']['acls_channel'];
     $query = "\n            INSERT INTO\n                " . $oDbh->quoteIdentifier($table, true) . "\n                (\n                    channelid,\n                    logical,\n                    type,\n                    comparison,\n                    data,\n                    executionorder\n                )\n            VALUES\n                (?, ?, ?, ?, ?, ?)";
     $aTypes = array('integer', 'text', 'text', 'text', 'text', 'integer');
     $st = $oDbh->prepare($query, $aTypes, MDB2_PREPARE_MANIP);
     $aData = array(3, 'and', 'Time:Date', '!=', '2005-05-25', 0);
     $rows = $st->execute($aData);
     $aData = array(3, 'and', 'Geo:Country', '==', 'GB', 1);
     $rows = $st->execute($aData);
     // Test 7
     $aResult = $oDalMaintenanceCommon->getAllDeliveryLimitationsByTypeId(1, 'ad');
     $this->assertNull($aResult);
     // Test 8
     $aResult = $oDalMaintenanceCommon->getAllDeliveryLimitationsByTypeId(1, 'channel');
     $this->assertNull($aResult);
     // Test 9
     $aResult = $oDalMaintenanceCommon->getAllDeliveryLimitationsByTypeId(3, 'foo');
     $this->assertNull($aResult);
     // Test 10
     $aResult = $oDalMaintenanceCommon->getAllDeliveryLimitationsByTypeId(3, 'channel');
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual(count($aResult[0]), 6);
     $this->assertEqual($aResult[0]['ad_id'], 3);
     $this->assertEqual($aResult[0]['logical'], 'and');
     $this->assertEqual($aResult[0]['type'], 'Time:Date');
     $this->assertEqual($aResult[0]['comparison'], '!=');
     $this->assertEqual($aResult[0]['data'], '2005-05-25');
     $this->assertEqual($aResult[0]['executionorder'], 0);
     $this->assertEqual(count($aResult[1]), 6);
     $this->assertEqual($aResult[1]['ad_id'], 3);
     $this->assertEqual($aResult[1]['logical'], 'and');
     $this->assertEqual($aResult[1]['type'], 'Geo:Country');
     $this->assertEqual($aResult[1]['comparison'], '==');
     $this->assertEqual($aResult[1]['data'], 'GB');
     $this->assertEqual($aResult[1]['executionorder'], 1);
     $aCleanupTables = array($aConf['table']['acls_channel']);
     foreach ($aCleanupTables as $table) {
         $query = "DELETE FROM {$aConf['table']['prefix']}{$table}";
         $oDbh->exec($query);
     }
     DataGenerator::resetSequence($aCleanupTables);
 }
 /**
  * Test 1: with lowercase prefix
  * Test 2: with uppercase prefix
  */
 function test_createAuditTable()
 {
     // Test 1
     $GLOBALS['_MAX']['CONF']['table']['prefix'] = 'oa_';
     $oAuditor = $this->_getAuditObject('OA_UpgradeAuditor');
     $this->_dropAuditTable($oAuditor->prefix . $oAuditor->logTable);
     $this->assertTrue($oAuditor->_createAuditTable(), 'failed to createAuditTable');
     $aDBTables = OA_DB_Table::listOATablesCaseSensitive();
     $this->assertTrue(in_array('oa_' . $oAuditor->logTable, $aDBTables));
     TestEnv::restoreConfig();
     TestEnv::restoreEnv();
     // Test 2
     $GLOBALS['_MAX']['CONF']['table']['prefix'] = 'OA_';
     $oAuditor = $this->_getAuditObject('OA_UpgradeAuditor');
     $this->_dropAuditTable($oAuditor->prefix . $oAuditor->logTable);
     $this->assertTrue($oAuditor->_createAuditTable(), 'failed to createAuditTable');
     $aDBTables = OA_DB_Table::listOATablesCaseSensitive();
     $this->assertTrue(in_array('OA_' . $oAuditor->logTable, $aDBTables));
     TestEnv::restoreConfig();
     TestEnv::restoreEnv();
 }