<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <iostream>
#include <itkImage.h>
#include <itkIndex.h>
#include <itkImageRegionIterator.h>

#include <itkGraphCutSegmentationGridGraphFilter.h>
#include <itkGraphCutSegmentationBoykovFilter.h>

int itkGraphCutSegmentationFilterTest(int, char* [] )
//int main(int, char* [] )
{
  //typedef short PixelType;
  typedef itk::Index<2> IndexType2D;
  typedef itk::Index<3> IndexType;

  int testValue2D = 0;
  int referenceValue2D = 2500;
  int testValue = 0;
  int referenceValue = 125000;

  typedef itk::Image< short, 2 > ImageType2D;
  typedef itk::Image< short, 3 > ImageType;
  typedef itk::ImageRegionIterator<ImageType2D>IteratorType2D;
  typedef itk::ImageRegionIterator<ImageType>IteratorType;

  typedef itk::GraphCutSegmentationGridGraphFilter<ImageType2D, ImageType2D> GraphCutSegmentationGridGraphFilterType2D;
 	typedef itk::GraphCutSegmentationBoykovFilter<ImageType2D, ImageType2D> GraphCutSegmentationBoykovFilterType2D;
  typedef itk::GraphCutSegmentationFilter<ImageType2D, ImageType2D> GraphCutSegmentationFilterType2D;
  GraphCutSegmentationFilterType2D::Pointer graphcutFilter2D;

 	typedef itk::GraphCutSegmentationGridGraphFilter<ImageType, ImageType> GraphCutSegmentationGridGraphFilterType;
 	typedef itk::GraphCutSegmentationBoykovFilter<ImageType, ImageType> GraphCutSegmentationBoykovFilterType;
  typedef itk::GraphCutSegmentationFilter<ImageType, ImageType> GraphCutSegmentationFilterType;
  GraphCutSegmentationFilterType::Pointer graphcutFilter;

  //{ start creating a 3D test image
  ImageType2D::Pointer testImage2D = ImageType2D::New();
  ImageType2D::IndexType imageStart2D;
  imageStart2D[0] = 0;
  imageStart2D[1] = 0;

  ImageType2D::SizeType imageSize2D;
  imageSize2D[0] = 128;
  imageSize2D[1] = 128;

  ImageType2D::RegionType imageRegion2D;
  imageRegion2D.SetSize( imageSize2D );
  imageRegion2D.SetIndex( imageStart2D );
  testImage2D->SetRegions(imageRegion2D);
  testImage2D->Allocate();

  IteratorType2D blackIterator2D(testImage2D, imageRegion2D);
  for (blackIterator2D.GoToBegin(); !blackIterator2D.IsAtEnd(); ++blackIterator2D){
	  blackIterator2D.Set(0);
  }

  ImageType2D::IndexType objectStart2D;
  objectStart2D[0] = 39;
  objectStart2D[1] = 39;

  ImageType2D::SizeType objectSize2D;
  objectSize2D[0] = 50;
  objectSize2D[1] = 50;

  ImageType2D::RegionType objectRegion2D;
  objectRegion2D.SetSize( objectSize2D );
  objectRegion2D.SetIndex( objectStart2D );

  IteratorType2D objectIterator2D(testImage2D, objectRegion2D);
  for (objectIterator2D.GoToBegin(); !objectIterator2D.IsAtEnd(); ++objectIterator2D){
	  objectIterator2D.Set(200);
  }
  //} end creating a 2D test image

  //{ start creating a 2D seeds image
  ImageType2D::Pointer seedsImage2D = ImageType2D::New();
  imageRegion2D.SetSize( imageSize2D );
  imageRegion2D.SetIndex( imageStart2D );
  seedsImage2D->SetRegions(imageRegion2D);
  seedsImage2D->Allocate();

  IteratorType2D blackIterator2_2D(seedsImage2D, imageRegion2D);
  for (blackIterator2_2D.GoToBegin(); !blackIterator2_2D.IsAtEnd(); ++blackIterator2_2D){
	  blackIterator2_2D.Set(0);
  }

  ImageType2D::IndexType objectSeedsStart2D;
  objectSeedsStart2D[0] = 60;
  objectSeedsStart2D[1] = 60;

  ImageType2D::SizeType objectSeedsSize2D;
  objectSeedsSize2D[0] = 10;
  objectSeedsSize2D[1] = 10;

  ImageType2D::RegionType objectSeedsRegion2D;
  objectSeedsRegion2D.SetSize( objectSeedsSize2D );
  objectSeedsRegion2D.SetIndex( objectSeedsStart2D );

  IteratorType2D objectSeedsIterator2D(seedsImage2D, objectSeedsRegion2D);
  for (objectSeedsIterator2D.GoToBegin(); !objectSeedsIterator2D.IsAtEnd(); ++objectSeedsIterator2D){
	  objectSeedsIterator2D.Set(255);
  }

  ImageType2D::IndexType backgroundSeedsStart2D;
  backgroundSeedsStart2D[0] = 5;
  backgroundSeedsStart2D[1] = 5;

  ImageType2D::SizeType backgroundSeedsSize2D;
  backgroundSeedsSize2D[0] = 10;
  backgroundSeedsSize2D[1] = 10;

  ImageType2D::RegionType backgroundSeedsRegion2D;
  backgroundSeedsRegion2D.SetSize( backgroundSeedsSize2D );
  backgroundSeedsRegion2D.SetIndex( backgroundSeedsStart2D );

  IteratorType2D backgroundSeedsIterator2D(seedsImage2D, backgroundSeedsRegion2D);
  for (backgroundSeedsIterator2D.GoToBegin(); !backgroundSeedsIterator2D.IsAtEnd(); ++backgroundSeedsIterator2D){
	  backgroundSeedsIterator2D.Set(254);
  }
  //} end creating a 2D seeds image

  //{ start creating a 3D test image
  ImageType::Pointer testImage = ImageType::New();
  ImageType::IndexType imageStart;
  imageStart[0] = 0;
  imageStart[1] = 0;
  imageStart[2] = 0;

  ImageType::SizeType imageSize;
  imageSize[0] = 128;
  imageSize[1] = 128;
  imageSize[2] = 128;

  ImageType::RegionType imageRegion;
  imageRegion.SetSize( imageSize );
  imageRegion.SetIndex( imageStart );
  testImage->SetRegions(imageRegion);
  testImage->Allocate();

  IteratorType blackIterator(testImage, imageRegion);
  for (blackIterator.GoToBegin(); !blackIterator.IsAtEnd(); ++blackIterator){
	  blackIterator.Set(0);
  }

  ImageType::IndexType objectStart;
  objectStart[0] = 39;
  objectStart[1] = 39;
  objectStart[2] = 39;

  ImageType::SizeType objectSize;
  objectSize[0] = 50;
  objectSize[1] = 50;
  objectSize[2] = 50;

  ImageType::RegionType objectRegion;
  objectRegion.SetSize( objectSize );
  objectRegion.SetIndex( objectStart );

  IteratorType objectIterator(testImage, objectRegion);
  for (objectIterator.GoToBegin(); !objectIterator.IsAtEnd(); ++objectIterator){
	  objectIterator.Set(200);
  }
  //} end creating a 3D test image

  //{ start creating a 3D seeds image
  ImageType::Pointer seedsImage = ImageType::New();
  imageRegion.SetSize( imageSize );
  imageRegion.SetIndex( imageStart );
  seedsImage->SetRegions(imageRegion);
  seedsImage->Allocate();

  IteratorType blackIterator2(seedsImage, imageRegion);
  for (blackIterator2.GoToBegin(); !blackIterator2.IsAtEnd(); ++blackIterator2){
	  blackIterator2.Set(0);
  }

  ImageType::IndexType objectSeedsStart;
  objectSeedsStart[0] = 60;
  objectSeedsStart[1] = 60;
  objectSeedsStart[2] = 60;

  ImageType::SizeType objectSeedsSize;
  objectSeedsSize[0] = 10;
  objectSeedsSize[1] = 10;
  objectSeedsSize[2] = 10;

  ImageType::RegionType objectSeedsRegion;
  objectSeedsRegion.SetSize( objectSeedsSize );
  objectSeedsRegion.SetIndex( objectSeedsStart );

  IteratorType objectSeedsIterator(seedsImage, objectSeedsRegion);
  for (objectSeedsIterator.GoToBegin(); !objectSeedsIterator.IsAtEnd(); ++objectSeedsIterator){
	  objectSeedsIterator.Set(255);
  }

  ImageType::IndexType backgroundSeedsStart;
  backgroundSeedsStart[0] = 5;
  backgroundSeedsStart[1] = 5;
  backgroundSeedsStart[2] = 5;

  ImageType::SizeType backgroundSeedsSize;
  backgroundSeedsSize[0] = 10;
  backgroundSeedsSize[1] = 10;
  backgroundSeedsSize[2] = 10;

  ImageType::RegionType backgroundSeedsRegion;
  backgroundSeedsRegion.SetSize( backgroundSeedsSize );
  backgroundSeedsRegion.SetIndex( backgroundSeedsStart );

  IteratorType backgroundSeedsIterator(seedsImage, backgroundSeedsRegion);
  for (backgroundSeedsIterator.GoToBegin(); !backgroundSeedsIterator.IsAtEnd(); ++backgroundSeedsIterator){
	  backgroundSeedsIterator.Set(254);
  }
  //} end creating a 3D seeds image

  //{ start testing itkGraphCutSegmentationGridGraphFilter with 2D image
  std::cout << "Testing itkGraphCutSegmentationGridGraphFilter with 2D image: " <<std::endl;

  graphcutFilter2D = GraphCutSegmentationGridGraphFilterType2D::New();
  graphcutFilter2D->SetInput(testImage2D);
  graphcutFilter2D->SetParameter_sigma_sqr(64);
  graphcutFilter2D->SetParameter_h(-1);
  graphcutFilter2D->SetIntensityDifference(100);
  graphcutFilter2D->SetGradientMagnitude(90);
  graphcutFilter2D->SetParameter_MaxMagni(15);
  graphcutFilter2D->SetParameter_Exp(8);
  graphcutFilter2D->SetLaplacian(70);
  graphcutFilter2D->SetSeedsImage(seedsImage2D);
  graphcutFilter2D->Update();

  ImageType2D::Pointer resultImage2D;
  resultImage2D = graphcutFilter2D->GetOutput();

  IteratorType2D testIterator2D(resultImage2D, resultImage2D->GetRequestedRegion());
  for (testIterator2D.GoToBegin(); !testIterator2D.IsAtEnd(); ++testIterator2D){
    if(testIterator2D.Get() == 1)
      testValue2D = testValue2D + 1;
  }

  if(referenceValue2D != testValue2D){
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;
  //} end testing itkGraphCutSegmentationGridGraphFilter with 2D image

  //{ start testing itkGraphCutSegmentationGridGraphFilter with 3D image
  std::cout << "Testing itkGraphCutSegmentationGridGraphFilter with 3D image: " <<std::endl;

  graphcutFilter = GraphCutSegmentationGridGraphFilterType::New();
  graphcutFilter->SetInput(testImage);
  graphcutFilter->SetParameter_sigma_sqr(64);
  graphcutFilter->SetParameter_h(-1);
  graphcutFilter->SetIntensityDifference(100);
  graphcutFilter->SetGradientMagnitude(90);
  graphcutFilter->SetParameter_MaxMagni(15);
  graphcutFilter->SetParameter_Exp(8);
  graphcutFilter->SetLaplacian(70);
  graphcutFilter->SetSeedsImage(seedsImage);
  graphcutFilter->Update();

  ImageType::Pointer resultImage;
  resultImage = graphcutFilter->GetOutput();

  IteratorType testIterator(resultImage, resultImage->GetRequestedRegion());
  for (testIterator.GoToBegin(); !testIterator.IsAtEnd(); ++testIterator){
	  if(testIterator.Get() == 1)
      testValue = testValue + 1;
  }

  if(referenceValue != testValue){
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;
  //} end testing itkGraphCutSegmentationGridGraphFilter with 3D image

  //{ start testing itkGraphCutSegmentationBoykovFilter with 2D image
  std::cout << "Testing itkGraphCutSegmentationBoykovFilter with 2D image: " <<std::endl;

  testValue2D = 0;
  graphcutFilter2D = GraphCutSegmentationBoykovFilterType2D::New();
  graphcutFilter2D->SetInput(testImage2D);
  graphcutFilter2D->SetParameter_sigma_sqr(64);
  graphcutFilter2D->SetParameter_h(-1);
  graphcutFilter2D->SetIntensityDifference(100);
  graphcutFilter2D->SetGradientMagnitude(90);
  graphcutFilter2D->SetParameter_MaxMagni(15);
  graphcutFilter2D->SetParameter_Exp(8);
  graphcutFilter2D->SetLaplacian(70);
  graphcutFilter2D->SetSeedsImage(seedsImage2D);
  graphcutFilter2D->Update();

  //ImageType2D::Pointer resultImage2D;
  resultImage2D = graphcutFilter2D->GetOutput();

  IteratorType2D testIteratorBoykov2D(resultImage2D, resultImage2D->GetRequestedRegion());
  for (testIteratorBoykov2D.GoToBegin(); !testIteratorBoykov2D.IsAtEnd(); ++testIteratorBoykov2D){
	  if(testIteratorBoykov2D.Get() == 1)
      testValue2D = testValue2D + 1;
  }

  if(referenceValue2D != testValue2D){
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;
  //} end testing itkGraphCutSegmentationBoykovFilter with 2D image

  //{ start testing itkGraphCutSegmentationBoykovFilter with 3D image
  std::cout << "Testing itkGraphCutSegmentationBoykovFilter with 3D image: " <<std::endl;

  testValue = 0;
  graphcutFilter = GraphCutSegmentationBoykovFilterType::New();
  graphcutFilter->SetInput(testImage);
  graphcutFilter->SetParameter_sigma_sqr(64);
  graphcutFilter->SetParameter_h(-1);
  graphcutFilter->SetIntensityDifference(100);
  graphcutFilter->SetGradientMagnitude(90);
  graphcutFilter->SetParameter_MaxMagni(15);
  graphcutFilter->SetParameter_Exp(8);
  graphcutFilter->SetLaplacian(70);
  graphcutFilter->SetSeedsImage(seedsImage);
  graphcutFilter->Update();

  resultImage = graphcutFilter->GetOutput();

  IteratorType testIteratorBoykov(resultImage, resultImage->GetRequestedRegion());
  for (testIteratorBoykov.GoToBegin(); !testIteratorBoykov.IsAtEnd(); ++testIteratorBoykov){
	  if(testIteratorBoykov.Get() == 1)
      testValue = testValue + 1;
  }

  if(referenceValue != testValue){
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;
  //} end testing itkGraphCutSegmentationBoykovFilter with 3D image

std::cout<<"[TEST DONE]"<<std::endl;
return EXIT_SUCCESS;
}
<commit_msg>FIX: comment out boykov filter<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <iostream>
#include <itkImage.h>
#include <itkIndex.h>
#include <itkImageRegionIterator.h>

#include <itkGraphCutSegmentationGridGraphFilter.h>
//#include <itkGraphCutSegmentationBoykovFilter.h>

int itkGraphCutSegmentationFilterTest(int, char* [] )
//int main(int, char* [] )
{
  //typedef short PixelType;
  typedef itk::Index<2> IndexType2D;
  typedef itk::Index<3> IndexType;

  int testValue2D = 0;
  int referenceValue2D = 2500;
  int testValue = 0;
  int referenceValue = 125000;

  typedef itk::Image< short, 2 > ImageType2D;
  typedef itk::Image< short, 3 > ImageType;
  typedef itk::ImageRegionIterator<ImageType2D>IteratorType2D;
  typedef itk::ImageRegionIterator<ImageType>IteratorType;

  typedef itk::GraphCutSegmentationGridGraphFilter<ImageType2D, ImageType2D> GraphCutSegmentationGridGraphFilterType2D;
 	//typedef itk::GraphCutSegmentationBoykovFilter<ImageType2D, ImageType2D> GraphCutSegmentationBoykovFilterType2D;
  typedef itk::GraphCutSegmentationFilter<ImageType2D, ImageType2D> GraphCutSegmentationFilterType2D;
  GraphCutSegmentationFilterType2D::Pointer graphcutFilter2D;

 	typedef itk::GraphCutSegmentationGridGraphFilter<ImageType, ImageType> GraphCutSegmentationGridGraphFilterType;
 	//typedef itk::GraphCutSegmentationBoykovFilter<ImageType, ImageType> GraphCutSegmentationBoykovFilterType;
  typedef itk::GraphCutSegmentationFilter<ImageType, ImageType> GraphCutSegmentationFilterType;
  GraphCutSegmentationFilterType::Pointer graphcutFilter;

  //{ start creating a 3D test image
  ImageType2D::Pointer testImage2D = ImageType2D::New();
  ImageType2D::IndexType imageStart2D;
  imageStart2D[0] = 0;
  imageStart2D[1] = 0;

  ImageType2D::SizeType imageSize2D;
  imageSize2D[0] = 128;
  imageSize2D[1] = 128;

  ImageType2D::RegionType imageRegion2D;
  imageRegion2D.SetSize( imageSize2D );
  imageRegion2D.SetIndex( imageStart2D );
  testImage2D->SetRegions(imageRegion2D);
  testImage2D->Allocate();

  IteratorType2D blackIterator2D(testImage2D, imageRegion2D);
  for (blackIterator2D.GoToBegin(); !blackIterator2D.IsAtEnd(); ++blackIterator2D){
	  blackIterator2D.Set(0);
  }

  ImageType2D::IndexType objectStart2D;
  objectStart2D[0] = 39;
  objectStart2D[1] = 39;

  ImageType2D::SizeType objectSize2D;
  objectSize2D[0] = 50;
  objectSize2D[1] = 50;

  ImageType2D::RegionType objectRegion2D;
  objectRegion2D.SetSize( objectSize2D );
  objectRegion2D.SetIndex( objectStart2D );

  IteratorType2D objectIterator2D(testImage2D, objectRegion2D);
  for (objectIterator2D.GoToBegin(); !objectIterator2D.IsAtEnd(); ++objectIterator2D){
	  objectIterator2D.Set(200);
  }
  //} end creating a 2D test image

  //{ start creating a 2D seeds image
  ImageType2D::Pointer seedsImage2D = ImageType2D::New();
  imageRegion2D.SetSize( imageSize2D );
  imageRegion2D.SetIndex( imageStart2D );
  seedsImage2D->SetRegions(imageRegion2D);
  seedsImage2D->Allocate();

  IteratorType2D blackIterator2_2D(seedsImage2D, imageRegion2D);
  for (blackIterator2_2D.GoToBegin(); !blackIterator2_2D.IsAtEnd(); ++blackIterator2_2D){
	  blackIterator2_2D.Set(0);
  }

  ImageType2D::IndexType objectSeedsStart2D;
  objectSeedsStart2D[0] = 60;
  objectSeedsStart2D[1] = 60;

  ImageType2D::SizeType objectSeedsSize2D;
  objectSeedsSize2D[0] = 10;
  objectSeedsSize2D[1] = 10;

  ImageType2D::RegionType objectSeedsRegion2D;
  objectSeedsRegion2D.SetSize( objectSeedsSize2D );
  objectSeedsRegion2D.SetIndex( objectSeedsStart2D );

  IteratorType2D objectSeedsIterator2D(seedsImage2D, objectSeedsRegion2D);
  for (objectSeedsIterator2D.GoToBegin(); !objectSeedsIterator2D.IsAtEnd(); ++objectSeedsIterator2D){
	  objectSeedsIterator2D.Set(255);
  }

  ImageType2D::IndexType backgroundSeedsStart2D;
  backgroundSeedsStart2D[0] = 5;
  backgroundSeedsStart2D[1] = 5;

  ImageType2D::SizeType backgroundSeedsSize2D;
  backgroundSeedsSize2D[0] = 10;
  backgroundSeedsSize2D[1] = 10;

  ImageType2D::RegionType backgroundSeedsRegion2D;
  backgroundSeedsRegion2D.SetSize( backgroundSeedsSize2D );
  backgroundSeedsRegion2D.SetIndex( backgroundSeedsStart2D );

  IteratorType2D backgroundSeedsIterator2D(seedsImage2D, backgroundSeedsRegion2D);
  for (backgroundSeedsIterator2D.GoToBegin(); !backgroundSeedsIterator2D.IsAtEnd(); ++backgroundSeedsIterator2D){
	  backgroundSeedsIterator2D.Set(254);
  }
  //} end creating a 2D seeds image

  //{ start creating a 3D test image
  ImageType::Pointer testImage = ImageType::New();
  ImageType::IndexType imageStart;
  imageStart[0] = 0;
  imageStart[1] = 0;
  imageStart[2] = 0;

  ImageType::SizeType imageSize;
  imageSize[0] = 128;
  imageSize[1] = 128;
  imageSize[2] = 128;

  ImageType::RegionType imageRegion;
  imageRegion.SetSize( imageSize );
  imageRegion.SetIndex( imageStart );
  testImage->SetRegions(imageRegion);
  testImage->Allocate();

  IteratorType blackIterator(testImage, imageRegion);
  for (blackIterator.GoToBegin(); !blackIterator.IsAtEnd(); ++blackIterator){
	  blackIterator.Set(0);
  }

  ImageType::IndexType objectStart;
  objectStart[0] = 39;
  objectStart[1] = 39;
  objectStart[2] = 39;

  ImageType::SizeType objectSize;
  objectSize[0] = 50;
  objectSize[1] = 50;
  objectSize[2] = 50;

  ImageType::RegionType objectRegion;
  objectRegion.SetSize( objectSize );
  objectRegion.SetIndex( objectStart );

  IteratorType objectIterator(testImage, objectRegion);
  for (objectIterator.GoToBegin(); !objectIterator.IsAtEnd(); ++objectIterator){
	  objectIterator.Set(200);
  }
  //} end creating a 3D test image

  //{ start creating a 3D seeds image
  ImageType::Pointer seedsImage = ImageType::New();
  imageRegion.SetSize( imageSize );
  imageRegion.SetIndex( imageStart );
  seedsImage->SetRegions(imageRegion);
  seedsImage->Allocate();

  IteratorType blackIterator2(seedsImage, imageRegion);
  for (blackIterator2.GoToBegin(); !blackIterator2.IsAtEnd(); ++blackIterator2){
	  blackIterator2.Set(0);
  }

  ImageType::IndexType objectSeedsStart;
  objectSeedsStart[0] = 60;
  objectSeedsStart[1] = 60;
  objectSeedsStart[2] = 60;

  ImageType::SizeType objectSeedsSize;
  objectSeedsSize[0] = 10;
  objectSeedsSize[1] = 10;
  objectSeedsSize[2] = 10;

  ImageType::RegionType objectSeedsRegion;
  objectSeedsRegion.SetSize( objectSeedsSize );
  objectSeedsRegion.SetIndex( objectSeedsStart );

  IteratorType objectSeedsIterator(seedsImage, objectSeedsRegion);
  for (objectSeedsIterator.GoToBegin(); !objectSeedsIterator.IsAtEnd(); ++objectSeedsIterator){
	  objectSeedsIterator.Set(255);
  }

  ImageType::IndexType backgroundSeedsStart;
  backgroundSeedsStart[0] = 5;
  backgroundSeedsStart[1] = 5;
  backgroundSeedsStart[2] = 5;

  ImageType::SizeType backgroundSeedsSize;
  backgroundSeedsSize[0] = 10;
  backgroundSeedsSize[1] = 10;
  backgroundSeedsSize[2] = 10;

  ImageType::RegionType backgroundSeedsRegion;
  backgroundSeedsRegion.SetSize( backgroundSeedsSize );
  backgroundSeedsRegion.SetIndex( backgroundSeedsStart );

  IteratorType backgroundSeedsIterator(seedsImage, backgroundSeedsRegion);
  for (backgroundSeedsIterator.GoToBegin(); !backgroundSeedsIterator.IsAtEnd(); ++backgroundSeedsIterator){
	  backgroundSeedsIterator.Set(254);
  }
  //} end creating a 3D seeds image

  //{ start testing itkGraphCutSegmentationGridGraphFilter with 2D image
  std::cout << "Testing itkGraphCutSegmentationGridGraphFilter with 2D image: " <<std::endl;

  graphcutFilter2D = GraphCutSegmentationGridGraphFilterType2D::New();
  graphcutFilter2D->SetInput(testImage2D);
  graphcutFilter2D->SetParameter_sigma_sqr(64);
  graphcutFilter2D->SetParameter_h(-1);
  graphcutFilter2D->SetIntensityDifference(100);
  graphcutFilter2D->SetGradientMagnitude(90);
  graphcutFilter2D->SetParameter_MaxMagni(15);
  graphcutFilter2D->SetParameter_Exp(8);
  graphcutFilter2D->SetLaplacian(70);
  graphcutFilter2D->SetSeedsImage(seedsImage2D);
  graphcutFilter2D->Update();

  ImageType2D::Pointer resultImage2D;
  resultImage2D = graphcutFilter2D->GetOutput();

  IteratorType2D testIterator2D(resultImage2D, resultImage2D->GetRequestedRegion());
  for (testIterator2D.GoToBegin(); !testIterator2D.IsAtEnd(); ++testIterator2D){
    if(testIterator2D.Get() == 1)
      testValue2D = testValue2D + 1;
  }

  if(referenceValue2D != testValue2D){
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;
  //} end testing itkGraphCutSegmentationGridGraphFilter with 2D image

  //{ start testing itkGraphCutSegmentationGridGraphFilter with 3D image
  std::cout << "Testing itkGraphCutSegmentationGridGraphFilter with 3D image: " <<std::endl;

  graphcutFilter = GraphCutSegmentationGridGraphFilterType::New();
  graphcutFilter->SetInput(testImage);
  graphcutFilter->SetParameter_sigma_sqr(64);
  graphcutFilter->SetParameter_h(-1);
  graphcutFilter->SetIntensityDifference(100);
  graphcutFilter->SetGradientMagnitude(90);
  graphcutFilter->SetParameter_MaxMagni(15);
  graphcutFilter->SetParameter_Exp(8);
  graphcutFilter->SetLaplacian(70);
  graphcutFilter->SetSeedsImage(seedsImage);
  graphcutFilter->Update();

  ImageType::Pointer resultImage;
  resultImage = graphcutFilter->GetOutput();

  IteratorType testIterator(resultImage, resultImage->GetRequestedRegion());
  for (testIterator.GoToBegin(); !testIterator.IsAtEnd(); ++testIterator){
	  if(testIterator.Get() == 1)
      testValue = testValue + 1;
  }

  if(referenceValue != testValue){
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;
  //} end testing itkGraphCutSegmentationGridGraphFilter with 3D image

/*
  //{ start testing itkGraphCutSegmentationBoykovFilter with 2D image
  std::cout << "Testing itkGraphCutSegmentationBoykovFilter with 2D image: " <<std::endl;

  testValue2D = 0;
  graphcutFilter2D = GraphCutSegmentationBoykovFilterType2D::New();
  graphcutFilter2D->SetInput(testImage2D);
  graphcutFilter2D->SetParameter_sigma_sqr(64);
  graphcutFilter2D->SetParameter_h(-1);
  graphcutFilter2D->SetIntensityDifference(100);
  graphcutFilter2D->SetGradientMagnitude(90);
  graphcutFilter2D->SetParameter_MaxMagni(15);
  graphcutFilter2D->SetParameter_Exp(8);
  graphcutFilter2D->SetLaplacian(70);
  graphcutFilter2D->SetSeedsImage(seedsImage2D);
  graphcutFilter2D->Update();

  //ImageType2D::Pointer resultImage2D;
  resultImage2D = graphcutFilter2D->GetOutput();

  IteratorType2D testIteratorBoykov2D(resultImage2D, resultImage2D->GetRequestedRegion());
  for (testIteratorBoykov2D.GoToBegin(); !testIteratorBoykov2D.IsAtEnd(); ++testIteratorBoykov2D){
	  if(testIteratorBoykov2D.Get() == 1)
      testValue2D = testValue2D + 1;
  }

  if(referenceValue2D != testValue2D){
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;
  //} end testing itkGraphCutSegmentationBoykovFilter with 2D image

  //{ start testing itkGraphCutSegmentationBoykovFilter with 3D image
  std::cout << "Testing itkGraphCutSegmentationBoykovFilter with 3D image: " <<std::endl;

  testValue = 0;
  graphcutFilter = GraphCutSegmentationBoykovFilterType::New();
  graphcutFilter->SetInput(testImage);
  graphcutFilter->SetParameter_sigma_sqr(64);
  graphcutFilter->SetParameter_h(-1);
  graphcutFilter->SetIntensityDifference(100);
  graphcutFilter->SetGradientMagnitude(90);
  graphcutFilter->SetParameter_MaxMagni(15);
  graphcutFilter->SetParameter_Exp(8);
  graphcutFilter->SetLaplacian(70);
  graphcutFilter->SetSeedsImage(seedsImage);
  graphcutFilter->Update();

  resultImage = graphcutFilter->GetOutput();

  IteratorType testIteratorBoykov(resultImage, resultImage->GetRequestedRegion());
  for (testIteratorBoykov.GoToBegin(); !testIteratorBoykov.IsAtEnd(); ++testIteratorBoykov){
	  if(testIteratorBoykov.Get() == 1)
      testValue = testValue + 1;
  }

  if(referenceValue != testValue){
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;
  //} end testing itkGraphCutSegmentationBoykovFilter with 3D image
*/
std::cout<<"[TEST DONE]"<<std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <bitset>
#include <sstream>
#include <unistd.h>
#include <vector>
#include <algorithm>
#include <list>
#include <map>

#include "segment.h"
#include "message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "execute_success_message.h"
#include "execute_failure_message.h"
#include "execute_request_message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"
#include "terminate_message.h"
#include "rpc.h"
#include "constants.h"
#include "network.h"
#include "helper_functions.h"

using namespace std;

// Global variables for client
static bool connectedToBinder = false;
static int clientBinderSocket = -1;
static int serverBinderSocket = -1;

// Global variables for server
static map<procedure_signature, skeleton, ps_compare> procSkeleDict;
static string serverIdentifier;
static unsigned int port = 0;
static int welcomeSocket = 0;
static bool onSwitch = true;

void mapPrint(){
  cout << "procSkeleDict size: "<<procSkeleDict.size() << endl;

  cout << "Map Print: ";

  for(map<procedure_signature, skeleton>::iterator it = procSkeleDict.begin();
   it != procSkeleDict.end(); ++it){

    cout << it->first.name << ", ";
  }

  cout << endl;
}

void printArgTypes(int * argTypes){
  cout << " Printing argTypes: " ;

  unsigned num = countNumOfArgTypes(argTypes);

  for(int i = 0; i < num; i++){
    cout << argTypes[i] << ", ";
  }
  cout << endl;
}

void printArgs(int * argTypes, void  ** args){
  cout << "Printing args: " ;

  // Parses the argument from the buffer
  unsigned numOfArgs = countNumOfArgTypes(argTypes) - 1;

  cout<<"Number of args: " << numOfArgs << endl;

  for (unsigned int i = 0; i < numOfArgs; i++) {
    int argType = argTypes[i];
    int argTypeInformation =
      (argType & ARG_TYPE_INFORMATION_MASK) >> ARG_TYPE_INFORMATION_SHIFT_AMOUNT;
    int argTypeArrayLength = argType & ARG_TYPE_ARRAY_LENGTH_MASK;
    argTypeArrayLength = (argTypeArrayLength == 0) ? 1: argTypeArrayLength;
    void *arg = args[i];

    switch (argTypeInformation) {
      case ARG_CHAR: {
        cout << "Printing ARG_CHAR: " << endl;
        char *argCharArray = (char *) arg;
        cout << argCharArray << endl;
        break;
      }

      case ARG_SHORT: {
        cout << "Printing ARG_SHORT: " << endl;
        short *argShortArray = (short *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argShortArray[i] << ", ";
        }
        cout << endl;
        break;
      }

      case ARG_INT: {
        cout << "Printing ARG_INT: " << endl;
        int *argIntArray = (int *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argIntArray[j] << ", ";
        }
        cout << endl;
        break;
      }

      case ARG_LONG: {
        cout << "Printing ARG_LONG: " << endl;
        long *argLongArray = (long *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argLongArray[j] << ",";
        }
        cout << endl;
        break;
      }

      case ARG_DOUBLE: {
        cout << "Printing ARG_DOUBLE: " << endl;
        double *argDoubleArray = (double *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argDoubleArray[j] << ", ";
        }
        cout << endl;
        break;
      }

      case ARG_FLOAT: {
        cout << "Printing ARG_FLOAT: " << endl;
        float *argFloatArray = (float *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argFloatArray[j] << ", ";
        }
        cout << endl;
        break;
      }
    }
  }
  cout << endl;
}

// See interface (header file).
int rpcInit(){
	cout << "Running rpcInit..." << endl;

	/*
   * Creates a connection socket to be used for accepting connections
	 * from clients
   */
	welcomeSocket = createSocket();
	setUpToListen(welcomeSocket);
	serverIdentifier = getHostAddress();
	port = getSocketPort(welcomeSocket);

  cout << "This servers welcomeSocket is: " << welcomeSocket << endl;

	// Opens a connection to the binderz
	serverBinderSocket = createSocket();
	string binderAddress = getBinderAddress();
	unsigned int binderPort = getBinderPort();
	setUpToConnect(serverBinderSocket, binderAddress, binderPort);
  connectedToBinder = true;

  cout << "This servers serverBinderSocket is: " << serverBinderSocket << endl;

  return 0;
}

// See interface (header file).
int rpcCall(char *name, int *argTypes, void **args) {
  cout << "Running rpcCall..." << endl;

	string serverAddress;
	unsigned int serverPort = 0;
	int status;

	if(!connectedToBinder){
    cout << "Connecting to binder..." << endl;
		clientBinderSocket = createSocket();
		string binderAddress = getBinderAddress();
		unsigned int binderPort = getBinderPort();
		status = setUpToConnect(clientBinderSocket, binderAddress, binderPort);
	  connectedToBinder = true;
    cout << "Connected to binder..." << endl;
	}
	//do something with returnVal

  LocRequestMessage messageToBinder = LocRequestMessage(string(name), argTypes);
  Segment segmentToBinder =
	  Segment(messageToBinder.getLength(), MSG_TYPE_LOC_REQUEST, &messageToBinder);
  int binder_status = segmentToBinder.send(clientBinderSocket);
  cout << "LOC REQUEST message sent..." << endl;

	//maybe error check with binder_status
  //TODO: SEGMENT FAULT IF NOT IN THIS FOR LOOP
	/**Server stuff **/
	if(binder_status >= 0){

    Segment *parsedSegment = 0;
    int tempStatus = 0;
    tempStatus = Segment::receive(clientBinderSocket, parsedSegment);

    Message *messageFromBinder = parsedSegment->getMessage();
		switch (parsedSegment->getType()) {
			case MSG_TYPE_LOC_SUCCESS: {
				cout << "LOC SUCCESS message received..." << endl;
        LocSuccessMessage *lsm =
				  dynamic_cast<LocSuccessMessage *>(messageFromBinder);
				serverAddress = lsm->getServerIdentifier();
				serverPort = lsm->getPort();
				cout << "serverAddress: " << serverAddress << endl;
        cout << "serverPort: " << serverPort << endl;
        break;
			}

			case MSG_TYPE_LOC_FAILURE: {
        cout << "LOC FAILURE message received..." << endl;
				return -1;
				break;
			}
		}
	}

  cout << "Connecting to server..." << endl;
  int serverSocket = createSocket();
	int status1 = setUpToConnect(serverSocket, serverAddress, serverPort);

  cout << "status1: " << status1 << endl;
  cout << "Server Socket: " << serverSocket << endl;
  cout << "Server Address: " << serverAddress << endl;
  cout << "Server Port: " << serverPort << endl;
  cout << "Connected to server..." << endl;

  ExecuteRequestMessage exeReqMsg = ExecuteRequestMessage(name, argTypes, args);
  Segment exeReqSeg = Segment(exeReqMsg.getLength(), MSG_TYPE_EXECUTE_REQUEST, &exeReqMsg);
  int status2 =  exeReqSeg.send(serverSocket);

  cout << "Status of exeRegMsg send: " << status2 << endl;

  int returnVal = 0;

  Segment * parsedSegmentEsm = 0;
  int status3 = 0;
  status3 = Segment::receive(serverSocket, parsedSegmentEsm);
  cout << "Flag 1" << endl;

  //instead we have

  cout << "Flag 2" << endl;

  switch (parsedSegmentEsm->getType()) {
    case MSG_TYPE_EXECUTE_SUCCESS: {
      cout << "EXECUTE SUCCESS message received..." << endl;

      Message * msg = parsedSegmentEsm->getMessage();
      ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(msg);

      // TODO FIX: name = esm->getName();
      //argTypes = esm->getArgTypes();
      void** newArgs = esm->getArgs();
      unsigned numOfArgs = countNumOfArgTypes(esm->getArgTypes()) - 1;

      for (unsigned int i = 0; i < numOfArgs; i++) {
        args[i] = newArgs[i];
      }

      break;
    }

    case MSG_TYPE_EXECUTE_FAILURE: {
      cout << "EXECUTE FAILURE message received..." << endl;

      Message * cast = parsedSegmentEsm->getMessage();
      ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast);
      returnVal = efm->getReasonCode();
      break;
    }
  }

  close(serverSocket);
  return returnVal;
}

  //TODO:
  // CREATE SERVER
  // CONNECT TO BINDER

int rpcRegister(char * name, int *argTypes, skeleton f){
  cout << "Running rpcRegister..." << endl;
  RegisterRequestMessage regReqMsg = RegisterRequestMessage(serverIdentifier, port, name, argTypes);

  /*
  cout << "rpcRegister name: " << name << endl;
  cout << "rpcRegister serverIdentifier: " << serverIdentifier << endl;
  cout << "rpcRegister port: " << port << endl;
  */

  /*
  We should get seg.send to give us some feed back maybe
  int status = regReqMsg->send(serverBinderSocket);
  */

  Segment regReqSeg = Segment(regReqMsg.getLength(), MSG_TYPE_REGISTER_REQUEST, &regReqMsg);
  int status = regReqSeg.send(serverBinderSocket);

  cout << "When we register we use this serverBinderSocket: " << serverBinderSocket << endl;
  //cout << "rpcRegister Status: " << status << endl;

  if(status >= 0){
    //Success
    Segment *parsedSegment = 0;
    int result = 0;
    result = Segment::receive(serverBinderSocket, parsedSegment);

    if(parsedSegment->getType() == MSG_TYPE_REGISTER_SUCCESS){

      cout << "MSG_TYPE_REGISTER_SUCCESS" << endl;

      Message * cast = parsedSegment->getMessage();
      //Error Checking maybe
      RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast);

      //struct procedure_signature k(string(name), argTypes);
      struct procedure_signature k = procedure_signature(string(name), argTypes);

      procSkeleDict[k] = f;

      cout << "k: " << k.name << ", "<< f << endl;

    }else if(parsedSegment->getType() == MSG_TYPE_REGISTER_FAILURE){
      return 0;
    }

  }else if( status < 0){
    //Error
    return -99;
  }

  return 1;
}

// See interface (header file).
int rpcExecute(){
  cout << "Running rpcExecute..." << endl;
  fd_set allSockets;
  fd_set readSockets;

  /*
   * Clears all entries from the all sockets set and the read
   * sockets set
   */
  FD_ZERO(&allSockets);
  FD_ZERO(&readSockets);

  /*
   * Adds the welcome socket to the all sockets set and sets
   * it as the maximum socket so far
   */
  FD_SET(serverBinderSocket, &allSockets);
  FD_SET(welcomeSocket, &allSockets);
  int maxSocket = welcomeSocket;

  while (onSwitch) {
    readSockets = allSockets;

    // Checks if some of the sockets are ready to be read from
    int result = select(maxSocket + 1, &readSockets, 0, 0, 0);
    if (result < 0) {
      continue;
    }

    for (int i = 0; i <= maxSocket; i++) {
      if (!FD_ISSET(i, &readSockets)) {
        continue;
      }

      if (i == welcomeSocket) {

        /*
         * Creates the connection socket when a connection is made
         * to the welcome socket
         */
        int connectionSocket = acceptConnection(i);
        if (connectionSocket < 0) {
          continue;
        }

        // Adds the connection socket to the all sockets set
        FD_SET(connectionSocket, &allSockets);

        /*
         * Sets the connection socket as the maximum socket so far
         * if necessary
         */
        if (connectionSocket > maxSocket) {
          maxSocket = connectionSocket;
        }

      } else {

        /*
         * Creates a segment to receive data from the client/binder and
         * reads into it from the connection socket
         */
        Segment *segment = 0;
        result = 0;
        result = Segment::receive(i, segment);
        if (result < 0) {
          /*
           * Closes the connection socket and removes it from the
           * all sockets set
           */
          cout << "Bad result, I'm closing, i is: "<< i << endl;
          destroySocket(i);
          FD_CLR(i, &allSockets);
          continue;
        }

        switch (segment->getType()) {
          case MSG_TYPE_EXECUTE_REQUEST: {
            Message * cast = segment->getMessage();
            ExecuteRequestMessage * erm = dynamic_cast<ExecuteRequestMessage*>(cast);

            procedure_signature * ps = new procedure_signature(erm->getName(), erm->getArgTypes());

            cout << "erm->getName(): " << erm->getName() << endl;
            printArgTypes(erm->getArgTypes());
            printArgs(erm->getArgTypes(), erm->getArgs());

            skeleton skel = procSkeleDict[*ps];

            if(skel == 0){
              cout << "Skel is null" << endl;
            }

            int result = skel(erm->getArgTypes(), erm->getArgs());

            cout << "Result: " << result << endl;
            printArgs(erm->getArgTypes(), erm->getArgs());

            if(result == 0 ){
              ExecuteSuccessMessage exeSuccessMsg = ExecuteSuccessMessage(erm->getName(), erm->getArgTypes(), erm->getArgs());
              Segment exeSuccessSeg = Segment(exeSuccessMsg.getLength(), MSG_TYPE_EXECUTE_SUCCESS, &exeSuccessMsg);
              int tstatus = exeSuccessSeg.send(i);
              cout << "ExecuteSuccessMessage status: " << tstatus << endl;

            }else{
              ExecuteFailureMessage exeFailMsg = ExecuteFailureMessage(result);
              Segment exeFailSeg = Segment(exeFailMsg.getLength(), MSG_TYPE_EXECUTE_FAILURE, &exeFailMsg);
              int tstatus = exeFailSeg.send(i);
            }

            break;
          }

          case MSG_TYPE_TERMINATE: {
            cout << "Got to terminate" << endl;
            if (i != serverBinderSocket) {
               return ERROR_CODE_TERMINATE;
            }
            onSwitch = false;
            break;
          }
        }

      }
    }
  }

  // Destroys the welcome socket
  cout << "We are destorying the welcomeSocket: " << welcomeSocket << endl;
  destroySocket(welcomeSocket);

  return SUCCESS_CODE;
}

int rpcCacheCall() {
  cout << "Running rpcCacheCall..." << endl;
	return SUCCESS_CODE;
}

int rpcTerminate() {
	cout << "Running rpcTerminate..." << endl;

  // Sends a terminate message to the binder
  TerminateMessage messageToBinder = TerminateMessage();
  Segment segmentToBinder =
    Segment(messageToBinder.getLength(), MSG_TYPE_TERMINATE, &messageToBinder);
  int binder_status = segmentToBinder.send(serverBinderSocket);
  cout << segmentToBinder.getType() << endl;

  cout << "serverBinderSocket: " << serverBinderSocket << endl;
  // Closes the connection to the binder
  destroySocket(serverBinderSocket);

	return SUCCESS_CODE;
}
<commit_msg>changes<commit_after>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <bitset>
#include <sstream>
#include <unistd.h>
#include <vector>
#include <algorithm>
#include <list>
#include <map>

#include "segment.h"
#include "message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "execute_success_message.h"
#include "execute_failure_message.h"
#include "execute_request_message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"
#include "terminate_message.h"
#include "rpc.h"
#include "constants.h"
#include "network.h"
#include "helper_functions.h"

using namespace std;

// Global variables for client
static bool connectedToBinder = false;
static int clientBinderSocket = -1;
static int serverBinderSocket = -1;

// Global variables for server
static map<procedure_signature, skeleton, ps_compare> procSkeleDict;
static string serverIdentifier;
static unsigned int port = 0;
static int welcomeSocket = 0;
static bool onSwitch = true;

void mapPrint(){
  cout << "procSkeleDict size: "<<procSkeleDict.size() << endl;

  cout << "Map Print: ";

  for(map<procedure_signature, skeleton>::iterator it = procSkeleDict.begin();
   it != procSkeleDict.end(); ++it){

    cout << it->first.name << ", ";
  }

  cout << endl;
}

void printArgTypes(int * argTypes){
  cout << " Printing argTypes: " ;

  unsigned num = countNumOfArgTypes(argTypes);

  for(int i = 0; i < num; i++){
    cout << argTypes[i] << ", ";
  }
  cout << endl;
}

void printArgs(int * argTypes, void  ** args){
  cout << "Printing args: " ;

  // Parses the argument from the buffer
  unsigned numOfArgs = countNumOfArgTypes(argTypes) - 1;

  cout<<"Number of args: " << numOfArgs << endl;

  for (unsigned int i = 0; i < numOfArgs; i++) {
    int argType = argTypes[i];
    int argTypeInformation =
      (argType & ARG_TYPE_INFORMATION_MASK) >> ARG_TYPE_INFORMATION_SHIFT_AMOUNT;
    int argTypeArrayLength = argType & ARG_TYPE_ARRAY_LENGTH_MASK;
    argTypeArrayLength = (argTypeArrayLength == 0) ? 1: argTypeArrayLength;
    void *arg = args[i];

    switch (argTypeInformation) {
      case ARG_CHAR: {
        cout << "Printing ARG_CHAR: " << endl;
        char *argCharArray = (char *) arg;
        cout << argCharArray << endl;
        break;
      }

      case ARG_SHORT: {
        cout << "Printing ARG_SHORT: " << endl;
        short *argShortArray = (short *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argShortArray[i] << ", ";
        }
        cout << endl;
        break;
      }

      case ARG_INT: {
        cout << "Printing ARG_INT: " << endl;
        int *argIntArray = (int *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argIntArray[j] << ", ";
        }
        cout << endl;
        break;
      }

      case ARG_LONG: {
        cout << "Printing ARG_LONG: " << endl;
        long *argLongArray = (long *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argLongArray[j] << ",";
        }
        cout << endl;
        break;
      }

      case ARG_DOUBLE: {
        cout << "Printing ARG_DOUBLE: " << endl;
        double *argDoubleArray = (double *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argDoubleArray[j] << ", ";
        }
        cout << endl;
        break;
      }

      case ARG_FLOAT: {
        cout << "Printing ARG_FLOAT: " << endl;
        float *argFloatArray = (float *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argFloatArray[j] << ", ";
        }
        cout << endl;
        break;
      }
    }
  }
  cout << endl;
}

// See interface (header file).
int rpcInit(){
	cout << "Running rpcInit..." << endl;

	/*
   * Creates a connection socket to be used for accepting connections
	 * from clients
   */
	welcomeSocket = createSocket();
	setUpToListen(welcomeSocket);
	serverIdentifier = getHostAddress();
	port = getSocketPort(welcomeSocket);

  cout << "This servers welcomeSocket is: " << welcomeSocket << endl;

	// Opens a connection to the binderz
	serverBinderSocket = createSocket();
	string binderAddress = getBinderAddress();
	unsigned int binderPort = getBinderPort();
	setUpToConnect(serverBinderSocket, binderAddress, binderPort);
  connectedToBinder = true;

  cout << "This servers serverBinderSocket is: " << serverBinderSocket << endl;

  return 0;
}

// See interface (header file).
int rpcCall(char *name, int *argTypes, void **args) {
  cout << "Running rpcCall..." << endl;

	string serverAddress;
	unsigned int serverPort = 0;
	int status;

	if(!connectedToBinder){
    cout << "Connecting to binder..." << endl;
		clientBinderSocket = createSocket();
		string binderAddress = getBinderAddress();
		unsigned int binderPort = getBinderPort();
		status = setUpToConnect(clientBinderSocket, binderAddress, binderPort);
	  connectedToBinder = true;
    cout << "Connected to binder..." << endl;
	}
	//do something with returnVal

  LocRequestMessage messageToBinder = LocRequestMessage(string(name), argTypes);
  Segment segmentToBinder =
	  Segment(messageToBinder.getLength(), MSG_TYPE_LOC_REQUEST, &messageToBinder);
  int binder_status = segmentToBinder.send(clientBinderSocket);
  cout << "LOC REQUEST message sent..." << endl;

	//maybe error check with binder_status
  //TODO: SEGMENT FAULT IF NOT IN THIS FOR LOOP
	/**Server stuff **/
	if(binder_status >= 0){

    Segment *parsedSegment = 0;
    int tempStatus = 0;
    tempStatus = Segment::receive(clientBinderSocket, parsedSegment);

    Message *messageFromBinder = parsedSegment->getMessage();
		switch (parsedSegment->getType()) {
			case MSG_TYPE_LOC_SUCCESS: {
				cout << "LOC SUCCESS message received..." << endl;
        LocSuccessMessage *lsm =
				  dynamic_cast<LocSuccessMessage *>(messageFromBinder);
				serverAddress = lsm->getServerIdentifier();
				serverPort = lsm->getPort();
				cout << "serverAddress: " << serverAddress << endl;
        cout << "serverPort: " << serverPort << endl;
        break;
			}

			case MSG_TYPE_LOC_FAILURE: {
        cout << "LOC FAILURE message received..." << endl;
				return -1;
				break;
			}
		}
	}

  cout << "Connecting to server..." << endl;
  int serverSocket = createSocket();
	int status1 = setUpToConnect(serverSocket, serverAddress, serverPort);

  cout << "status1: " << status1 << endl;
  cout << "Server Socket: " << serverSocket << endl;
  cout << "Server Address: " << serverAddress << endl;
  cout << "Server Port: " << serverPort << endl;
  cout << "Connected to server..." << endl;

  ExecuteRequestMessage exeReqMsg = ExecuteRequestMessage(name, argTypes, args);
  Segment exeReqSeg = Segment(exeReqMsg.getLength(), MSG_TYPE_EXECUTE_REQUEST, &exeReqMsg);
  int status2 =  exeReqSeg.send(serverSocket);

  cout << "Status of exeRegMsg send: " << status2 << endl;

  int returnVal = 0;

  Segment * parsedSegmentEsm = 0;
  int status3 = 0;
  status3 = Segment::receive(serverSocket, parsedSegmentEsm);
  cout << "Flag 1" << endl;

  //instead we have

  cout << "Flag 2" << endl;

  switch (parsedSegmentEsm->getType()) {
    case MSG_TYPE_EXECUTE_SUCCESS: {
      cout << "EXECUTE SUCCESS message received..." << endl;

      Message * msg = parsedSegmentEsm->getMessage();
      ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(msg);

      // TODO FIX: name = esm->getName();
      //argTypes = esm->getArgTypes();
      void** newArgs = esm->getArgs();
      unsigned numOfArgs = countNumOfArgTypes(esm->getArgTypes()) - 1;

      for (unsigned int i = 0; i < numOfArgs; i++) {
        args[i] = newArgs[i];
      }

      break;
    }

    case MSG_TYPE_EXECUTE_FAILURE: {
      cout << "EXECUTE FAILURE message received..." << endl;

      Message * cast = parsedSegmentEsm->getMessage();
      ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast);
      returnVal = efm->getReasonCode();
      break;
    }
  }

  close(serverSocket);
  return returnVal;
}

  //TODO:
  // CREATE SERVER
  // CONNECT TO BINDER

int rpcRegister(char * name, int *argTypes, skeleton f){
  cout << "Running rpcRegister..." << endl;
  RegisterRequestMessage regReqMsg = RegisterRequestMessage(serverIdentifier, port, name, argTypes);

  /*
  cout << "rpcRegister name: " << name << endl;
  cout << "rpcRegister serverIdentifier: " << serverIdentifier << endl;
  cout << "rpcRegister port: " << port << endl;
  */

  /*
  We should get seg.send to give us some feed back maybe
  int status = regReqMsg->send(serverBinderSocket);
  */

  Segment regReqSeg = Segment(regReqMsg.getLength(), MSG_TYPE_REGISTER_REQUEST, &regReqMsg);
  int status = regReqSeg.send(serverBinderSocket);

  cout << "When we register we use this serverBinderSocket: " << serverBinderSocket << endl;
  //cout << "rpcRegister Status: " << status << endl;

  if(status >= 0){
    //Success
    Segment *parsedSegment = 0;
    int result = 0;
    result = Segment::receive(serverBinderSocket, parsedSegment);

    if(parsedSegment->getType() == MSG_TYPE_REGISTER_SUCCESS){

      cout << "MSG_TYPE_REGISTER_SUCCESS" << endl;

      Message * cast = parsedSegment->getMessage();
      //Error Checking maybe
      RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast);

      //struct procedure_signature k(string(name), argTypes);
      struct procedure_signature k = procedure_signature(string(name), argTypes);

      procSkeleDict[k] = f;

      cout << "k: " << k.name << ", "<< f << endl;

    }else if(parsedSegment->getType() == MSG_TYPE_REGISTER_FAILURE){
      return 0;
    }

  }else if( status < 0){
    //Error
    return -99;
  }

  return 1;
}

// See interface (header file).
int rpcExecute(){
  cout << "Running rpcExecute..." << endl;
  fd_set allSockets;
  fd_set readSockets;

  /*
   * Clears all entries from the all sockets set and the read
   * sockets set
   */
  FD_ZERO(&allSockets);
  FD_ZERO(&readSockets);

  /*
   * Adds the welcome socket to the all sockets set and sets
   * it as the maximum socket so far
   */
  FD_SET(serverBinderSocket, &allSockets);
  FD_SET(welcomeSocket, &allSockets);
  int maxSocket = welcomeSocket;

  while (onSwitch) {
    readSockets = allSockets;

    // Checks if some of the sockets are ready to be read from
    int result = select(maxSocket + 1, &readSockets, 0, 0, 0);
    if (result < 0) {
      continue;
    }

    for (int i = 0; i <= maxSocket; i++) {
      if (!FD_ISSET(i, &readSockets)) {
        continue;
      }

      if (i == welcomeSocket) {

        /*
         * Creates the connection socket when a connection is made
         * to the welcome socket
         */
        int connectionSocket = acceptConnection(i);
        if (connectionSocket < 0) {
          continue;
        }

        // Adds the connection socket to the all sockets set
        FD_SET(connectionSocket, &allSockets);

        /*
         * Sets the connection socket as the maximum socket so far
         * if necessary
         */
        if (connectionSocket > maxSocket) {
          maxSocket = connectionSocket;
        }

      } else {

        /*
         * Creates a segment to receive data from the client/binder and
         * reads into it from the connection socket
         */
        Segment *segment = 0;
        result = 0;
        result = Segment::receive(i, segment);
        if (result < 0) {
          /*
           * Closes the connection socket and removes it from the
           * all sockets set
           */
          cout << "Bad result, I'm closing, i is: "<< i << endl;
          destroySocket(i);
          FD_CLR(i, &allSockets);
          continue;
        }

        switch (segment->getType()) {
          case MSG_TYPE_EXECUTE_REQUEST: {
            Message * cast = segment->getMessage();
            ExecuteRequestMessage * erm = dynamic_cast<ExecuteRequestMessage*>(cast);

            procedure_signature * ps = new procedure_signature(erm->getName(), erm->getArgTypes());

            cout << "erm->getName(): " << erm->getName() << endl;
            printArgTypes(erm->getArgTypes());
            printArgs(erm->getArgTypes(), erm->getArgs());

            skeleton skel = procSkeleDict[*ps];

            if(skel == 0){
              cout << "Skel is null" << endl;
            }

            int result = skel(erm->getArgTypes(), erm->getArgs());

            cout << "Result: " << result << endl;
            printArgs(erm->getArgTypes(), erm->getArgs());

            if(result == 0 ){
              ExecuteSuccessMessage exeSuccessMsg = ExecuteSuccessMessage(erm->getName(), erm->getArgTypes(), erm->getArgs());
              Segment exeSuccessSeg = Segment(exeSuccessMsg.getLength(), MSG_TYPE_EXECUTE_SUCCESS, &exeSuccessMsg);
              int tstatus = exeSuccessSeg.send(i);
              cout << "ExecuteSuccessMessage status: " << tstatus << endl;

            }else{
              ExecuteFailureMessage exeFailMsg = ExecuteFailureMessage(result);
              Segment exeFailSeg = Segment(exeFailMsg.getLength(), MSG_TYPE_EXECUTE_FAILURE, &exeFailMsg);
              int tstatus = exeFailSeg.send(i);
            }

            break;
          }

          case MSG_TYPE_TERMINATE: {
            cout << "Got to terminate" << endl;
            if (i != serverBinderSocket) {
               return ERROR_CODE_TERMINATE;
            }
            onSwitch = false;
            break;
          }
        }

      }
    }
  }

  // Destroys the welcome socket
  cout << "We are destorying the welcomeSocket: " << welcomeSocket << endl;
  destroySocket(welcomeSocket);

  return SUCCESS_CODE;
}

int rpcCacheCall() {
  cout << "Running rpcCacheCall..." << endl;
	return SUCCESS_CODE;
}

int rpcTerminate() {
	cout << "Running rpcTerminate..." << endl;

  // Sends a terminate message to the binder
  TerminateMessage messageToBinder = TerminateMessage();
  Segment segmentToBinder =
    Segment(messageToBinder.getLength(), MSG_TYPE_TERMINATE, &messageToBinder);
  int binder_status = segmentToBinder.send(clientBinderSocket);
  cout << segmentToBinder.getType() << endl;

  cout << "clientBinderSocket: " << clientBinderSocket << endl;
  // Closes the connection to the binder
  destroySocket(clientBinderSocket);

	return SUCCESS_CODE;
}
<|endoftext|>


<commit_before>// Copyright 2013 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/extensions/extension_apitest.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace extensions {

class CrazyExtensionTest : public ExtensionApiTest {
};

IN_PROC_BROWSER_TEST_F(CrazyExtensionTest, Crazy) {
  ASSERT_TRUE(RunExtensionTest("crazy_extension"));
}

}  // namespace extensions
<commit_msg>Disable CrazyExtensionTest.<commit_after>// Copyright 2013 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/extensions/extension_apitest.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace extensions {

class CrazyExtensionTest : public ExtensionApiTest {
};

IN_PROC_BROWSER_TEST_F(DISABLED_CrazyExtensionTest, Crazy) {
  ASSERT_TRUE(RunExtensionTest("crazy_extension"));
}

}  // namespace extensions
<|endoftext|>


<commit_before>// Copyright (c) 2010 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 "base/path_service.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebSocket) {
  FilePath websocket_root_dir;
  PathService::Get(chrome::DIR_TEST_DATA, &websocket_root_dir);
  websocket_root_dir = websocket_root_dir.AppendASCII("layout_tests")
      .AppendASCII("LayoutTests");
  ui_test_utils::TestWebSocketServer server(websocket_root_dir);
  ASSERT_TRUE(RunExtensionTest("websocket")) << message_;
}
<commit_msg>Disable ExtensionApiTest.WebSocket on Mac<commit_after>// Copyright (c) 2010 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 "base/path_service.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

