<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <fstream>
#include <string>
#include <vector>
#include <exception>
// StdAir
#include <stdair/stdair_demand_types.hpp>
#include <stdair/bom/EventStruct.hpp>
#include <stdair/bom/EventQueue.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/service/Logger.hpp>
// Distribution
#include <simcrs/SIMCRS_Service.hpp>
// TRADEMGEN
#include <trademgen/TRADEMGEN_Service.hpp>
// Airsched
#include <airsched/AIRSCHED_Service.hpp>
// Dsim
#include <dsim/DSIM_Types.hpp>
#include <dsim/command/Simulator.hpp>

namespace DSIM {

  // ////////////////////////////////////////////////////////////////////
  void Simulator::simulate (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
                            TRADEMGEN::TRADEMGEN_Service& ioTRADEMGEN_Service) {

    try {

      // DEBUG
      STDAIR_LOG_DEBUG ("The simulation is starting");

      /**
         Initialisation step.

Generate the first event for each demand stream.
      */
      ioTRADEMGEN_Service.generateFirstRequests();

      /** (Boost) progress display (current number of events, total
          number of events) for every demand stream. */
      stdair::ProgressDisplayMap_T lProgressDisplays;
      ioTRADEMGEN_Service.initProgressDisplays (lProgressDisplays);

      /**
         Main loop.

Pop a request and get its associated type/demand stream.

Generate the next request for the same type/demand stream.

      */
      stdair::Count_T eventIdx = 1;
      while (ioTRADEMGEN_Service.isQueueDone() == false) {

        // Get the next event from the event queue
        const stdair::EventStruct& lEventStruct= ioTRADEMGEN_Service.popEvent();

        // Extract the corresponding demand/booking request
        const stdair::BookingRequestStruct& lPoppedRequest =
          lEventStruct.getBookingRequest ();

        // DEBUG
        STDAIR_LOG_DEBUG ("[" << eventIdx << "] Poped booking request: '"
                          << lPoppedRequest.describe() << "'.");

        // Play booking request
        playBookingRequest (ioSIMCRS_Service, lPoppedRequest);

        // Retrieve the corresponding demand stream
        const stdair::DemandStreamKeyStr_T& lDemandStreamKey =
          lEventStruct.getDemandStreamKey ();

        // Assess whether more events should be generated for that
        // demand stream
        bool stillHavingRequestsToBeGenerated = ioTRADEMGEN_Service.
          stillHavingRequestsToBeGenerated (lDemandStreamKey);

        // Retrieve, from the demand stream, the total number of events
        // to be generated
        const stdair::NbOfRequests_T& lNbOfRequests = ioTRADEMGEN_Service.
          getTotalNumberOfRequestsToBeGenerated (lDemandStreamKey);

        // DEBUG
        STDAIR_LOG_DEBUG ("=> [" << lDemandStreamKey << "] is now processed. "
                          << "Still generate events for that demand stream? "
                          << stillHavingRequestsToBeGenerated);

        // If there are still events to be generated for that demand
        // stream, generate and add them to the event queue
        if (stillHavingRequestsToBeGenerated) {
          stdair::BookingRequestPtr_T lNextRequest_ptr =
            ioTRADEMGEN_Service.generateNextRequest (lDemandStreamKey);
          assert (lNextRequest_ptr != NULL);

          // Sanity check
          const stdair::Duration_T lDuration =
            lNextRequest_ptr->getRequestDateTime()
            - lPoppedRequest.getRequestDateTime();
          if (lDuration.total_milliseconds() < 0) {
            STDAIR_LOG_ERROR ("[" << lDemandStreamKey
                              << "] The date-time of the generated event ("
                              << lNextRequest_ptr->getRequestDateTime()
                              << ") is lower than the date-time "
                              << "of the current event ("
                              << lPoppedRequest.getRequestDateTime() << ")");
            assert (false);
          }

          //
          stdair::EventStruct lNextEventStruct (stdair::EventType::BKG_REQ,
                                                lDemandStreamKey,
                                                lNextRequest_ptr);

          /**
             Note that when adding an event in the event queue, the
             former can be altered. It happends when an event already
             exists in the event queue with exactly the same date-time
             stamp. In that case, the date-time stamp is altered for the
             newly added event, so that the unicity on the date-time
             stamp can be guaranteed.
          */
          ioTRADEMGEN_Service.addEvent (lNextEventStruct);

          // DEBUG
          STDAIR_LOG_DEBUG ("[" << lDemandStreamKey << "] Added request: '"
                            << lNextRequest_ptr->describe()
                            << "'. Is queue done? "
                            << ioTRADEMGEN_Service.isQueueDone());
        }

        // Iterate
        ++eventIdx;
      }

      // DEBUG
      STDAIR_LOG_DEBUG ("The simulation has ended");

    } catch (const std::exception& lStdError) {
      STDAIR_LOG_ERROR ("Error: " << lStdError.what());
      throw SimulationException();
    }
  }

  // ////////////////////////////////////////////////////////////////////
  void Simulator::
  playBookingRequest (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
                      const stdair::BookingRequestStruct& iBookingRequest) {
    // Retrieve a list of travel solutions corresponding the given
    // booking request.
    const stdair::SegmentPathList_T& lSegmentPathList =
      ioSIMCRS_Service.calculateSegmentPathList (iBookingRequest);
    if (lSegmentPathList.empty() == false) {
      // Get the fare quote for each travel solution.
      stdair::TravelSolutionList_T lTravelSolutionList =
        ioSIMCRS_Service.fareQuote (iBookingRequest, lSegmentPathList);

      // Get the availability for each travel solution.
      ioSIMCRS_Service.calculateAvailability (lTravelSolutionList);

      // Hardcode a travel solution choice.
      stdair::TravelSolutionList_T::const_iterator itTS =
        lTravelSolutionList.begin();
      const stdair::TravelSolutionStruct& lChosenTS = *itTS;

      // DEBUG
      STDAIR_LOG_DEBUG ("Chosen TS: " << lChosenTS << "\n");

      // Make a sale.
      const stdair::NbOfSeats_T& lPartySize = iBookingRequest.getPartySize();
      ioSIMCRS_Service.sell (lChosenTS, lPartySize);

    } else {
      // DEBUG
      STDAIR_LOG_DEBUG ("No travel solution has been found/chosen.");
    }
  }

}
<commit_msg>[DSim] Updated the code for the new Discrete Event related StdAir code.<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <fstream>
#include <string>
#include <vector>
#include <exception>
// StdAir
#include <stdair/stdair_demand_types.hpp>
#include <stdair/bom/EventStruct.hpp>
#include <stdair/bom/EventQueue.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/service/Logger.hpp>
// Distribution
#include <simcrs/SIMCRS_Service.hpp>
// TRADEMGEN
#include <trademgen/TRADEMGEN_Service.hpp>
// Airsched
#include <airsched/AIRSCHED_Service.hpp>
// Dsim
#include <dsim/DSIM_Types.hpp>
#include <dsim/command/Simulator.hpp>

namespace DSIM {

  // ////////////////////////////////////////////////////////////////////
  void Simulator::simulate (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
                            TRADEMGEN::TRADEMGEN_Service& ioTRADEMGEN_Service) {

    try {

      // DEBUG
      STDAIR_LOG_DEBUG ("The simulation is starting");

      /**
         Initialisation step.

Generate the first event for each demand stream.
      */
      ioTRADEMGEN_Service.generateFirstRequests();

      /** (Boost) progress display (current number of events, total
          number of events) for every demand stream.
      stdair::ProgressDisplayMap_T lProgressDisplays;
      ioTRADEMGEN_Service.initProgressDisplays (lProgressDisplays);
       */

      /**
         Main loop.

Pop a request and get its associated type/demand stream.

Generate the next request for the same type/demand stream.

      */
      while (ioTRADEMGEN_Service.isQueueDone() == false) {

        // Get the next event from the event queue
        const stdair::EventStruct& lEventStruct= ioTRADEMGEN_Service.popEvent();

        // DEBUG
        STDAIR_LOG_DEBUG ("Poped event: '" << lEventStruct.describe() << "'.");

        // Extract the corresponding demand/booking request
        const stdair::BookingRequestStruct& lPoppedRequest =
          lEventStruct.getBookingRequest ();

        // DEBUG
        STDAIR_LOG_DEBUG ("Poped booking request: '"
                          << lPoppedRequest.describe() << "'.");

        // Play booking request
        playBookingRequest (ioSIMCRS_Service, lPoppedRequest);

        // Retrieve the corresponding demand stream
        const stdair::DemandStreamKeyStr_T& lDemandStreamKey =
          lEventStruct.getDemandStreamKey ();

        // Assess whether more events should be generated for that
        // demand stream
        bool stillHavingRequestsToBeGenerated = ioTRADEMGEN_Service.
          stillHavingRequestsToBeGenerated (lDemandStreamKey);

        // Retrieve, from the demand stream, the total number of events
        // to be generated
        const stdair::NbOfRequests_T& lNbOfRequests = ioTRADEMGEN_Service.
          getTotalNumberOfRequestsToBeGenerated (lDemandStreamKey);

        // DEBUG
        STDAIR_LOG_DEBUG ("=> [" << lDemandStreamKey << "] is now processed. "
                          << "Still generate events for that demand stream? "
                          << stillHavingRequestsToBeGenerated);

        // If there are still events to be generated for that demand
        // stream, generate and add them to the event queue
        if (stillHavingRequestsToBeGenerated) {
          stdair::BookingRequestPtr_T lNextRequest_ptr =
            ioTRADEMGEN_Service.generateNextRequest (lDemandStreamKey);
          assert (lNextRequest_ptr != NULL);

          // Sanity check
          const stdair::Duration_T lDuration =
            lNextRequest_ptr->getRequestDateTime()
            - lPoppedRequest.getRequestDateTime();
          if (lDuration.total_milliseconds() < 0) {
            STDAIR_LOG_ERROR ("[" << lDemandStreamKey
                              << "] The date-time of the generated event ("
                              << lNextRequest_ptr->getRequestDateTime()
                              << ") is lower than the date-time "
                              << "of the current event ("
                              << lPoppedRequest.getRequestDateTime() << ")");
            assert (false);
          }

          // DEBUG
          STDAIR_LOG_DEBUG ("[" << lDemandStreamKey << "] Added request: '"
                            << lNextRequest_ptr->describe()
                            << "'. Is queue done? "
                            << ioTRADEMGEN_Service.isQueueDone());
        }
      }

      // DEBUG
      STDAIR_LOG_DEBUG ("The simulation has ended");

    } catch (const std::exception& lStdError) {
      STDAIR_LOG_ERROR ("Error: " << lStdError.what());
      throw SimulationException();
    }
  }

