Ejemplo n.º 1
0
void AcsAlarmTestCase::testFaultState()
{
	const std::string member(MEMBER_VALUE);
	const std::string family(FAMILY_VALUE);
	const std::string descriptor(DESCRIPTOR_VALUE);

	acsalarm::ASIMessage message;
	laserSource::CERNASIMessage cernMsg(message);

	// create the FaultState
	std::auto_ptr<acsalarm::FaultState> fltstate = ACSAlarmSystemInterfaceFactory::createFaultState(family, member, CODE_VALUE);

	// test family getters
	CPPUNIT_ASSERT_MESSAGE("FaultState::getFamily appears to be broken", (family == fltstate->getFamily()) );
	CPPUNIT_ASSERT_MESSAGE("FaultState::getMember appears to be broken", (member == fltstate->getMember()) );
	CPPUNIT_ASSERT_MESSAGE("FaultState::getCode appears to be broken", (CODE_VALUE == fltstate->getCode()) );

	// test family setter
	std::string newfamily = "newfamily";
	fltstate->setFamily(newfamily);
	CPPUNIT_ASSERT_MESSAGE("FaultState::setFamily appears to be broken", (newfamily == fltstate->getFamily()) );

	// restore previous value
	fltstate->setFamily(family);

	// test member setter
	std::string newmember = "newmember";
	fltstate->setMember(newmember);
	CPPUNIT_ASSERT_MESSAGE("FaultState::setMember appears to be broken", (newmember == fltstate->getMember()) );

	// restore previous value
	fltstate->setMember(member);

	// test code setter
	int newcode = 2;
	fltstate->setCode(newcode);
	CPPUNIT_ASSERT_MESSAGE("FaultState::setCode appears to be broken", (newcode == fltstate->getCode()) );

	// restore previous value
	fltstate->setCode(CODE_VALUE);

	// test descriptor setter
	fltstate->setDescriptor(descriptor);
	CPPUNIT_ASSERT_MESSAGE("FaultState::setDescriptor appears to be broken", (descriptor == fltstate->getDescriptor()) );

	// test timestamp getters/setters
	acsalarm::Timestamp * tstampPtr = new acsalarm::Timestamp(SECONDS_VALUE, MICROSECONDS_VALUE);
	std::auto_ptr<acsalarm::Timestamp> tstampAutoPtr(tstampPtr);
	fltstate->setUserTimestamp(tstampAutoPtr);
	CPPUNIT_ASSERT_MESSAGE("FaultState::setUserTimestamp appears to be broken", (*tstampPtr == fltstate->getUserTimestamp()) );

	// test properties getters/setters
	acsalarm::Properties * propsPtr = new acsalarm::Properties();
	propsPtr->setProperty(faultState::ASI_PREFIX_PROPERTY_STRING, PREFIX_VALUE_VALUE);
	propsPtr->setProperty(faultState::ASI_SUFFIX_PROPERTY_STRING, SUFFIX_VALUE_VALUE);
	propsPtr->setProperty(TEST_NAME_VALUE, TEST_VALUE_VALUE);
	std::auto_ptr<acsalarm::Properties> propsAutoPtr(propsPtr);
	fltstate->setUserProperties(propsAutoPtr);
	CPPUNIT_ASSERT_MESSAGE("FaultState::setUserProperties appears to be broken", (*propsPtr == fltstate->getUserProperties()) );

	// test activated by backup getters/setters
	bool activatedByBackup = true;
	fltstate->setActivatedByBackup(activatedByBackup);
	CPPUNIT_ASSERT_MESSAGE("FaultState::setActivatedByBackup appears to be broken", (activatedByBackup == fltstate->getActivatedByBackup()) );
	activatedByBackup = false;
	fltstate->setActivatedByBackup(activatedByBackup);
	CPPUNIT_ASSERT_MESSAGE("FaultState::setActivatedByBackup appears to be broken", (activatedByBackup == fltstate->getActivatedByBackup()) );

	// test terminated by backup getters/setters
	bool terminatedByBackup = true;
	fltstate->setTerminatedByBackup(terminatedByBackup);
	CPPUNIT_ASSERT_MESSAGE("FaultState::setTerminatedByBackup appears to be broken", (terminatedByBackup == fltstate->getTerminatedByBackup()) );
	terminatedByBackup = false;
	fltstate->setTerminatedByBackup(terminatedByBackup);
	CPPUNIT_ASSERT_MESSAGE("FaultState::setTerminatedByBackup appears to be broken", (terminatedByBackup == fltstate->getTerminatedByBackup()) );

	// test faultStateToXMLmethod
	verifyFaultStateXML(cernMsg.faultStateToXML(fltstate.get()));
}
void AnnotatedHierarchicalAStarTest::getPathShouldReturnTheShortestPathBetweenTwoLowLevelNodesGivenACapabilityAndClearanceAndAnnotatedClusterAbstractionParameter()
{
	Map *m = new Map(acmap.c_str());
	AnnotatedClusterAbstraction* aca = new AnnotatedClusterAbstraction(m, new AnnotatedAStar(), TESTCLUSTERSIZE);
	AnnotatedClusterFactory* acfactory = new AnnotatedClusterFactory();
	aca->buildClusters(acfactory);
	aca->buildEntrances();

	graph  *absg = aca->getAbstractGraph(1);
	int numNodesExpected = absg->getNumNodes();
	int numEdgesExpected = absg->getNumEdges();
	int numCachedPathsExpected = aca->getPathCacheSize();
	
	node *start = aca->getNodeFromMap(2,1);
	node* goal = aca->getNodeFromMap(4,5);
	
	int capability = kGround;
	int size = 1;

	ahastar->setGraphAbstraction(aca);
	ahastar->setClearance(size);
	ahastar->setCapability(capability);

	path* p = ahastar->getPath(aca, start,goal);	
	
	int expectedLength = 10;	
	CPPUNIT_ASSERT_EQUAL_MESSAGE("path length wrong", expectedLength, (int)p->length());	

	CPPUNIT_ASSERT_MESSAGE("failed to find a valid path when one exists", p != 0);
	CPPUNIT_ASSERT_MESSAGE("start of path is wrong", start == p->n);
	path* cur = p->next;
	CPPUNIT_ASSERT_MESSAGE("node @ start+1 in path is wrong", aca->getNodeFromMap(3,1)== cur->n);
	cur = cur->next;
	CPPUNIT_ASSERT_MESSAGE("node @ start+2 in path is wrong", aca->getNodeFromMap(4,1)== cur->n);
	cur = cur->next;
	CPPUNIT_ASSERT_MESSAGE("node @ start+3 in path is wrong", aca->getNodeFromMap(5,1)== cur->n);
	cur = cur->next;
	CPPUNIT_ASSERT_MESSAGE("node @ start+4 in path is wrong", aca->getNodeFromMap(6,2)== cur->n);
	cur = cur->next;
	CPPUNIT_ASSERT_MESSAGE("node @ start+5 in path is wrong", aca->getNodeFromMap(6,3)== cur->n);
	cur = cur->next;
	CPPUNIT_ASSERT_MESSAGE("node @ start+6 in path is wrong", aca->getNodeFromMap(6,4) == cur->n);
	cur = cur->next;
	CPPUNIT_ASSERT_MESSAGE("node @ start+7 in path is wrong", aca->getNodeFromMap(5,4)== cur->n);
	cur = cur->next;
	CPPUNIT_ASSERT_MESSAGE("node @ start+8 in path is wrong", aca->getNodeFromMap(5,5)== cur->n);
	CPPUNIT_ASSERT_MESSAGE("end of path is wrong", goal == p->tail()->n);
	
	double expectedDist =  9.41;
	double dist = aca->distance(p);
	dist = ((int)(dist*100+0.5))/100.0;

	CPPUNIT_ASSERT_EQUAL_MESSAGE("path distance wrong", expectedDist, dist);
	
	CPPUNIT_ASSERT_EQUAL_MESSAGE("node count in abstract graph is wrong", numNodesExpected, absg->getNumNodes());
	CPPUNIT_ASSERT_EQUAL_MESSAGE("edge count in abstract graph is wrong", numEdgesExpected, absg->getNumEdges());
	CPPUNIT_ASSERT_EQUAL_MESSAGE("path cache size is wrong", numCachedPathsExpected, aca->getPathCacheSize());
	
	delete p;
	delete acfactory;
	delete aca;
}
 void testImageToUnstructuredGridFilterInitialization()
 {
   mitk::ImageToUnstructuredGridFilter::Pointer testFilter = mitk::ImageToUnstructuredGridFilter::New();
   CPPUNIT_ASSERT_MESSAGE("Testing instantiation of test object", testFilter.IsNotNull());
   CPPUNIT_ASSERT_MESSAGE("Testing initialization of threshold member variable", testFilter->GetThreshold() == -0.1);
 }