#if defined(OS_MACOSX)
// WebSocket test started timing out - suspect webkit roll from 67965->68051.
// http://crbug.com/56596
#define MAYBE_WebSocket DISABLED_WebSocket
#else
#define MAYBE_WebSocket WebSocket
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_WebSocket) {
  FilePath websocket_root_dir;
  PathService::Get(chrome::DIR_TEST_DATA, &websocket_root_dir);
  websocket_root_dir = websocket_root_dir.AppendASCII("layout_tests")
      .AppendASCII("LayoutTests");
  ui_test_utils::TestWebSocketServer server(websocket_root_dir);
  ASSERT_TRUE(RunExtensionTest("websocket")) << message_;
}
<|endoftext|>


<commit_before>// Copyright (c) 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 "chrome/browser/extensions/user_script_master.h"

#include <fstream>

#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/chrome_thread.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "testing/gtest/include/gtest/gtest.h"

// Test bringing up a master on a specific directory, putting a script
// in there, etc.

class UserScriptMasterTest : public testing::Test,
                             public NotificationObserver {
 public:
  UserScriptMasterTest()
      : message_loop_(MessageLoop::TYPE_UI),
        shared_memory_(NULL) {
  }

  virtual void SetUp() {
    // Name a subdirectory of the temp directory.
    FilePath tmp_dir;
    ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &tmp_dir));
    script_dir_ = tmp_dir.AppendASCII("UserScriptTest");

    // Create a fresh, empty copy of this directory.
    file_util::Delete(script_dir_, true);
    file_util::CreateDirectory(script_dir_);

    // Register for all user script notifications.
    registrar_.Add(this, NotificationType::USER_SCRIPTS_UPDATED,
                   NotificationService::AllSources());

    // UserScriptMaster posts tasks to the file thread so make the current
    // thread look like one.
    file_thread_.reset(new ChromeThread(
        ChromeThread::FILE, MessageLoop::current()));
  }

  virtual void TearDown() {
    // Clean up test directory.
    ASSERT_TRUE(file_util::Delete(script_dir_, true));
    ASSERT_FALSE(file_util::PathExists(script_dir_));
    file_thread_.reset();
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    DCHECK(type == NotificationType::USER_SCRIPTS_UPDATED);

    shared_memory_ = Details<base::SharedMemory>(details).ptr();
    if (MessageLoop::current() == &message_loop_)
      MessageLoop::current()->Quit();
  }

  NotificationRegistrar registrar_;

  // MessageLoop used in tests.
  MessageLoop message_loop_;

  scoped_ptr<ChromeThread> file_thread_;

  // Directory containing user scripts.
  FilePath script_dir_;

  // Updated to the script shared memory when we get notified.
  base::SharedMemory* shared_memory_;
};