  // ////////////////////////////////////////////////////////////////////
  void Simulator::
  playBookingRequest (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
                      const stdair::BookingRequestStruct& iBookingRequest) {
    // Retrieve a list of travel solutions corresponding the given
    // booking request.
    const stdair::SegmentPathList_T& lSegmentPathList =
      ioSIMCRS_Service.calculateSegmentPathList (iBookingRequest);
    if (lSegmentPathList.empty() == false) {
      // Get the fare quote for each travel solution.
      stdair::TravelSolutionList_T lTravelSolutionList =
        ioSIMCRS_Service.fareQuote (iBookingRequest, lSegmentPathList);

      // Get the availability for each travel solution.
      ioSIMCRS_Service.calculateAvailability (lTravelSolutionList);

      // Hardcode a travel solution choice.
      stdair::TravelSolutionList_T::const_iterator itTS =
        lTravelSolutionList.begin();
      const stdair::TravelSolutionStruct& lChosenTS = *itTS;

      // DEBUG
      STDAIR_LOG_DEBUG ("Chosen TS: " << lChosenTS << "\n");

      // Make a sale.
      const stdair::NbOfSeats_T& lPartySize = iBookingRequest.getPartySize();
      ioSIMCRS_Service.sell (lChosenTS, lPartySize);

    } else {
      // DEBUG
      STDAIR_LOG_DEBUG ("No travel solution has been found/chosen.");
    }
  }

}
<|endoftext|>


<commit_before>/*************************************************************************
 * Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

// Task to create a tree for SPD trigger efficiency studies
// evgeny.kryshen@cern.ch

#include "AliSPDTriggerEfficiencyTask.h"

#include "AliAnalysisTaskSE.h"
#include "TChain.h"
#include "AliVEvent.h"
#include "AliESDEvent.h"
#include "AliVHeader.h"
#include "AliMultiplicity.h"
#include "AliESDEvent.h"
#include "AliESDHeader.h"
#include "AliESDtrack.h"
#include "TTree.h"
#include "TList.h"
#include "TFile.h"
#include "TObjString.h"
#include "TH2D.h"
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliUpcParticle.h"
#include "AliESDtrackCuts.h"
#include "AliMCEvent.h"
#include "AliTOFTriggerMask.h"
#include "AliTriggerIR.h"
#include "AliESDtrackCuts.h"
#include "AliTOFGeometry.h"
#include "AliTrackerBase.h"
#include "AliGeomManager.h"
#include "AliCDBManager.h"
#include "AliGRPManager.h"
#include "TArrayI.h"

ClassImp(AliSPDTriggerEfficiencyTask)

//-----------------------------------------------------------------------------
AliSPDTriggerEfficiencyTask::AliSPDTriggerEfficiencyTask(const char* name) :
AliAnalysisTaskSE(name),
fTrackCutsBit0(NULL),
fTrackCutsBit5(NULL),
fListOfHistos(NULL),
fTree(NULL),
fTriggersVsRun(NULL),
fTracks(NULL),
fClassesFired(),
fRunNumber(0),
fPeriod(-1),
fOrbit(-1),
fBC(-1),
fL0inputs(0),
fVtxX(-1000),
fVtxY(-1000),
fVtxZ(-1000),
fVtxTPC(kFALSE),
fVtxContributors(0),
fNofTracklets(0),
fNofITSClusters(),
fIR1(),
fIR2(),
fFOmap(),
fFiredChipMap()
{
  DefineInput(0,TChain::Class());
  DefineOutput(1,TList::Class());
  DefineOutput(2,TTree::Class());
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
void AliSPDTriggerEfficiencyTask::UserCreateOutputObjects(){
  fTrackCutsBit5 = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011();
  fTrackCutsBit0 = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
  fListOfHistos = new TList();
  fListOfHistos->SetOwner();
  fTriggersVsRun = new TH2D("fTriggersVsRun","",8,0,8,30000,270000,300000);
  fListOfHistos->Add(fTriggersVsRun);
  fTracks      = new TClonesArray("AliUpcParticle",10);
  TDirectory *owd = gDirectory;
  OpenFile(1);
  fTree = new TTree("events","events");
  owd->cd();
  fTree->Branch("fClassesFired",&fClassesFired);
  fTree->Branch("fTracks",&fTracks);
  fTree->Branch("fPeriod",&fPeriod);
  fTree->Branch("fOrbit",&fOrbit);
  fTree->Branch("fBC",&fBC);
  fTree->Branch("fRunNumber",&fRunNumber);
  fTree->Branch("fNofTracklets",&fNofTracklets);
  fTree->Branch("fVtxX",&fVtxX);
  fTree->Branch("fVtxY",&fVtxY);
  fTree->Branch("fVtxZ",&fVtxZ);
  fTree->Branch("fVtxTPC",&fVtxTPC);
  fTree->Branch("fVtxContributors",&fVtxContributors);
  fTree->Branch("fNofITSClusters",&fNofITSClusters,"fNofITSClusters[6]/I");
  fTree->Branch("fL0inputs",&fL0inputs);
  fTree->Branch("fIR1",&fIR1);
  fTree->Branch("fIR2",&fIR2);
  fTree->Branch("fFOmap",&fFOmap);
  fTree->Branch("fFiredChipMap",&fFiredChipMap);

  PostData(1,fListOfHistos);
  PostData(2,fTree);
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
void AliSPDTriggerEfficiencyTask::UserExec(Option_t *){
  fClassesFired.SetString(fInputEvent->GetFiredTriggerClasses());
  fRunNumber  = fInputEvent->GetRunNumber();
  if (!fMCEvent) {
    Bool_t accept = 0;
    if (fClassesFired.String().Contains("CINT7-B"))     { accept = 1; fTriggersVsRun->Fill(0.5,fRunNumber); }
    if (fClassesFired.String().Contains("CINT7ZAC-B"))  { accept = 1; fTriggersVsRun->Fill(1.5,fRunNumber); }
    if (!accept) { PostData(1,fListOfHistos); return; }
  } else {
    fTriggersVsRun->Fill(0.5,fRunNumber);
  }

  Bool_t int7selected = fInputHandler->IsEventSelected() & AliVEvent::kINT7;
  if (fClassesFired.String().Contains("CINT7") && !int7selected) { PostData(1,fListOfHistos); return; }

  fPeriod       = fInputEvent->GetPeriodNumber();
  fOrbit        = fInputEvent->GetOrbitNumber();
  fBC           = fInputEvent->GetBunchCrossNumber();
  fL0inputs     = fInputEvent->GetHeader()->GetL0TriggerInputs();
  fIR1          = fInputEvent->GetHeader()->GetIRInt1InteractionMap();
  fIR2          = fInputEvent->GetHeader()->GetIRInt2InteractionMap();

  AliVMultiplicity* mult = fInputEvent->GetMultiplicity();
  fNofTracklets = mult->GetNumberOfTracklets();
  fFOmap        = mult->GetFastOrFiredChips();
  fFiredChipMap = mult->GetFiredChipMap();

  // avoid high multiplicity events
  if (fNofTracklets>100) { PostData(1,fListOfHistos); return; }

  for (Int_t i=0;i<6;i++) fNofITSClusters[i] = fInputEvent->GetNumberOfITSClusters(i);

  const AliVVertex* vertex  = fInputEvent->GetPrimaryVertex();
  fVtxX   = vertex->GetX();
  fVtxY   = vertex->GetY();
  fVtxZ   = vertex->GetZ();
  fVtxTPC = TString(vertex->GetName()).CompareTo("PrimaryVertex") && TString(vertex->GetName()).CompareTo("SPDVertex");
  fVtxContributors = vertex->GetNContributors();

  // vertex selection
  if (fVtxX<-0.5 || fVtxX>0.5 || fVtxY<-0.5 || fVtxY>1.0 || fVtxZ<-10 || fVtxZ>10 || fVtxContributors<2)
  { PostData(1,fListOfHistos); return; }

  fTracks->Clear();
  for (Int_t ipart=0;ipart<fInputEvent->GetNumberOfTracks();ipart++){
    AliESDtrack* track = (AliESDtrack*) fInputEvent->GetTrack(ipart);
    if (!track) continue;
    Bool_t isBit0 = fTrackCutsBit0->AcceptTrack(track);
    Bool_t isBit5 = fTrackCutsBit5->AcceptTrack(track);
    if (!isBit0) continue;
    UChar_t itsMap = track->GetITSClusterMap();
    if (!TESTBIT(itsMap,0) && !TESTBIT(itsMap,1)) continue;
    UInt_t filterMap = 0;
    filterMap |= isBit0 << 0;
    filterMap |= isBit5 << 5;
    Float_t pt     = track->Pt();
    Float_t eta    = track->Eta();
    Float_t phi0   = track->Phi();
    Short_t charge = track->Charge();
    Int_t   label  = track->GetLabel();
    ULong_t status = track->GetStatus();
    Int_t crossedRows = track->GetTPCCrossedRows();
    Int_t indexITSModule0 = track->GetITSModuleIndex(0);
    Int_t indexITSModule1 = track->GetITSModuleIndex(1);
    Int_t indexITSModule6 = track->GetITSModuleIndex(6);
    Int_t indexITSModule7 = track->GetITSModuleIndex(7);
    float* fitsMap          = (float *) &itsMap;
    float* fstatus          = (float *) &status;
    float* ffilterMap       = (float *) &filterMap;
    float* fcrossedRows     = (float *) &crossedRows;
    float* findexITSModule0 = (float *) &indexITSModule0;
    float* findexITSModule1 = (float *) &indexITSModule1;
    float* findexITSModule6 = (float *) &indexITSModule6;
    float* findexITSModule7 = (float *) &indexITSModule7;

    AliUpcParticle* part = new ((*fTracks)[fTracks->GetEntriesFast()]) AliUpcParticle(pt,eta,phi0,charge,label,8);
    part->SetAt(*(fitsMap)         ,0);
    part->SetAt(*(fstatus)         ,1);
    part->SetAt(*(ffilterMap)      ,2);
    part->SetAt(*(fcrossedRows)    ,3);
    part->SetAt(*(findexITSModule0),4);
    part->SetAt(*(findexITSModule1),5);
    part->SetAt(*(findexITSModule6),6);
    part->SetAt(*(findexITSModule7),7);
  }

  fTree->Fill();
  PostData(1,fListOfHistos);
  PostData(2,fTree);
}
//-----------------------------------------------------------------------------
<commit_msg>Removed z-vertex cut<commit_after>/*************************************************************************
 * Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

// Task to create a tree for SPD trigger efficiency studies
// evgeny.kryshen@cern.ch

#include "AliSPDTriggerEfficiencyTask.h"

#include "AliAnalysisTaskSE.h"
#include "TChain.h"
#include "AliVEvent.h"
#include "AliESDEvent.h"
#include "AliVHeader.h"
#include "AliMultiplicity.h"
#include "AliESDEvent.h"
#include "AliESDHeader.h"
#include "AliESDtrack.h"
#include "TTree.h"
#include "TList.h"
#include "TFile.h"
#include "TObjString.h"
#include "TH2D.h"
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliUpcParticle.h"
#include "AliESDtrackCuts.h"
#include "AliMCEvent.h"
#include "AliTOFTriggerMask.h"
#include "AliTriggerIR.h"
#include "AliESDtrackCuts.h"
#include "AliTOFGeometry.h"
#include "AliTrackerBase.h"
#include "AliGeomManager.h"
#include "AliCDBManager.h"
#include "AliGRPManager.h"
#include "TArrayI.h"

ClassImp(AliSPDTriggerEfficiencyTask)

//-----------------------------------------------------------------------------
AliSPDTriggerEfficiencyTask::AliSPDTriggerEfficiencyTask(const char* name) :
AliAnalysisTaskSE(name),
fTrackCutsBit0(NULL),
fTrackCutsBit5(NULL),
fListOfHistos(NULL),
fTree(NULL),
fTriggersVsRun(NULL),
fTracks(NULL),
fClassesFired(),
fRunNumber(0),
fPeriod(-1),
fOrbit(-1),
fBC(-1),
fL0inputs(0),
fVtxX(-1000),
fVtxY(-1000),
fVtxZ(-1000),
fVtxTPC(kFALSE),
fVtxContributors(0),
fNofTracklets(0),
fNofITSClusters(),
fIR1(),
fIR2(),
fFOmap(),
fFiredChipMap()
{
  DefineInput(0,TChain::Class());
  DefineOutput(1,TList::Class());
  DefineOutput(2,TTree::Class());
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
void AliSPDTriggerEfficiencyTask::UserCreateOutputObjects(){
  fTrackCutsBit5 = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011();
  fTrackCutsBit0 = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
  fListOfHistos = new TList();
  fListOfHistos->SetOwner();
  fTriggersVsRun = new TH2D("fTriggersVsRun","",8,0,8,30000,270000,300000);
  fListOfHistos->Add(fTriggersVsRun);
  fTracks      = new TClonesArray("AliUpcParticle",10);
  TDirectory *owd = gDirectory;
  OpenFile(1);
  fTree = new TTree("events","events");
  owd->cd();
  fTree->Branch("fClassesFired",&fClassesFired);
  fTree->Branch("fTracks",&fTracks);
  fTree->Branch("fPeriod",&fPeriod);
  fTree->Branch("fOrbit",&fOrbit);
  fTree->Branch("fBC",&fBC);
  fTree->Branch("fRunNumber",&fRunNumber);
  fTree->Branch("fNofTracklets",&fNofTracklets);
  fTree->Branch("fVtxX",&fVtxX);
  fTree->Branch("fVtxY",&fVtxY);
  fTree->Branch("fVtxZ",&fVtxZ);
  fTree->Branch("fVtxTPC",&fVtxTPC);
  fTree->Branch("fVtxContributors",&fVtxContributors);
  fTree->Branch("fNofITSClusters",&fNofITSClusters,"fNofITSClusters[6]/I");
  fTree->Branch("fL0inputs",&fL0inputs);
  fTree->Branch("fIR1",&fIR1);
  fTree->Branch("fIR2",&fIR2);
  fTree->Branch("fFOmap",&fFOmap);
  fTree->Branch("fFiredChipMap",&fFiredChipMap);

  PostData(1,fListOfHistos);
  PostData(2,fTree);
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
void AliSPDTriggerEfficiencyTask::UserExec(Option_t *){
  fClassesFired.SetString(fInputEvent->GetFiredTriggerClasses());
  fRunNumber  = fInputEvent->GetRunNumber();
  if (!fMCEvent) {
    Bool_t accept = 0;
    if (fClassesFired.String().Contains("CINT7-B"))     { accept = 1; fTriggersVsRun->Fill(0.5,fRunNumber); }
    if (fClassesFired.String().Contains("CINT7ZAC-B"))  { accept = 1; fTriggersVsRun->Fill(1.5,fRunNumber); }
    if (!accept) { PostData(1,fListOfHistos); return; }
  } else {
    fTriggersVsRun->Fill(0.5,fRunNumber);
  }

  Bool_t int7selected = fInputHandler->IsEventSelected() & AliVEvent::kINT7;
  if (fClassesFired.String().Contains("CINT7") && !int7selected) { PostData(1,fListOfHistos); return; }

  fPeriod       = fInputEvent->GetPeriodNumber();
  fOrbit        = fInputEvent->GetOrbitNumber();
  fBC           = fInputEvent->GetBunchCrossNumber();
  fL0inputs     = fInputEvent->GetHeader()->GetL0TriggerInputs();
  fIR1          = fInputEvent->GetHeader()->GetIRInt1InteractionMap();
  fIR2          = fInputEvent->GetHeader()->GetIRInt2InteractionMap();

  AliVMultiplicity* mult = fInputEvent->GetMultiplicity();
  fNofTracklets = mult->GetNumberOfTracklets();
  fFOmap        = mult->GetFastOrFiredChips();
  fFiredChipMap = mult->GetFiredChipMap();

  // avoid high multiplicity events
  if (fNofTracklets>100) { PostData(1,fListOfHistos); return; }

  for (Int_t i=0;i<6;i++) fNofITSClusters[i] = fInputEvent->GetNumberOfITSClusters(i);

  const AliVVertex* vertex  = fInputEvent->GetPrimaryVertex();
  fVtxX   = vertex->GetX();
  fVtxY   = vertex->GetY();
  fVtxZ   = vertex->GetZ();
  fVtxTPC = TString(vertex->GetName()).CompareTo("PrimaryVertex") && TString(vertex->GetName()).CompareTo("SPDVertex");
  fVtxContributors = vertex->GetNContributors();

  // vertex selection
  if (fVtxX<-0.5 || fVtxX>0.5 || fVtxY<-0.5 || fVtxY>1.0 || fVtxContributors<2)
  { PostData(1,fListOfHistos); return; }

  fTracks->Clear();
  for (Int_t ipart=0;ipart<fInputEvent->GetNumberOfTracks();ipart++){
    AliESDtrack* track = (AliESDtrack*) fInputEvent->GetTrack(ipart);
    if (!track) continue;
    Bool_t isBit0 = fTrackCutsBit0->AcceptTrack(track);
    Bool_t isBit5 = fTrackCutsBit5->AcceptTrack(track);
    if (!isBit0) continue;
    UChar_t itsMap = track->GetITSClusterMap();
    if (!TESTBIT(itsMap,0) && !TESTBIT(itsMap,1)) continue;
    UInt_t filterMap = 0;
    filterMap |= isBit0 << 0;
    filterMap |= isBit5 << 5;
    Float_t pt     = track->Pt();
    Float_t eta    = track->Eta();
    Float_t phi0   = track->Phi();
    Short_t charge = track->Charge();
    Int_t   label  = track->GetLabel();
    ULong_t status = track->GetStatus();
    Int_t crossedRows = track->GetTPCCrossedRows();
    Int_t indexITSModule0 = track->GetITSModuleIndex(0);
    Int_t indexITSModule1 = track->GetITSModuleIndex(1);
    Int_t indexITSModule6 = track->GetITSModuleIndex(6);
    Int_t indexITSModule7 = track->GetITSModuleIndex(7);
    float* fitsMap          = (float *) &itsMap;
    float* fstatus          = (float *) &status;
    float* ffilterMap       = (float *) &filterMap;
    float* fcrossedRows     = (float *) &crossedRows;
    float* findexITSModule0 = (float *) &indexITSModule0;
    float* findexITSModule1 = (float *) &indexITSModule1;
    float* findexITSModule6 = (float *) &indexITSModule6;
    float* findexITSModule7 = (float *) &indexITSModule7;

    AliUpcParticle* part = new ((*fTracks)[fTracks->GetEntriesFast()]) AliUpcParticle(pt,eta,phi0,charge,label,8);
    part->SetAt(*(fitsMap)         ,0);
    part->SetAt(*(fstatus)         ,1);
    part->SetAt(*(ffilterMap)      ,2);
    part->SetAt(*(fcrossedRows)    ,3);
    part->SetAt(*(findexITSModule0),4);
    part->SetAt(*(findexITSModule1),5);
    part->SetAt(*(findexITSModule6),6);
    part->SetAt(*(findexITSModule7),7);
  }

  fTree->Fill();
  PostData(1,fListOfHistos);
  PostData(2,fTree);
}
//-----------------------------------------------------------------------------
<|endoftext|>


<commit_before>/**
 * 3.5.4 C风格字符串
 * @Author Bob
 * @Eamil 0haizhu0@gmail.com
 * @Date 2017/7/26
 */