Ejemplo n.º 4
0
 void GetErrorMessage_Default_ReturnsEmptyString()
 {
   CPPUNIT_ASSERT_MESSAGE("Error message should be empty", !strcmp(m_TrackingTool->GetErrorMessage(), ""));
 }
Ejemplo n.º 5
0
void MultiAgentTest::doTest()
{
	sml::Kernel* pKernel = sml::Kernel::CreateKernelInNewThread();
	CPPUNIT_ASSERT_MESSAGE( pKernel->GetLastErrorDescription(), !pKernel->HadError() );

	// We'll require commits, just so we're testing that path
	pKernel->SetAutoCommit( false ) ;

	// Comment this in if you need to debug the messages going back and forth.
	//pKernel->SetTraceCommunications(true) ;

	CPPUNIT_ASSERT( numberAgents < MAX_AGENTS );

	std::vector< std::string > names;
	std::vector< sml::Agent* > agents;
	std::vector< std::stringstream* > trace;
	std::vector< int > callbackPrint;

	// Create the agents
	for ( int agentCounter = 0 ; agentCounter < numberAgents ; ++agentCounter )
	{
		std::stringstream name;
		name << "agent" << 1 + agentCounter;
		names.push_back( name.str() );

		sml::Agent* pAgent   = pKernel->CreateAgent( name.str().c_str() ) ;
		CPPUNIT_ASSERT( pAgent != NULL );
		CPPUNIT_ASSERT_MESSAGE( pKernel->GetLastErrorDescription(), !pKernel->HadError() );

		agents.push_back( pAgent );

		std::stringstream path;
		// TODO: use boost filesystem
		CPPUNIT_ASSERT( pAgent->LoadProductions( "test_agents/testmulti.soar" ) );
		createInput( pAgent, 0 );

		// Collect the trace output from the run
		trace.push_back( new std::stringstream() );
		callbackPrint.push_back( pAgent->RegisterForPrintEvent( sml::smlEVENT_PRINT, MultiAgentTest::MyPrintEventHandler, trace[agentCounter] ) );
	}

	pKernel->RegisterForUpdateEvent( sml::smlEVENT_AFTER_ALL_GENERATED_OUTPUT, MultiAgentTest::MyUpdateEventHandler, NULL ) ;

	// Run for a first set of output, so we can see whether that worked
	pKernel->RunAllTilOutput() ;

	// Print out some information
	reportAgentStatus( pKernel, numberAgents, trace ) ;

	// Now get serious about a decent run
	const int kFirstRun = 5 ;
	for (int i = 0 ; i < kFirstRun ; i++)
	{
		// Run for a bit
		pKernel->RunAllTilOutput() ;
	}

	reportAgentStatus(pKernel, numberAgents, trace) ;

	// Toss in an init-soar and then go on a bit further
	initAll(pKernel) ;

	// Second run
	const int kSecondRun = 5 ;
	for (int i = 0 ; i < kSecondRun ; i++)
	{
		// Run for a bit
		pKernel->RunAllTilOutput() ;
	}

	reportAgentStatus(pKernel, numberAgents, trace) ;

	for ( std::vector< std::stringstream* >::iterator iter = trace.begin(); iter != trace.end(); ++iter )
	{
		delete *iter;
	}

	//cout << "Calling shutdown on the kernel now" << endl ;
	pKernel->Shutdown() ;
	//cout << "Shutdown completed now" << endl ;

	// Delete the kernel.  If this is an embedded connection this destroys the kernel.
	// If it's a remote connection we just disconnect.
	delete pKernel ;
}
Ejemplo n.º 6
0
void TestMapModel::testSetMapOrientation_validOrientation_updateMapOrientation() {
	this->mapModel->setMapOrientation(Orthogonal);
	Orientation orientation = this->mapModel->getMapOrientation();
	CPPUNIT_ASSERT_MESSAGE("Map orientation is not updated", orientation == Orthogonal);
}
 void setUp() override
 {
   m_ContourNormalsFilter = mitk::ComputeContourSetNormalsFilter::New();
   CPPUNIT_ASSERT_MESSAGE("Failed to initialize ReduceContourSetFilter", m_ContourNormalsFilter.IsNotNull());
 }
Ejemplo n.º 8
0
  void TestRemoveLayer()
  {
    // Cache active layer
    mitk::LabelSet::ConstPointer activeLayer = m_LabelSetImage->GetActiveLabelSet();

    // Add new layers
    m_LabelSetImage->AddLayer();

    mitk::LabelSet::Pointer newlayer = mitk::LabelSet::New();
    mitk::Label::Pointer label1 = mitk::Label::New();
    label1->SetName("Label1");
    label1->SetValue(1);

    mitk::Label::Pointer label2 = mitk::Label::New();
    label2->SetName("Label2");
    label2->SetValue(200);

    newlayer->AddLabel(label1);
    newlayer->AddLabel(label2);
    newlayer->SetActiveLabel(200);

    m_LabelSetImage->AddLayer(newlayer);

    CPPUNIT_ASSERT_MESSAGE("Wrong active labelset returned",
                           mitk::Equal(*newlayer, *m_LabelSetImage->GetActiveLabelSet(), 0.00001, true));

    m_LabelSetImage->RemoveLayer();
    CPPUNIT_ASSERT_MESSAGE("Wrong number of layers, after a layer was removed",
                           m_LabelSetImage->GetNumberOfLayers() == 2);
    CPPUNIT_ASSERT_MESSAGE("Check for existing layer failed", m_LabelSetImage->ExistLabelSet(2) == false);
    CPPUNIT_ASSERT_MESSAGE("Check for existing layer failed", m_LabelSetImage->ExistLabelSet(1) == true);
    CPPUNIT_ASSERT_MESSAGE("Check for existing layer failed", m_LabelSetImage->ExistLabelSet(0) == true);

    m_LabelSetImage->RemoveLayer();
    CPPUNIT_ASSERT_MESSAGE("Wrong number of layers, after a layer was removed",
                           m_LabelSetImage->GetNumberOfLayers() == 1);
    CPPUNIT_ASSERT_MESSAGE("Check for existing layer failed", m_LabelSetImage->ExistLabelSet(1) == false);
    CPPUNIT_ASSERT_MESSAGE("Check for existing layer failed", m_LabelSetImage->ExistLabelSet(0) == true);
    CPPUNIT_ASSERT_MESSAGE("Wrong active layer",
                           mitk::Equal(*activeLayer, *m_LabelSetImage->GetActiveLabelSet(), 0.00001, true));

    m_LabelSetImage->RemoveLayer();
    CPPUNIT_ASSERT_MESSAGE("Wrong number of layers, after a layer was removed",
                           m_LabelSetImage->GetNumberOfLayers() == 0);
    CPPUNIT_ASSERT_MESSAGE("Check for existing layer failed", m_LabelSetImage->ExistLabelSet(0) == false);
    CPPUNIT_ASSERT_MESSAGE("Active layers is not nullptr although all layer have been removed",
                           m_LabelSetImage->GetActiveLabelSet() == 0);
  }