// Test that we get notified even when there are no scripts.
TEST_F(UserScriptMasterTest, NoScripts) {
  scoped_refptr<UserScriptMaster> master(new UserScriptMaster(script_dir_));
  master->StartScan();
  message_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask);
  message_loop_.Run();

  ASSERT_TRUE(shared_memory_ != NULL);
}

// TODO(shess): Disabled on Linux because of missing DirectoryWatcher.
#if defined(OS_WIN) || defined(OS_MACOSX)
// Test that we get notified about new scripts after they're added.
TEST_F(UserScriptMasterTest, NewScripts) {
  scoped_refptr<UserScriptMaster> master(new UserScriptMaster(script_dir_));

  FilePath path = script_dir_.AppendASCII("script.user.js");

  const char content[] = "some content";
  size_t written = file_util::WriteFile(path, content, sizeof(content));
  ASSERT_EQ(written, sizeof(content));

  // Post a delayed task so that we fail rather than hanging if things
  // don't work.
  message_loop_.PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask, 5000);

  message_loop_.Run();

  ASSERT_TRUE(shared_memory_ != NULL);
}
#endif

// Test that we get notified about scripts if they're already in the test dir.
TEST_F(UserScriptMasterTest, ExistingScripts) {
  FilePath path = script_dir_.AppendASCII("script.user.js");

  const char content[] = "some content";
  size_t written = file_util::WriteFile(path, content, sizeof(content));
  ASSERT_EQ(written, sizeof(content));

  scoped_refptr<UserScriptMaster> master(new UserScriptMaster(script_dir_));
  master->StartScan();

  message_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask);
  message_loop_.Run();

  ASSERT_TRUE(shared_memory_ != NULL);
}