int main(){
  // TODO 这个不重要吧？暂时不看，需要的时候学习吧
  return 0;
}
<commit_msg>3.5.4 C风格字符串 代码格式化<commit_after>/**
 * 3.5.4 C风格字符串
 * @Author Bob
 * @Eamil 0haizhu0@gmail.com
 * @Date 2017/7/26
 */
int main() {
  // TODO 这个不重要吧？暂时不看，需要的时候学习吧
  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/dom_ui/shown_sections_handler.h"

#include "base/file_path.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/pref_service.h"
#include "chrome/common/pref_names.h"
#include "testing/gtest/include/gtest/gtest.h"

class ShownSectionsHandlerTest : public testing::Test {
};

TEST_F(ShownSectionsHandlerTest, MigrateUserPrefs) {
  PrefService pref((FilePath()));

  // Set an *old* value
  pref.RegisterIntegerPref(prefs::kNTPShownSections, 0);
  pref.SetInteger(prefs::kNTPShownSections, THUMB);

  ShownSectionsHandler::MigrateUserPrefs(&pref, 0, 1);

  int shown_sections = pref.GetInteger(prefs::kNTPShownSections);

  EXPECT_TRUE(shown_sections & THUMB);
  EXPECT_FALSE(shown_sections & LIST);
  EXPECT_FALSE(shown_sections & RECENT);
  EXPECT_TRUE(shown_sections & TIPS);
  EXPECT_TRUE(shown_sections & SYNC);
}

TEST_F(ShownSectionsHandlerTest, MigrateUserPrefs1To2) {
  PrefService pref(new JsonPrefStore(FilePath()));

  // Set an *old* value
  pref.RegisterIntegerPref(prefs::kNTPShownSections, 0);
  pref.SetInteger(prefs::kNTPShownSections, LIST);

  ShownSectionsHandler::MigrateUserPrefs(&pref, 1, 2);

  int shown_sections = pref.GetInteger(prefs::kNTPShownSections);

  EXPECT_TRUE(shown_sections & THUMB);
  EXPECT_FALSE(shown_sections & LIST);
}
<commit_msg>Revert 45169 - Fix compile error in ShownSectionsHandlerTest.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/dom_ui/shown_sections_handler.h"

#include "base/file_path.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/pref_service.h"
#include "chrome/common/pref_names.h"
#include "testing/gtest/include/gtest/gtest.h"

class ShownSectionsHandlerTest : public testing::Test {
};

TEST_F(ShownSectionsHandlerTest, MigrateUserPrefs) {
  PrefService pref((FilePath()));

  // Set an *old* value
  pref.RegisterIntegerPref(prefs::kNTPShownSections, 0);
  pref.SetInteger(prefs::kNTPShownSections, THUMB);

  ShownSectionsHandler::MigrateUserPrefs(&pref, 0, 1);

  int shown_sections = pref.GetInteger(prefs::kNTPShownSections);

  EXPECT_TRUE(shown_sections & THUMB);
  EXPECT_FALSE(shown_sections & LIST);
  EXPECT_FALSE(shown_sections & RECENT);
  EXPECT_TRUE(shown_sections & TIPS);
  EXPECT_TRUE(shown_sections & SYNC);
}

TEST_F(ShownSectionsHandlerTest, MigrateUserPrefs1To2) {
  PrefService pref((FilePath()));

  // Set an *old* value
  pref.RegisterIntegerPref(prefs::kNTPShownSections, 0);
  pref.SetInteger(prefs::kNTPShownSections, LIST);

  ShownSectionsHandler::MigrateUserPrefs(&pref, 1, 2);

  int shown_sections = pref.GetInteger(prefs::kNTPShownSections);

  EXPECT_TRUE(shown_sections & THUMB);
  EXPECT_FALSE(shown_sections & LIST);
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <vector>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/json_value_serializer.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"

// A mock implementation of ExtensionsServiceFrontendInterface for testing the
// backend.
class ExtensionsServiceTestFrontend
    : public ExtensionsServiceFrontendInterface {
 public:
  ~ExtensionsServiceTestFrontend() {
    for (ExtensionList::iterator iter = extensions_.begin();
         iter != extensions_.end(); ++iter) {
      delete *iter;
    }
  }

  std::vector<std::string>* errors() {
    return &errors_;
  }

  ExtensionList* extensions() {
    return &extensions_;
  }

  // ExtensionsServiceFrontendInterface
  virtual MessageLoop* GetMessageLoop() {
    return &message_loop_;
  }

  virtual void OnExtensionLoadError(const std::string& message) {
    errors_.push_back(message);
  }

  virtual void OnExtensionsLoadedFromDirectory(ExtensionList* new_extensions) {
    extensions_.insert(extensions_.end(), new_extensions->begin(),
                       new_extensions->end());
    delete new_extensions;
  }

 private:
  MessageLoop message_loop_;
  ExtensionList extensions_;
  std::vector<std::string> errors_;
};

// make the test a PlatformTest to setup autorelease pools properly on mac
typedef PlatformTest ExtensionsServiceTest;

// Test loading extensions from the profile directory.
TEST_F(ExtensionsServiceTest, LoadAllExtensionsFromDirectory) {
  std::wstring extensions_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &extensions_dir));
  FilePath manifest_path = FilePath::FromWStringHack(extensions_dir).Append(
      FILE_PATH_LITERAL("extensions"));

  scoped_refptr<ExtensionsServiceBackend> backend(new ExtensionsServiceBackend);
  scoped_refptr<ExtensionsServiceTestFrontend> frontend(
      new ExtensionsServiceTestFrontend);

  std::vector<Extension*> extensions;
  EXPECT_TRUE(backend->LoadExtensionsFromDirectory(manifest_path,
      scoped_refptr<ExtensionsServiceFrontendInterface>(frontend.get())));
  frontend->GetMessageLoop()->RunAllPending();

  // Note: There can be more errors if there are extra directories, like .svn
  // directories.
  EXPECT_TRUE(frontend->errors()->size() >= 2u);
  EXPECT_EQ(2u, frontend->extensions()->size());

  EXPECT_EQ(std::wstring(L"com.google.myextension1"),
            frontend->extensions()->at(0)->id());
  EXPECT_EQ(std::wstring(L"My extension 1"),
            frontend->extensions()->at(0)->name());
  EXPECT_EQ(std::wstring(L"The first extension that I made."),
            frontend->extensions()->at(0)->description());
  EXPECT_EQ(2u, frontend->extensions()->at(0)->content_scripts().size());
  EXPECT_EQ(std::wstring(L"script1.user.js"),
            frontend->extensions()->at(0)->content_scripts().at(0));
  EXPECT_EQ(std::wstring(L"script2.user.js"),
            frontend->extensions()->at(0)->content_scripts().at(1));

  EXPECT_EQ(std::wstring(L"com.google.myextension2"),
            frontend->extensions()->at(1)->id());
  EXPECT_EQ(std::wstring(L"My extension 2"),
            frontend->extensions()->at(1)->name());
  EXPECT_EQ(std::wstring(L""),
            frontend->extensions()->at(1)->description());
  EXPECT_EQ(0u, frontend->extensions()->at(1)->content_scripts().size());
};
<commit_msg>Fix extensions_service_unittest on Linux.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <algorithm>
#include <vector>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/extension.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/json_value_serializer.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"