Ejemplo n.º 9
0
void
ThrottleTest::testRequest()
{
    auto_ptr<Throttle> throttle;

    throttle.reset(new Throttle(10,4096));

    boost::posix_time::ptime begin =
            boost::posix_time::microsec_clock::local_time();
    CPPUNIT_ASSERT( true == throttle->Request(8192) );
    boost::posix_time::ptime end =
            boost::posix_time::microsec_clock::local_time();
    int duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT( duration <= 1 );
    begin = end;

    CPPUNIT_ASSERT( true == throttle->Request(0) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT( duration <= 1 );
    begin = end;

    CPPUNIT_ASSERT( true == throttle->Request(1024) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT_MESSAGE( boost::lexical_cast<string>(duration),
            duration >= 9 && duration <= 11 );
    begin = end;

    CPPUNIT_ASSERT( true == throttle->Request(1024) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT_MESSAGE( boost::lexical_cast<string>(duration),
            duration >= 2 && duration <= 3 );
    begin = end;

    boost::this_thread::sleep(
            boost::posix_time::milliseconds(10) );

    begin = boost::posix_time::microsec_clock::local_time();
    CPPUNIT_ASSERT( true == throttle->Request(1024) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT( duration <= 1 );
    begin = end;

    CPPUNIT_ASSERT( true == throttle->Request(1024) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT( duration <= 1 );
    begin = end;

    CPPUNIT_ASSERT( true == throttle->Request(1024) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT( duration <= 1 );
    begin = end;

    CPPUNIT_ASSERT( true == throttle->Request(1024) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT_MESSAGE( boost::lexical_cast<string>(duration),
            duration <= 1 );
    begin = end;

    CPPUNIT_ASSERT( true == throttle->Request(1024) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT_MESSAGE( boost::lexical_cast<string>(duration),
            duration >= 2 && duration <= 3 );
    begin = end;

    CPPUNIT_ASSERT( true == throttle->Reset(10,4096) );
    CPPUNIT_ASSERT( true == throttle->Request(1024) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT( duration <= 1 );
}
Ejemplo n.º 10
0
void FileNameTestCase::TestConstruction()
{
    for ( size_t n = 0; n < WXSIZEOF(filenames); n++ )
    {
        const TestFileNameInfo& fni = filenames[n];

        wxFileName fn(fni.fullname, fni.format);

        // the original full name could contain consecutive [back]slashes,
        // squeeze them except for the double backslash in the beginning in
        // Windows filenames where it has special meaning
        wxString fullnameOrig;
        if ( fni.format == wxPATH_DOS )
        {
            // copy the backslashes at beginning unchanged
            const char *p = fni.fullname;
            while ( *p == '\\' )
                fullnameOrig += *p++;

            // replace consecutive slashes with single ones in the rest
            for ( char chPrev = '\0'; *p; p++ )
            {
                if ( *p == '\\' && chPrev == '\\' )
                    continue;

                chPrev = *p;
                fullnameOrig += chPrev;
            }
        }
        else // !wxPATH_DOS
        {
            fullnameOrig = fni.fullname;
        }

        fullnameOrig.Replace("//", "/");


        wxString fullname = fn.GetFullPath(fni.format);
        CPPUNIT_ASSERT_EQUAL( fullnameOrig, fullname );

        // notice that we use a dummy working directory to ensure that paths
        // with "../.." in them could be normalized, otherwise this would fail
        // if the test is run from root directory or its direct subdirectory
        CPPUNIT_ASSERT_MESSAGE
        (
            (const char *)wxString::Format("Normalize(%s) failed", fni.fullname).mb_str(),
            fn.Normalize(wxPATH_NORM_ALL, "/foo/bar/baz", fni.format)
        );

        if ( *fni.volume && *fni.path )
        {
            // check that specifying the volume separately or as part of the
            // path doesn't make any difference
            wxString pathWithVolume = fni.volume;
            pathWithVolume += wxFileName::GetVolumeSeparator(fni.format);
            pathWithVolume += fni.path;

            CPPUNIT_ASSERT_EQUAL( wxFileName(pathWithVolume,
                                             fni.name,
                                             fni.ext,
                                             fni.format), fn );
        }
    }

    wxFileName fn;

    // empty strings
    fn.AssignDir(wxEmptyString);
    CPPUNIT_ASSERT( !fn.IsOk() );

    fn.Assign(wxEmptyString);
    CPPUNIT_ASSERT( !fn.IsOk() );

    fn.Assign(wxEmptyString, wxEmptyString);
    CPPUNIT_ASSERT( !fn.IsOk() );

    fn.Assign(wxEmptyString, wxEmptyString, wxEmptyString);
    CPPUNIT_ASSERT( !fn.IsOk() );

    fn.Assign(wxEmptyString, wxEmptyString, wxEmptyString, wxEmptyString);
    CPPUNIT_ASSERT( !fn.IsOk() );
}
Ejemplo n.º 11
0
// Tests for functions that are changed by ShouldFollowLink()
void FileNameTestCase::TestSymlinks()
{
    const wxString tmpdir(wxStandardPaths::Get().GetTempDir());

    wxFileName tmpfn(wxFileName::DirName(tmpdir));

    // Create a temporary directory
#ifdef __VMS
    wxString name = tmpdir + ".filenametestXXXXXX]";
    mkdir( name.char_str() , 0222 );
    wxString tempdir = name;
#else
    wxString name = tmpdir + "/filenametestXXXXXX";
    wxString tempdir = wxString::From8BitData(mkdtemp(name.char_str()));
    tempdir << wxFileName::GetPathSeparator();
#endif
    wxFileName tempdirfn(wxFileName::DirName(tempdir));
    CPPUNIT_ASSERT(tempdirfn.DirExists());

    // Create a regular file in that dir, to act as a symlink target
    wxFileName targetfn(wxFileName::CreateTempFileName(tempdir));
    CPPUNIT_ASSERT(targetfn.FileExists());

    // Create a symlink to that file
    wxFileName linktofile(tempdir, "linktofile");
    CPPUNIT_ASSERT_EQUAL(0, symlink(targetfn.GetFullPath().c_str(),
                                        linktofile.GetFullPath().c_str()));

    // ... and another to the temporary directory
    const wxString linktodirName(tempdir + "/linktodir");
    wxFileName linktodir(wxFileName::DirName(linktodirName));
    CPPUNIT_ASSERT_EQUAL(0, symlink(tmpfn.GetFullPath().c_str(),
                                        linktodirName.c_str()));

    // And symlinks to both of those symlinks
    wxFileName linktofilelnk(tempdir, "linktofilelnk");
    CPPUNIT_ASSERT_EQUAL(0, symlink(linktofile.GetFullPath().c_str(),
                                    linktofilelnk.GetFullPath().c_str()));
    wxFileName linktodirlnk(tempdir, "linktodirlnk");
    CPPUNIT_ASSERT_EQUAL(0, symlink(linktodir.GetFullPath().c_str(),
                                    linktodirlnk.GetFullPath().c_str()));

    // Run the tests twice: once in the default symlink following mode and the
    // second time without following symlinks.
    bool deref = true;
    for ( int n = 0; n < 2; ++n, deref = !deref )
    {
        const std::string msg(deref ? " failed for the link target"
                                    : " failed for the path itself");

        if ( !deref )
        {
            linktofile.DontFollowLink();
            linktodir.DontFollowLink();
            linktofilelnk.DontFollowLink();
            linktodirlnk.DontFollowLink();
        }

        // Test SameAs()
        CPPUNIT_ASSERT_EQUAL_MESSAGE
        (
            "Comparison with file" + msg,
            deref, linktofile.SameAs(targetfn)
        );

        CPPUNIT_ASSERT_EQUAL_MESSAGE
        (
            "Comparison with directory" + msg,
            deref, linktodir.SameAs(tmpfn)
        );

        // A link-to-a-link should dereference through to the final target
        CPPUNIT_ASSERT_EQUAL_MESSAGE
        (
            "Comparison with link to a file" + msg,
            deref,
            linktofilelnk.SameAs(targetfn)
        );
        CPPUNIT_ASSERT_EQUAL_MESSAGE
        (
            "Comparison with link to a directory" + msg,
            deref,
            linktodirlnk.SameAs(tmpfn)
        );

        // Test GetTimes()
        wxDateTime dtAccess, dtMod, dtCreate;
        CPPUNIT_ASSERT_MESSAGE
        (
            "Getting times of a directory" + msg,
            linktodir.GetTimes(&dtAccess, &dtMod, &dtCreate)
        );

        // Test (File|Dir)Exists()
        CPPUNIT_ASSERT_EQUAL_MESSAGE
        (
            "Testing file existence" + msg,
            deref,
            linktofile.FileExists()
        );
        CPPUNIT_ASSERT_EQUAL_MESSAGE
        (
            "Testing directory existence" + msg,
            deref,
            linktodir.DirExists()
        );

        // Test wxFileName::Exists
        // The wxFILE_EXISTS_NO_FOLLOW flag should override DontFollowLink()
        CPPUNIT_ASSERT_EQUAL_MESSAGE
        (
            "Testing file existence" + msg,
            false,
            linktofile.Exists(wxFILE_EXISTS_REGULAR | wxFILE_EXISTS_NO_FOLLOW)
        );
        CPPUNIT_ASSERT_EQUAL_MESSAGE
        (
            "Testing directory existence" + msg,
            false,
            linktodir.Exists(wxFILE_EXISTS_DIR | wxFILE_EXISTS_NO_FOLLOW)
        );
        // and the static versions
        CPPUNIT_ASSERT_EQUAL_MESSAGE
        (
            "Testing file existence" + msg,
            false,
            wxFileName::Exists(linktofile.GetFullPath(), wxFILE_EXISTS_REGULAR | wxFILE_EXISTS_NO_FOLLOW)
        );
        CPPUNIT_ASSERT_EQUAL_MESSAGE
        (
            "Testing file existence" + msg,
            true,
            wxFileName::Exists(linktofile.GetFullPath(), wxFILE_EXISTS_REGULAR)
        );
        CPPUNIT_ASSERT_EQUAL_MESSAGE
        (
            "Testing directory existence" + msg,
            false,
            wxFileName::Exists(linktodir.GetFullPath(), wxFILE_EXISTS_DIR | wxFILE_EXISTS_NO_FOLLOW)
        );
        CPPUNIT_ASSERT_EQUAL_MESSAGE
        (
            "Testing directory existence" + msg,
            true,
            wxFileName::Exists(linktodir.GetFullPath(), wxFILE_EXISTS_DIR)
        );
    }

    // Finally test Exists() after removing the file.
    CPPUNIT_ASSERT(wxRemoveFile(targetfn.GetFullPath()));
    // This should succeed, as the symlink still exists and
    // the default wxFILE_EXISTS_ANY implies wxFILE_EXISTS_NO_FOLLOW
    CPPUNIT_ASSERT(wxFileName(tempdir, "linktofile").Exists());
    // So should this one, as wxFILE_EXISTS_SYMLINK does too
    CPPUNIT_ASSERT(wxFileName(tempdir, "linktofile").
                                            Exists(wxFILE_EXISTS_SYMLINK));
    // but not this one, as the now broken symlink is followed
    CPPUNIT_ASSERT(!wxFileName(tempdir, "linktofile").
                                            Exists(wxFILE_EXISTS_REGULAR));
    CPPUNIT_ASSERT(linktofile.Exists());

    // This is also a convenient place to test Rmdir() as we have things to
    // remove.

    // First, check that removing a symlink to a directory fails.
    CPPUNIT_ASSERT( !wxFileName::Rmdir(linktodirName) );

    // And recursively removing it only removes the symlink itself, not the
    // directory.
    CPPUNIT_ASSERT( wxFileName::Rmdir(linktodirName, wxPATH_RMDIR_RECURSIVE) );
    CPPUNIT_ASSERT( tmpfn.Exists() );

    // Finally removing the directory itself does remove everything.
    CPPUNIT_ASSERT(tempdirfn.Rmdir(wxPATH_RMDIR_RECURSIVE));
    CPPUNIT_ASSERT( !tempdirfn.Exists() );
}
void 
GeometricHelperTest::LineSegmentRayIntersectionTest() {
    {
        LineSegment ls1(Vertex(0, 1), Vertex(1, 1));
        Ray ray(Vertex(0, 0), Vertex(1, 2));

        // segment/ray intersect
        boost::optional<Vertex> intersection_point_opt = GeometricHelper::intersect(ls1, ray);
        CPPUNIT_ASSERT_MESSAGE("Intersection point expected", bool(intersection_point_opt));

        Vertex intersection_point = *intersection_point_opt;
        CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Intersection point error", 0.5, intersection_point.x(), 1E-10);
        CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Intersection point error", 1.0, intersection_point.y(), 1E-10);
    }

    {
        LineSegment ls1(Vertex(0, 3), Vertex(1, 3));
        Ray ray(Vertex(0, 0), Vertex(0.25, 1));

        // segment/ray intersect
        boost::optional<Vertex> intersection_point_opt = GeometricHelper::intersect(ls1, ray);
        CPPUNIT_ASSERT_MESSAGE("Intersection point expected", bool(intersection_point_opt));

        Vertex intersection_point = *intersection_point_opt;
        CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Intersection point error", 0.75, intersection_point.x(), 1E-10);
        CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Intersection point error", 3.0, intersection_point.y(), 1E-10);
    }


    {
        LineSegment ls1(Vertex(0, 1), Vertex(1, 1));
        Ray ray(Vertex(0.25, 2), Vertex(1, 4));

        // segment/ray do not intersect
        boost::optional<Vertex> intersection_point_opt = GeometricHelper::intersect(ls1, ray);
        CPPUNIT_ASSERT_MESSAGE("No intersection point expected", !bool(intersection_point_opt));
    }

    {
        LineSegment ls(Vertex(0, 1), Vertex(1, 1));
        Ray ray(Vertex(0, 0), Vertex(2, 1));

        // segments do not intersect
        boost::optional<Vertex> intersection_point_opt = GeometricHelper::intersect(ls, ray);
        CPPUNIT_ASSERT_MESSAGE("No intersection point expected", !bool(intersection_point_opt));
    }

    {
        LineSegment ls(Vertex(0, 1), Vertex(1, 1));
        Ray ray(Vertex(0.5, 1), Vertex(2, 1));

        // segment/ray overlap
        boost::optional<Vertex> intersection_point_opt = GeometricHelper::intersect(ls, ray);
        CPPUNIT_ASSERT_MESSAGE("No intersection point expected", !bool(intersection_point_opt));
    }

    {
        LineSegment ls(Vertex(0.5, 1), Vertex(1, 1));
        Ray ray(Vertex(0, 1), Vertex(2, 1));

        // segment contained in ray
        boost::optional<Vertex> intersection_point_opt = GeometricHelper::intersect(ls, ray);
        CPPUNIT_ASSERT_MESSAGE("No intersection point expected", !bool(intersection_point_opt));
    }

    {
        LineSegment ls(Vertex(0, 1), Vertex(1, 1));
        Ray ray(Vertex(1.5, 1), Vertex(2, 1));

        // segment and ray parallel
        boost::optional<Vertex> intersection_point_opt = GeometricHelper::intersect(ls, ray);
        CPPUNIT_ASSERT_MESSAGE("No intersection point expected", !bool(intersection_point_opt));
    }
}
void 
GeometricHelperTest::LineSegmentLineIntersectionTest() {
    {
        LineSegment ls(Vertex(0, 1), Vertex(1, 1));
        Line line(Vertex(0, 0), Vertex(1, 2));

        // segment/line intersect
        boost::optional<Vertex> intersection_point_opt = GeometricHelper::intersect(ls, line);
        CPPUNIT_ASSERT_MESSAGE("Intersection point expected", bool(intersection_point_opt));

        Vertex intersection_point = *intersection_point_opt;
        CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Intersection point error", 0.5, intersection_point.x(), 1E-10);
        CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Intersection point error", 1.0, intersection_point.y(), 1E-10);
    }

    {
        LineSegment ls(Vertex(0, 3), Vertex(1, 3));
        Line line(Vertex(0, 0), Vertex(0.25, 1));

        // segment/line intersect
        boost::optional<Vertex> intersection_point_opt = GeometricHelper::intersect(ls, line);
        CPPUNIT_ASSERT_MESSAGE("Intersection point expected", bool(intersection_point_opt));

        Vertex intersection_point = *intersection_point_opt;
        CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Intersection point error", 0.75, intersection_point.x(), 1E-10);
        CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Intersection point error", 3.0, intersection_point.y(), 1E-10);
    }


    {
        LineSegment ls(Vertex(0, 1), Vertex(1, 1));
        Line line(Vertex(0.25, 2), Vertex(1, 4));

        // segment/line do not intersect
        boost::optional<Vertex> intersection_point_opt = GeometricHelper::intersect(ls, line);
        CPPUNIT_ASSERT_MESSAGE("No intersection point expected", !bool(intersection_point_opt));
    }

    {
        LineSegment ls(Vertex(0, 1), Vertex(1, 1));
        Line line(Vertex(0, 0), Vertex(2, 1));

        // segments do not intersect
        boost::optional<Vertex> intersection_point_opt = GeometricHelper::intersect(ls, line);
        CPPUNIT_ASSERT_MESSAGE("No intersection point expected", !bool(intersection_point_opt));
    }

    {
        LineSegment ls(Vertex(0, 1), Vertex(1, 1));
        Line line(Vertex(0.5, 1), Vertex(2, 1));

        // segment/line overlap
        boost::optional<Vertex> intersection_point_opt = GeometricHelper::intersect(ls, line);
        CPPUNIT_ASSERT_MESSAGE("No intersection point expected", !bool(intersection_point_opt));
    }

    {
        LineSegment ls(Vertex(0.5, 1), Vertex(1, 1));
        Line line(Vertex(0, 1), Vertex(2, 1));

        // segment contained in line
        boost::optional<Vertex> intersection_point_opt = GeometricHelper::intersect(ls, line);
        CPPUNIT_ASSERT_MESSAGE("No intersection point expected", !bool(intersection_point_opt));
    }

    {
        LineSegment ls(Vertex(0, 1), Vertex(1, 1));
        Line line(Vertex(1.5, 1), Vertex(2, 1));

        // segment and line parallel
        boost::optional<Vertex> intersection_point_opt = GeometricHelper::intersect(ls, line);
        CPPUNIT_ASSERT_MESSAGE("No intersection point expected", !bool(intersection_point_opt));
    }

    {
        LineSegment ls(Vertex(0, 1), Vertex(1, 1));
        Line line(Vertex(1.5, 2), Vertex(2, 2));

        // segment and line parallel, but not collinear
        boost::optional<Vertex> intersection_point_opt = GeometricHelper::intersect(ls, line);
        CPPUNIT_ASSERT_MESSAGE("No intersection point expected", !bool(intersection_point_opt));
    }
}
Ejemplo n.º 14
0
void AcsAlarmTestCase::verifyUserPropertiesElement(DOMDocument * doc)
{
	// Verify the user-properties element
	DOMNodeList * userPropertiesNodes = doc->getElementsByTagName(USER_PROPERTIES_TAG_NAME);
	CPPUNIT_ASSERT_MESSAGE("FaultState::toXML appears to be broken; no user-properties element found",
		(NULL != userPropertiesNodes && userPropertiesNodes->getLength() == 1));

	// check for 3 property sub-element(s)
	DOMNodeList * propertyNodes = doc->getElementsByTagName(PROPERTY_TAG_NAME);
	CPPUNIT_ASSERT_MESSAGE("FaultState::toXML appears to be broken; did not find 3 property elements",
		(NULL != propertyNodes && propertyNodes->getLength() == 3));

	// verify for each property element that it has the expected attributes
	for(XMLSize_t i = 0; i < propertyNodes->getLength(); i++)
	{
		DOMNamedNodeMap * attributesMap = propertyNodes->item(i)->getAttributes();
		CPPUNIT_ASSERT_MESSAGE("FaultState::toXML appears to be broken; property element does not contain 2 attributes",
			(NULL!= attributesMap && attributesMap->getLength() == 2));

		// check that the property element has a "name" attribute
		DOMNode * familyNode = attributesMap->getNamedItem(NAME_TAG_NAME);
		CPPUNIT_ASSERT_MESSAGE("FaultState::toXML appears to be broken; property element does not contain 'name' attribute",
			(NULL!= familyNode));

		// check that the property element has a "value" attribute
		DOMNode * valueNode = attributesMap->getNamedItem(VALUE_TAG_NAME);
		CPPUNIT_ASSERT_MESSAGE("FaultState::toXML appears to be broken; property element does not contain 'value' attribute",
			(NULL!= valueNode));
	}

	// for each property, check the 'name' attribute
	DOMNamedNodeMap * firstPropAttrMap = propertyNodes->item(0)->getAttributes();
	DOMNode * prefixNameNode = firstPropAttrMap->getNamedItem(NAME_TAG_NAME);
	const XMLCh * prefixNameNodeValue = prefixNameNode->getNodeValue();
	CPPUNIT_ASSERT_MESSAGE("FaultState::toXML appears to be broken; 1st property element, 'name' attribute value is not correct",
		(NULL!= prefixNameNodeValue && XMLString::equals(prefixNameNodeValue, PREFIX_NAME_VALUE_XMLCH)));

	DOMNamedNodeMap * secondPropAttrMap = propertyNodes->item(1)->getAttributes();
	DOMNode * suffixNameNode = secondPropAttrMap->getNamedItem(NAME_TAG_NAME);
	const XMLCh * suffixNameNodeValue = suffixNameNode->getNodeValue();
	CPPUNIT_ASSERT_MESSAGE("FaultState::toXML appears to be broken; 2nd property element, 'name' attribute value is not correct",
		(NULL!= suffixNameNodeValue && XMLString::equals(suffixNameNodeValue, SUFFIX_NAME_VALUE_XMLCH)));

	DOMNamedNodeMap * thirdPropAttrMap = propertyNodes->item(2)->getAttributes();
	DOMNode * testPropNameNode = thirdPropAttrMap->getNamedItem(NAME_TAG_NAME);
	const XMLCh * testPropNameNodeValue = testPropNameNode->getNodeValue();
	CPPUNIT_ASSERT_MESSAGE("FaultState::toXML appears to be broken; 3rd property element, 'name' attribute value is not correct",
		(NULL!= testPropNameNodeValue && XMLString::equals(testPropNameNodeValue, TEST_NAME_VALUE_XMLCH)));

	// for each property, check the 'value' attribute
	DOMNamedNodeMap * firstAttrMap = propertyNodes->item(0)->getAttributes();
	DOMNode * prefixValueNode = firstAttrMap->getNamedItem(VALUE_TAG_NAME);
	const XMLCh * prefixValueNodeValue = prefixValueNode->getNodeValue();
	CPPUNIT_ASSERT_MESSAGE("FaultState::toXML appears to be broken; 1st property element, 'value' attribute value is not correct",
		(NULL!= prefixValueNodeValue && XMLString::equals(prefixValueNodeValue, PREFIX_VALUE_VALUE_XMLCH)));

	DOMNamedNodeMap * secondAttrMap = propertyNodes->item(1)->getAttributes();
	DOMNode * suffixValueNode = secondAttrMap->getNamedItem(VALUE_TAG_NAME);
	const XMLCh * suffixValueNodeValue = suffixValueNode->getNodeValue();
	CPPUNIT_ASSERT_MESSAGE("FaultState::toXML appears to be broken; 2nd property element, 'value' attribute value is not correct",
		(NULL!= suffixValueNodeValue && XMLString::equals(suffixValueNodeValue, SUFFIX_VALUE_VALUE_XMLCH)));

	DOMNamedNodeMap * thirdAttrMap = propertyNodes->item(2)->getAttributes();
	DOMNode * testValueNode = thirdAttrMap->getNamedItem(VALUE_TAG_NAME);
	const XMLCh * testValueNodeValue = testValueNode->getNodeValue();
	CPPUNIT_ASSERT_MESSAGE("FaultState::toXML appears to be broken; 3rd property element, 'value' attribute value is not correct",
		(NULL!= testValueNodeValue && XMLString::equals(testValueNodeValue, TEST_VALUE_VALUE_XMLCH)));
}
Ejemplo n.º 15
0
void TestMapModel::testSetTileWidth_widthGreaterThan0_updateTileWidth() {
	this->mapModel->setTileWidth(10);
	int tileWidth = this->mapModel->getTileWidth();
	CPPUNIT_ASSERT_MESSAGE("Tile width is not updated", tileWidth == 10);
}
Ejemplo n.º 16
0
void HTTPWSTest::testReloadWhileDisconnecting()
{
    const std::string documentPath = Util::getTempFilePath(TDOC, "hello.odt");
    const std::string documentURL = "file://" + Poco::Path(documentPath).makeAbsolute().toString();

    int kitcount = -1;
    try
    {
        // Load a document and get its status.
        Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, documentURL);
        Poco::Net::WebSocket socket = *connectLOKit(request, _response);

        sendTextFrame(socket, "load url=" + documentURL);
        CPPUNIT_ASSERT_MESSAGE("cannot load the document " + documentURL, isDocumentLoaded(socket));

        sendTextFrame(socket, "uno .uno:SelectAll");
        sendTextFrame(socket, "uno .uno:Delete");
        sendTextFrame(socket, "paste mimetype=text/plain;charset=utf-8\naaa bbb ccc");

        kitcount = countLoolKitProcesses();

        // Shutdown abruptly.
        socket.shutdown();
    }
    catch (const Poco::Exception& exc)
    {
        CPPUNIT_FAIL(exc.displayText());
    }

    std::cout << "Loading again." << std::endl;
    try
    {
        // Load the same document and check that the last changes (pasted text) is saved.
        Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, documentURL);
        Poco::Net::WebSocket socket = *connectLOKit(request, _response);

        sendTextFrame(socket, "load url=" + documentURL);
        sendTextFrame(socket, "status");
        CPPUNIT_ASSERT_MESSAGE("cannot load the document " + documentURL, isDocumentLoaded(socket));

        // Should have no new instances.
        CPPUNIT_ASSERT_EQUAL(kitcount, countLoolKitProcesses());

        // Check if the document contains the pasted text.
        sendTextFrame(socket, "uno .uno:SelectAll");
        sendTextFrame(socket, "gettextselection mimetype=text/plain;charset=utf-8");
        std::string selection;
        int flags;
        int n;
        do
        {
            char buffer[READ_BUFFER_SIZE];
            n = socket.receiveFrame(buffer, sizeof(buffer), flags);
            std::cout << "Got " << n << " bytes, flags: " << std::hex << flags << std::dec << '\n';
            if (n > 0 && (flags & Poco::Net::WebSocket::FRAME_OP_BITMASK) != Poco::Net::WebSocket::FRAME_OP_CLOSE)
            {
                std::cout << "Received message: " << LOOLProtocol::getAbbreviatedMessage(buffer, n) << '\n';
                const std::string line = LOOLProtocol::getFirstLine(buffer, n);
                if (line.find("editlock: ") == 0)
                {
                    // We must have the editlock, otherwise we aren't alone.
                    CPPUNIT_ASSERT_EQUAL(std::string("editlock: 1"), line);
                }

                const std::string prefix = "textselectioncontent: ";
                if (line.find(prefix) == 0)
                {
                    selection = line.substr(prefix.length());
                    break;
                }
            }
        }
        while (n > 0 && (flags & Poco::Net::WebSocket::FRAME_OP_BITMASK) != Poco::Net::WebSocket::FRAME_OP_CLOSE);
        socket.shutdown();
        Util::removeFile(documentPath);
        CPPUNIT_ASSERT_EQUAL(std::string("aaa bbb ccc"), selection);
    }
    catch (const Poco::Exception& exc)
    {
        CPPUNIT_FAIL(exc.displayText());
    }
}
Ejemplo n.º 17
0
void TestMapModel::testSetTileHeight_heightGreaterThan0_updateTileHeight() {
	this->mapModel->setTileHeight(10);
	int tileHeight = this->mapModel->getTileHeight();
	CPPUNIT_ASSERT_MESSAGE("Tile height is not updated", tileHeight == 10);
}
Ejemplo n.º 18
0
void HTTPWSTest::testImpressPartCountChanged()
{
    try
    {
        // Load a document
        const std::string documentPath = Util::getTempFilePath(TDOC, "insert-delete.odp");
        const std::string documentURL = "file://" + Poco::Path(documentPath).makeAbsolute().toString();

        Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, documentURL);
        Poco::Net::WebSocket socket = *connectLOKit(request, _response);

        sendTextFrame(socket, "load url=" + documentURL);
        sendTextFrame(socket, "status");
        CPPUNIT_ASSERT_MESSAGE("cannot load the document " + documentURL, isDocumentLoaded(socket));

        // check total slides 1
        sendTextFrame(socket, "status");

        std::string response;
        getResponseMessage(socket, "status:", response, true);
        CPPUNIT_ASSERT_MESSAGE("did not receive a status: message as expected", !response.empty());
        {
            Poco::StringTokenizer tokens(response, " ", Poco::StringTokenizer::TOK_IGNORE_EMPTY | Poco::StringTokenizer::TOK_TRIM);
            CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(5), tokens.count());

            // Expected format is something like 'type= parts= current= width= height='.
            const std::string prefix = "parts=";
            const int totalParts = std::stoi(tokens[1].substr(prefix.size()));
            CPPUNIT_ASSERT_EQUAL(1, totalParts);
        }

        /* FIXME partscountchanged: was removed, update accordingly
        // insert 10 slides
        for (unsigned it = 1; it <= 10; it++)
        {
            sendTextFrame(socket, "uno .uno:InsertPage");
            getResponseMessage(socket, "partscountchanged:", response, false);
            CPPUNIT_ASSERT_MESSAGE("did not receive a partscountchanged: message as expected", !response.empty());
            {
                Poco::JSON::Parser parser;
                Poco::Dynamic::Var result = parser.parse(response);
                Poco::DynamicStruct values = *result.extract<Poco::JSON::Object::Ptr>();
                CPPUNIT_ASSERT(values["action"] == "PartInserted");
            }
        }

        // delete 10 slides
        for (unsigned it = 1; it <= 10; it++)
        {
            sendTextFrame(socket, "uno .uno:DeletePage");
            getResponseMessage(socket, "partscountchanged:", response, false);
            CPPUNIT_ASSERT_MESSAGE("did not receive a partscountchanged: message as expected", !response.empty());
            {
                Poco::JSON::Parser parser;
                Poco::Dynamic::Var result = parser.parse(response);
                Poco::DynamicStruct values = *result.extract<Poco::JSON::Object::Ptr>();
                CPPUNIT_ASSERT(values["action"] == "PartDeleted");
            }
        }

        // undo delete slides
        for (unsigned it = 1; it <= 10; it++)
        {
            sendTextFrame(socket, "uno .uno:Undo");
            getResponseMessage(socket, "partscountchanged:", response, false);
            CPPUNIT_ASSERT_MESSAGE("did not receive a partscountchanged: message as expected", !response.empty());
            {
                Poco::JSON::Parser parser;
                Poco::Dynamic::Var result = parser.parse(response);
                Poco::DynamicStruct values = *result.extract<Poco::JSON::Object::Ptr>();
                CPPUNIT_ASSERT(values["action"] == "PartInserted");
            }
        }

        // redo inserted slides
        for (unsigned it = 1; it <= 10; it++)
        {
            sendTextFrame(socket, "uno .uno:Redo");
            getResponseMessage(socket, "partscountchanged:", response, false);
            CPPUNIT_ASSERT_MESSAGE("did not receive a partscountchanged: message as expected", !response.empty());
            {
                Poco::JSON::Parser parser;
                Poco::Dynamic::Var result = parser.parse(response);
                Poco::DynamicStruct values = *result.extract<Poco::JSON::Object::Ptr>();
                CPPUNIT_ASSERT(values["action"] == "PartDeleted");
            }
        }
        */

        socket.shutdown();
        Util::removeFile(documentPath);
    }
    catch (const Poco::Exception& exc)
    {
        CPPUNIT_FAIL(exc.displayText());
    }
}
 void testUnstructuredGridToUnstructuredGridFilterInitialization()
 {
   mitk::UnstructuredGridToUnstructuredGridFilter::Pointer testFilter =
     mitk::UnstructuredGridToUnstructuredGridFilter::New();
   CPPUNIT_ASSERT_MESSAGE("Testing instantiation of test object", testFilter.IsNotNull());
 }
Ejemplo n.º 20
0
 void testInput()
 {
   mitk::ImageToSurfaceFilter::Pointer testObject = mitk::ImageToSurfaceFilter::New();
   testObject->SetInput(m_BallImage);
   CPPUNIT_ASSERT_MESSAGE("Testing set / get input!", testObject->GetInput() == m_BallImage);
 }
Ejemplo n.º 21
0
 void GetToolName_Default_ReturnsEmptyString()
 {
   CPPUNIT_ASSERT_MESSAGE("Tool name should be empty", !strcmp(m_TrackingTool->GetToolName(), ""));
 }
Ejemplo n.º 22
0
void SQLTests::query ()
{
    if (CreateSchemaOnly())  return;

    try
    {
        FdoPtr<FdoISQLCommand> sqlCmd = (FdoISQLCommand*)mConnection->CreateCommand (FdoCommandType_SQLCommand);

        // Clean up previous tests (ignore exceptions, we'll get one if the table doesn't actually exist):
        try
        {
            sqlCmd->SetSQLStatement (L"drop table bar");
            sqlCmd->ExecuteNonQuery ();
        }
        catch (FdoException *e)
        {
            e->Release();
        }

        // Execute various tests:
        sqlCmd->SetSQLStatement (ArcSDETestConfig::SqlStmtCreateTable());
        sqlCmd->ExecuteNonQuery ();
        sqlCmd->SetSQLStatement (ArcSDETestConfig::SqlStmtInsert1());
        sqlCmd->ExecuteNonQuery ();
        sqlCmd->SetSQLStatement (L"select * from bar");
        {
            FdoPtr<FdoISQLDataReader> reader = sqlCmd->ExecuteReader ();

            // Test accessing SQLDataReader's metadata BEFORE calling ReadNext():
            IterateSQLDataReaderProperties(reader);

            reader->ReadNext ();
            CPPUNIT_ASSERT_MESSAGE ("int16 wrong", 42 == reader->GetInt16 (L"ID"));
            CPPUNIT_ASSERT_MESSAGE ("int32 wrong", 8272772 == reader->GetInt32 (L"COUNT"));
            float x = (float)reader->GetSingle (L"SCALE");
            float diff = x - 1e-2f;
            if (0 > diff)
                diff = -diff;
            CPPUNIT_ASSERT_MESSAGE ("float wrong", 1e-9 > diff);
            double y = reader->GetDouble (L"LENGTH");
            double difference = y - 10280288.29929;
            if (0 > difference)
                difference = -difference;
            CPPUNIT_ASSERT_MESSAGE ("double wrong", 1e-4 > difference);
            CPPUNIT_ASSERT_MESSAGE ("string wrong", 0 == wcscmp (L"the quick brown fox jumps over a lazy dog", reader->GetString(L"DESCRIPTION")));

            FdoPtr<FdoBLOBValue> blobValue = static_cast<FdoBLOBValue*>(reader->GetLOB(L"DATA"));
            FdoByteArray* data = blobValue->GetData();
            FdoByte test[] = { 0x25, 0x2f, 0x82, 0xe3 };
            for (int i = 0; i < data->GetCount (); i++)
                CPPUNIT_ASSERT_MESSAGE ("blob wrong", test[i] == (*data)[i]);
            data->Release ();

            FdoDateTime now = reader->GetDateTime (L"MODIFIED");
            struct tm systime;
#ifdef _WIN32
#pragma warning(disable : 4996)
            _getsystime (&systime);
#pragma warning(default : 4996)
#else
            time_t current;
            time (&current);
            localtime_r (&current, &systime);
#endif
            CPPUNIT_ASSERT_MESSAGE ("year wrong (NOTE: THIS IS MAY BE CAUSED BY TIME ZONE DIFFERENCE BETWEEN SERVER AND CLIENT MACHINES)", now.year == systime.tm_year + 1900);
            CPPUNIT_ASSERT_MESSAGE ("month wrong (NOTE: THIS IS MAY BE CAUSED BY TIME ZONE DIFFERENCE BETWEEN SERVER AND CLIENT MACHINES)", now.month == systime.tm_mon + 1);
            CPPUNIT_ASSERT_MESSAGE ("day wrong (NOTE: THIS IS OFTEN CAUSED BY TIME ZONE DIFFERENCE BETWEEN SERVER AND CLIENT MACHINES)", now.day == systime.tm_mday);
            //THE FOLLOWING TEST FAILS FREQUENTLY, SINCE THE CLIENT'S TIME AND SERVER'S TIME ARE USUALLY NOT IN SYNC:
            //CPPUNIT_ASSERT_MESSAGE ("hour wrong", now.hour == systime.tm_hour);
        }

        // Test aggregate functions in select clause:
        sqlCmd->SetSQLStatement (ArcSDETestConfig::SqlStmtInsert2());
        sqlCmd->ExecuteNonQuery ();
        sqlCmd->SetSQLStatement (L"select count(*) from bar");
        FdoPtr<FdoISQLDataReader> reader = sqlCmd->ExecuteReader();
        CPPUNIT_ASSERT_MESSAGE("Expected 1 row, got 0 rows instead.", reader->ReadNext ());
        FdoInt32 colCount = reader->GetColumnCount();
        CPPUNIT_ASSERT_MESSAGE ("column count wrong", colCount == 1);
        FdoString *colName = reader->GetColumnName(0);
        CPPUNIT_ASSERT_MESSAGE ("column name wrong", 0==FdoCommonOSUtil::wcsicmp(colName, ArcSDETestConfig::SqlCountStarColumnName()));
        FdoDataType colType = reader->GetColumnType(colName);
        if (colType==FdoDataType_Int32)
        {
            FdoInt32 iRowCount = reader->GetInt32(colName);
            CPPUNIT_ASSERT_MESSAGE("count(*) value wrong", iRowCount == 2);
        }
        else if (colType==FdoDataType_Double)
        {
            double dRowCount = reader->GetDouble(colName);
            CPPUNIT_ASSERT_MESSAGE("count(*) value wrong", dRowCount == 2);
        }
        CPPUNIT_ASSERT_MESSAGE("Expected 1 row, got 2 or more rows instead.", !reader->ReadNext ());

        // Test functions in where clause:
        sqlCmd->SetSQLStatement (ArcSDETestConfig::SqlStmtAggrQuery1());
        reader = sqlCmd->ExecuteReader();
        CPPUNIT_ASSERT_MESSAGE("Expected 1 row, got 0 rows instead.", reader->ReadNext ());
        colCount = reader->GetColumnCount();
        CPPUNIT_ASSERT_MESSAGE ("column count wrong", colCount == 1);
        colName = reader->GetColumnName(0);
        CPPUNIT_ASSERT_MESSAGE ("column name wrong", 0==FdoCommonOSUtil::wcsicmp(colName, ArcSDETestConfig::SqlAggrColumnName()));
        colType = reader->GetColumnType(colName);
        CPPUNIT_ASSERT_MESSAGE ("column type wrong", colType==FdoDataType_Double);
        double dResult = reader->GetDouble(colName);
        CPPUNIT_ASSERT_MESSAGE("ABS(SUM(length)) value wrong", ArcSDETests::fuzzyEqual(dResult, ArcSDETestConfig::SqlStmtAggrQuery1Result()));
        CPPUNIT_ASSERT_MESSAGE("Expected 1 row, got 2 or more rows instead.", !reader->ReadNext ());


        // Clean up:
        sqlCmd->SetSQLStatement (L"drop table bar");
        sqlCmd->ExecuteNonQuery ();
    }
    catch (FdoException *e)
    {
        fail(e);
    }
}
    // The tests all do the same, only in different directions
    void testRoutine(mitk::SliceNavigationController::ViewDirection viewDirection)
    {
        int dim;
        switch(viewDirection)
        {
        case(mitk::SliceNavigationController::Axial): dim = 2; break;
        case(mitk::SliceNavigationController::Frontal): dim = 1; break;
        case(mitk::SliceNavigationController::Sagittal): dim = 0; break;
        case(mitk::SliceNavigationController::Original): dim = -1; break; // This is just to get rid of a warning
        }

        /* Fill segmentation
         *
         * 1st slice: 3x3 square segmentation
         * 2nd slice: empty
         * 3rd slice: 1x1 square segmentation in corner
         * -> 2nd slice should become 2x2 square in corner
         *
         * put accessor in scope
         */

        itk::Index<3> currentPoint;
        {
            mitk::ImagePixelWriteAccessor<mitk::Tool::DefaultSegmentationDataType, 3> writeAccessor(m_SegmentationImage);

            // Fill 3x3 slice
            currentPoint[dim] = m_CenterPoint[dim] - 1;
            for (int i=-1; i<=1; ++i)
            {
                for (int j=-1; j<=1; ++j)
                {
                    currentPoint[(dim+1)%3] = m_CenterPoint[(dim+1)%3] + i;
                    currentPoint[(dim+2)%3] = m_CenterPoint[(dim+2)%3] + j;
                    writeAccessor.SetPixelByIndexSafe(currentPoint, 1);
                }
            }
            // Now i=j=1, set point two slices up
            currentPoint[dim] = m_CenterPoint[dim] + 1;
            writeAccessor.SetPixelByIndexSafe(currentPoint, 1);
        }

    //        mitk::IOUtil::Save(m_SegmentationImage, "SOME PATH");

        m_InterpolationController->SetSegmentationVolume(m_SegmentationImage);
        m_InterpolationController->SetReferenceVolume(m_ReferenceImage);

        // This could be easier...
        mitk::SliceNavigationController::Pointer navigationController = mitk::SliceNavigationController::New();
        navigationController->SetInputWorldTimeGeometry(m_SegmentationImage->GetTimeGeometry());
        navigationController->Update(viewDirection);
        mitk::Point3D pointMM;
        m_SegmentationImage->GetTimeGeometry()->GetGeometryForTimeStep(0)->IndexToWorld(m_CenterPoint, pointMM);
        navigationController->SelectSliceByPoint(pointMM);
        auto plane = navigationController->GetCurrentPlaneGeometry();
        mitk::Image::Pointer interpolationResult = m_InterpolationController->Interpolate(dim, m_CenterPoint[dim], plane, 0);

    //        mitk::IOUtil::Save(interpolationResult, "SOME PATH");

        // Write result into segmentation image
        vtkSmartPointer<mitkVtkImageOverwrite> reslicer = vtkSmartPointer<mitkVtkImageOverwrite>::New();
        reslicer->SetInputSlice(interpolationResult->GetSliceData()->GetVtkImageAccessor(interpolationResult)->GetVtkImageData());
        reslicer->SetOverwriteMode(true);
        reslicer->Modified();
        mitk::ExtractSliceFilter::Pointer extractor =  mitk::ExtractSliceFilter::New(reslicer);
        extractor->SetInput(m_SegmentationImage);
        extractor->SetTimeStep(0);
        extractor->SetWorldGeometry(plane);
        extractor->SetVtkOutputRequest(true);
        extractor->SetResliceTransformByGeometry(m_SegmentationImage->GetTimeGeometry()->GetGeometryForTimeStep(0));
        extractor->Modified();
        extractor->Update();

    //        mitk::IOUtil::Save(m_SegmentationImage, "SOME PATH");

        // Check a 4x4 square, the center of which needs to be filled
        mitk::ImagePixelReadAccessor<mitk::Tool::DefaultSegmentationDataType, 3> readAccess(m_SegmentationImage);
        currentPoint = m_CenterPoint;

        for (int i=-1; i<=2; ++i)
        {
            for (int j=-1; j<=2; ++j)
            {
                currentPoint[(dim+1)%3] = m_CenterPoint[(dim+1)%3] + i;
                currentPoint[(dim+2)%3] = m_CenterPoint[(dim+2)%3] + j;

                if (i == -1 || i == 2 || j == -1 || j == 2)
                {
                    CPPUNIT_ASSERT_MESSAGE("Have false positive segmentation.", readAccess.GetPixelByIndexSafe(currentPoint) == 0);
                }
                else
                {
                    CPPUNIT_ASSERT_MESSAGE("Have false negative segmentation.", readAccess.GetPixelByIndexSafe(currentPoint) == 1);
                }
            }
        }
    }
Ejemplo n.º 24
0
void TestMapModel::testSetMapSize_sizeGreaterThan0_updateMapSize() {
	this->mapModel->setMapSize(10);
	int mapSize = this->mapModel->getMapSize();
	CPPUNIT_ASSERT_MESSAGE("Map size is not updated", mapSize == 10);
}
Ejemplo n.º 25
0
   void testHandleAlarm()
   {
      OsSysLog::add(FAC_ALARM, PRI_DEBUG, "AlarmServerTest::testHandleAlarm");

      UtlString localhost("localhost");
      UtlString alarmId("NO_LOG");
      UtlString alarmParam("testing");
      UtlSList alarmParams;
      alarmParams.append(&alarmParam);
      UtlString oldLastString;
      tail(mAlarmFile, oldLastString);
      OsSysLog::add(FAC_ALARM, PRI_DEBUG, "oldLastString %s", oldLastString.data());
      bool rc=cAlarmServer::getInstance()->handleAlarm(localhost, alarmId, alarmParams);
      OsTask::delay(500);
      CPPUNIT_ASSERT_MESSAGE("handleAlarm('NO_LOG') failed", rc==true);
      UtlString newLastString;
      tail(mAlarmFile, newLastString);
      OsSysLog::add(FAC_ALARM, PRI_DEBUG, "newLastString %s", newLastString.data());
      CPPUNIT_ASSERT_MESSAGE("alarm with 'NO_LOG' was logged", !oldLastString.compareTo(newLastString));

      alarmId = "TEST_LOG";
      alarmParam = "single parameter";
      alarmParams.removeAll();
      alarmParams.append(&alarmParam);
      OsSysLog::add(FAC_ALARM, PRI_DEBUG, "Test TEST_LOG");
      cAlarmServer::getInstance()->handleAlarm(localhost, alarmId, alarmParams);
      OsTask::delay(DELAY);
      UtlString actualString;
      UtlString expectedString = "This is a test of the log function. Single parameter should be here: single parameter, and that's all that is required";
      tail(mAlarmFile, actualString);
      char msg[1000];
      sprintf(msg, "incorrect message was logged: actualString '%s'  expected '%s'", actualString.data(), expectedString.data());
      CPPUNIT_ASSERT_MESSAGE(msg, actualString.contains(expectedString));

      // test that non-existant alarm returns false
      alarmId = "NONEXISTANT_ID";
      rc=cAlarmServer::getInstance()->handleAlarm(localhost, alarmId, alarmParams);
      CPPUNIT_ASSERT_MESSAGE("handleAlarm('NONEXISTANT_ID') did not fail, and should have", rc!=true);

      // test that alarm with min_threshold is only logged after n attempts
      alarmId = "MIN_THRESHOLD";
      alarmParam = "one";
      alarmParams.removeAll();
      alarmParams.append(&alarmParam);
      tail(mAlarmFile, oldLastString);
      OsSysLog::add(FAC_ALARM, PRI_DEBUG, "oldLastString %s", oldLastString.data());
      cAlarmServer::getInstance()->handleAlarm(localhost, alarmId, alarmParams);
      OsTask::delay(DELAY);
      tail(mAlarmFile, newLastString);
      OsSysLog::add(FAC_ALARM, PRI_DEBUG, "newLastString %s", newLastString.data());
      CPPUNIT_ASSERT_MESSAGE("first instance of alarm with 'min_threshold' was logged", !oldLastString.compareTo(newLastString));
      alarmParam = "two";
      alarmParams.append(&alarmParam);
      cAlarmServer::getInstance()->handleAlarm(localhost, alarmId, alarmParams);
      OsTask::delay(DELAY);
      tail(mAlarmFile, actualString);
      expectedString = "This should only be logged the second time";
      sprintf(msg, "incorrect message was logged: actualString '%s'  expected '%s'", actualString.data(), expectedString.data());
      CPPUNIT_ASSERT_MESSAGE(msg, actualString.contains(expectedString));

   }
Ejemplo n.º 26
0
void TestMapModel::testSetMapHeight_heightGreaterThan0_updateMapHeight() {
	this->mapModel->setMapHeight(10);
	int mapHeight = this->mapModel->getMapHeight();
	CPPUNIT_ASSERT_MESSAGE("Map height is not updated", mapHeight == 10);
}
Ejemplo n.º 27
0
 void TestInstantiation()
 {
   mitk::ProgressBar::Pointer pb = mitk::ProgressBar::GetInstance();
   CPPUNIT_ASSERT_MESSAGE("Single instance can be created on demand", pb.IsNotNull());
 }
Ejemplo n.º 28
0
void TestMapModel::testSetMapWidth_widthGreaterThan0_updateMapWidth() {
	this->mapModel->setMapWidth(10);
	int mapWidth = this->mapModel->getMapWidth();
	CPPUNIT_ASSERT_MESSAGE("Map width is not updated", mapWidth == 10);
}
 void testInput()
 {
   mitk::ImageToUnstructuredGridFilter::Pointer testFilter = mitk::ImageToUnstructuredGridFilter::New();
   testFilter->SetInput(m_BallImage);
   CPPUNIT_ASSERT_MESSAGE("Testing set / get input!", testFilter->GetInput() == m_BallImage);
 }
Ejemplo n.º 30
0
void FilesystemTest::testDirectory() {
#ifdef _WIN32
	const string test_subdir = test_dir->Path() + "\\a";
	const string test_subsubdir = test_subdir + "\\b";
	const string test_file = test_subsubdir + "\\c.txt";
#else
	const string test_subdir = test_dir->Path() + "/a";
	const string test_subsubdir = test_subdir + "/b";
	const string test_file = test_subsubdir + "/c";
#endif

	CPPUNIT_ASSERT_MESSAGE(
		"inexistant directory is a file",
		!is_file(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"inexistant directory is a directory",
		!is_dir(test_subdir));

	CPPUNIT_ASSERT_MESSAGE(
		"failed to create test subdir",
		make_dir(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"created directory is a file",
		!is_file(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"created directory is not a directory",
		is_dir(test_subdir));

	CPPUNIT_ASSERT_MESSAGE(
		"failed to remove test subdir",
		remove_dir(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"removed directory became a file",
		!is_file(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"removed directory is still a directory",
		!is_dir(test_subdir));

	CPPUNIT_ASSERT_MESSAGE(
		"failed to create test subdirs",
		make_dirs(test_subsubdir));
	CPPUNIT_ASSERT_MESSAGE(
		"created directory is a file",
		!is_file(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"created directory is not a directory",
		is_dir(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"created directory is a file",
		!is_file(test_subsubdir));
	CPPUNIT_ASSERT_MESSAGE(
		"created directory is not a directory",
		is_dir(test_subsubdir));

	{ // create file
		ofstream file(test_file);
		file << "hello" << endl;
	}
	CPPUNIT_ASSERT_MESSAGE(
		"failed to create test file",
		is_file(test_file));

	CPPUNIT_ASSERT_MESSAGE(
		"failed to remove test subdir",
		remove_dir(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"removed directory became a file",
		!is_file(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"removed directory is still a directory",
		!is_dir(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"removed directory became a file",
		!is_file(test_subsubdir));
	CPPUNIT_ASSERT_MESSAGE(
		"removed directory is still a directory",
		!is_dir(test_subsubdir));
	CPPUNIT_ASSERT_MESSAGE(
		"removed file became a directory",
		!is_dir(test_file));
	CPPUNIT_ASSERT_MESSAGE(
		"removed file is still a file",
		!is_file(test_file));
}