TEST_F(UserScriptMasterTest, Parse1) {
  const std::string text(
    "// This is my awesome script\n"
    "// It does stuff.\n"
    "// ==UserScript==   trailing garbage\n"
    "// @name foobar script\n"
    "// @namespace http://www.google.com/\n"
    "// @include *mail.google.com*\n"
    "// \n"
    "// @othergarbage\n"
    "// @include *mail.yahoo.com*\r\n"
    "// @include  \t *mail.msn.com*\n" // extra spaces after "@include" OK
    "//@include not-recognized\n" // must have one space after "//"
    "// ==/UserScript==  trailing garbage\n"
    "\n"
    "\n"
    "alert('hoo!');\n");

  UserScript script;
  EXPECT_TRUE(UserScriptMaster::ScriptReloader::ParseMetadataHeader(
      text, &script));
  EXPECT_EQ(3U, script.globs().size());
  EXPECT_EQ("*mail.google.com*", script.globs()[0]);
  EXPECT_EQ("*mail.yahoo.com*", script.globs()[1]);
  EXPECT_EQ("*mail.msn.com*", script.globs()[2]);
}

TEST_F(UserScriptMasterTest, Parse2) {
  const std::string text("default to @include *");

  UserScript script;
  EXPECT_TRUE(UserScriptMaster::ScriptReloader::ParseMetadataHeader(
      text, &script));
  EXPECT_EQ(1U, script.globs().size());
  EXPECT_EQ("*", script.globs()[0]);
}