namespace {

struct ExtensionsOrder {
  bool operator()(const Extension* a, const Extension* b) {
    return a->name() < b->name();
  }
};

}  // namespace

// A mock implementation of ExtensionsServiceFrontendInterface for testing the
// backend.
class ExtensionsServiceTestFrontend
    : public ExtensionsServiceFrontendInterface {
 public:
  ~ExtensionsServiceTestFrontend() {
    for (ExtensionList::iterator iter = extensions_.begin();
         iter != extensions_.end(); ++iter) {
      delete *iter;
    }
  }

  std::vector<std::string>* errors() {
    return &errors_;
  }

  ExtensionList* extensions() {
    return &extensions_;
  }

  // ExtensionsServiceFrontendInterface
  virtual MessageLoop* GetMessageLoop() {
    return &message_loop_;
  }

  virtual void OnExtensionLoadError(const std::string& message) {
    errors_.push_back(message);
  }

  virtual void OnExtensionsLoadedFromDirectory(ExtensionList* new_extensions) {
    extensions_.insert(extensions_.end(), new_extensions->begin(),
                       new_extensions->end());
    delete new_extensions;
    // In the tests we rely on extensions being in particular order,
    // which is not always the case (and is not guaranteed by used APIs).
    std::stable_sort(extensions_.begin(), extensions_.end(), ExtensionsOrder());
  }

 private:
  MessageLoop message_loop_;
  ExtensionList extensions_;
  std::vector<std::string> errors_;
};

// make the test a PlatformTest to setup autorelease pools properly on mac
typedef PlatformTest ExtensionsServiceTest;

// Test loading extensions from the profile directory.
TEST_F(ExtensionsServiceTest, LoadAllExtensionsFromDirectory) {
  std::wstring extensions_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &extensions_dir));
  FilePath manifest_path = FilePath::FromWStringHack(extensions_dir).Append(
      FILE_PATH_LITERAL("extensions"));

  scoped_refptr<ExtensionsServiceBackend> backend(new ExtensionsServiceBackend);
  scoped_refptr<ExtensionsServiceTestFrontend> frontend(
      new ExtensionsServiceTestFrontend);

  std::vector<Extension*> extensions;
  EXPECT_TRUE(backend->LoadExtensionsFromDirectory(manifest_path,
      scoped_refptr<ExtensionsServiceFrontendInterface>(frontend.get())));
  frontend->GetMessageLoop()->RunAllPending();

  // Note: There can be more errors if there are extra directories, like .svn
  // directories.
  EXPECT_TRUE(frontend->errors()->size() >= 2u);
  ASSERT_EQ(2u, frontend->extensions()->size());

  EXPECT_EQ(std::wstring(L"com.google.myextension1"),
            frontend->extensions()->at(0)->id());
  EXPECT_EQ(std::wstring(L"My extension 1"),
            frontend->extensions()->at(0)->name());
  EXPECT_EQ(std::wstring(L"The first extension that I made."),
            frontend->extensions()->at(0)->description());
  ASSERT_EQ(2u, frontend->extensions()->at(0)->content_scripts().size());
  EXPECT_EQ(std::wstring(L"script1.user.js"),
            frontend->extensions()->at(0)->content_scripts().at(0));
  EXPECT_EQ(std::wstring(L"script2.user.js"),
            frontend->extensions()->at(0)->content_scripts().at(1));

  EXPECT_EQ(std::wstring(L"com.google.myextension2"),
            frontend->extensions()->at(1)->id());
  EXPECT_EQ(std::wstring(L"My extension 2"),
            frontend->extensions()->at(1)->name());
  EXPECT_EQ(std::wstring(L""),
            frontend->extensions()->at(1)->description());
  ASSERT_EQ(0u, frontend->extensions()->at(1)->content_scripts().size());
};
<|endoftext|>


<commit_before><commit_msg>Disable failing test temporarily.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <vector>

#include "base/message_loop.h"
#include "base/scoped_temp_dir.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/policy/cloud_policy_identity_strategy.h"
#include "chrome/browser/policy/logging_work_scheduler.h"
#include "chrome/browser/policy/mock_configuration_policy_store.h"
#include "chrome/browser/policy/proto/cloud_policy.pb.h"
#include "chrome/browser/policy/proto/device_management_backend.pb.h"
#include "chrome/browser/policy/testing_cloud_policy_subsystem.h"
#include "chrome/browser/policy/testing_policy_url_fetcher_factory.h"
#include "chrome/browser/policy/user_policy_cache.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/testing_browser_process.h"
#include "chrome/test/testing_pref_service.h"
#include "content/common/url_fetcher.h"
#include "policy/policy_constants.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace policy {

using ::testing::_;
using ::testing::AtLeast;
using ::testing::AtMost;
using ::testing::DoAll;
using ::testing::InSequence;
using ::testing::Invoke;
using ::testing::Return;

namespace em = enterprise_management;

class CloudPolicySubsystemTest;

namespace {

const char kGaiaAuthHeader[] = "GoogleLogin auth=secret123";
const char kDMAuthHeader[] = "GoogleDMToken token=token123456";
const char kDMToken[] = "token123456";

const char kDeviceManagementUrl[] =
    "http://localhost:12345/device_management_test";

// Constant responses of the identity strategy.
const char kMachineId[] = "dummy-cros-machine-123";
const char kMachineModel[] = "Pony";
const char kDeviceId[] = "abc-xyz-123";
const char kUsername[] = "john@smith.com";
const char kAuthToken[] = "secret123";
const char kPolicyType[] = "google/chrome/test";

}  // namespace

// A stripped-down identity strategy for the tests.
class TestingIdentityStrategy : public CloudPolicyIdentityStrategy {
 public:
  TestingIdentityStrategy() {
  }

  virtual std::string GetDeviceToken() OVERRIDE {
    return device_token_;
  }

  virtual std::string GetDeviceID() OVERRIDE {
    return kDeviceId;
  }

  virtual std::string GetMachineID() OVERRIDE {
    return kMachineId;
  }

  virtual std::string GetMachineModel() OVERRIDE {
    return kMachineModel;
  }

  virtual em::DeviceRegisterRequest_Type GetPolicyRegisterType() OVERRIDE {
    return em::DeviceRegisterRequest::USER;
  }

  virtual std::string GetPolicyType() OVERRIDE {
    return kPolicyType;
  }

  virtual bool GetCredentials(std::string* username,
                              std::string* auth_token) OVERRIDE {
    *username = kUsername;
    *auth_token = kAuthToken;;
    return !username->empty() && !auth_token->empty();
  }

  virtual void OnDeviceTokenAvailable(const std::string& token) OVERRIDE {
    device_token_ = token;
    NotifyDeviceTokenChanged();
  }

 private:
  std::string device_token_;

  DISALLOW_COPY_AND_ASSIGN(TestingIdentityStrategy);
};

// Tests CloudPolicySubsystem by intercepting its network requests.
// The requests are intercepted by PolicyRequestInterceptor and they are
// logged by LoggingWorkScheduler for further examination.
class CloudPolicySubsystemTest : public testing::Test {
 public:
  CloudPolicySubsystemTest()
      : ui_thread_(BrowserThread::UI, &loop_),
        io_thread_(BrowserThread::IO, &loop_) {
  }

 protected:
  void StopMessageLoop() {
    loop_.QuitNow();
  }

  virtual void SetUp() {
    prefs_.reset(new TestingPrefService);
    CloudPolicySubsystem::RegisterPrefs(prefs_.get());
    ((TestingBrowserProcess*) g_browser_process)->SetLocalState(prefs_.get());

    logger_.reset(new EventLogger);
    factory_.reset(new TestingPolicyURLFetcherFactory(logger_.get()));
    URLFetcher::set_factory(factory_.get());
    identity_strategy_.reset(new TestingIdentityStrategy);
    ASSERT_TRUE(temp_user_data_dir_.CreateUniqueTempDir());
    cache_ = new UserPolicyCache(
        temp_user_data_dir_.path().AppendASCII("CloudPolicyControllerTest"));
    cloud_policy_subsystem_.reset(new TestingCloudPolicySubsystem(
        identity_strategy_.get(), cache_, kDeviceManagementUrl,
        logger_.get()));
    cloud_policy_subsystem_->CompleteInitialization(
        prefs::kDevicePolicyRefreshRate, 0);
  }

  virtual void TearDown() {
    ((TestingBrowserProcess*) g_browser_process)->SetLocalState(NULL);
    cloud_policy_subsystem_->Shutdown();
    cloud_policy_subsystem_.reset();
    factory_.reset();
    logger_.reset();
    prefs_.reset();
  }

  // Verifies for a given policy that it is provided by the subsystem.
  void VerifyPolicy(enum ConfigurationPolicyType type, Value* expected) {
    MockConfigurationPolicyStore store;
    EXPECT_CALL(store, Apply(_, _)).Times(AtLeast(1));
    cache_->GetManagedPolicyProvider()->Provide(&store);
    ASSERT_TRUE(Value::Equals(expected, store.Get(type)));
  }

  // Verifies that the last recorded run of the subsystem did not issue
  // too frequent requests:
  // - no more than 10 requests in the first 10 minutes
  // - no more then 12 requests per hour in the next 10 hours
  // TODO(gfeher): Thighten these conditions further. This will require
  // fine-tuning of the subsystem. See: http://crosbug.com/15195
  void VerifyServerLoad() {
    std::vector<int64> events;
    logger_->Swap(&events);

    ASSERT_FALSE(events.empty());

    int64 cur = 0;
    int count = 0;

    // Length and max number of requests for the first interval.
    int64 length = 10*60*1000; // 10 minutes
    int64 limit = 10; // maximum nr of requests in the first 10 minutes

    while (cur <= events.back()) {
      EXPECT_LE(EventLogger::CountEvents(events, cur, length), limit);
      count++;

      cur += length;

      // Length and max number of requests for the subsequent intervals.
      length = 60*60*1000; // 60 minutes
      limit = 12; // maxminum nr of requests in the next 60 minutes
    }

    EXPECT_GE(count, 11)
        << "No enough requests were fired during the test run.";
  }

  void ExecuteTest(const std::string& homepage_location) {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    // The first unexptected request of the policy subsystem will stop the
    // message loop.
    // This code relies on the fact that an InSequence object is active.
    EXPECT_CALL(*(factory_.get()), Intercept(_, _, _)).
       Times(AtMost(1)).
       WillOnce(InvokeWithoutArgs(
           this,
           &CloudPolicySubsystemTest::StopMessageLoop));
    loop_.RunAllPending();

    // Test conditions.
    EXPECT_EQ(CloudPolicySubsystem::SUCCESS, cloud_policy_subsystem_->state());
    StringValue homepage_value(homepage_location);
    VerifyPolicy(kPolicyHomepageLocation, &homepage_value);
    VerifyServerLoad();
  }

  scoped_ptr<TestingPolicyURLFetcherFactory> factory_;

 private:
  ScopedTempDir temp_user_data_dir_;

  MessageLoop loop_;
  BrowserThread ui_thread_;
  BrowserThread io_thread_;

  scoped_ptr<EventLogger> logger_;
  scoped_ptr<TestingIdentityStrategy> identity_strategy_;
  scoped_ptr<CloudPolicySubsystem> cloud_policy_subsystem_;
  scoped_ptr<PrefService> prefs_;
  CloudPolicyCacheBase* cache_;

  DISALLOW_COPY_AND_ASSIGN(CloudPolicySubsystemTest);
};

// An action that returns an URLRequestJob with an HTTP error code.
ACTION_P(CreateFailedResponse, http_error_code) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  em::DeviceManagementResponse response_data;

  arg2->response_data = response_data.SerializeAsString();
  arg2->response_code = http_error_code;
}

// An action that returns an URLRequestJob with a successful device
// registration response.
ACTION_P(CreateSuccessfulRegisterResponse, token) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  em::DeviceManagementResponse response_data;
  response_data.mutable_register_response()->set_device_management_token(token);

  arg2->response_data = response_data.SerializeAsString();
  arg2->response_code = 200;
}

// An action that returns an URLRequestJob with a successful policy response.
ACTION_P(CreateSuccessfulPolicyResponse, homepage_location) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  em::CloudPolicySettings settings;
  settings.mutable_homepagelocation()->set_homepagelocation(homepage_location);
  em::PolicyData policy_data;
  policy_data.set_policy_type(kPolicyType);
  policy_data.set_policy_value(settings.SerializeAsString());

  em::DeviceManagementResponse response_data;
  em::DevicePolicyResponse* policy_response =
      response_data.mutable_policy_response();
  em::PolicyFetchResponse* fetch_response = policy_response->add_response();
  fetch_response->set_error_code(200);
  fetch_response->set_policy_data(policy_data.SerializeAsString());

  arg2->response_data = response_data.SerializeAsString();
  arg2->response_code = 200;
}

TEST_F(CloudPolicySubsystemTest, SuccessAfterSingleErrors) {
  InSequence c;

  EXPECT_CALL(*(factory_.get()), Intercept(kGaiaAuthHeader, "register", _)).
      WillOnce(CreateFailedResponse(901));
  EXPECT_CALL(*(factory_.get()), Intercept(kGaiaAuthHeader, "register", _)).
      WillOnce(CreateSuccessfulRegisterResponse(kDMToken));

  EXPECT_CALL(*(factory_.get()), Intercept(kDMAuthHeader, "policy", _)).
      WillOnce(CreateFailedResponse(501));
  EXPECT_CALL(*(factory_.get()), Intercept(kDMAuthHeader, "policy", _)).
      Times(200).
      WillRepeatedly(CreateSuccessfulPolicyResponse("http://www.google.com"));
  EXPECT_CALL(*(factory_.get()), Intercept(kDMAuthHeader, "policy", _)).
      WillOnce(CreateSuccessfulPolicyResponse("http://www.chromium.org"));

  ExecuteTest("http://www.chromium.org");
}

TEST_F(CloudPolicySubsystemTest, SuccessAfterRegistrationErrors) {
  InSequence c;

  EXPECT_CALL(*(factory_.get()), Intercept(kGaiaAuthHeader, "register", _)).
      Times(200).
      WillRepeatedly(CreateFailedResponse(901));
  EXPECT_CALL(*(factory_.get()), Intercept(kGaiaAuthHeader, "register", _)).
      WillOnce(CreateSuccessfulRegisterResponse(kDMToken));

  EXPECT_CALL(*(factory_.get()), Intercept(kDMAuthHeader, "policy", _)).
      WillOnce(CreateSuccessfulPolicyResponse("http://www.example.com"));

  ExecuteTest("http://www.example.com");
}

}  // policy
<commit_msg>Test cases for the cloud policy subsystem<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <vector>

#include "base/message_loop.h"
#include "base/scoped_temp_dir.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/policy/cloud_policy_identity_strategy.h"
#include "chrome/browser/policy/logging_work_scheduler.h"
#include "chrome/browser/policy/mock_configuration_policy_store.h"
#include "chrome/browser/policy/proto/cloud_policy.pb.h"
#include "chrome/browser/policy/proto/device_management_backend.pb.h"
#include "chrome/browser/policy/testing_cloud_policy_subsystem.h"
#include "chrome/browser/policy/testing_policy_url_fetcher_factory.h"
#include "chrome/browser/policy/user_policy_cache.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/testing_browser_process.h"
#include "chrome/test/testing_pref_service.h"
#include "content/common/url_fetcher.h"
#include "policy/policy_constants.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace policy {

using ::testing::_;
using ::testing::AtLeast;
using ::testing::AtMost;
using ::testing::DoAll;
using ::testing::InSequence;
using ::testing::Invoke;
using ::testing::Return;

namespace em = enterprise_management;

class CloudPolicySubsystemTest;

namespace {

const char kGaiaAuthHeader[] = "GoogleLogin auth=secret123";
const char kDMAuthHeader[] = "GoogleDMToken token=token123456";
const char kDMToken[] = "token123456";

const char kDeviceManagementUrl[] =
    "http://localhost:12345/device_management_test";

// Constant responses of the identity strategy.
const char kMachineId[] = "dummy-cros-machine-123";
const char kMachineModel[] = "Pony";
const char kDeviceId[] = "abc-xyz-123";
const char kUsername[] = "john@smith.com";
const char kAuthToken[] = "secret123";
const char kPolicyType[] = "google/chrome/test";

}  // namespace

// A stripped-down identity strategy for the tests.
class TestingIdentityStrategy : public CloudPolicyIdentityStrategy {
 public:
  TestingIdentityStrategy() {
  }

  virtual std::string GetDeviceToken() OVERRIDE {
    return device_token_;
  }

  virtual std::string GetDeviceID() OVERRIDE {
    return kDeviceId;
  }