TEST_F(UserScriptMasterTest, Parse3) {
  const std::string text(
    "// ==UserScript==\n"
    "// @include *foo*\n"
    "// ==/UserScript=="); // no trailing newline

  UserScript script;
  UserScriptMaster::ScriptReloader::ParseMetadataHeader(text, &script);
  EXPECT_EQ(1U, script.globs().size());
  EXPECT_EQ("*foo*", script.globs()[0]);
}

TEST_F(UserScriptMasterTest, Parse4) {
  const std::string text(
    "// ==UserScript==\n"
    "// @match http://*.mail.google.com/*\n"
    "// @match  \t http://mail.yahoo.com/*\n"
    "// ==/UserScript==\n");

  UserScript script;
  EXPECT_TRUE(UserScriptMaster::ScriptReloader::ParseMetadataHeader(
      text, &script));
  EXPECT_EQ(0U, script.globs().size());
  EXPECT_EQ(2U, script.url_patterns().size());
  EXPECT_EQ("http://*.mail.google.com/*",
            script.url_patterns()[0].GetAsString());
  EXPECT_EQ("http://mail.yahoo.com/*",
            script.url_patterns()[1].GetAsString());
}

TEST_F(UserScriptMasterTest, Parse5) {
  const std::string text(
    "// ==UserScript==\n"
    "// @match http://*mail.google.com/*\n"
    "// ==/UserScript==\n");

  // Invalid @match value.
  UserScript script;
  EXPECT_FALSE(UserScriptMaster::ScriptReloader::ParseMetadataHeader(
      text, &script));
}