  virtual std::string GetMachineID() OVERRIDE {
    return kMachineId;
  }

  virtual std::string GetMachineModel() OVERRIDE {
    return kMachineModel;
  }

  virtual em::DeviceRegisterRequest_Type GetPolicyRegisterType() OVERRIDE {
    return em::DeviceRegisterRequest::USER;
  }

  virtual std::string GetPolicyType() OVERRIDE {
    return kPolicyType;
  }

  virtual bool GetCredentials(std::string* username,
                              std::string* auth_token) OVERRIDE {
    *username = kUsername;
    *auth_token = kAuthToken;;
    return !username->empty() && !auth_token->empty();
  }

  virtual void OnDeviceTokenAvailable(const std::string& token) OVERRIDE {
    device_token_ = token;
    NotifyDeviceTokenChanged();
  }

 private:
  std::string device_token_;

  DISALLOW_COPY_AND_ASSIGN(TestingIdentityStrategy);
};

// An action that returns an URLRequestJob with an HTTP error code.
ACTION_P(CreateFailedResponse, http_error_code) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  em::DeviceManagementResponse response_data;

  arg2->response_data = response_data.SerializeAsString();
  arg2->response_code = http_error_code;
}

// An action that returns an URLRequestJob with a successful device
// registration response.
ACTION_P(CreateSuccessfulRegisterResponse, token) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  em::DeviceManagementResponse response_data;
  response_data.mutable_register_response()->set_device_management_token(token);

  arg2->response_data = response_data.SerializeAsString();
  arg2->response_code = 200;
}

// An action that returns an URLRequestJob with a successful policy response.
ACTION_P(CreateSuccessfulPolicyResponse, homepage_location) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  em::CloudPolicySettings settings;
  settings.mutable_homepagelocation()->set_homepagelocation(homepage_location);
  em::PolicyData policy_data;
  policy_data.set_policy_type(kPolicyType);
  policy_data.set_policy_value(settings.SerializeAsString());

  em::DeviceManagementResponse response_data;
  em::DevicePolicyResponse* policy_response =
      response_data.mutable_policy_response();
  em::PolicyFetchResponse* fetch_response = policy_response->add_response();
  fetch_response->set_error_code(200);
  fetch_response->set_policy_data(policy_data.SerializeAsString());

  arg2->response_data = response_data.SerializeAsString();
  arg2->response_code = 200;
}

// Tests CloudPolicySubsystem by intercepting its network requests.
// The requests are intercepted by PolicyRequestInterceptor and they are
// logged by LoggingWorkScheduler for further examination.
template<typename TESTBASE>
class CloudPolicySubsystemTestBase : public TESTBASE {
 public:
  CloudPolicySubsystemTestBase()
      : ui_thread_(BrowserThread::UI, &loop_),
        io_thread_(BrowserThread::IO, &loop_) {
  }

  virtual ~CloudPolicySubsystemTestBase() {
  }

 protected:
  void StopMessageLoop() {
    loop_.QuitNow();
  }

  virtual void SetUp() {
    prefs_.reset(new TestingPrefService);
    CloudPolicySubsystem::RegisterPrefs(prefs_.get());
    ((TestingBrowserProcess*) g_browser_process)->SetLocalState(prefs_.get());

    logger_.reset(new EventLogger);
    factory_.reset(new TestingPolicyURLFetcherFactory(logger_.get()));
    URLFetcher::set_factory(factory_.get());
    identity_strategy_.reset(new TestingIdentityStrategy);
    ASSERT_TRUE(temp_user_data_dir_.CreateUniqueTempDir());
    cache_ = new UserPolicyCache(
        temp_user_data_dir_.path().AppendASCII("CloudPolicyControllerTest"));
    cloud_policy_subsystem_.reset(new TestingCloudPolicySubsystem(
        identity_strategy_.get(), cache_, kDeviceManagementUrl,
        logger_.get()));
    cloud_policy_subsystem_->CompleteInitialization(
        prefs::kDevicePolicyRefreshRate, 0);
  }

  virtual void TearDown() {
    ((TestingBrowserProcess*) g_browser_process)->SetLocalState(NULL);
    cloud_policy_subsystem_->Shutdown();
    cloud_policy_subsystem_.reset();
    factory_.reset();
    logger_.reset();
    prefs_.reset();
  }

  void ExecuteTest() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    // The first unexpected request of the policy subsystem will stop the
    // message loop.
    // This code relies on the fact that an InSequence object is active.
    EXPECT_CALL(*(factory_.get()), Intercept(_, _, _))
       .Times(AtMost(1))
       .WillOnce(InvokeWithoutArgs(
           this,
           &CloudPolicySubsystemTestBase::StopMessageLoop));
    loop_.RunAllPending();
  }

  void VerifyTest(const std::string& homepage_location) {
    // Test conditions.
    EXPECT_EQ(CloudPolicySubsystem::SUCCESS, cloud_policy_subsystem_->state());
    StringValue homepage_value(homepage_location);
    VerifyPolicy(kPolicyHomepageLocation, &homepage_value);
    VerifyServerLoad();
  }

  void VerifyState(CloudPolicySubsystem::PolicySubsystemState state) {
    EXPECT_EQ(state, cloud_policy_subsystem_->state());
  }

  void ExpectSuccessfulRegistration() {
    EXPECT_CALL(*(factory_.get()), Intercept(kGaiaAuthHeader, "register", _))
        .WillOnce(CreateSuccessfulRegisterResponse(kDMToken));
  }

  void ExpectFailedRegistration(int n, int code) {
    EXPECT_CALL(*(factory_.get()), Intercept(kGaiaAuthHeader, "register", _))
        .Times(n)
        .WillRepeatedly(CreateFailedResponse(code));
  }

  void ExpectFailedPolicy(int n, int code) {
    EXPECT_CALL(*(factory_.get()), Intercept(kDMAuthHeader, "policy", _))
        .Times(n)
        .WillRepeatedly(CreateFailedResponse(code));
  }

  void ExpectSuccessfulPolicy(int n, const std::string& homepage) {
    EXPECT_CALL(*(factory_.get()), Intercept(kDMAuthHeader, "policy", _))
        .Times(n)
        .WillRepeatedly(CreateSuccessfulPolicyResponse(homepage));
  }

 private:
  // Verifies for a given policy that it is provided by the subsystem.
  void VerifyPolicy(enum ConfigurationPolicyType type, Value* expected) {
    MockConfigurationPolicyStore store;
    EXPECT_CALL(store, Apply(_, _)).Times(AtLeast(1));
    cache_->GetManagedPolicyProvider()->Provide(&store);
    ASSERT_TRUE(Value::Equals(expected, store.Get(type)));
  }

  // Verifies that the last recorded run of the subsystem did not issue
  // too frequent requests:
  // - no more than 10 requests in the first 10 minutes
  // - no more then 12 requests per hour in the next 10 hours
  // TODO(gfeher): Thighten these conditions further. This will require
  // fine-tuning of the subsystem. See: http://crosbug.com/16637
  void VerifyServerLoad() {
    std::vector<int64> events;
    logger_->Swap(&events);

    ASSERT_FALSE(events.empty());

    int64 cur = 0;
    int count = 0;

    // Length and max number of requests for the first interval.
    int64 length = 10*60*1000; // 10 minutes
    int64 limit = 10; // maximum nr of requests in the first 10 minutes

    while (cur <= events.back()) {
      EXPECT_LE(EventLogger::CountEvents(events, cur, length), limit);
      count++;

      cur += length;

      // Length and max number of requests for the subsequent intervals.
      length = 60*60*1000; // 60 minutes
      limit = 12; // maxminum nr of requests in the next 60 minutes
    }

    EXPECT_GE(count, 11)
        << "No enough requests were fired during the test run.";
  }

  ScopedTempDir temp_user_data_dir_;

  MessageLoop loop_;
  BrowserThread ui_thread_;
  BrowserThread io_thread_;

  scoped_ptr<EventLogger> logger_;
  scoped_ptr<TestingIdentityStrategy> identity_strategy_;
  scoped_ptr<CloudPolicySubsystem> cloud_policy_subsystem_;
  scoped_ptr<PrefService> prefs_;
  CloudPolicyCacheBase* cache_;

  scoped_ptr<TestingPolicyURLFetcherFactory> factory_;

  DISALLOW_COPY_AND_ASSIGN(CloudPolicySubsystemTestBase);
};

// A parameterized test case that simulates 100 failed registration attempts,
// then a successful one, then 100 failed policy fetch attempts and then 100
// successful policy fetches. The two parameters are the error codes for the
// failed registration and policy responses.

class CombinedTestDesc {
 public:
  CombinedTestDesc(int registration_error_code, int policy_error_code)
      : registration_error_code_(registration_error_code),
        policy_error_code_(policy_error_code) {
  }

  ~CombinedTestDesc() {}

  int registration_error_code() const { return registration_error_code_; }
  int policy_error_code() const { return policy_error_code_; }

 private:
  int registration_error_code_;
  int policy_error_code_;
};

class CloudPolicySubsystemCombinedTest
    : public CloudPolicySubsystemTestBase<
                 testing::TestWithParam<CombinedTestDesc> > {
};

TEST_P(CloudPolicySubsystemCombinedTest, Combined) {
  InSequence s;
  ExpectFailedRegistration(100, GetParam().registration_error_code());
  ExpectSuccessfulRegistration();
  ExpectFailedPolicy(100, GetParam().policy_error_code());
  ExpectSuccessfulPolicy(100, "http://www.google.com");
  ExpectSuccessfulPolicy(1, "http://www.chromium.org");
  ExecuteTest();
  VerifyTest("http://www.chromium.org");
}

// A random sample of error code pairs. Note that the following policy error
// codes (401, 403, 410) make the policy subsystem to try and reregister, and
// that is not expected in these tests.
INSTANTIATE_TEST_CASE_P(
    CloudPolicySubsystemCombinedTestInstance,
    CloudPolicySubsystemCombinedTest,
    testing::Values(
        CombinedTestDesc(403, 400),
        CombinedTestDesc(403, 404),
        CombinedTestDesc(403, 412),
        CombinedTestDesc(403, 500),
        CombinedTestDesc(403, 503),
        CombinedTestDesc(403, 902),
        CombinedTestDesc(902, 400),
        CombinedTestDesc(503, 404),
        CombinedTestDesc(500, 412),
        CombinedTestDesc(412, 500),
        CombinedTestDesc(404, 503),
        CombinedTestDesc(400, 902)));

// A parameterized test case that simulates 100 failed registration attempts,
// then a successful one, and then a succesful policy fetch. The parameter is
// the error code returned for registration attempts.

class CloudPolicySubsystemRegistrationTest
    : public CloudPolicySubsystemTestBase<testing::TestWithParam<int> > {
};

TEST_P(CloudPolicySubsystemRegistrationTest, Registration) {
  InSequence s;
  ExpectFailedRegistration(100, GetParam());
  ExpectSuccessfulRegistration();
  ExpectSuccessfulPolicy(1, "http://www.youtube.com");
  ExecuteTest();
  VerifyTest("http://www.youtube.com");
}

INSTANTIATE_TEST_CASE_P(
    CloudPolicySubsystemRegistrationTestInstance,
    CloudPolicySubsystemRegistrationTest,
    // For the case of 401 see CloudPolicySubsystemRegistrationFailureTest
    testing::Values(400, 403, 404, 410, 412, 500, 503, 902));

// A test case that verifies that the subsystem understands the "not managed"
// response from the server.

class CloudPolicySubsystemRegistrationFailureTest
    : public CloudPolicySubsystemTestBase<testing::Test> {
};

TEST_F(CloudPolicySubsystemRegistrationFailureTest, RegistrationFailure) {
  InSequence s;
  ExpectFailedRegistration(1, 401);
  ExecuteTest();
  VerifyState(CloudPolicySubsystem::BAD_GAIA_TOKEN);
}

// A parameterized test case that simulates a successful registration, then 100
// failed policy fetch attempts and then a successful one. The parameter is
// the error code returned for failed policy attempts.

class CloudPolicySubsystemPolicyTest
    : public CloudPolicySubsystemTestBase<testing::TestWithParam<int> > {
};

TEST_P(CloudPolicySubsystemPolicyTest, Policy) {
  InSequence s;
  ExpectSuccessfulRegistration();
  ExpectFailedPolicy(100, GetParam());
  ExpectSuccessfulPolicy(1, "http://www.youtube.com");
  ExecuteTest();
  VerifyTest("http://www.youtube.com");
}

INSTANTIATE_TEST_CASE_P(
    CloudPolicySubsystemPolicyTestInstance,
    CloudPolicySubsystemPolicyTest,
    testing::Values(400, 404, 412, 500, 503, 902));

// A parameterized test case that simulates a successful registration, then 40
// failed policy fetch attempts and a successful registration after each of
// them. The parameter is the error code returned for registration attempts.

class CloudPolicySubsystemPolicyReregisterTest
    : public CloudPolicySubsystemTestBase<testing::TestWithParam<int> > {
};

TEST_P(CloudPolicySubsystemPolicyReregisterTest, Policy) {
  InSequence s;
  for (int i = 0; i < 40; i++) {
    ExpectSuccessfulRegistration();
    ExpectFailedPolicy(1, GetParam());
  }
  ExpectSuccessfulRegistration();
  ExpectSuccessfulPolicy(1, "http://www.youtube.com");
  ExecuteTest();
  VerifyTest("http://www.youtube.com");
}

INSTANTIATE_TEST_CASE_P(
    CloudPolicySubsystemPolicyReregisterTestInstance,
    CloudPolicySubsystemPolicyReregisterTest,
    testing::Values(401, 403, 410));

}  // policy
<|endoftext|>


<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "depfile_parser.h"

#include "test.h"

struct DepfileParserTest : public testing::Test {
  bool Parse(const char* input, string* err);

  DepfileParser parser_;
  string input_;
};

bool DepfileParserTest::Parse(const char* input, string* err) {
  input_ = input;
  return parser_.Parse(&input_, err);
}

TEST_F(DepfileParserTest, Basic) {
  string err;
  EXPECT_TRUE(Parse(
"build/ninja.o: ninja.cc ninja.h eval_env.h manifest_parser.h\n",
      &err));
  ASSERT_EQ("", err);
  EXPECT_EQ("build/ninja.o", parser_.out_.AsString());
  EXPECT_EQ(4u, parser_.ins_.size());
}

TEST_F(DepfileParserTest, EarlyNewlineAndWhitespace) {
  string err;
  EXPECT_TRUE(Parse(
" \\\n"
"  out: in\n",
      &err));
  ASSERT_EQ("", err);
}

TEST_F(DepfileParserTest, Continuation) {
  string err;
  EXPECT_TRUE(Parse(
"foo.o: \\\n"
"  bar.h baz.h\n",
      &err));
  ASSERT_EQ("", err);
  EXPECT_EQ("foo.o", parser_.out_.AsString());
  EXPECT_EQ(2u, parser_.ins_.size());
}

TEST_F(DepfileParserTest, CarriageReturnContinuation) {
  string err;
  EXPECT_TRUE(Parse(
"foo.o: \\\r\n"
"  bar.h baz.h\r\n",
      &err));
  ASSERT_EQ("", err);
  EXPECT_EQ("foo.o", parser_.out_.AsString());
  EXPECT_EQ(2u, parser_.ins_.size());
}

TEST_F(DepfileParserTest, BackSlashes) {
  string err;
  EXPECT_TRUE(Parse(
"Project\\Dir\\Build\\Release8\\Foo\\Foo.res : \\\n"
"  Dir\\Library\\Foo.rc \\\n"
"  Dir\\Library\\Version\\Bar.h \\\n"
"  Dir\\Library\\Foo.ico \\\n"
"  Project\\Thing\\Bar.tlb \\\n",
      &err));
  ASSERT_EQ("", err);
  EXPECT_EQ("Project\\Dir\\Build\\Release8\\Foo\\Foo.res",
            parser_.out_.AsString());
  EXPECT_EQ(4u, parser_.ins_.size());
}

TEST_F(DepfileParserTest, Spaces) {
  string err;
  EXPECT_TRUE(Parse(
"a\\ bc\\ def:   a\\ b c d",
      &err));
  ASSERT_EQ("", err);
  EXPECT_EQ("a bc def",
            parser_.out_.AsString());
  ASSERT_EQ(3u, parser_.ins_.size());
  EXPECT_EQ("a b",
            parser_.ins_[0].AsString());
  EXPECT_EQ("c",
            parser_.ins_[1].AsString());
  EXPECT_EQ("d",
            parser_.ins_[2].AsString());
}

TEST_F(DepfileParserTest, Escapes) {
  // Put backslashes before a variety of characters, see which ones make
  // it through.
  string err;
  EXPECT_TRUE(Parse(
"\\!\\@\\#$$\\%\\^\\&\\\\:",
      &err));
  ASSERT_EQ("", err);
  EXPECT_EQ("\\!\\@#$\\%\\^\\&\\",
            parser_.out_.AsString());
  ASSERT_EQ(0u, parser_.ins_.size());
}

TEST_F(DepfileParserTest, SpecialChars) {
  // See filenames like istreambuf.iterator_op!= in
  // https://github.com/google/libcxx/tree/master/test/iterators/stream.iterators/istreambuf.iterator/
  string err;
  EXPECT_TRUE(Parse(
"C:/Program\\ Files\\ (x86)/Microsoft\\ crtdefs.h: \n"
" en@quot.header~ t+t-x!=1 \n"
" openldap/slapd.d/cn=config/cn=schema/cn={0}core.ldif",
      &err));
  ASSERT_EQ("", err);
  EXPECT_EQ("C:/Program Files (x86)/Microsoft crtdefs.h",
            parser_.out_.AsString());
  ASSERT_EQ(3u, parser_.ins_.size());
  EXPECT_EQ("en@quot.header~",
            parser_.ins_[0].AsString());
  EXPECT_EQ("t+t-x!=1",
            parser_.ins_[1].AsString());
  EXPECT_EQ("openldap/slapd.d/cn=config/cn=schema/cn={0}core.ldif",
            parser_.ins_[2].AsString());
}

TEST_F(DepfileParserTest, UnifyMultipleOutputs) {
  // check that multiple duplicate targets are properly unified
  string err;
  EXPECT_TRUE(Parse("foo foo: x y z", &err));
  ASSERT_EQ(parser_.out_.AsString(), "foo");
  ASSERT_EQ(parser_.ins_.size(), 3u);
  EXPECT_EQ("x", parser_.ins_[0].AsString());
  EXPECT_EQ("y", parser_.ins_[1].AsString());
  EXPECT_EQ("z", parser_.ins_[2].AsString());
}

TEST_F(DepfileParserTest, RejectMultipleDifferentOutputs) {
  // check that multiple different outputs are rejected by the parser
  string err;
  EXPECT_FALSE(Parse("foo bar: x y z", &err));
  ASSERT_EQ("depfile has multiple output paths", err);
}
<commit_msg>Correct order of ASSERT_EQ arguments<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "depfile_parser.h"

#include "test.h"

struct DepfileParserTest : public testing::Test {
  bool Parse(const char* input, string* err);

  DepfileParser parser_;
  string input_;
};

bool DepfileParserTest::Parse(const char* input, string* err) {
  input_ = input;
  return parser_.Parse(&input_, err);
}

TEST_F(DepfileParserTest, Basic) {
  string err;
  EXPECT_TRUE(Parse(
"build/ninja.o: ninja.cc ninja.h eval_env.h manifest_parser.h\n",
      &err));
  ASSERT_EQ("", err);
  EXPECT_EQ("build/ninja.o", parser_.out_.AsString());
  EXPECT_EQ(4u, parser_.ins_.size());
}

TEST_F(DepfileParserTest, EarlyNewlineAndWhitespace) {
  string err;
  EXPECT_TRUE(Parse(
" \\\n"
"  out: in\n",
      &err));
  ASSERT_EQ("", err);
}

TEST_F(DepfileParserTest, Continuation) {
  string err;
  EXPECT_TRUE(Parse(
"foo.o: \\\n"
"  bar.h baz.h\n",
      &err));
  ASSERT_EQ("", err);
  EXPECT_EQ("foo.o", parser_.out_.AsString());
  EXPECT_EQ(2u, parser_.ins_.size());
}

TEST_F(DepfileParserTest, CarriageReturnContinuation) {
  string err;
  EXPECT_TRUE(Parse(
"foo.o: \\\r\n"
"  bar.h baz.h\r\n",
      &err));
  ASSERT_EQ("", err);
  EXPECT_EQ("foo.o", parser_.out_.AsString());
  EXPECT_EQ(2u, parser_.ins_.size());
}

TEST_F(DepfileParserTest, BackSlashes) {
  string err;
  EXPECT_TRUE(Parse(
"Project\\Dir\\Build\\Release8\\Foo\\Foo.res : \\\n"
"  Dir\\Library\\Foo.rc \\\n"
"  Dir\\Library\\Version\\Bar.h \\\n"
"  Dir\\Library\\Foo.ico \\\n"
"  Project\\Thing\\Bar.tlb \\\n",
      &err));
  ASSERT_EQ("", err);
  EXPECT_EQ("Project\\Dir\\Build\\Release8\\Foo\\Foo.res",
            parser_.out_.AsString());
  EXPECT_EQ(4u, parser_.ins_.size());
}