TEST_F(UserScriptMasterTest, Parse6) {
  const std::string text(
    "// ==UserScript==\n"
    "// @include http://*.mail.google.com/*\n"
    "// @match  \t http://mail.yahoo.com/*\n"
    "// ==/UserScript==\n");

  // Allowed to match @include and @match.
  UserScript script;
  EXPECT_TRUE(UserScriptMaster::ScriptReloader::ParseMetadataHeader(
      text, &script));
}
<commit_msg>Tiny clean up. Use ASSERT_EQ instead of EXPECT_EQ.<commit_after>// Copyright (c) 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 "chrome/browser/extensions/user_script_master.h"

#include <string>

#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/chrome_thread.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "testing/gtest/include/gtest/gtest.h"

// Test bringing up a master on a specific directory, putting a script
// in there, etc.

class UserScriptMasterTest : public testing::Test,
                             public NotificationObserver {
 public:
  UserScriptMasterTest()
      : message_loop_(MessageLoop::TYPE_UI),
        shared_memory_(NULL) {
  }

  virtual void SetUp() {
    // Name a subdirectory of the temp directory.
    FilePath tmp_dir;
    ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &tmp_dir));
    script_dir_ = tmp_dir.AppendASCII("UserScriptTest");

    // Create a fresh, empty copy of this directory.
    file_util::Delete(script_dir_, true);
    file_util::CreateDirectory(script_dir_);

    // Register for all user script notifications.
    registrar_.Add(this, NotificationType::USER_SCRIPTS_UPDATED,
                   NotificationService::AllSources());

    // UserScriptMaster posts tasks to the file thread so make the current
    // thread look like one.
    file_thread_.reset(new ChromeThread(
        ChromeThread::FILE, MessageLoop::current()));
  }

  virtual void TearDown() {
    // Clean up test directory.
    ASSERT_TRUE(file_util::Delete(script_dir_, true));
    ASSERT_FALSE(file_util::PathExists(script_dir_));
    file_thread_.reset();
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    DCHECK(type == NotificationType::USER_SCRIPTS_UPDATED);

    shared_memory_ = Details<base::SharedMemory>(details).ptr();
    if (MessageLoop::current() == &message_loop_)
      MessageLoop::current()->Quit();
  }

  NotificationRegistrar registrar_;

  // MessageLoop used in tests.
  MessageLoop message_loop_;

  scoped_ptr<ChromeThread> file_thread_;

  // Directory containing user scripts.
  FilePath script_dir_;

  // Updated to the script shared memory when we get notified.
  base::SharedMemory* shared_memory_;
};

// Test that we get notified even when there are no scripts.
TEST_F(UserScriptMasterTest, NoScripts) {
  scoped_refptr<UserScriptMaster> master(new UserScriptMaster(script_dir_));
  master->StartScan();
  message_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask);
  message_loop_.Run();

  ASSERT_TRUE(shared_memory_ != NULL);
}

// TODO(shess): Disabled on Linux because of missing DirectoryWatcher.
#if defined(OS_WIN) || defined(OS_MACOSX)
// Test that we get notified about new scripts after they're added.
TEST_F(UserScriptMasterTest, NewScripts) {
  scoped_refptr<UserScriptMaster> master(new UserScriptMaster(script_dir_));

  FilePath path = script_dir_.AppendASCII("script.user.js");

  const char content[] = "some content";
  size_t written = file_util::WriteFile(path, content, sizeof(content));
  ASSERT_EQ(written, sizeof(content));

  // Post a delayed task so that we fail rather than hanging if things
  // don't work.
  message_loop_.PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask, 5000);

  message_loop_.Run();

  ASSERT_TRUE(shared_memory_ != NULL);
}
#endif

// Test that we get notified about scripts if they're already in the test dir.
TEST_F(UserScriptMasterTest, ExistingScripts) {
  FilePath path = script_dir_.AppendASCII("script.user.js");

  const char content[] = "some content";
  size_t written = file_util::WriteFile(path, content, sizeof(content));
  ASSERT_EQ(written, sizeof(content));

  scoped_refptr<UserScriptMaster> master(new UserScriptMaster(script_dir_));
  master->StartScan();

  message_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask);
  message_loop_.Run();

  ASSERT_TRUE(shared_memory_ != NULL);
}

TEST_F(UserScriptMasterTest, Parse1) {
  const std::string text(
    "// This is my awesome script\n"
    "// It does stuff.\n"
    "// ==UserScript==   trailing garbage\n"
    "// @name foobar script\n"
    "// @namespace http://www.google.com/\n"
    "// @include *mail.google.com*\n"
    "// \n"
    "// @othergarbage\n"
    "// @include *mail.yahoo.com*\r\n"
    "// @include  \t *mail.msn.com*\n" // extra spaces after "@include" OK
    "//@include not-recognized\n" // must have one space after "//"
    "// ==/UserScript==  trailing garbage\n"
    "\n"
    "\n"
    "alert('hoo!');\n");

  UserScript script;
  EXPECT_TRUE(UserScriptMaster::ScriptReloader::ParseMetadataHeader(
      text, &script));
  ASSERT_EQ(3U, script.globs().size());
  EXPECT_EQ("*mail.google.com*", script.globs()[0]);
  EXPECT_EQ("*mail.yahoo.com*", script.globs()[1]);
  EXPECT_EQ("*mail.msn.com*", script.globs()[2]);
}

TEST_F(UserScriptMasterTest, Parse2) {
  const std::string text("default to @include *");

  UserScript script;
  EXPECT_TRUE(UserScriptMaster::ScriptReloader::ParseMetadataHeader(
      text, &script));
  ASSERT_EQ(1U, script.globs().size());
  EXPECT_EQ("*", script.globs()[0]);
}

TEST_F(UserScriptMasterTest, Parse3) {
  const std::string text(
    "// ==UserScript==\n"
    "// @include *foo*\n"
    "// ==/UserScript=="); // no trailing newline

  UserScript script;
  UserScriptMaster::ScriptReloader::ParseMetadataHeader(text, &script);
  ASSERT_EQ(1U, script.globs().size());
  EXPECT_EQ("*foo*", script.globs()[0]);
}

TEST_F(UserScriptMasterTest, Parse4) {
  const std::string text(
    "// ==UserScript==\n"
    "// @match http://*.mail.google.com/*\n"
    "// @match  \t http://mail.yahoo.com/*\n"
    "// ==/UserScript==\n");

  UserScript script;
  EXPECT_TRUE(UserScriptMaster::ScriptReloader::ParseMetadataHeader(
      text, &script));
  EXPECT_EQ(0U, script.globs().size());
  ASSERT_EQ(2U, script.url_patterns().size());
  EXPECT_EQ("http://*.mail.google.com/*",
            script.url_patterns()[0].GetAsString());
  EXPECT_EQ("http://mail.yahoo.com/*",
            script.url_patterns()[1].GetAsString());
}

TEST_F(UserScriptMasterTest, Parse5) {
  const std::string text(
    "// ==UserScript==\n"
    "// @match http://*mail.google.com/*\n"
    "// ==/UserScript==\n");

  // Invalid @match value.
  UserScript script;
  EXPECT_FALSE(UserScriptMaster::ScriptReloader::ParseMetadataHeader(
      text, &script));
}

TEST_F(UserScriptMasterTest, Parse6) {
  const std::string text(
    "// ==UserScript==\n"
    "// @include http://*.mail.google.com/*\n"
    "// @match  \t http://mail.yahoo.com/*\n"
    "// ==/UserScript==\n");

  // Allowed to match @include and @match.
  UserScript script;
  EXPECT_TRUE(UserScriptMaster::ScriptReloader::ParseMetadataHeader(
      text, &script));
}
<|endoftext|>


<commit_before>// Copyright (c) 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 "chrome/browser/template_url.h"
#include "chrome/browser/template_url_prepopulate_data.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"

typedef testing::Test TemplateURLPrepopulateDataTest;

// Verifies the set of prepopulate data doesn't contain entries with duplicate
// ids.
TEST_F(TemplateURLPrepopulateDataTest, UniqueIDs) {
  // GEO ids.
  int ids[] = { 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC,
                0xE, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
                0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x20, 0x22, 0x23, 0x25, 0x26,
                0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x31, 0x32,
                0x33, 0x36, 0x37, 0x38, 0x39, 0x3B, 0x3D, 0x3E, 0x3F, 0x41,
                0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4B, 0x4D,
                0x4E, 0x50, 0x51, 0x54, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B,
                0x5D, 0x5E, 0x62, 0x63, 0x64, 0x65, 0x67, 0x68, 0x6A, 0x6C,
                0x6D, 0x6E, 0x6F, 0x71, 0x72, 0x74, 0x75, 0x76, 0x77, 0x79,
                0x7A, 0x7C, 0x7D, 0x7E, 0x7F, 0x81, 0x82, 0x83, 0x85, 0x86,
                0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x91, 0x92,
                0x93, 0x94, 0x95, 0x97, 0x98, 0x9A, 0x9C, 0x9D, 0x9E, 0x9F,
                0xA0, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xAD, 0xAE,
                0xAF, 0xB0, 0xB1, 0xB2, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9,
                0xBB, 0xBE, 0xBF, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6,
                0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0,
                0xD1, 0xD2, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB,
                0xDC, 0xDD, 0xDE, 0xDF, 0xE0, 0xE1, 0xE3, 0xE4, 0xE7, 0xE8,
                0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2,
                0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFB, 0xFC, 0xFD, 0xFE,
                0x102, 0x103, 0x104, 0x105, 0x107, 0x108, 0x10D, 0x12C, 0x12D,
                0x12E, 0x12F, 0x130, 0x131, 0x132, 0x133, 0x134, 0x135, 0x136,
                0x137, 0x138, 0x139, 0x13A, 0x13B, 0x13D, 0x13E, 0x13F, 0x141,
                0x142, 0x143, 0x144, 0x145, 0x146, 0x147, 0x148, 0x149, 0x14A,
                0x14B, 0x14C, 0x14D, 0x14E, 0x14F, 0x150, 0x151, 0x152, 0x153,
                0x154, 0x155, 0x156, 0x157, 0x15A, 0x15B, 0x15C, 0x15D, 0x15F,
                0x160, 0x3B16, 0x4CA2, 0x52FA, 0x6F60E7, -1 };
  TestingProfile profile;
  for (size_t i = 0; i < arraysize(ids); ++i) {
    profile.GetPrefs()->SetInteger(prefs::kGeoIDAtInstall, ids[i]);
    std::vector<TemplateURL*> urls;
    size_t url_count;
    TemplateURLPrepopulateData::GetPrepopulatedEngines(
        profile.GetPrefs(), &urls, &url_count);
    std::set<int> unique_ids;
    for (size_t turl_i = 0; turl_i < urls.size(); ++turl_i) {
      ASSERT_TRUE(unique_ids.find(urls[turl_i]->prepopulate_id()) ==
                  unique_ids.end());
      unique_ids.insert(urls[turl_i]->prepopulate_id());
    }
  }
}
<commit_msg>Fixes leak in new test.<commit_after>// Copyright (c) 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 "chrome/browser/template_url.h"
#include "chrome/browser/template_url_prepopulate_data.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/scoped_vector.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"

typedef testing::Test TemplateURLPrepopulateDataTest;

// Verifies the set of prepopulate data doesn't contain entries with duplicate
// ids.
TEST_F(TemplateURLPrepopulateDataTest, UniqueIDs) {
  // GEO ids.
  int ids[] = { 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC,
                0xE, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
                0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x20, 0x22, 0x23, 0x25, 0x26,
                0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x31, 0x32,
                0x33, 0x36, 0x37, 0x38, 0x39, 0x3B, 0x3D, 0x3E, 0x3F, 0x41,
                0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4B, 0x4D,
                0x4E, 0x50, 0x51, 0x54, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B,
                0x5D, 0x5E, 0x62, 0x63, 0x64, 0x65, 0x67, 0x68, 0x6A, 0x6C,
                0x6D, 0x6E, 0x6F, 0x71, 0x72, 0x74, 0x75, 0x76, 0x77, 0x79,
                0x7A, 0x7C, 0x7D, 0x7E, 0x7F, 0x81, 0x82, 0x83, 0x85, 0x86,
                0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x91, 0x92,
                0x93, 0x94, 0x95, 0x97, 0x98, 0x9A, 0x9C, 0x9D, 0x9E, 0x9F,
                0xA0, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xAD, 0xAE,
                0xAF, 0xB0, 0xB1, 0xB2, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9,
                0xBB, 0xBE, 0xBF, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6,
                0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0,
                0xD1, 0xD2, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB,
                0xDC, 0xDD, 0xDE, 0xDF, 0xE0, 0xE1, 0xE3, 0xE4, 0xE7, 0xE8,
                0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2,
                0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFB, 0xFC, 0xFD, 0xFE,
                0x102, 0x103, 0x104, 0x105, 0x107, 0x108, 0x10D, 0x12C, 0x12D,
                0x12E, 0x12F, 0x130, 0x131, 0x132, 0x133, 0x134, 0x135, 0x136,
                0x137, 0x138, 0x139, 0x13A, 0x13B, 0x13D, 0x13E, 0x13F, 0x141,
                0x142, 0x143, 0x144, 0x145, 0x146, 0x147, 0x148, 0x149, 0x14A,
                0x14B, 0x14C, 0x14D, 0x14E, 0x14F, 0x150, 0x151, 0x152, 0x153,
                0x154, 0x155, 0x156, 0x157, 0x15A, 0x15B, 0x15C, 0x15D, 0x15F,
                0x160, 0x3B16, 0x4CA2, 0x52FA, 0x6F60E7, -1 };
  TestingProfile profile;
  for (size_t i = 0; i < arraysize(ids); ++i) {
    profile.GetPrefs()->SetInteger(prefs::kGeoIDAtInstall, ids[i]);
    ScopedVector<TemplateURL> urls;
    size_t url_count;
    TemplateURLPrepopulateData::GetPrepopulatedEngines(
        profile.GetPrefs(), &(urls.get()), &url_count);
    std::set<int> unique_ids;
    for (size_t turl_i = 0; turl_i < urls.size(); ++turl_i) {
      ASSERT_TRUE(unique_ids.find(urls[turl_i]->prepopulate_id()) ==
                  unique_ids.end());
      unique_ids.insert(urls[turl_i]->prepopulate_id());
    }
  }
}
<|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 "chrome/common/extensions/extension_file_util.h"

#include "base/file_util.h"
#include "base/json/json_value_serializer.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace keys = extension_manifest_keys;

TEST(ExtensionFileUtil, InstallUninstallGarbageCollect) {
  ScopedTempDir temp;
  ASSERT_TRUE(temp.CreateUniqueTempDir());

  // Create a source extension.
  std::string extension_id("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
  std::string version("1.0");
  FilePath src = temp.path().AppendASCII(extension_id);
  ASSERT_TRUE(file_util::CreateDirectory(src));

  // Create a extensions tree.
  FilePath all_extensions = temp.path().AppendASCII("extensions");
  ASSERT_TRUE(file_util::CreateDirectory(all_extensions));

  // Install in empty directory. Should create parent directories as needed.
  FilePath version_1 = extension_file_util::InstallExtension(src,
                                                             extension_id,
                                                             version,
                                                             all_extensions);
  ASSERT_EQ(version_1.value(),
            all_extensions.AppendASCII(extension_id).AppendASCII("1.0_0")
                .value());
  ASSERT_TRUE(file_util::DirectoryExists(version_1));

  // Should have moved the source.
  ASSERT_FALSE(file_util::DirectoryExists(src));

  // Install again. Should create a new one with different name.
  ASSERT_TRUE(file_util::CreateDirectory(src));
  FilePath version_2 = extension_file_util::InstallExtension(src,
                                                             extension_id,
                                                             version,
                                                             all_extensions);
  ASSERT_EQ(version_2.value(),
            all_extensions.AppendASCII(extension_id).AppendASCII("1.0_1")
                .value());
  ASSERT_TRUE(file_util::DirectoryExists(version_2));

  // Collect garbage. Should remove first one.
  std::map<std::string, FilePath> extension_paths;
  extension_paths[extension_id] =
      FilePath().AppendASCII(extension_id).Append(version_2.BaseName());
  extension_file_util::GarbageCollectExtensions(all_extensions,
                                                extension_paths);
  ASSERT_FALSE(file_util::DirectoryExists(version_1));
  ASSERT_TRUE(file_util::DirectoryExists(version_2));

  // Uninstall. Should remove entire extension subtree.
  extension_file_util::UninstallExtension(all_extensions, extension_id);
  ASSERT_FALSE(file_util::DirectoryExists(version_2.DirName()));
  ASSERT_TRUE(file_util::DirectoryExists(all_extensions));
}

TEST(ExtensionFileUtil, LoadExtensionWithValidLocales) {
  FilePath install_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
  install_dir = install_dir.AppendASCII("extensions")
      .AppendASCII("good")
      .AppendASCII("Extensions")
      .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
      .AppendASCII("1.0.0.0");

  std::string error;
  scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
      install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
  ASSERT_TRUE(extension != NULL);
  EXPECT_EQ("The first extension that I made.", extension->description());
}

TEST(ExtensionFileUtil, LoadExtensionWithoutLocalesFolder) {
  FilePath install_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
  install_dir = install_dir.AppendASCII("extensions")
      .AppendASCII("good")
      .AppendASCII("Extensions")
      .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa")
      .AppendASCII("1.0");

  std::string error;
  scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
      install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
  ASSERT_FALSE(extension == NULL);
  EXPECT_TRUE(error.empty());
}

TEST(ExtensionFileUtil, CheckIllegalFilenamesNoUnderscores) {
  ScopedTempDir temp;
  ASSERT_TRUE(temp.CreateUniqueTempDir());

  FilePath src_path = temp.path().AppendASCII("some_dir");
  ASSERT_TRUE(file_util::CreateDirectory(src_path));

  std::string data = "{ \"name\": { \"message\": \"foobar\" } }";
  ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("some_file.txt"),
                                   data.c_str(), data.length()));
  std::string error;
  EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(),
                                                            &error));
}

TEST(ExtensionFileUtil, CheckIllegalFilenamesOnlyReserved) {
  ScopedTempDir temp;
  ASSERT_TRUE(temp.CreateUniqueTempDir());

  FilePath src_path = temp.path().Append(Extension::kLocaleFolder);
  ASSERT_TRUE(file_util::CreateDirectory(src_path));

  std::string error;
  EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(),
                                                            &error));
}

TEST(ExtensionFileUtil, CheckIllegalFilenamesReservedAndIllegal) {
  ScopedTempDir temp;
  ASSERT_TRUE(temp.CreateUniqueTempDir());

  FilePath src_path = temp.path().Append(Extension::kLocaleFolder);
  ASSERT_TRUE(file_util::CreateDirectory(src_path));

  src_path = temp.path().AppendASCII("_some_dir");
  ASSERT_TRUE(file_util::CreateDirectory(src_path));

  std::string error;
  EXPECT_FALSE(extension_file_util::CheckForIllegalFilenames(temp.path(),
                                                             &error));
}

TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnMissingManifest) {
  FilePath install_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
  install_dir = install_dir.AppendASCII("extensions")
      .AppendASCII("bad")
      .AppendASCII("Extensions")
      .AppendASCII("dddddddddddddddddddddddddddddddd")
      .AppendASCII("1.0");

  std::string error;
  scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
      install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
  ASSERT_TRUE(extension == NULL);
  ASSERT_FALSE(error.empty());
  ASSERT_STREQ("Manifest file is missing or unreadable.", error.c_str());
}

TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnBadManifest) {
  FilePath install_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
  install_dir = install_dir.AppendASCII("extensions")
      .AppendASCII("bad")
      .AppendASCII("Extensions")
      .AppendASCII("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
      .AppendASCII("1.0");

  std::string error;
  scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
      install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
  ASSERT_TRUE(extension == NULL);
  ASSERT_FALSE(error.empty());
  ASSERT_STREQ("Manifest is not valid JSON.  "
               "Line: 2, column: 16, Syntax error.", error.c_str());
}

TEST(ExtensionFileUtil, FailLoadingNonUTF8Scripts) {
  FilePath install_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
  install_dir = install_dir.AppendASCII("extensions")
      .AppendASCII("bad")
      .AppendASCII("bad_encoding");

  std::string error;
  scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
      install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
  ASSERT_TRUE(extension == NULL);
  ASSERT_STREQ("Could not load file 'bad_encoding.js' for content script. "
               "It isn't UTF-8 encoded.", error.c_str());
}

#define URL_PREFIX "chrome-extension://extension-id/"

TEST(ExtensionFileUtil, ExtensionURLToRelativeFilePath) {
  struct TestCase {
    const char* url;
    const char* expected_relative_path;
  } test_cases[] = {
    { URL_PREFIX "simple.html",
      "simple.html" },
    { URL_PREFIX "directory/to/file.html",
      "directory/to/file.html" },
    { URL_PREFIX "escape%20spaces.html",
      "escape spaces.html" },
    { URL_PREFIX "%C3%9Cber.html",
      "\xC3\x9C" "ber.html" },
#if defined(OS_WIN)
    { URL_PREFIX "C%3A/simple.html",
      "" },
#endif
    { URL_PREFIX "////simple.html",
      "simple.html" },
    { URL_PREFIX "/simple.html",
      "simple.html" },
    { URL_PREFIX "\\simple.html",
      "simple.html" },
    { URL_PREFIX "\\\\foo\\simple.html",
      "foo/simple.html" },
  };

  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
    GURL url(test_cases[i].url);
#if defined(OS_POSIX)
    FilePath expected_path(test_cases[i].expected_relative_path);
#elif defined(OS_WIN)
    FilePath expected_path(UTF8ToWide(test_cases[i].expected_relative_path));
#endif

    FilePath actual_path =
        extension_file_util::ExtensionURLToRelativeFilePath(url);
    EXPECT_FALSE(actual_path.IsAbsolute()) <<
      " For the path " << actual_path.value();
    EXPECT_EQ(expected_path.value(), actual_path.value()) <<
      " For the path " << url;
  }
}