TEST_F(DepfileParserTest, Spaces) {
  string err;
  EXPECT_TRUE(Parse(
"a\\ bc\\ def:   a\\ b c d",
      &err));
  ASSERT_EQ("", err);
  EXPECT_EQ("a bc def",
            parser_.out_.AsString());
  ASSERT_EQ(3u, parser_.ins_.size());
  EXPECT_EQ("a b",
            parser_.ins_[0].AsString());
  EXPECT_EQ("c",
            parser_.ins_[1].AsString());
  EXPECT_EQ("d",
            parser_.ins_[2].AsString());
}

TEST_F(DepfileParserTest, Escapes) {
  // Put backslashes before a variety of characters, see which ones make
  // it through.
  string err;
  EXPECT_TRUE(Parse(
"\\!\\@\\#$$\\%\\^\\&\\\\:",
      &err));
  ASSERT_EQ("", err);
  EXPECT_EQ("\\!\\@#$\\%\\^\\&\\",
            parser_.out_.AsString());
  ASSERT_EQ(0u, parser_.ins_.size());
}

TEST_F(DepfileParserTest, SpecialChars) {
  // See filenames like istreambuf.iterator_op!= in
  // https://github.com/google/libcxx/tree/master/test/iterators/stream.iterators/istreambuf.iterator/
  string err;
  EXPECT_TRUE(Parse(
"C:/Program\\ Files\\ (x86)/Microsoft\\ crtdefs.h: \n"
" en@quot.header~ t+t-x!=1 \n"
" openldap/slapd.d/cn=config/cn=schema/cn={0}core.ldif",
      &err));
  ASSERT_EQ("", err);
  EXPECT_EQ("C:/Program Files (x86)/Microsoft crtdefs.h",
            parser_.out_.AsString());
  ASSERT_EQ(3u, parser_.ins_.size());
  EXPECT_EQ("en@quot.header~",
            parser_.ins_[0].AsString());
  EXPECT_EQ("t+t-x!=1",
            parser_.ins_[1].AsString());
  EXPECT_EQ("openldap/slapd.d/cn=config/cn=schema/cn={0}core.ldif",
            parser_.ins_[2].AsString());
}

TEST_F(DepfileParserTest, UnifyMultipleOutputs) {
  // check that multiple duplicate targets are properly unified
  string err;
  EXPECT_TRUE(Parse("foo foo: x y z", &err));
  ASSERT_EQ("foo", parser_.out_.AsString());
  ASSERT_EQ(3u, parser_.ins_.size());
  EXPECT_EQ("x", parser_.ins_[0].AsString());
  EXPECT_EQ("y", parser_.ins_[1].AsString());
  EXPECT_EQ("z", parser_.ins_[2].AsString());
}

TEST_F(DepfileParserTest, RejectMultipleDifferentOutputs) {
  // check that multiple different outputs are rejected by the parser
  string err;
  EXPECT_FALSE(Parse("foo bar: x y z", &err));
  ASSERT_EQ("depfile has multiple output paths", err);
}
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <os>
#include <net/inet4>
#include <net/dhcp/dh4client.hpp>
#include <math.h> // rand()
#include <sstream>

// An IP-stack object
std::unique_ptr<net::Inet4<VirtioNet> > inet;

using namespace std::chrono;

std::string HTML_RESPONSE() {
  int color = rand();
  std::stringstream stream;

  /* HTML Fonts */
  std::string ubuntu_medium  = "font-family: \'Ubuntu\', sans-serif; font-weight: 500; ";
  std::string ubuntu_normal  = "font-family: \'Ubuntu\', sans-serif; font-weight: 400; ";
  std::string ubuntu_light  = "font-family: \'Ubuntu\', sans-serif; font-weight: 300; ";

  /* HTML */
  stream << ""
         << "<link href='https://fonts.googleapis.com/css?family=Ubuntu:500,300' rel='stylesheet' type='text/css'>"
         << ""
         << "<h1 style= \"color: " << "#" << std::hex << (color >> 8) << "\">"
         <<  "IncludeOS
"
         <<  "
Now speaks TCP!
"
    // .... generate more dynamic content
         << "
  ...and can improvise http. With limitations of course, but it's been easier than expected so far
"
         << "
 © 2015, Oslo and Akershus University College of Applied Sciences "
         << "\n";

  std::string html = stream.str();

  std::string header="HTTP/1.1 200 OK \n "        \
    "Date: Mon, 01 Jan 1970 00:00:01 GMT \n"      \
    "Server: IncludeOS prototype 4.0 \n"        \
    "Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT \n"   \
    "Content-Type: text/html; charset=UTF-8 \n"     \
    "Content-Length: "+std::to_string(html.size())+"\n"   \
    "Accept-Ranges: bytes\n"          \
    "Connection: close\n\n";
  return header + html;
}

void Service::start() {
  // Assign a driver (VirtioNet) to a network interface (eth0)
  // @note: We could determine the appropirate driver dynamically, but then we'd
  // have to include all the drivers into the image, which  we want to avoid.
  hw::Nic<VirtioNet>& eth0 = hw::Dev::eth<0,VirtioNet>();

  // Bring up a network stack, attached to the nic
  // @note : No parameters after 'nic' means we'll use DHCP for IP config.
  inet = std::make_unique<net::Inet4<VirtioNet> >(eth0);

  // Static IP configuration, until we (possibly) get DHCP
  // @note : Mostly to get a robust demo service that it works with and without DHCP
  inet->network_config( { 10,0,0,42 },      // IP
                        { 255,255,255,0 },  // Netmask
                        { 10,0,0,1 },       // Gateway
                        { 8,8,8,8 } );      // DNS

  srand(OS::cycles_since_boot());

  // Set up a TCP server on port 80
  auto& server = inet->tcp().bind(80);

  hw::PIT::instance().onRepeatedTimeout(30s, []{
      printf("<Service> TCP STATUS:\n%s \n", inet->tcp().status().c_str());
    });

  // Add a TCP connection handler - here a hardcoded HTTP-service
  server.onAccept([](auto conn) -> bool {
      printf("<Service> @onAccept - Connection attempt from: %s \n",
             conn->to_string().c_str());
      return true; // allow all connections

    }).onConnect([](auto conn) {
        printf("<Service> @onConnect - Connection successfully established.\n");
        // read async with a buffer size of 1024 bytes
        // define what to do when data is read
        conn->read(1024, [conn](net::TCP::buffer_t buf, size_t n) {
            // create string from buffer
            std::string data { (char*)buf.get(), n };
            printf("<Service> @read:\n%s\n", data.c_str());

            // create response
            std::string response = HTML_RESPONSE();
            // write the data from the string with the strings size
            conn->write(response.data(), response.size(), [](size_t n) {
                printf("<Service> @write: %u bytes written\n", n);
              });
          });

      }).onDisconnect([](auto, auto reason) {
          printf("<Service> @onDisconnect - Reason: %s \n", reason.to_string().c_str());
        });

  printf("*** TEST SERVICE STARTED *** \n");
}
<commit_msg>example: demo now closes connections when peer disconnects<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <os>
#include <net/inet4>
#include <net/dhcp/dh4client.hpp>
#include <math.h> // rand()
#include <sstream>

// An IP-stack object
std::unique_ptr<net::Inet4<VirtioNet> > inet;

using namespace std::chrono;

std::string HTML_RESPONSE() {
  int color = rand();
  std::stringstream stream;

  /* HTML Fonts */
  std::string ubuntu_medium  = "font-family: \'Ubuntu\', sans-serif; font-weight: 500; ";
  std::string ubuntu_normal  = "font-family: \'Ubuntu\', sans-serif; font-weight: 400; ";
  std::string ubuntu_light  = "font-family: \'Ubuntu\', sans-serif; font-weight: 300; ";

  /* HTML */
  stream << ""
         << "<link href='https://fonts.googleapis.com/css?family=Ubuntu:500,300' rel='stylesheet' type='text/css'>"
         << ""
         << "<h1 style= \"color: " << "#" << std::hex << (color >> 8) << "\">"
         <<  "IncludeOS
"
         <<  "
Now speaks TCP!
"
    // .... generate more dynamic content
         << "
  ...and can improvise http. With limitations of course, but it's been easier than expected so far
"
         << "
 © 2015, Oslo and Akershus University College of Applied Sciences "
         << "\n";

  std::string html = stream.str();

  std::string header="HTTP/1.1 200 OK \n "        \
    "Date: Mon, 01 Jan 1970 00:00:01 GMT \n"      \
    "Server: IncludeOS prototype 4.0 \n"        \
    "Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT \n"   \
    "Content-Type: text/html; charset=UTF-8 \n"     \
    "Content-Length: "+std::to_string(html.size())+"\n"   \
    "Accept-Ranges: bytes\n"          \
    "Connection: close\n\n";
  return header + html;
}

void Service::start() {
  // Assign a driver (VirtioNet) to a network interface (eth0)
  // @note: We could determine the appropirate driver dynamically, but then we'd
  // have to include all the drivers into the image, which  we want to avoid.
  hw::Nic<VirtioNet>& eth0 = hw::Dev::eth<0,VirtioNet>();

  // Bring up a network stack, attached to the nic
  // @note : No parameters after 'nic' means we'll use DHCP for IP config.
  inet = std::make_unique<net::Inet4<VirtioNet> >(eth0);

  // Static IP configuration, until we (possibly) get DHCP
  // @note : Mostly to get a robust demo service that it works with and without DHCP
  inet->network_config( { 10,0,0,42 },      // IP
                        { 255,255,255,0 },  // Netmask
                        { 10,0,0,1 },       // Gateway
                        { 8,8,8,8 } );      // DNS

  srand(OS::cycles_since_boot());

  // Set up a TCP server on port 80
  auto& server = inet->tcp().bind(80);

  hw::PIT::instance().onRepeatedTimeout(30s, []{
      printf("<Service> TCP STATUS:\n%s \n", inet->tcp().status().c_str());
    });

  // Add a TCP connection handler - here a hardcoded HTTP-service
  server.onAccept([](auto conn) -> bool {
      printf("<Service> @onAccept - Connection attempt from: %s \n",
             conn->to_string().c_str());
      return true; // allow all connections

    }).onConnect([](auto conn) {
        printf("<Service> @onConnect - Connection successfully established.\n");
        // read async with a buffer size of 1024 bytes
        // define what to do when data is read
        conn->read(1024, [conn](net::TCP::buffer_t buf, size_t n) {
            // create string from buffer
            std::string data { (char*)buf.get(), n };
            printf("<Service> @read:\n%s\n", data.c_str());

            // create response
            std::string response = HTML_RESPONSE();
            // write the data from the string with the strings size
            conn->write(response.data(), response.size(), [](size_t n) {
                printf("<Service> @write: %u bytes written\n", n);
              });
          });

      }).onDisconnect([](auto conn, auto reason) {
          printf("<Service> @onDisconnect - Reason: %s \n", reason.to_string().c_str());
          conn->close();
        });

  printf("*** TEST SERVICE STARTED *** \n");
}
<|endoftext|>