static scoped_refptr<Extension> LoadExtensionManifest(
    const std::string& manifest_value,
    const FilePath& manifest_dir,
    Extension::Location location,
    int extra_flags,
    std::string* error) {
  JSONStringValueSerializer serializer(manifest_value);
  scoped_ptr<Value> result(serializer.Deserialize(NULL, error));
  if (!result.get())
    return NULL;

  scoped_refptr<Extension> extension = Extension::Create(
      manifest_dir, location, *static_cast<DictionaryValue*>(result.get()),
      extra_flags, error);
  return extension;
}

TEST(ExtensionFileUtil, ValidateThemeUTF8) {
  ScopedTempDir temp;
  ASSERT_TRUE(temp.CreateUniqueTempDir());

  // "aeo" with accents. Use http://0xcc.net/jsescape/ to decode them.
  std::string non_ascii_file = "\xC3\xA0\xC3\xA8\xC3\xB2.png";
  FilePath non_ascii_path = temp.path().Append(FilePath::FromUTF8Unsafe(
      non_ascii_file));
  file_util::WriteFile(non_ascii_path, "", 0);

  std::string kManifest =
      base::StringPrintf(
          "{ \"name\": \"Test\", \"version\": \"1.0\", "
          "  \"theme\": { \"images\": { \"theme_frame\": \"%s\" } }"
          "}", non_ascii_file.c_str());
  std::string error;
  scoped_refptr<Extension> extension = LoadExtensionManifest(
      kManifest, temp.path(), Extension::LOAD, 0, &error);
  ASSERT_TRUE(extension.get()) << error;

  EXPECT_TRUE(extension_file_util::ValidateExtension(extension, &error)) <<
      error;
}

// TODO(aa): More tests as motivation allows. Maybe steal some from
// ExtensionService? Many of them could probably be tested here without the
// MessageLoop shenanigans.
<commit_msg>Crashing: ExtensionFileUtil.InstallUninstallGarbageCollect.<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 "chrome/common/extensions/extension_file_util.h"

#include "base/file_util.h"
#include "base/json/json_value_serializer.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace keys = extension_manifest_keys;

// http://crbug.com/106381
TEST(ExtensionFileUtil, DISABLED_InstallUninstallGarbageCollect) {
  ScopedTempDir temp;
  ASSERT_TRUE(temp.CreateUniqueTempDir());

  // Create a source extension.
  std::string extension_id("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
  std::string version("1.0");
  FilePath src = temp.path().AppendASCII(extension_id);
  ASSERT_TRUE(file_util::CreateDirectory(src));

  // Create a extensions tree.
  FilePath all_extensions = temp.path().AppendASCII("extensions");
  ASSERT_TRUE(file_util::CreateDirectory(all_extensions));

  // Install in empty directory. Should create parent directories as needed.
  FilePath version_1 = extension_file_util::InstallExtension(src,
                                                             extension_id,
                                                             version,
                                                             all_extensions);
  ASSERT_EQ(version_1.value(),
            all_extensions.AppendASCII(extension_id).AppendASCII("1.0_0")
                .value());
  ASSERT_TRUE(file_util::DirectoryExists(version_1));

  // Should have moved the source.
  ASSERT_FALSE(file_util::DirectoryExists(src));

  // Install again. Should create a new one with different name.
  ASSERT_TRUE(file_util::CreateDirectory(src));
  FilePath version_2 = extension_file_util::InstallExtension(src,
                                                             extension_id,
                                                             version,
                                                             all_extensions);
  ASSERT_EQ(version_2.value(),
            all_extensions.AppendASCII(extension_id).AppendASCII("1.0_1")
                .value());
  ASSERT_TRUE(file_util::DirectoryExists(version_2));

  // Collect garbage. Should remove first one.
  std::map<std::string, FilePath> extension_paths;
  extension_paths[extension_id] =
      FilePath().AppendASCII(extension_id).Append(version_2.BaseName());
  extension_file_util::GarbageCollectExtensions(all_extensions,
                                                extension_paths);
  ASSERT_FALSE(file_util::DirectoryExists(version_1));
  ASSERT_TRUE(file_util::DirectoryExists(version_2));

  // Uninstall. Should remove entire extension subtree.
  extension_file_util::UninstallExtension(all_extensions, extension_id);
  ASSERT_FALSE(file_util::DirectoryExists(version_2.DirName()));
  ASSERT_TRUE(file_util::DirectoryExists(all_extensions));
}

TEST(ExtensionFileUtil, LoadExtensionWithValidLocales) {
  FilePath install_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
  install_dir = install_dir.AppendASCII("extensions")
      .AppendASCII("good")
      .AppendASCII("Extensions")
      .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
      .AppendASCII("1.0.0.0");

  std::string error;
  scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
      install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
  ASSERT_TRUE(extension != NULL);
  EXPECT_EQ("The first extension that I made.", extension->description());
}

TEST(ExtensionFileUtil, LoadExtensionWithoutLocalesFolder) {
  FilePath install_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
  install_dir = install_dir.AppendASCII("extensions")
      .AppendASCII("good")
      .AppendASCII("Extensions")
      .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa")
      .AppendASCII("1.0");

  std::string error;
  scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
      install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
  ASSERT_FALSE(extension == NULL);
  EXPECT_TRUE(error.empty());
}

TEST(ExtensionFileUtil, CheckIllegalFilenamesNoUnderscores) {
  ScopedTempDir temp;
  ASSERT_TRUE(temp.CreateUniqueTempDir());

  FilePath src_path = temp.path().AppendASCII("some_dir");
  ASSERT_TRUE(file_util::CreateDirectory(src_path));

  std::string data = "{ \"name\": { \"message\": \"foobar\" } }";
  ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("some_file.txt"),
                                   data.c_str(), data.length()));
  std::string error;
  EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(),
                                                            &error));
}

TEST(ExtensionFileUtil, CheckIllegalFilenamesOnlyReserved) {
  ScopedTempDir temp;
  ASSERT_TRUE(temp.CreateUniqueTempDir());

  FilePath src_path = temp.path().Append(Extension::kLocaleFolder);
  ASSERT_TRUE(file_util::CreateDirectory(src_path));

  std::string error;
  EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(),
                                                            &error));
}

TEST(ExtensionFileUtil, CheckIllegalFilenamesReservedAndIllegal) {
  ScopedTempDir temp;
  ASSERT_TRUE(temp.CreateUniqueTempDir());

  FilePath src_path = temp.path().Append(Extension::kLocaleFolder);
  ASSERT_TRUE(file_util::CreateDirectory(src_path));

  src_path = temp.path().AppendASCII("_some_dir");
  ASSERT_TRUE(file_util::CreateDirectory(src_path));

  std::string error;
  EXPECT_FALSE(extension_file_util::CheckForIllegalFilenames(temp.path(),
                                                             &error));
}

TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnMissingManifest) {
  FilePath install_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
  install_dir = install_dir.AppendASCII("extensions")
      .AppendASCII("bad")
      .AppendASCII("Extensions")
      .AppendASCII("dddddddddddddddddddddddddddddddd")
      .AppendASCII("1.0");

  std::string error;
  scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
      install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
  ASSERT_TRUE(extension == NULL);
  ASSERT_FALSE(error.empty());
  ASSERT_STREQ("Manifest file is missing or unreadable.", error.c_str());
}

TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnBadManifest) {
  FilePath install_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
  install_dir = install_dir.AppendASCII("extensions")
      .AppendASCII("bad")
      .AppendASCII("Extensions")
      .AppendASCII("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
      .AppendASCII("1.0");

  std::string error;
  scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
      install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
  ASSERT_TRUE(extension == NULL);
  ASSERT_FALSE(error.empty());
  ASSERT_STREQ("Manifest is not valid JSON.  "
               "Line: 2, column: 16, Syntax error.", error.c_str());
}

TEST(ExtensionFileUtil, FailLoadingNonUTF8Scripts) {
  FilePath install_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
  install_dir = install_dir.AppendASCII("extensions")
      .AppendASCII("bad")
      .AppendASCII("bad_encoding");

  std::string error;
  scoped_refptr<Extension> extension(extension_file_util::LoadExtension(
      install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error));
  ASSERT_TRUE(extension == NULL);
  ASSERT_STREQ("Could not load file 'bad_encoding.js' for content script. "
               "It isn't UTF-8 encoded.", error.c_str());
}

#define URL_PREFIX "chrome-extension://extension-id/"

TEST(ExtensionFileUtil, ExtensionURLToRelativeFilePath) {
  struct TestCase {
    const char* url;
    const char* expected_relative_path;
  } test_cases[] = {
    { URL_PREFIX "simple.html",
      "simple.html" },
    { URL_PREFIX "directory/to/file.html",
      "directory/to/file.html" },
    { URL_PREFIX "escape%20spaces.html",
      "escape spaces.html" },
    { URL_PREFIX "%C3%9Cber.html",
      "\xC3\x9C" "ber.html" },
#if defined(OS_WIN)
    { URL_PREFIX "C%3A/simple.html",
      "" },
#endif
    { URL_PREFIX "////simple.html",
      "simple.html" },
    { URL_PREFIX "/simple.html",
      "simple.html" },
    { URL_PREFIX "\\simple.html",
      "simple.html" },
    { URL_PREFIX "\\\\foo\\simple.html",
      "foo/simple.html" },
  };

  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
    GURL url(test_cases[i].url);
#if defined(OS_POSIX)
    FilePath expected_path(test_cases[i].expected_relative_path);
#elif defined(OS_WIN)
    FilePath expected_path(UTF8ToWide(test_cases[i].expected_relative_path));
#endif

    FilePath actual_path =
        extension_file_util::ExtensionURLToRelativeFilePath(url);
    EXPECT_FALSE(actual_path.IsAbsolute()) <<
      " For the path " << actual_path.value();
    EXPECT_EQ(expected_path.value(), actual_path.value()) <<
      " For the path " << url;
  }
}

static scoped_refptr<Extension> LoadExtensionManifest(
    const std::string& manifest_value,
    const FilePath& manifest_dir,
    Extension::Location location,
    int extra_flags,
    std::string* error) {
  JSONStringValueSerializer serializer(manifest_value);
  scoped_ptr<Value> result(serializer.Deserialize(NULL, error));
  if (!result.get())
    return NULL;

  scoped_refptr<Extension> extension = Extension::Create(
      manifest_dir, location, *static_cast<DictionaryValue*>(result.get()),
      extra_flags, error);
  return extension;
}

TEST(ExtensionFileUtil, ValidateThemeUTF8) {
  ScopedTempDir temp;
  ASSERT_TRUE(temp.CreateUniqueTempDir());

  // "aeo" with accents. Use http://0xcc.net/jsescape/ to decode them.
  std::string non_ascii_file = "\xC3\xA0\xC3\xA8\xC3\xB2.png";
  FilePath non_ascii_path = temp.path().Append(FilePath::FromUTF8Unsafe(
      non_ascii_file));
  file_util::WriteFile(non_ascii_path, "", 0);

  std::string kManifest =
      base::StringPrintf(
          "{ \"name\": \"Test\", \"version\": \"1.0\", "
          "  \"theme\": { \"images\": { \"theme_frame\": \"%s\" } }"
          "}", non_ascii_file.c_str());
  std::string error;
  scoped_refptr<Extension> extension = LoadExtensionManifest(
      kManifest, temp.path(), Extension::LOAD, 0, &error);
  ASSERT_TRUE(extension.get()) << error;

  EXPECT_TRUE(extension_file_util::ValidateExtension(extension, &error)) <<
      error;
}

// TODO(aa): More tests as motivation allows. Maybe steal some from
// ExtensionService? Many of them could probably be tested here without the
// MessageLoop shenanigans.
<|endoftext|>