diff options
Diffstat (limited to 'sal/qa/osl')
52 files changed, 24325 insertions, 0 deletions
diff --git a/sal/qa/osl/condition/makefile.mk b/sal/qa/osl/condition/makefile.mk new file mode 100644 index 000000000000..784f9c27a86e --- /dev/null +++ b/sal/qa/osl/condition/makefile.mk @@ -0,0 +1,60 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# <http://www.openoffice.org/license.html> +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +PRJ=..$/..$/.. + +PRJNAME=sal +TARGET=qa_osl_condition + +ENABLE_EXCEPTIONS=TRUE + +# --- Settings ----------------------------------------------------- + +.INCLUDE : settings.mk + +CFLAGS+= $(LFS_CFLAGS) +CXXFLAGS+= $(LFS_CFLAGS) + +# BEGIN ---------------------------------------------------------------- +# auto generated Target:Condition by codegen.pl +SHL1OBJS= \ + $(SLO)$/osl_Condition.obj + +SHL1TARGET= osl_Condition +SHL1STDLIBS= $(SALLIB) $(CPPUNITLIB) + +SHL1IMPLIB= i$(SHL1TARGET) + +DEF1NAME =$(SHL1TARGET) +SHL1VERSIONMAP = $(PRJ)$/qa$/export.map +# auto generated Target:Condition +# END ------------------------------------------------------------------ + +# --- Targets ------------------------------------------------------ + +.INCLUDE : target.mk +.INCLUDE : $(PRJ)$/qa$/cppunit_local.mk diff --git a/sal/qa/osl/condition/osl_Condition.cxx b/sal/qa/osl/condition/osl_Condition.cxx new file mode 100644 index 000000000000..415f17f6a881 --- /dev/null +++ b/sal/qa/osl/condition/osl_Condition.cxx @@ -0,0 +1,369 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ + /************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +//------------------------------------------------------------------------ +// include files +//------------------------------------------------------------------------ +#include <osl_Condition_Const.h> +#include <stdlib.h> + +using namespace osl; +using namespace rtl; + + +//------------------------------------------------------------------------ +// helper functions and classes +//------------------------------------------------------------------------ + +/** print Boolean value. +*/ +inline void printBool( sal_Bool bOk ) +{ + printf("#printBool# " ); + ( sal_True == bOk ) ? printf("TRUE!\n" ): printf("FALSE!\n" ); +} + +/** print a UNI_CODE String. +*/ +inline void printUString( const ::rtl::OUString & str ) +{ + rtl::OString aString; + + printf("#printUString_u# " ); + aString = ::rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US ); + printf("%s\n", aString.getStr( ) ); +} + +enum ConditionType +{ + thread_type_set, + thread_type_reset, + thread_type_wait, + thread_type_check +}; + +/** thread for testing Condition. + */ +class ConditionThread : public Thread +{ +public: + //get the Condition to operate + ConditionThread( ::osl::Condition& Con, ConditionType tType): m_MyCon( Con ), m_MyType( tType ) { } + + ~ConditionThread( ) + { + // LLA: do not throw in DTors! + // LLA: CPPUNIT_ASSERT_MESSAGE( "#ConditionThread does not shutdown properly.\n", sal_False == this -> isRunning( ) ); + } +protected: + ::osl::Condition& m_MyCon; + ConditionType m_MyType; + + void SAL_CALL run() + { + switch ( m_MyType ) + { + case thread_type_wait: + m_MyCon.wait(); break; + case thread_type_set: + m_MyCon.set(); break; + case thread_type_reset: + m_MyCon.reset(); break; + default: + break; + } + } +}; + + +//------------------------------------------------------------------------ +// test code start here +//------------------------------------------------------------------------ + +namespace osl_Condition +{ + + /** testing the method: + Condition() + */ + class ctors : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void ctors_001( ) + { + ::osl::Condition aCond; + bRes = aCond.check( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: create a condition its initial check state should be sal_False.", + sal_False == bRes ); + } + + void ctors_002( ) + { + ::osl::Condition aCond; + aCond.set( ); + bRes = aCond.check( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: create a condition and set it.", + sal_True == bRes ); + } + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_001 ); + CPPUNIT_TEST( ctors_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class ctors + + + /** testing the method: + void set() + */ + class set : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1, bRes2; + + void set_001( ) + { + ::osl::Condition aCond; + aCond.set( ); + bRes = aCond.check( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: check state should be sal_True after set.", + sal_True == bRes ); + } + + void set_002( ) + { + ::osl::Condition aCond; + ConditionThread myThread1( aCond, thread_type_wait ); + myThread1.create(); + bRes = myThread1.isRunning( ); + + ConditionThread myThread2( aCond, thread_type_set ); + myThread2.create(); + + myThread1.join( ); + bRes1 = myThread1.isRunning( ); + bRes2 = aCond.check( ); + myThread2.join( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: use one thread to set the condition in order to release another thread.", + sal_True == bRes && sal_False == bRes1 && sal_True == bRes2 ); + } + + + CPPUNIT_TEST_SUITE( set ); + CPPUNIT_TEST( set_001 ); + CPPUNIT_TEST( set_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class set + + + /** testing the method: + void reset() + */ + class reset : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1, bRes2; + + void reset_001( ) + { + ::osl::Condition aCond; + aCond.reset( ); + + ConditionThread myThread( aCond, thread_type_wait ); + myThread.create(); + bRes = myThread.isRunning( ); + bRes2 = aCond.check( ); + + aCond.set( ); + myThread.join( ); + bRes1 = myThread.isRunning( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: wait will cause a reset thread block, use set to release it.", + sal_True == bRes && sal_False == bRes1 && sal_False == bRes2 ); + } + + void reset_002( ) + { + ::osl::Condition aCond; + aCond.reset( ); + bRes = aCond.check( ); + aCond.set( ); + bRes1 = aCond.check( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: create a condition and reset/set it.", + ( sal_False == bRes && sal_True == bRes1 ) ); + } + + CPPUNIT_TEST_SUITE( reset ); + CPPUNIT_TEST( reset_001 ); + CPPUNIT_TEST( reset_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class reset + + + /** testing the method: + Result wait(const TimeValue *pTimeout = 0) + */ + class wait : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1, bRes2; + TimeValue *tv1; + + void setUp( ) + { + tv1 = new TimeValue; + tv1->Seconds = 1; + tv1->Nanosec = 0; + + } + + void tearDown( ) + { + delete tv1; + } + + + void wait_001( ) + { + ::osl::Condition cond1; + ::osl::Condition cond2; + ::osl::Condition cond3; + + cond1.set(); + cond2.set(); + + osl::Condition::Result r1=cond1.wait(tv1); + osl::Condition::Result r2=cond2.wait(); + osl::Condition::Result r3=cond3.wait(tv1); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test three types of wait.", + (r1 == ::osl::Condition::result_ok) && + (r2 == ::osl::Condition::result_ok) && + (r3 == ::osl::Condition::result_timeout) ); + } + + void wait_002( ) + { + ::osl::Condition aCond; + ::osl::Condition::Result wRes, wRes1; + + aCond.reset( ); + bRes = aCond.check( ); + wRes = aCond.wait( tv1 ); + + aCond.set( ); + wRes1 = aCond.wait( tv1 ); + bRes1 = aCond.check( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: wait a condition after set/reset.", + ( sal_False == bRes ) && ( sal_True == bRes1 ) && + ( ::osl::Condition::result_timeout == wRes ) && + ( ::osl::Condition::result_ok == wRes1 ) ); + } + + CPPUNIT_TEST_SUITE( wait ); + CPPUNIT_TEST( wait_001 ); + CPPUNIT_TEST( wait_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class wait + + + /** testing the method: + sal_Bool check() + */ + class check : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1, bRes2; + + void check_001( ) + { + ::osl::Condition aCond; + + aCond.reset( ); + bRes = aCond.check( ); + aCond.set( ); + bRes1 = aCond.check( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: check the condition states.", + ( sal_False == bRes && sal_True == bRes1 ) ); + } + + void check_002( ) + { + ::osl::Condition aCond; + aCond.reset( ); + + ConditionThread myThread( aCond, thread_type_set ); + myThread.create( ); + myThread.join( ); + bRes = aCond.check( ); + + ConditionThread myThread1( aCond, thread_type_reset ); + myThread1.create( ); + myThread1.join( ); + bRes1 = aCond.check( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: use threads to set/reset Condition and check it in main routine.", + ( sal_True == bRes && sal_False == bRes1 ) ); + } + + CPPUNIT_TEST_SUITE( check ); + CPPUNIT_TEST( check_001 ); + CPPUNIT_TEST( check_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class check + + +// ----------------------------------------------------------------------------- +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Condition::ctors); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Condition::set); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Condition::reset); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Condition::wait); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Condition::check); +// ----------------------------------------------------------------------------- + +} // namespace osl_Condition + + +// ----------------------------------------------------------------------------- + +CPPUNIT_PLUGIN_IMPLEMENT(); + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/condition/osl_Condition_Const.h b/sal/qa/osl/condition/osl_Condition_Const.h new file mode 100644 index 000000000000..e000e7c415a0 --- /dev/null +++ b/sal/qa/osl/condition/osl_Condition_Const.h @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _OSL_CONDITION_CONST_H_ +#define _OSL_CONDITION_CONST_H_ + +#include <sal/types.h> +#include <rtl/ustring.hxx> + +#ifndef _OSL_THREAD_HXX_ +#include <osl/thread.hxx> +#endif +#include <osl/mutex.hxx> +#include <osl/pipe.hxx> + +#ifndef _OSL_SEMAPHOR_HXX_ +#include <osl/semaphor.hxx> +#endif + +#ifndef _OSL_CONDITION_HXX_ +#include <osl/conditn.hxx> +#endif +#include <osl/time.h> + +#ifdef UNX +#include <unistd.h> +#endif + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> + +#define OSLTEST_DECLARE_USTRING( str_name, str_value ) \ + ::rtl::OUString a##str_name = rtl::OUString::createFromAscii( str_value ) + +//------------------------------------------------------------------------ +// condition names +//------------------------------------------------------------------------ +OSLTEST_DECLARE_USTRING( TestCon, "testcondition" ); + +const char pTestString[17] = "Sun Microsystems"; + + +#endif /* _OSL_CONDITION_CONST_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/file/makefile.mk b/sal/qa/osl/file/makefile.mk new file mode 100644 index 000000000000..1fad4b4d0125 --- /dev/null +++ b/sal/qa/osl/file/makefile.mk @@ -0,0 +1,85 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# <http://www.openoffice.org/license.html> +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +PRJ=..$/..$/.. + +PRJNAME=sal +TARGET=qa_osl_file + +ENABLE_EXCEPTIONS=TRUE + +# --- Settings ----------------------------------------------------- + +.INCLUDE : settings.mk + +CFLAGS+= $(LFS_CFLAGS) +CXXFLAGS+= $(LFS_CFLAGS) + +# --- BEGIN -------------------------------------------------------- +SHL1OBJS= \ + $(SLO)$/osl_File.obj +SHL1TARGET= osl_File +SHL1STDLIBS= $(SALLIB) $(CPPUNITLIB) + +SHL1IMPLIB= i$(SHL1TARGET) + +DEF1NAME =$(SHL1TARGET) +SHL1VERSIONMAP = $(PRJ)$/qa$/export.map + +#------------------------------------------------------------------- + +SHL2OBJS=$(SLO)$/test_cpy_wrt_file.obj +SHL2TARGET=tcwf +SHL2STDLIBS= $(SALLIB) $(CPPUNITLIB) +SHL2IMPLIB=i$(SHL2TARGET) +SHL2DEF=$(MISC)$/$(SHL2TARGET).def +SHL2VERSIONMAP = $(PRJ)$/qa$/export.map +DEF2NAME =$(SHL2TARGET) + + +# END -------------------------------------------------------------- + +# --- BEGIN -------------------------------------------------------- +SHL3OBJS= \ + $(SLO)$/osl_old_test_file.obj +SHL3TARGET= osl_old_test_file +SHL3STDLIBS= $(SALLIB) $(CPPUNITLIB) + +SHL3IMPLIB= i$(SHL3TARGET) + +DEF3NAME =$(SHL3TARGET) +SHL3VERSIONMAP = $(PRJ)$/qa$/export.map +# END -------------------------------------------------------------- + +#------------------------------- All object files ------------------------------- +# do this here, so we get right dependencies +SLOFILES=$(SHL1OBJS) + +# --- Targets ------------------------------------------------------ + +.INCLUDE : target.mk +.INCLUDE : $(PRJ)$/qa$/cppunit_local.mk diff --git a/sal/qa/osl/file/osl_File.cxx b/sal/qa/osl/file/osl_File.cxx new file mode 100644 index 000000000000..40eb7bc767f6 --- /dev/null +++ b/sal/qa/osl/file/osl_File.cxx @@ -0,0 +1,6338 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +//------------------------------------------------------------------------ +// include files +//------------------------------------------------------------------------ +#include <sal/types.h> +#include <rtl/ustring.hxx> +#include <rtl/ustrbuf.hxx> + +#include "osl/thread.h" + +#include "rtl/ustrbuf.hxx" +#include <osl/file.hxx> +#include <osl_File_Const.h> + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> + +using namespace osl; + +using ::rtl::OUString; +using ::rtl::OUStringToOString; +using ::rtl::OString; +using ::rtl::OStringToOUString; + +//------------------------------------------------------------------------ +// helper functions +//------------------------------------------------------------------------ + +/** detailed wrong message. +*/ +inline ::rtl::OString errorToString( const ::osl::FileBase::RC _nError ) +{ + ::rtl::OString sResult; + switch ( _nError ) { + case ::osl::FileBase::E_None: + sResult = "Success"; + break; + case ::osl::FileBase::E_PERM: + sResult = "Operation not permitted"; + break; + case ::osl::FileBase::E_NOENT: + sResult = "No such file or directory"; + break; + case ::osl::FileBase::E_EXIST: + sResult = "Already Exist"; + break; + case ::osl::FileBase::E_ACCES: + sResult = "Permission denied"; + break; + case ::osl::FileBase::E_INVAL: + sResult = "The format of the parameters was not valid"; + break; + case ::osl::FileBase::E_NOTDIR: + sResult = "Not a directory"; + break; + case ::osl::FileBase::E_ISDIR: + sResult = "Is a directory"; + break; + case ::osl::FileBase::E_BADF: + sResult = "Bad file"; + break; + case ::osl::FileBase::E_NOTEMPTY: + sResult = "The directory is not empty"; + break; + default: + sResult = "Unknown Error"; + break; + } + return sResult; +} + +rtl::OString errorToStr( ::osl::FileBase::RC const& nError) +{ + rtl::OString suBuf; + suBuf += "The returned error is: " ; + suBuf += errorToString(nError); + suBuf += "!\n"; + return suBuf; +} + +/** print a file type name. +*/ +inline void printFileType( const ::osl::FileStatus::Type nType ) +{ + printf( "#printFileType# " ); + switch ( nType ) { + case ::osl::FileStatus::Directory: + printf( "This file is a: Directory.\n" ); + break; + case ::osl::FileStatus::Volume: + printf( "This file is a: volume device.\n" ); + break; + case ::osl::FileStatus::Regular: + printf( "This file is a: regular file.\n" ); + break; + case ::osl::FileStatus::Fifo: + printf( "This file is a: fifo.\n" ); + break; + case ::osl::FileStatus::Socket: + printf( "This file is a: socket.\n" ); + break; + case ::osl::FileStatus::Link: + printf( "This file is a: link file.\n" ); + break; + case ::osl::FileStatus::Special: + printf( "This file is a: special.\n" ); + break; + case ::osl::FileStatus::Unknown: + printf( "The file type is unknown %d \n", nType ); + break; + } +} + +/** print a file attributes. +*/ +inline void printFileAttributes( const sal_Int64 nAttributes ) +{ + printf( "#printFileAttributes# This file is a: (" ); + if ( ( nAttributes | Attribute_ReadOnly ) == nAttributes ) + printf( " ReadOnly " ); + if ( ( nAttributes | Attribute_Hidden ) == nAttributes ) + printf( " Hidden " ); + if ( ( nAttributes | Attribute_Executable ) == nAttributes ) + printf( " Executable " ); + if ( ( nAttributes | Attribute_GrpWrite ) == nAttributes ) + printf( " GrpWrite " ); + if ( ( nAttributes | Attribute_GrpRead ) == nAttributes ) + printf( " GrpRead " ); + if ( ( nAttributes | Attribute_GrpExe ) == nAttributes ) + printf( " GrpExe " ); + if ( ( nAttributes | Attribute_OwnWrite ) == nAttributes ) + printf( " OwnWrite " ); + if ( ( nAttributes | Attribute_OwnRead ) == nAttributes ) + printf( " OwnRead " ); + if ( ( nAttributes | Attribute_OwnExe ) == nAttributes ) + printf( " OwnExe " ); + if ( ( nAttributes | Attribute_OthWrite ) == nAttributes ) + printf( " OthWrite " ); + if ( ( nAttributes | Attribute_OthRead ) == nAttributes ) + printf( " OthRead " ); + if ( ( nAttributes | Attribute_OthExe ) == nAttributes ) + printf( " OthExe " ); + printf( ") file!\n" ); +} + +/** print an output wrong message. +*/ +inline void printError( const ::osl::FileBase::RC nError ) +{ + printf( "#printError# " ); + printf( "%s\n", errorToStr(nError).getStr() ); +} + +/** print an signed Integer Number. +*/ +inline void printInt( sal_Int64 i ) +{ + printf( "#printInt_i64# " ); + printf( "The Integer64 is %"SAL_PRIdINT64"\n", i); +} + +/** print an unsigned Integer Number. +*/ +inline void printInt( sal_uInt64 i ) +{ + printf( "#printInt_u64# " ); + printf( "The unsigned Integer64 is %"SAL_PRIuUINT64"\n", i); +} + +/** print Boolean value. +*/ +inline void printBool( sal_Bool bOk ) +{ + printf( "#printBool# " ); + ( sal_True == bOk ) ? printf( "YES!\n" ): printf( "NO!\n" ); +} + +/** print struct TimeValue in local time format. +*/ +inline void printTime( TimeValue *tv ) +{ + oslDateTime *pDateTime = ( oslDateTime* )malloc( sizeof( oslDateTime ) ) ; + CPPUNIT_ASSERT_MESSAGE( "Error in printTime() function,malloc ", pDateTime != NULL ); + TimeValue *pLocalTV = ( TimeValue* )malloc( sizeof( TimeValue ) ); + CPPUNIT_ASSERT_MESSAGE( "Error in printTime() function,malloc ", pLocalTV != NULL ); + + CPPUNIT_ASSERT_MESSAGE( "Error in printTime() function,osl_getLocalTimeFromSystemTime ",sal_True == osl_getLocalTimeFromSystemTime( tv, pLocalTV ) ); + CPPUNIT_ASSERT_MESSAGE( "Error in printTime() function,osl_gepDateTimeFromTimeValue ",sal_True == osl_getDateTimeFromTimeValue( pLocalTV, pDateTime ) ); + + printf( "#printTime# " ); + printf( " Time is: %d/%d/%d ", pDateTime->Month, pDateTime->Day, pDateTime->Year); + switch ( pDateTime->DayOfWeek ) + { + case 0: printf("Sun. "); break; + case 1: printf("Mon. "); break; + case 2: printf("Tue. "); break; + case 3: printf("Thr. "); break; + case 4: printf("Wen. "); break; + case 5: printf("Fri. "); break; + case 6: printf("Sat. "); break; + } + printf( " %d:%d:%d %d nsecs\n", pDateTime->Hours, pDateTime->Minutes, pDateTime->Seconds, (int) pDateTime->NanoSeconds); + + free( pDateTime ); + free( pLocalTV ); +} + +/** compare two TimeValue, unit is "ms", since Windows time precision is better than UNX. +*/ + +#if ( defined UNX ) || ( defined OS2 ) //precision of time in Windows is better than UNX +# define delta 2000 //time precision, 2000ms +#else +# define delta 1800 //time precision, 1.8s +#endif + +inline sal_Int64 t_abs64(sal_Int64 _nValue) +{ + // std::abs() seems to have some ambiguity problems (so-texas) + // return abs(_nValue); + printf("t_abs64(%ld)\n", (long) _nValue); + // CPPUNIT_ASSERT(_nValue < 2147483647); + + if (_nValue < 0) + { + _nValue = -_nValue; + } + return _nValue; +} + +inline sal_Bool t_compareTime( TimeValue *m_aEndTime, TimeValue *m_aStartTime, sal_Int32 nDelta) +{ + // sal_uInt64 uTimeValue; + // sal_Int64 iTimeValue; + // + // iTimeValue = t_abs64(( tv1->Seconds - tv2->Seconds) * 1000000000 + tv1->Nanosec - tv2->Nanosec); + // uTimeValue = ( iTimeValue / 1000000 ); + + sal_Int32 nDeltaSeconds = m_aEndTime->Seconds - m_aStartTime->Seconds; + sal_Int32 nDeltaNanoSec = sal_Int32(m_aEndTime->Nanosec) - sal_Int32(m_aStartTime->Nanosec); + if (nDeltaNanoSec < 0) + { + nDeltaNanoSec = 1000000000 + nDeltaNanoSec; + nDeltaSeconds--; + } + + sal_Int32 nDeltaMilliSec = (nDeltaSeconds * 1000) + (nDeltaNanoSec / 1000000); + return ( nDeltaMilliSec < nDelta ); +} + +/** compare two OUString file name. +*/ +inline sal_Bool compareFileName( const ::rtl::OUString & ustr1, const ::rtl::OUString & ustr2 ) +{ + sal_Bool bOk; +//on Windows, the seperatar is '\', so here change to '/', then compare +#if defined (WNT ) + ::rtl::OUString ustr1new,ustr2new; + sal_Unicode reverseSlash = (sal_Unicode)'\\'; + + if (ustr1.lastIndexOf(reverseSlash) != -1) + ustr1new = ustr1.replace(reverseSlash,(sal_Unicode)'/'); + else + ustr1new = ustr1; + if (ustr2.lastIndexOf(reverseSlash) != -1) + ustr2new = ustr2.replace(reverseSlash,(sal_Unicode)'/'); + else + ustr2new = ustr2; + bOk = ustr1new.equalsIgnoreAsciiCase( ustr2new ) ; +#else + bOk = ustr1.equalsIgnoreAsciiCase( ustr2 ); +#endif + return bOk; +} + +/** compare a OUString and an ASCII file name. +*/ +inline sal_Bool compareFileName( const ::rtl::OUString & ustr, const sal_Char *astr ) +{ + (void)ustr; + ::rtl::OUString ustr1 = rtl::OUString::createFromAscii( astr ); + sal_Bool bOk = ustr1.equalsIgnoreAsciiCase( ustr1 ); // TODO: does it really compare with the same var? + + return bOk; +} + +/** simple version to judge if a file name or directory name is a URL or a system path, just to see if it + is start with "file:///";. +*/ +inline sal_Bool isURL( const sal_Char *pathname ) +{ + return ( 0 == strncmp( pathname, FILE_PREFIX, sizeof( FILE_PREFIX ) - 1 ) ); +} + +/** simple version to judge if a file name or directory name is a URL or a system path, just to see if it + is start with "file:///";. +*/ +inline sal_Bool isURL( const ::rtl::OUString pathname ) +{ + return ( ( pathname.indexOf( aPreURL ) == 0 ) ? sal_True : sal_False ); +} + +/** concat two part to form a URL or system path, add PATH_SEPERATOR between them if necessary, add "file:///" to begining if necessary. +*/ +inline void concatURL( ::rtl::OUString & pathname1, const ::rtl::OUString & pathname2 ) +{ + //check if pathname1 is full qualified URL; + if ( !isURL( pathname1 ) ) + { + ::rtl::OUString aPathName = pathname1.copy( 0 ); + ::osl::FileBase::getFileURLFromSystemPath( pathname1, aPathName ); //convert if not full qualified URL + pathname1 = aPathName.copy( 0 ); + } + + sal_Int32 index = 0; + //check if '/' is in the end of pathname1 or at the begin of pathname2; + if ( ( ( index = pathname1.lastIndexOf( aSlashURL ) ) != ( pathname1.getLength( ) - 1 ) ) && + ( ( index = pathname2.indexOf( aSlashURL ) ) != 0 ) ) + pathname1 += aSlashURL; + pathname1 += pathname2; +} + +/** create a temp test file using OUString name of full qualified URL or system path. +*/ +inline void createTestFile( const ::rtl::OUString filename ) +{ + ::rtl::OUString aPathURL = filename.copy( 0 ); + ::osl::FileBase::RC nError; + + if ( !isURL( filename ) ) + ::osl::FileBase::getFileURLFromSystemPath( filename, aPathURL ); //convert if not full qualified URL + + File aFile(aPathURL); + nError = aFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write | osl_File_OpenFlag_Create ); + //CPPUNIT_ASSERT_MESSAGE( "In createTestFile Function: creation ", ( ::osl::FileBase::E_None == nError ) || ( nError == ::osl::FileBase::E_EXIST ) ); + if ( ( ::osl::FileBase::E_None != nError ) && ( nError != ::osl::FileBase::E_EXIST )) + { + printf("createTestFile failed!\n"); + } + aFile.close(); + +} + +/** create a temp test file using OUString name of full qualified URL or system path in a base directory. +*/ +inline void createTestFile( const ::rtl::OUString basename, const ::rtl::OUString filename ) +{ + ::rtl::OUString aBaseURL = basename.copy( 0 ); + + concatURL( aBaseURL, filename ); + createTestFile( aBaseURL ); +} + +/** detete a temp test file using OUString name. +*/ +inline void deleteTestFile( const ::rtl::OUString filename ) +{ + // LLA: printf("deleteTestFile\n"); + ::rtl::OUString aPathURL = filename.copy( 0 ); + ::osl::FileBase::RC nError; + + if ( !isURL( filename ) ) + ::osl::FileBase::getFileURLFromSystemPath( filename, aPathURL ); //convert if not full qualified URL + + nError = ::osl::File::setAttributes( aPathURL, Attribute_GrpWrite| Attribute_OwnWrite| Attribute_OthWrite ); // if readonly, make writtenable. + CPPUNIT_ASSERT_MESSAGE( "In deleteTestFile Function: set writtenable ", ( ::osl::FileBase::E_None == nError ) || ( ::osl::FileBase::E_NOENT == nError ) ); + + nError = ::osl::File::remove( aPathURL ); + CPPUNIT_ASSERT_MESSAGE( "In deleteTestFile Function: remove ", ( ::osl::FileBase::E_None == nError ) || ( nError == ::osl::FileBase::E_NOENT ) ); +} + +/** delete a temp test file using OUString name of full qualified URL or system path in a base directory. +*/ +inline void deleteTestFile( const ::rtl::OUString basename, const ::rtl::OUString filename ) +{ + ::rtl::OUString aBaseURL = basename.copy( 0 ); + + concatURL( aBaseURL, filename ); + deleteTestFile( aBaseURL ); +} + +/** create a temp test directory using OUString name of full qualified URL or system path. +*/ +inline void createTestDirectory( const ::rtl::OUString dirname ) +{ + ::rtl::OUString aPathURL = dirname.copy( 0 ); + ::osl::FileBase::RC nError; + + if ( !isURL( dirname ) ) + ::osl::FileBase::getFileURLFromSystemPath( dirname, aPathURL ); //convert if not full qualified URL + nError = ::osl::Directory::create( aPathURL ); + //CPPUNIT_ASSERT_MESSAGE( "In createTestDirectory Function: creation: ", ( ::osl::FileBase::E_None == nError ) || ( nError == ::osl::FileBase::E_EXIST ) ); + if ( ( ::osl::FileBase::E_None != nError ) && ( nError != ::osl::FileBase::E_EXIST )) + printf("createTestDirectory failed!\n"); +} + +/** create a temp test directory using OUString name of full qualified URL or system path in a base directory. +*/ +inline void createTestDirectory( const ::rtl::OUString basename, const ::rtl::OUString dirname ) +{ + ::rtl::OUString aBaseURL = basename.copy( 0 ); + ::rtl::OString aString; + + concatURL( aBaseURL, dirname ); + createTestDirectory( aBaseURL ); +} + +/** delete a temp test directory using OUString name of full qualified URL or system path. +*/ +inline void deleteTestDirectory( const ::rtl::OUString dirname ) +{ + ::rtl::OUString aPathURL = dirname.copy( 0 ); + ::osl::FileBase::RC nError; + if ( !isURL( dirname ) ) + ::osl::FileBase::getFileURLFromSystemPath( dirname, aPathURL ); //convert if not full qualified URL + + ::osl::Directory testDir( aPathURL ); + if ( testDir.isOpen( ) == sal_True ) + testDir.close( ); //close if still open. + + nError = ::osl::Directory::remove( aPathURL ); + + rtl::OString strError (RTL_CONSTASCII_STRINGPARAM("In deleteTestDirectory function: remove Directory ")); + strError += ::rtl::OUStringToOString( aPathURL, RTL_TEXTENCODING_ASCII_US ); + CPPUNIT_ASSERT_MESSAGE( strError.getStr(), ( ::osl::FileBase::E_None == nError ) || ( nError == ::osl::FileBase::E_NOENT ) ); +} + +/** delete a temp test directory using OUString name of full qualified URL or system path in a base directory. +*/ +inline void deleteTestDirectory( const ::rtl::OUString basename, const ::rtl::OUString dirname ) +{ + ::rtl::OUString aBaseURL = basename.copy( 0 ); + + concatURL( aBaseURL, dirname ); + deleteTestDirectory( aBaseURL ); +} + + +/** Check for the file and directory access right. +*/ +typedef enum { + osl_Check_Mode_Exist, + osl_Check_Mode_OpenAccess, + osl_Check_Mode_ReadAccess, + osl_Check_Mode_WriteAccess +} oslCheckMode; + +// not used here +inline sal_Bool checkFile( const ::rtl::OUString & str, oslCheckMode nCheckMode ) +{ + ::osl::FileBase::RC nError1, nError2; + ::osl::File testFile( str ); + sal_Bool bCheckResult; + + bCheckResult = sal_False; + nError1 = testFile.open ( osl_File_OpenFlag_Read ); + if ( ( ::osl::FileBase::E_NOENT != nError1 ) && ( ::osl::FileBase::E_ACCES != nError1 ) ){ + + switch ( nCheckMode ) { + case osl_Check_Mode_Exist: + /// check if the file is exist. + if ( ::osl::FileBase::E_None == nError1 ) + bCheckResult = sal_True; + break; + case osl_Check_Mode_OpenAccess: + /// check if the file is openable. + if ( ::osl::FileBase::E_None == nError1 ) + bCheckResult = sal_True; + break; + case osl_Check_Mode_WriteAccess: + /// check the file name and whether it can be written. + /// write chars into the file. + sal_uInt64 nCount_write; + nError2 = testFile.write( pBuffer_Char, 10, nCount_write ); + if ( ::osl::FileBase::E_None == nError2 ) + bCheckResult = sal_True; + break; + + default: + bCheckResult = sal_False; + }/// swith + + nError2 = testFile.close( ); + CPPUNIT_ASSERT_MESSAGE( " in CheckFile() function, close file ", nError2 == FileBase::E_None ); + + } + + return bCheckResult; +} + +//check if the file exist +inline sal_Bool ifFileExist( const ::rtl::OUString & str ) +{ + sal_Bool bCheckResult = sal_False; + +/*#ifdef WNT + ::rtl::OUString aUStr = str.copy( 0 ); + if ( isURL( str ) ) + ::osl::FileBase::getSystemPathFromFileURL( str, aUStr ); + + ::rtl::OString aString = ::rtl::OUStringToOString( aUStr, RTL_TEXTENCODING_ASCII_US ); + const char *path = aString.getStr( ); + if (( _access( path, 0 ) ) != -1 ) + bCheckResult = sal_True; +#else*/ + ::rtl::OString aString = ::rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US ); + // const char *path = aString.getStr( ); + ::osl::File testFile( str ); + bCheckResult = ( osl::FileBase::E_None == testFile.open( osl_File_OpenFlag_Read ) ); + //if (bCheckResult) + //printf("%s exist!\n", path); + //else + //printf("%s not exist!\n", path); +//#endif + return bCheckResult; + +} + +//check if the file can be writen +inline sal_Bool ifFileCanWrite( const ::rtl::OUString & str ) +{ + sal_Bool bCheckResult = sal_False; + //on Windows, the file has no write right, but can be written +#ifdef WNT + ::rtl::OUString aUStr = str.copy( 0 ); + if ( isURL( str ) ) + ::osl::FileBase::getSystemPathFromFileURL( str, aUStr ); + + ::rtl::OString aString = ::rtl::OUStringToOString( aUStr, RTL_TEXTENCODING_ASCII_US ); + const char *path = aString.getStr( ); + if (( _access( path, 2 ) ) != -1 ) + bCheckResult = sal_True; + //on UNX, just test if open success with osl_File_OpenFlag_Write +#else + ::osl::File testFile( str ); + bCheckResult = (osl::FileBase::E_None == testFile.open( osl_File_OpenFlag_Write )); +#endif + return bCheckResult; +} + +inline sal_Bool checkDirectory( const ::rtl::OUString & str, oslCheckMode nCheckMode ) +{ + rtl::OUString aUString; + DirectoryItem rItem; + FileBase::RC rc; + sal_Bool bCheckResult= sal_False; + + //::std::auto_ptr<Directory> pDir( new Directory( str ) ); + Directory aDir( str ); + rc = aDir.open( ); + + if ( ( ::osl::FileBase::E_NOENT != rc ) && ( ::osl::FileBase::E_ACCES != rc ) ){ + + switch ( nCheckMode ) { + case osl_Check_Mode_Exist: + if ( rc == ::osl::FileBase::E_None ) + bCheckResult = sal_True; + break; + case osl_Check_Mode_OpenAccess: + if ( rc == ::osl::FileBase::E_None ) + bCheckResult = sal_True; + break; + case osl_Check_Mode_ReadAccess: + //rc = pDir->getNextItem( rItem, 0 ); + rc = aDir.getNextItem( rItem, 0 ); + if ( ( rc == ::osl::FileBase::E_None ) || ( rc == ::osl::FileBase::E_NOENT ) ) + bCheckResult = sal_True; + else + bCheckResult = sal_False; + break; + case osl_Check_Mode_WriteAccess: + ( ( aUString += str ) += aSlashURL ) += aTmpName2; + //if ( ( rc = pDir->create( aUString ) ) == ::osl::FileBase::E_None ) + if ( ( rc = Directory::create( aUString ) ) == ::osl::FileBase::E_None ) + { + bCheckResult = sal_True; + //rc = pDir->remove( aUString ); + rc = Directory::remove( aUString ); + CPPUNIT_ASSERT( rc == ::osl::FileBase::E_None ); + } + else + bCheckResult = sal_False; + break; + + default: + bCheckResult = sal_False; + }// switch + + rc = aDir.close( ); + CPPUNIT_ASSERT( rc == FileBase::E_None ); + + }//if + + return bCheckResult; +} + +/** construct error message +*/ +inline ::rtl::OString outputError( const ::rtl::OString & returnVal, const ::rtl::OString & rightVal, const sal_Char * msg = "") +{ + ::rtl::OString aString; + if ( returnVal.equals( rightVal ) ) + return aString; + aString += msg; + aString += ": the returned value is '"; + aString += returnVal; + aString += "', but the value should be '"; + aString += rightVal; + aString += "'."; + return aString; +} + +/** Change file mode, two version in UNIX and Windows;. +*/ +#if ( defined UNX ) || ( defined OS2 ) //chmod() method is differ in Windows +inline void changeFileMode( ::rtl::OUString & filepath, sal_Int32 mode ) +{ + rtl::OString aString; + rtl::OUString aUStr = filepath.copy( 0 ); + + if ( isURL( filepath ) ) + ::osl::FileBase::getSystemPathFromFileURL( filepath, aUStr ); + aString = ::rtl::OUStringToOString( aUStr, RTL_TEXTENCODING_ASCII_US ); + chmod( aString.getStr( ), mode ); +} +#else //Windows version +inline void changeFileMode( ::rtl::OUString & filepath, sal_Int32 mode ) +{ + (void)filepath; + (void)mode; + printf("this method is not implemented yet"); +} +#endif + +inline ::rtl::OUString getCurrentPID( void ); + + + +//------------------------------------------------------------------------ +// Beginning of the test cases for FileBase class +//------------------------------------------------------------------------ +namespace osl_FileBase +{ + + //--------------------------------------------------------------------- + // testing the method + // static inline RC getAbsoluteFileURL( const ::rtl::OUString& ustrBaseDirectoryURL, + // const ::rtl::OUString& ustrRelativeFileURL, + // ::rtl::OUString& ustrAbsoluteFileURL ) + //--------------------------------------------------------------------- + + class getAbsoluteFileURL:public CppUnit::TestFixture + { + //::osl::FileBase aFileBase; + ::rtl::OUString aResultURL1, aResultURL2, aResultURL3, aResultURL4, aResultURL5, aResultURL6; + // ::osl::FileBase::RC nError; + sal_Bool bOk; + + public: + + void check_getAbsoluteFileURL( rtl::OUString const& _suBaseURL, rtl::OString const& _sRelativeURL, ::osl::FileBase::RC _nAssumeError, rtl::OUString const& _suAssumeResultStr ); + + void getAbsoluteFileURL_001_1(); + void getAbsoluteFileURL_001_2(); + void getAbsoluteFileURL_001_3(); + void getAbsoluteFileURL_001_4(); + void getAbsoluteFileURL_001_5(); + void getAbsoluteFileURL_001_6(); + void getAbsoluteFileURL_001_7(); + void getAbsoluteFileURL_001_8(); + void getAbsoluteFileURL_002(); + void getAbsoluteFileURL_003(); + void getAbsoluteFileURL_004(); + + CPPUNIT_TEST_SUITE( getAbsoluteFileURL ); + CPPUNIT_TEST( getAbsoluteFileURL_001_1 ); + CPPUNIT_TEST( getAbsoluteFileURL_001_2 ); + CPPUNIT_TEST( getAbsoluteFileURL_001_3 ); + CPPUNIT_TEST( getAbsoluteFileURL_001_4 ); + CPPUNIT_TEST( getAbsoluteFileURL_001_5 ); + CPPUNIT_TEST( getAbsoluteFileURL_001_6 ); + CPPUNIT_TEST( getAbsoluteFileURL_001_7 ); + CPPUNIT_TEST( getAbsoluteFileURL_001_8 ); + CPPUNIT_TEST( getAbsoluteFileURL_002 ); + CPPUNIT_TEST( getAbsoluteFileURL_003 ); + CPPUNIT_TEST( getAbsoluteFileURL_004 ); + CPPUNIT_TEST_SUITE_END( ); + + }; //class getAbsoluteFileURL + + void getAbsoluteFileURL::check_getAbsoluteFileURL( rtl::OUString const& _suBaseURL, rtl::OString const& _sRelativeURL, ::osl::FileBase::RC _nAssumeError, rtl::OUString const& _suAssumeResultStr ) + { + rtl::OUString suRelativeURL = rtl::OStringToOUString(_sRelativeURL, RTL_TEXTENCODING_UTF8); + rtl::OString sBaseURL = rtl::OUStringToOString(_suBaseURL, RTL_TEXTENCODING_UTF8); + rtl::OUString suResultURL; + osl::FileBase::RC nError = FileBase::getAbsoluteFileURL( _suBaseURL, suRelativeURL, suResultURL ); + rtl::OString sResultURL = rtl::OUStringToOString( suResultURL, RTL_TEXTENCODING_UTF8); + rtl::OString sError = errorToString(nError); + printf("getAbsoluteFileURL('%s','%s') deliver absolute URL: '%s', error '%s'\n", sBaseURL.getStr(), _sRelativeURL.getStr(),sResultURL.getStr(), sError.getStr() ); + CPPUNIT_ASSERT_MESSAGE( "Assumption is wrong: error number is wrong", nError == _nAssumeError ); + if ( nError == ::osl::FileBase::E_None ) + { + sal_Bool bStrAreEqual = _suAssumeResultStr.equals( suResultURL ); + CPPUNIT_ASSERT_MESSAGE( "Assumption is wrong: ResultURL is not equal to expected URL ", bStrAreEqual == sal_True ); + } + } + + void getAbsoluteFileURL::getAbsoluteFileURL_001_1() + { + rtl::OUString suAssume = aUserDirectoryURL.concat( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/relative/file1")) ); + check_getAbsoluteFileURL( aUserDirectoryURL, "relative/file1",::osl::FileBase::E_None, suAssume ); + } + void getAbsoluteFileURL::getAbsoluteFileURL_001_2() + { + rtl::OUString suAssume = aUserDirectoryURL.concat( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/relative/file2")) ); + check_getAbsoluteFileURL( aUserDirectoryURL, "relative/./file2",::osl::FileBase::E_None, suAssume ); + } + void getAbsoluteFileURL::getAbsoluteFileURL_001_3() + { + rtl::OUString suAssume = aUserDirectoryURL.concat( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/file3")) ); + check_getAbsoluteFileURL( aUserDirectoryURL, "relative/../file3",::osl::FileBase::E_None, suAssume ); + } + void getAbsoluteFileURL::getAbsoluteFileURL_001_4() + { + rtl::OUString suAssume = aUserDirectoryURL.concat( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/file4")) ); + check_getAbsoluteFileURL( aUserDirectoryURL, "././relative/../file4",::osl::FileBase::E_None, suAssume ); + } + void getAbsoluteFileURL::getAbsoluteFileURL_001_5() + { + rtl::OUString suAssume; +#if ( defined UNX ) + suAssume = aUserDirectoryURL.concat( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/relative/")) ); +#else + suAssume = aUserDirectoryURL.concat( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/relative")) ); +#endif + check_getAbsoluteFileURL( aUserDirectoryURL, "././relative/.",::osl::FileBase::E_None, suAssume ); + } + void getAbsoluteFileURL::getAbsoluteFileURL_001_6() + { + rtl::OUString suAssume = aUserDirectoryURL.concat( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/.relative")) ); + check_getAbsoluteFileURL( aUserDirectoryURL, "./.relative",::osl::FileBase::E_None, suAssume ); + } + void getAbsoluteFileURL::getAbsoluteFileURL_001_7() + { + rtl::OUString suAssume; +#if (defined UNX ) + suAssume = aUserDirectoryURL.concat( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/.a/")) ); +#else //windows + suAssume = aUserDirectoryURL.concat( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/.a")) ); +#endif + check_getAbsoluteFileURL( aUserDirectoryURL, "./.a/mydir/..",::osl::FileBase::E_None, suAssume ); + } + void getAbsoluteFileURL::getAbsoluteFileURL_001_8() + { + rtl::OUString suAssume = aUserDirectoryURL.concat( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/tmp/ok")) ); +#if ( defined UNX ) || ( defined OS2 ) + check_getAbsoluteFileURL( aUserDirectoryURL, "tmp//ok",::osl::FileBase::E_None, suAssume ); +#else + check_getAbsoluteFileURL( aUserDirectoryURL, "tmp//ok",::osl::FileBase::E_INVAL, suAssume ); +#endif + } + void getAbsoluteFileURL::getAbsoluteFileURL_002() + { +#if ( defined UNX ) || ( defined OS2 ) //Link is not defined in Windows + ::rtl::OUString aUStr_AbsURL, aUStr_LnkFileSys( aTempDirectorySys ), aUStr_SrcFileSys( aTempDirectorySys ); + ( ( aUStr_LnkFileSys += aSlashURL ) += getCurrentPID( ) ) += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/link.file")); + ( ( aUStr_SrcFileSys += aSlashURL ) += getCurrentPID( ) ) += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/canonical.name")); + + rtl::OString strLinkFileName, strSrcFileName; + strLinkFileName = OUStringToOString( aUStr_LnkFileSys, RTL_TEXTENCODING_ASCII_US ); + strSrcFileName = OUStringToOString( aUStr_SrcFileSys, RTL_TEXTENCODING_ASCII_US ); + + createTestFile( aCanURL1 ); + sal_Int32 fd = symlink( strSrcFileName.getStr(), strLinkFileName.getStr() ); + CPPUNIT_ASSERT( fd == 0 ); + rtl::OString sLnkURL = OUStringToOString( aLnkURL1, RTL_TEXTENCODING_ASCII_US ); + rtl::OUString suAssume = aUserDirectoryURL.concat( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/canonical.name")) ); + check_getAbsoluteFileURL( aUserDirectoryURL, sLnkURL, ::osl::FileBase::E_None, suAssume ); + deleteTestFile( aCanURL1 ); + fd = remove( strLinkFileName.getStr() ); + CPPUNIT_ASSERT( fd == 0 ); +#endif + } + //please see line# 930 + void getAbsoluteFileURL::getAbsoluteFileURL_003() + { + } + void getAbsoluteFileURL::getAbsoluteFileURL_004() + { + //create two level directories under $Temp/PID/ + ::rtl::OUString aUStrUpBase = aUserDirectoryURL + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/test1")); + createTestDirectory( aUStrUpBase ); + ::rtl::OUString aUStrBase = aUserDirectoryURL + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/test1/dir1")); + createTestDirectory( aUStrBase ); + + ::rtl::OUString suAssume = aUserDirectoryURL.concat( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/mytestfile")) ); + check_getAbsoluteFileURL( aUStrBase, "../../mytestfile" , ::osl::FileBase::E_None, suAssume ); + deleteTestDirectory( aUStrBase ); + deleteTestDirectory( aUStrUpBase ); + } + //--------------------------------------------------------------------- + // testing two methods: + // static inline RC getSystemPathFromFileURL( const ::rtl::OUString& ustrFileURL, + // ::rtl::OUString& ustrSystemPath ) + // static RC getFileURLFromSystemPath( const ::rtl::OUString & ustrSystemPath, + // ::rtl::OUString & ustrFileURL ); + //--------------------------------------------------------------------- + class SystemPath_FileURL:public CppUnit::TestFixture + { + //::osl::FileBase aFileBase; + // ::rtl::OUString aUStr; + // ::osl::FileBase::RC nError; + + //void check_getSystemPathFromFileURL(rtl::OString const& _sURL, ::osl::FileBase::RC _nAssumeError, rtl::OString const& _sAssumeResultStr); + void check_SystemPath_FileURL(rtl::OString const& _sSource, ::osl::FileBase::RC _nAssumeError, rtl::OString const& _sAssumeResultStr, sal_Bool bDirection = sal_True ); + void checkWNTBehaviour_getSystemPathFromFileURL(rtl::OString const& _sURL, ::osl::FileBase::RC _nAssumeError, rtl::OString const& _sWNTAssumeResultString ); + void checkUNXBehaviour_getSystemPathFromFileURL(rtl::OString const& _sURL, ::osl::FileBase::RC _nAssumeError, rtl::OString const& _sUnixAssumeResultString ); + void checkWNTBehaviour_getFileURLFromSystemPath(rtl::OString const& _sSysPath, ::osl::FileBase::RC _nAssumeError, rtl::OString const& _sWNTAssumeResultString); + void checkUNXBehaviour_getFileURLFromSystemPath(rtl::OString const& _sSysPath, ::osl::FileBase::RC _nAssumeError, rtl::OString const& _sUnixAssumeResultString); + + public: + // test code. + void getSystemPathFromFileURL_001_1( ); + void getSystemPathFromFileURL_001_2( ); + void getSystemPathFromFileURL_001_21( ); + void getSystemPathFromFileURL_001_22( ); + void getSystemPathFromFileURL_001_3( ); + void getSystemPathFromFileURL_001_31( ); + void getSystemPathFromFileURL_001_4( ); + void getSystemPathFromFileURL_001_41( ); + void getSystemPathFromFileURL_001_5( ); + void getSystemPathFromFileURL_001_51( ); + void getSystemPathFromFileURL_001_52( ); + void getSystemPathFromFileURL_001_53( ); + void getSystemPathFromFileURL_001_6( ); + void getSystemPathFromFileURL_001_61( ); + void getSystemPathFromFileURL_001_7( ); + void getSystemPathFromFileURL_001_71( ); + void getSystemPathFromFileURL_001_8( ); + void getSystemPathFromFileURL_001_81( ); + void getSystemPathFromFileURL_001_9( ); + void getSystemPathFromFileURL_001_91( ); + void getSystemPathFromFileURL_001_92( ); + void getSystemPathFromFileURL_004( ); + void getSystemPathFromFileURL_005( ); + + //test case fot getFileURLFromSystemPath + void getFileURLFromSystemPath_001( ); + void getFileURLFromSystemPath_002( ); + void getFileURLFromSystemPath_003( ); + void getFileURLFromSystemPath_004( ); + void getFileURLFromSystemPath_005( ); + + CPPUNIT_TEST_SUITE( SystemPath_FileURL ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_1 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_2 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_21 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_22 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_3 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_31 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_4 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_41 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_5 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_51 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_52 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_53 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_6 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_61 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_7 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_71 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_8 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_81 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_9 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_91 ); + CPPUNIT_TEST( getSystemPathFromFileURL_001_92 ); + CPPUNIT_TEST( getSystemPathFromFileURL_004 ); + CPPUNIT_TEST( getSystemPathFromFileURL_005 ); + CPPUNIT_TEST( getFileURLFromSystemPath_001 ); + CPPUNIT_TEST( getFileURLFromSystemPath_002 ); + CPPUNIT_TEST( getFileURLFromSystemPath_003 ); + CPPUNIT_TEST( getFileURLFromSystemPath_004 ); + CPPUNIT_TEST( getFileURLFromSystemPath_005 ); + CPPUNIT_TEST_SUITE_END( ); + };// class SystemPath_FileURL + + + // if bDirection==sal_True, check getSystemPathFromFileURL + // if bDirection==sal_False, check getFileURLFromSystemPath + void SystemPath_FileURL::check_SystemPath_FileURL(rtl::OString const& _sSource, ::osl::FileBase::RC _nAssumeError, rtl::OString const& _sAssumeResultStr, sal_Bool bDirection) + { + // PRE: URL as String + rtl::OUString suSource; + rtl::OUString suStr; + suSource = rtl::OStringToOUString(_sSource, RTL_TEXTENCODING_UTF8); + ::osl::FileBase::RC nError; + if ( bDirection == sal_True ) + nError = osl::FileBase::getSystemPathFromFileURL( suSource, suStr ); + else + nError = osl::FileBase::getFileURLFromSystemPath( suSource, suStr ); + + // if the given string is gt length 0, + // we check also this string + rtl::OString sStr = rtl::OUStringToOString(suStr, RTL_TEXTENCODING_UTF8); + rtl::OString sError = errorToString(nError); + if ( bDirection == sal_True ) + printf("getSystemPathFromFileURL('%s') deliver system path: '%s', error '%s'\n", _sSource.getStr(), sStr.getStr(), sError.getStr() ); + else + printf("getFileURLFromSystemPath('%s') deliver File URL: '%s', error '%s'\n", _sSource.getStr(), sStr.getStr(), sError.getStr() ); + + // rtl::OUString suStrEncode = rtl::Uri::encode(suStr, rtl_UriCharClassUnoParamValue, rtl_UriEncodeKeepEscapes, RTL_TEXTENCODING_UTF8); + // sStr = rtl::OUStringToOString(suStr, RTL_TEXTENCODING_UTF8); + // printf("UTF8: %s\n", sStr.getStr() ); + + if (_sAssumeResultStr.getLength() > 0) + { + sal_Bool bStrAreEqual = _sAssumeResultStr.equals(sStr); + CPPUNIT_ASSERT_MESSAGE( "Assumption is wrong", + nError == _nAssumeError && bStrAreEqual == sal_True ); + } + else + { + CPPUNIT_ASSERT_MESSAGE( "Assumption is wrong", nError == _nAssumeError ); + } + } + void SystemPath_FileURL::checkWNTBehaviour_getSystemPathFromFileURL(rtl::OString const& _sURL, ::osl::FileBase::RC _nAssumeError, rtl::OString const& _sWNTAssumeResultString) + { +#if ( defined WNT ) + check_SystemPath_FileURL(_sURL, _nAssumeError, _sWNTAssumeResultString); +#else + (void)_sURL; + (void)_nAssumeError; + (void)_sWNTAssumeResultString; +#endif + } + + void SystemPath_FileURL::checkUNXBehaviour_getSystemPathFromFileURL(rtl::OString const& _sURL, ::osl::FileBase::RC _nAssumeError, rtl::OString const& _sUnixAssumeResultString) + { +#if ( defined UNX ) + check_SystemPath_FileURL(_sURL, _nAssumeError, _sUnixAssumeResultString); +#else + (void)_sURL; + (void)_nAssumeError; + (void)_sUnixAssumeResultString; +#endif + } + + void SystemPath_FileURL::checkWNTBehaviour_getFileURLFromSystemPath(rtl::OString const& _sSysPath, ::osl::FileBase::RC _nAssumeError, rtl::OString const& _sWNTAssumeResultString) + { +#if ( defined WNT ) + check_SystemPath_FileURL(_sSysPath, _nAssumeError, _sWNTAssumeResultString, sal_False ); +#else + (void)_sSysPath; + (void)_nAssumeError; + (void)_sWNTAssumeResultString; +#endif + } + + void SystemPath_FileURL::checkUNXBehaviour_getFileURLFromSystemPath(rtl::OString const& _sSysPath, ::osl::FileBase::RC _nAssumeError, rtl::OString const& _sUnixAssumeResultString) + { +#if ( defined UNX ) + check_SystemPath_FileURL(_sSysPath, _nAssumeError, _sUnixAssumeResultString, sal_False ); +#else + (void)_sSysPath; + (void)_nAssumeError; + (void)_sUnixAssumeResultString; +#endif + } + + /** LLA: Test for getSystemPathFromFileURL() + this test is splitted into 2 different OS tests, + the first function checkUNXBehaviour... runs only on Unix based Systems, + the second only on windows based systems + the first parameter are a file URL where we want to get the system path of, + the second parameter is the assumed error of the osl_getSystemPathFromFileURL() function, + the thrid parameter is the assumed result string, the string will only test, if it's length is greater 0 + */ + + void SystemPath_FileURL::getSystemPathFromFileURL_001_1() + { + rtl::OString sURL(""); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_INVAL, ""); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_INVAL, ""); + } + + void SystemPath_FileURL::getSystemPathFromFileURL_001_2() + { + rtl::OString sURL("/"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_INVAL, ""); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "\\"); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_21() + { + // rtl::OString sURL("%2f"); + rtl::OString sURL("%2F"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "/"); // LLA: this is may be a BUG + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_INVAL, ""); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_22() + { + rtl::OString sURL("file:///tmp%2Fmydir"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_INVAL, ""); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_INVAL, ""); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_3() + { + rtl::OString sURL("a"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "a"); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "a"); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_31() + { + rtl::OString sURL("tmpname"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "tmpname"); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "tmpname"); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_4() + { + rtl::OString sURL("file://"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, ""); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_INVAL, ""); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_41() + { + rtl::OString sURL("file://localhost/tmp"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, ""); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_INVAL, ""); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_5() + { + rtl::OString sURL("file:///tmp"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "/tmp"); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_INVAL, ""); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_51() + { + rtl::OString sURL("file://c:/tmp"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "c:/tmp"); // LLA: this is may be a BUG + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_INVAL, ""); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_52() + { + rtl::OString sURL("file:///c:/tmp"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "/c:/tmp"); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "c:\\tmp"); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_53() + { +// LLA: is this a legal file path? + rtl::OString sURL("file:///c|/tmp"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "/c|/tmp"); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "c:\\tmp"); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_6() + { + rtl::OString sURL("file:///tmp/first"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "/tmp/first"); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_INVAL, ""); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_61() + { + rtl::OString sURL("file:///c:/tmp/first"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "/c:/tmp/first"); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "c:\\tmp\\first"); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_7() + { + rtl::OString sURL("file:///tmp/../second"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "/tmp/../second"); // LLA: may be a BUG + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_INVAL, ""); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_71() + { + rtl::OString sURL("file:///c:/tmp/../second"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "/c:/tmp/../second"); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "c:\\tmp\\..\\second"); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_8() + { + rtl::OString sURL("../tmp"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "../tmp"); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "..\\tmp"); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_81() + { + rtl::OString sURL("file://~/tmp"); + char* home_path; + home_path = getenv("HOME"); + rtl::OString expResult(home_path); + expResult += "/tmp"; + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, expResult ); + // checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "\\tmp"); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_9() + { + rtl::OString sURL("file:///tmp/first%20second"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "/tmp/first second"); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_INVAL, ""); + } + void SystemPath_FileURL::getSystemPathFromFileURL_001_91() + { + rtl::OString sURL("file:///c:/tmp/first%20second"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "/c:/tmp/first second"); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, "c:\\tmp\\first second"); + } + + void SystemPath_FileURL::getSystemPathFromFileURL_001_92() + { + rtl::OString sURL("ca@#;+.,$///78no%01ni..name"); + checkUNXBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_None, ""); + checkWNTBehaviour_getSystemPathFromFileURL(sURL, osl::FileBase::E_INVAL, ""); + } + + //normal legal case + void SystemPath_FileURL::getSystemPathFromFileURL_004( ) + { + ::rtl::OUString aUStr; + ::rtl::OUString aUNormalURL( aTmpName6 ); + ::rtl::OUString aUResultURL ( aSysPath4 ); + ::osl::FileBase::RC nError = osl::FileBase::getSystemPathFromFileURL( aUNormalURL, aUStr ); + + sal_Bool bOk = compareFileName( aUStr, aUResultURL ); + + ::rtl::OString sError("test for getSystemPathFromFileURL(' "); + sError += ::rtl::OUStringToOString( aUNormalURL, RTL_TEXTENCODING_ASCII_US ); + sError += " ') function:use an absolute file URL, "; + sError += outputError(::rtl::OUStringToOString( aUStr, RTL_TEXTENCODING_ASCII_US ), + ::rtl::OUStringToOString( aUResultURL, RTL_TEXTENCODING_ASCII_US )); + + CPPUNIT_ASSERT_MESSAGE(sError.getStr(), ( osl::FileBase::E_None == nError ) && ( sal_True == bOk ) ); + + } + + //CJK charactors case + void SystemPath_FileURL::getSystemPathFromFileURL_005( ) + { + ::rtl::OUString aUStr; + createTestDirectory( aTmpName10 ); + ::rtl::OUString aUNormalURL( aTmpName10 ); + ::rtl::OUString aUResultURL ( aSysPath5 ); + + ::osl::FileBase::RC nError = osl::FileBase::getSystemPathFromFileURL( aUNormalURL, aUStr ); + + sal_Bool bOk = compareFileName( aUStr, aUResultURL ); + + ::rtl::OString sError("test for getSystemPathFromFileURL(' "); + sError += ::rtl::OUStringToOString( aUNormalURL, RTL_TEXTENCODING_ASCII_US ); + sError += " ') function:use a CJK coded absolute URL, "; + sError += outputError(::rtl::OUStringToOString( aUStr, RTL_TEXTENCODING_ASCII_US ), + ::rtl::OUStringToOString( aUResultURL, RTL_TEXTENCODING_ASCII_US )); + deleteTestDirectory( aTmpName10 ); + + CPPUNIT_ASSERT_MESSAGE( sError.getStr(), ( osl::FileBase::E_None == nError ) && ( sal_True == bOk ) ); + } + + void SystemPath_FileURL::getFileURLFromSystemPath_001() + { + rtl::OString sSysPath("~/tmp"); + char* home_path; + home_path = getenv("HOME"); + rtl::OString expResult(home_path); + expResult = "file://"+ expResult + "/tmp"; + checkUNXBehaviour_getFileURLFromSystemPath(sSysPath, osl::FileBase::E_None, expResult ); + checkWNTBehaviour_getFileURLFromSystemPath(sSysPath, osl::FileBase::E_None, "~/tmp"); + } + void SystemPath_FileURL::getFileURLFromSystemPath_002() + { + rtl::OString sSysPath("c:/tmp"); + checkUNXBehaviour_getFileURLFromSystemPath(sSysPath, osl::FileBase::E_None, "c:/tmp"); + checkWNTBehaviour_getFileURLFromSystemPath(sSysPath, osl::FileBase::E_None, "file:///c:/tmp"); + } + void SystemPath_FileURL::getFileURLFromSystemPath_003() + { + rtl::OString sSysPath("file:///temp"); + checkUNXBehaviour_getFileURLFromSystemPath(sSysPath, osl::FileBase::E_INVAL, ""); + checkWNTBehaviour_getFileURLFromSystemPath(sSysPath, osl::FileBase::E_INVAL, ""); + } + void SystemPath_FileURL::getFileURLFromSystemPath_004() + { + rtl::OString sSysPath("//tmp//first start"); + checkUNXBehaviour_getFileURLFromSystemPath(sSysPath, osl::FileBase::E_None, "file:///tmp/first%20start"); + checkWNTBehaviour_getFileURLFromSystemPath(sSysPath, osl::FileBase::E_INVAL, ""); + } + void SystemPath_FileURL::getFileURLFromSystemPath_005() + { + rtl::OString sSysPath(""); + checkUNXBehaviour_getFileURLFromSystemPath(sSysPath, osl::FileBase::E_INVAL, ""); + checkWNTBehaviour_getFileURLFromSystemPath(sSysPath, osl::FileBase::E_INVAL, ""); + } + // start with "~user", not impletment + // void SystemPath_FileURL::getFileURLFromSystemPath_006() + + + + + //--------------------------------------------------------------------- + // testing the method + // static inline RC searchFileURL( const ::rtl::OUString& ustrFileName, + // const ::rtl::OUString& ustrSearchPath, + // ::rtl::OUString& ustrFileURL ) + //--------------------------------------------------------------------- + class searchFileURL:public CppUnit::TestFixture + { + //::osl::FileBase aFileBase; + ::rtl::OUString aUStr; + ::osl::FileBase::RC nError1, nError2, nError3,nError4; + + public: + + // test code. + void searchFileURL_001( ) + { + /* search file is passed by system filename */ + nError1 = ::osl::FileBase::searchFileURL( aTmpName1, aUserDirectorySys, aUStr ); + /* search file is passed by full qualified file URL */ + nError2 = ::osl::FileBase::searchFileURL( aCanURL1, aUserDirectorySys, aUStr ); + /* search file is passed by relative file path */ + nError3 = ::osl::FileBase::searchFileURL( aRelURL4, aUserDirectorySys, aUStr ); + + CPPUNIT_ASSERT_MESSAGE( "test for searchFileURL function: system filename/URL filename/relative path, system directory, searched files that is not exist, but it reply invalid error, did not pass in (W32) ", + ( osl::FileBase::E_NOENT == nError1 ) && + ( osl::FileBase::E_NOENT == nError2 ) && + ( osl::FileBase::E_NOENT == nError3 )); + } + + void searchFileURL_002( ) + { + /* search file is passed by system filename */ + nError1 = ::osl::FileBase::searchFileURL( aTempDirectorySys, aRootSys, aUStr ); + sal_Bool bOk1 = compareFileName( aUStr, aTempDirectoryURL ); + /* search file is passed by full qualified file URL */ + nError2 = ::osl::FileBase::searchFileURL( aTempDirectoryURL, aRootSys, aUStr ); + sal_Bool bOk2 = compareFileName( aUStr, aTempDirectoryURL ); + /* search file is passed by relative file path */ + nError3 = ::osl::FileBase::searchFileURL( aRelURL5, aRootSys, aUStr ); + sal_Bool bOk3 = compareFileName( aUStr, aTempDirectoryURL ); + /* search file is passed by an exist file */ + createTestFile( aCanURL1 ); + nError4 = ::osl::FileBase::searchFileURL( aCanURL4, aUserDirectorySys, aUStr ); + sal_Bool bOk4 = compareFileName( aUStr, aCanURL1 ); + deleteTestFile( aCanURL1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for searchFileURL function: system filename/URL filename/relative path, system directory, searched file already exist.", + ( osl::FileBase::E_None == nError1 ) && + ( osl::FileBase::E_None == nError2 ) && + ( osl::FileBase::E_None == nError3 ) && + ( osl::FileBase::E_None == nError4 ) && + ( sal_True == bOk1 ) && + ( sal_True == bOk2 ) && + ( sal_True == bOk3 ) && + ( sal_True == bOk4 ) ); + } + + + void searchFileURL_003( ) + { + OSLTEST_DECLARE( SystemPathList, TEST_PLATFORM_ROOT":"TEST_PLATFORM_ROOT TEST_PLATFORM_TEMP":"TEST_PLATFORM_ROOT"system/path" ); + nError1 = ::osl::FileBase::searchFileURL( aUserDirectoryURL, aSystemPathList, aUStr ); + sal_Bool bOk = compareFileName( aUStr, aUserDirectoryURL ); + CPPUNIT_ASSERT_MESSAGE( "test for searchFileURL function: search directory is a list of system paths", + ( osl::FileBase::E_None == nError1 ) && + ( sal_True == bOk ) ); + } + + void searchFileURL_004( ) + { + OSLTEST_DECLARE( SystemPathList, TEST_PLATFORM_ROOT PATH_LIST_DELIMITER TEST_PLATFORM_ROOT TEST_PLATFORM_TEMP PATH_LIST_DELIMITER TEST_PLATFORM_ROOT "system/path/../name" ); + nError1 = ::osl::FileBase::searchFileURL( aUserDirectoryURL, aSystemPathList, aUStr ); + sal_Bool bOk = compareFileName( aUStr, aUserDirectoryURL ); + CPPUNIT_ASSERT_MESSAGE( "test for searchFileURL function: search directory is a list of system paths", + ( osl::FileBase::E_None == nError1 ) && + ( sal_True == bOk ) ); + } + + void searchFileURL_005( ) + { + nError1 = ::osl::FileBase::searchFileURL( aUserDirectoryURL, aNullURL, aUStr ); + sal_Bool bOk = compareFileName( aUStr, aUserDirectoryURL ); + CPPUNIT_ASSERT_MESSAGE( "test for searchFileURL function: search directory is NULL", + ( osl::FileBase::E_None == nError1 ) && + ( sal_True == bOk ) ); + } + + CPPUNIT_TEST_SUITE( searchFileURL ); + CPPUNIT_TEST( searchFileURL_001 ); + CPPUNIT_TEST( searchFileURL_002 ); + CPPUNIT_TEST( searchFileURL_003 ); + CPPUNIT_TEST( searchFileURL_004 ); + CPPUNIT_TEST( searchFileURL_005 ); + CPPUNIT_TEST_SUITE_END( ); + };// class searchFileURL + + + //--------------------------------------------------------------------- + // testing the method + // static inline RC getTempDirURL( ::rtl::OUString& ustrTempDirURL ) + //--------------------------------------------------------------------- + class getTempDirURL:public CppUnit::TestFixture + { + //::osl::FileBase aFileBase; + ::rtl::OUString aUStr; + ::osl::FileBase::RC nError; + + public: + // initialization + void setUp( ) + { + nError = FileBase::getTempDirURL( aUStr ); + } + + void tearDown( ) + { + } + + // test code. + void getTempDirURL_001( ) + { + + CPPUNIT_ASSERT_MESSAGE( "test for getTempDirURL function: excution", + ( osl::FileBase::E_None == nError ) ); + } + + void getTempDirURL_002( ) + { + CPPUNIT_ASSERT_MESSAGE( "test for getTempDirURL function: test for open and write access rights", + checkDirectory( aUStr, osl_Check_Mode_OpenAccess ) && + checkDirectory( aUStr, osl_Check_Mode_ReadAccess ) && + checkDirectory( aUStr,osl_Check_Mode_WriteAccess ) ); + } + + CPPUNIT_TEST_SUITE( getTempDirURL ); + CPPUNIT_TEST( getTempDirURL_001 ); + CPPUNIT_TEST( getTempDirURL_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getTempDirURL + + + //--------------------------------------------------------------------- + // testing the method + // static inline RC createTempFile( ::rtl::OUString* pustrDirectoryURL, + // oslFileHandle* pHandle, + // ::rtl::OUString* pustrTempFileURL) + //--------------------------------------------------------------------- + class createTempFile:public CppUnit::TestFixture + { + //::osl::FileBase aFileBase; + ::osl::FileBase::RC nError1, nError2; + sal_Bool bOK; + + oslFileHandle *pHandle; + ::rtl::OUString *pUStr_DirURL; + ::rtl::OUString *pUStr_FileURL; + + public: + + // initialization + void setUp( ) + { + pHandle = new oslFileHandle(); + pUStr_DirURL = new ::rtl::OUString( aUserDirectoryURL ); + pUStr_FileURL = new ::rtl::OUString(); + //*pUStr_DirURL = aUserDirectoryURL; /// create temp file in /tmp/PID or c:\temp\PID.*/ + } + + void tearDown( ) + { + delete pUStr_DirURL; + delete pUStr_FileURL; + delete pHandle; + } + + // test code. + void createTempFile_001( ) + { + nError1 = FileBase::createTempFile( pUStr_DirURL, pHandle, pUStr_FileURL ); + ::osl::File testFile( *pUStr_FileURL ); + nError2 = testFile.open( osl_File_OpenFlag_Create ); + if ( osl::FileBase::E_EXIST == nError2 ) { + osl_closeFile( *pHandle ); + deleteTestFile( *pUStr_FileURL ); + } + + CPPUNIT_ASSERT_MESSAGE( "test for createTempFile function: create temp file and test the existence", + ( osl::FileBase::E_None == nError1 ) && ( pHandle != NULL ) && ( osl::FileBase::E_EXIST== nError2 ) ); + } + + void createTempFile_002( ) + { + bOK = sal_False; + nError1 = FileBase::createTempFile( pUStr_DirURL, pHandle, pUStr_FileURL ); + ::osl::File testFile( *pUStr_FileURL ); + nError2 = testFile.open( osl_File_OpenFlag_Create ); + + CPPUNIT_ASSERT_MESSAGE( "createTempFile function: create a temp file, but it does not exist", + ( osl::FileBase::E_None == nError1 ) && ( pHandle != NULL ) && + ( osl::FileBase::E_EXIST == nError2 ) ); + + //check file if have the write permission + if ( osl::FileBase::E_EXIST == nError2 ) { + bOK = ifFileCanWrite( *pUStr_FileURL ); + osl_closeFile( *pHandle ); + deleteTestFile( *pUStr_FileURL ); + } + + CPPUNIT_ASSERT_MESSAGE( "test for open and write access rights, in (W32), it did not have write access right, but it should be writtenable.", + ( sal_True == bOK ) ); + } + + void createTempFile_003( ) + { + nError1 = FileBase::createTempFile( pUStr_DirURL, pHandle, 0 ); + //the temp file will be removed when return from createTempFile + bOK = ( pHandle != NULL && pHandle != 0); + if ( sal_True == bOK ) + osl_closeFile( *pHandle ); + + CPPUNIT_ASSERT_MESSAGE( "test for createTempFile function: set pUStrFileURL to 0 to let it remove the file after call.", + ( ::osl::FileBase::E_None == nError1 ) &&( sal_True == bOK ) ); + } + void createTempFile_004( ) + { + nError1 = FileBase::createTempFile( pUStr_DirURL, 0, pUStr_FileURL ); + bOK = ( pUStr_FileURL != 0); + ::osl::File testFile( *pUStr_FileURL ); + nError2 = testFile.open( osl_File_OpenFlag_Create ); + deleteTestFile( *pUStr_FileURL ); + CPPUNIT_ASSERT_MESSAGE( "createTempFile function: create a temp file, but it does not exist", + ( osl::FileBase::E_None == nError1 ) && ( osl::FileBase::E_EXIST == nError2 ) &&( sal_True == bOK ) ); + + } + + CPPUNIT_TEST_SUITE( createTempFile ); + CPPUNIT_TEST( createTempFile_001 ); + CPPUNIT_TEST( createTempFile_002 ); + CPPUNIT_TEST( createTempFile_003 ); + CPPUNIT_TEST( createTempFile_004 ); + CPPUNIT_TEST_SUITE_END( ); + };// class createTempFile + + // ----------------------------------------------------------------------------- + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_FileBase::getAbsoluteFileURL, "osl_FileBase" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_FileBase::SystemPath_FileURL, "osl_FileBase" ); + // CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_FileBase::getFileURLFromSystemPath, "osl_FileBase" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_FileBase::searchFileURL, "osl_FileBase" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_FileBase::getTempDirURL, "osl_FileBase" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_FileBase::createTempFile, "osl_FileBase" ); +}// namespace osl_FileBase + + +//------------------------------------------------------------------------ +// Beginning of the test cases for VolumeInfo class +//------------------------------------------------------------------------ +namespace osl_VolumeInfo +{ + + //--------------------------------------------------------------------- + // testing the method + // VolumeInfo( sal_uInt32 nMask ): _nMask( nMask ) + //--------------------------------------------------------------------- + class ctors : public CppUnit::TestFixture + { + ::rtl::OUString aUStr; + ::osl::FileBase::RC nError1, nError2; + + ::osl::VolumeDevice aVolumeDevice1; + + public: + // initialization + void setUp( ) + { + } + + void tearDown( ) + { + } + + // test code. + void ctors_001( ) + { + ::osl::VolumeInfo aVolumeInfo( 0 ); + nError1 = ::osl::Directory::getVolumeInfo( aRootURL, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + sal_uInt64 uiTotalSpace = aVolumeInfo.getTotalSpace( ); + sal_uInt32 uiMaxPathLength = aVolumeInfo.getMaxPathLength( ); + aUStr = aVolumeInfo.getFileSystemName( ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors function: mask is empty", + ( 0 == uiTotalSpace ) && + ( 0 == uiMaxPathLength ) && + sal_True == compareFileName( aUStr, aNullURL ) ); + } + +#if ( defined UNX ) || ( defined OS2 ) + void ctors_002( ) + { + ::osl::VolumeInfo aVolumeInfo( VolumeInfoMask_TotalSpace | + VolumeInfoMask_UsedSpace | + VolumeInfoMask_FileSystemName ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL4, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + //CPPUNIT_ASSERT( aVolumeInfo.isValid( mask ) ); + sal_uInt64 uiTotalSpace = aVolumeInfo.getTotalSpace( ); + sal_uInt64 uiUsedSpace = aVolumeInfo.getUsedSpace( ); + aUStr = aVolumeInfo.getFileSystemName( ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors function: mask is specified as certain valid fields, and get the masked fields", + ( 0 != uiTotalSpace ) && + ( 0 != uiUsedSpace ) && + sal_True == compareFileName( aUStr, "nfs" ) ); + } +#else /// Windows version,here we can not determine whichvolume in Windows is serve as an nfs volume. + void ctors_002( ) + { + CPPUNIT_ASSERT_MESSAGE( "test for ctors function: mask is specified as certain valid fields, and get the masked fields( Windows version )", + 1 == 1 ); + } +#endif + + void ctors_003( ) + { + + sal_Int32 mask1 = VolumeInfoMask_FreeSpace; + ::osl::VolumeInfo aVolumeInfo1( mask1 ); + nError1 = ::osl::Directory::getVolumeInfo( aRootURL, aVolumeInfo1 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo1.isValid( mask1 ) ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + + sal_uInt64 uiTotalSpace1 = aVolumeInfo1.getTotalSpace( ); + aUStr = aVolumeInfo1.getFileSystemName( ); + + sal_Int32 mask2 = VolumeInfoMask_TotalSpace; + ::osl::VolumeInfo aVolumeInfo2( mask2 ); + nError2 = ::osl::Directory::getVolumeInfo( aRootURL, aVolumeInfo2 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo2.isValid( mask2 ) ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError2 ); + + sal_uInt64 uiTotalSpace2 = aVolumeInfo2.getTotalSpace( ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors function: mask is specified as certain valid fields, but get unmasked fields, use mask to FreeSpace, but I can get TotalSpace, did not pass in (UNX)(W32)", + ( 0 == uiTotalSpace1 ) && ( 0 != uiTotalSpace2 ) && + sal_True == compareFileName( aUStr, aNullURL ) ); + } + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_001 ); + CPPUNIT_TEST( ctors_002 ); + CPPUNIT_TEST( ctors_003 ); + CPPUNIT_TEST_SUITE_END( ); + };// class ctors + + + //--------------------------------------------------------------------- + // testing the method + // inline sal_Bool isValid( sal_uInt32 nMask ) const + //--------------------------------------------------------------------- + class isValid : public CppUnit::TestFixture + { + ::osl::VolumeDevice aVolumeDevice; + ::rtl::OUString aUStr; + ::osl::FileBase::RC nError1, nError2; + + public: + // initialization + void setUp( ) + { + } + + void tearDown( ) + { + + } + + // test code. + void isValid_001( ) + { + sal_Int32 mask = 0; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL4, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for isValid function: no fields specified.", + sal_True == aVolumeInfo.isValid( mask ) ); + } + +#if ( defined UNX ) || ( defined OS2 ) + void isValid_002( ) + { + sal_Int32 mask = VolumeInfoMask_Attributes | VolumeInfoMask_TotalSpace | osl_VolumeInfo_Mask_UsedSpace | + osl_VolumeInfo_Mask_FreeSpace | osl_VolumeInfo_Mask_MaxNameLength | + osl_VolumeInfo_Mask_MaxPathLength | osl_VolumeInfo_Mask_FileSystemName; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL4, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for isValid function: all valid fields specified for a nfs volume.", + sal_True == aVolumeInfo.isValid( mask ) ); + } +#else /// Windows version,here we can not determine whichvolume in Windows is serve as an nfs volume. + void isValid_002( ) + { + CPPUNIT_ASSERT_MESSAGE( "test for isValid function: all valid fields specified for a nfs volume.( Windows version )", + 1 == 1 ); + } +#endif + + void isValid_003( ) + { + ::osl::VolumeDevice aVolumeDevice1; + sal_Int32 mask = VolumeInfoMask_Attributes; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + sal_Bool bOk1 = aVolumeInfo.isValid( mask ); + + nError1 = ::osl::Directory::getVolumeInfo( aVolURL2, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + sal_Bool bOk2 = aVolumeInfo.isValid( mask ); + + CPPUNIT_ASSERT_MESSAGE( "test for isValid function: VolumeInfoMask_Attributes, it should be valid for some volume such as /, floppy, cdrom, etc. but it did not pass", + ( sal_True == bOk1 ) && ( sal_True == bOk2 ) ); + } + + CPPUNIT_TEST_SUITE( isValid ); + CPPUNIT_TEST( isValid_001 ); + CPPUNIT_TEST( isValid_002 ); + CPPUNIT_TEST( isValid_003 ); + CPPUNIT_TEST_SUITE_END( ); + };// class isValid + + //--------------------------------------------------------------------- + // testing the method + // inline sal_Bool getRemoteFlag() const + //--------------------------------------------------------------------- + class getRemoteFlag : public CppUnit::TestFixture + { + ::osl::VolumeDevice aVolumeDevice; + ::rtl::OUString aUStr; + ::osl::FileBase::RC nError1, nError2; + + public: + // test code. + void getRemoteFlag_001( ) + { + sal_Int32 mask = VolumeInfoMask_Attributes; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + sal_Bool bOk = aVolumeInfo.getRemoteFlag( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getRemoteFlag function: get a volume device which is not remote.", + ( sal_False == bOk ) ); + } + + #if ( defined UNX ) || ( defined OS2 ) //remote Volume is different in Solaris and Windows + void getRemoteFlag_002( ) + { + sal_Int32 mask = VolumeInfoMask_Attributes; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL4, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + sal_Bool bOk = aVolumeInfo.getRemoteFlag( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getRemoteFlag function: get a volume device which is remote( Solaris version ).", + ( sal_True == bOk ) ); + } +#else //Windows version + void getRemoteFlag_002( ) + { + CPPUNIT_ASSERT_MESSAGE( "test for getRemoteFlag function: get a volume device which is remote( Windows version )", + 1 == 1 ); + } +#endif + + CPPUNIT_TEST_SUITE( getRemoteFlag ); + CPPUNIT_TEST( getRemoteFlag_001 ); + CPPUNIT_TEST( getRemoteFlag_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getRemoteFlag + + //--------------------------------------------------------------------- + // testing the method + // inline sal_Bool getRemoveableFlag() const + //--------------------------------------------------------------------- + class getRemoveableFlag : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + + public: + // test code. + void getRemoveableFlag_001( ) + { + sal_Int32 mask = VolumeInfoMask_Attributes; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + sal_Bool bOk = aVolumeInfo.getRemoveableFlag( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getRemoveableFlag function: get a volume device which is not removable.", + sal_False == bOk ); + } + + void getRemoveableFlag_002( ) + { + sal_Int32 mask = VolumeInfoMask_Attributes; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL2, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + sal_Bool bOk = aVolumeInfo.getRemoveableFlag( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getRemoveableFlag function: get a volume device which is removable, not sure, here we use floppy disk, but it did not pass.", + sal_True == bOk ); + } + CPPUNIT_TEST_SUITE( getRemoveableFlag ); + CPPUNIT_TEST( getRemoveableFlag_001 ); + CPPUNIT_TEST( getRemoveableFlag_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getRemoveableFlag + + + //--------------------------------------------------------------------- + // testing the method + // inline sal_Bool getCompactDiscFlag() const + //--------------------------------------------------------------------- + class getCompactDiscFlag : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + + public: + // test code. + void getCompactDiscFlag_001( ) + { + sal_Int32 mask = VolumeInfoMask_Attributes; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + sal_Bool bOk = aVolumeInfo.getCompactDiscFlag( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getCompactDiscFlag function: get a volume device which is not a cdrom.", + ( sal_False == bOk ) ); + } + + void getCompactDiscFlag_002( ) + { + sal_Int32 mask = VolumeInfoMask_Attributes; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL6, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + sal_Bool bOk = aVolumeInfo.getCompactDiscFlag( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getCompactDiscFlag function: get a cdrom volume device flag, it did not pass.", + ( sal_True == bOk ) ); + } + CPPUNIT_TEST_SUITE( getCompactDiscFlag ); + CPPUNIT_TEST( getCompactDiscFlag_001 ); + CPPUNIT_TEST( getCompactDiscFlag_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getCompactDiscFlag + + + //--------------------------------------------------------------------- + // testing the method + // inline sal_Bool getFloppyDiskFlag() const + //--------------------------------------------------------------------- + class getFloppyDiskFlag : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + + public: + // test code. + void getFloppyDiskFlag_001( ) + { + sal_Int32 mask = VolumeInfoMask_Attributes; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + sal_Bool bOk = aVolumeInfo.getFloppyDiskFlag( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFloppyDiskFlag function: get a volume device which is not a floppy disk.", + ( sal_False == bOk ) ); + } + + void getFloppyDiskFlag_002( ) + { + sal_Int32 mask = VolumeInfoMask_Attributes; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL2, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + sal_Bool bOk = aVolumeInfo.getFloppyDiskFlag( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFloppyDiskFlag function: get a floppy volume device flag, it did not pass.", + ( sal_True == bOk ) ); + } + CPPUNIT_TEST_SUITE( getFloppyDiskFlag ); + CPPUNIT_TEST( getFloppyDiskFlag_001 ); + CPPUNIT_TEST( getFloppyDiskFlag_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getFloppyDiskFlag + + + //--------------------------------------------------------------------- + // testing the method + // inline sal_Bool getFixedDiskFlag() const + //--------------------------------------------------------------------- + class getFixedDiskFlag : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + + public: + // test code. + void getFixedDiskFlag_001( ) + { + sal_Int32 mask = VolumeInfoMask_Attributes; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL2, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + sal_Bool bOk = aVolumeInfo.getFixedDiskFlag( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFixedDiskFlag function: get a volume device which is not a fixed disk.", + ( sal_False == bOk ) ); + } + + void getFixedDiskFlag_002( ) + { + sal_Int32 mask = VolumeInfoMask_Attributes; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + sal_Bool bOk = aVolumeInfo.getFixedDiskFlag( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFixedDiskFlag function: get a fixed disk volume device flag, it did not pass.", + ( sal_True == bOk ) ); + } + CPPUNIT_TEST_SUITE( getFixedDiskFlag ); + CPPUNIT_TEST( getFixedDiskFlag_001 ); + CPPUNIT_TEST( getFixedDiskFlag_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getFixedDiskFlag + + //--------------------------------------------------------------------- + // testing the method + // inline sal_Bool getRAMDiskFlag() const + //--------------------------------------------------------------------- + class getRAMDiskFlag : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + + public: + // test code. + void getRAMDiskFlag_001( ) + { + sal_Int32 mask = VolumeInfoMask_Attributes; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + sal_Bool bOk = aVolumeInfo.getRAMDiskFlag( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getRAMDiskFlag function: get a volume device which is not a RAM disk.", + ( sal_False == bOk ) ); + } + + void getRAMDiskFlag_002( ) + { + sal_Int32 mask = VolumeInfoMask_Attributes; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + sal_Bool bOk = aVolumeInfo.getRAMDiskFlag( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getRAMDiskFlag function: FIX ME, don't know how to get a RAM disk flag, perhaps Windows 98 boot disk can create a RAM disk, it did not pass in (UNX)(W32).", + ( sal_True == bOk ) ); + } + CPPUNIT_TEST_SUITE( getRAMDiskFlag ); + CPPUNIT_TEST( getRAMDiskFlag_001 ); + CPPUNIT_TEST( getRAMDiskFlag_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getRAMDiskFlag + + + //--------------------------------------------------------------------- + // testing the method + // inline sal_uInt64 getTotalSpace() const + //--------------------------------------------------------------------- + class getTotalSpace : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + + public: + // test code. + void getTotalSpace_001( ) + { + sal_Int32 mask = VolumeInfoMask_TotalSpace; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo.isValid( mask ) ); + sal_uInt64 uiTotalSpace = aVolumeInfo.getTotalSpace( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getTotalSpace function: get total space of Fixed disk volume mounted on /, it should not be 0", + 0 != uiTotalSpace ); + } + + #if defined( UNX ) + void getTotalSpace_002( ) + { + sal_Int32 mask = VolumeInfoMask_TotalSpace; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL3, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo.isValid( mask ) ); + sal_uInt64 uiTotalSpace = aVolumeInfo.getTotalSpace( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getTotalSpace function: get total space of /proc, it should be 0", + 0 == uiTotalSpace ); + } +#else /// Windows version, in Windows, there is no /proc directory + void getTotalSpace_002( ) + { + CPPUNIT_ASSERT_MESSAGE( "test for getTotalSpace function:not applicable for /proc( Windows version )", + 1 == 1 ); + } +#endif + + + +#if defined(SOLARIS) + void getTotalSpace_003( ) + { + struct statvfs aStatFS; + static const sal_Char name[] = "/"; + + memset (&aStatFS, 0, sizeof(aStatFS)); + statvfs( name, &aStatFS); + sal_uInt64 TotalSpace = aStatFS.f_frsize * aStatFS.f_blocks ; + + sal_Int32 mask = VolumeInfoMask_TotalSpace; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo.isValid( mask ) ); + sal_uInt64 uiTotalSpace = aVolumeInfo.getTotalSpace( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getTotalSpace function: get total space by hand, then compare with getTotalSpace, it did not pass", + uiTotalSpace == TotalSpace ); + } +#else /// Windows version + void getTotalSpace_003( ) + { + CPPUNIT_ASSERT_MESSAGE( "test for getTotalSpace function:not implemented yet( Windows version )", + 1 == 1 ); + } +#endif + + CPPUNIT_TEST_SUITE( getTotalSpace ); + CPPUNIT_TEST( getTotalSpace_001 ); + CPPUNIT_TEST( getTotalSpace_002 ); + CPPUNIT_TEST( getTotalSpace_003 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getTotalSpace + + //--------------------------------------------------------------------- + // testing the method + // inline sal_uInt64 getFreeSpace() const + //--------------------------------------------------------------------- + class getFreeSpace : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + + public: + // test code. + void getFreeSpace_001( ) + { + sal_Int32 mask = VolumeInfoMask_FreeSpace; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo.isValid( mask ) ); + sal_uInt64 uiFreeSpace = aVolumeInfo.getFreeSpace( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFreeSpace function: get free space of Fixed disk volume mounted on /, it should not be 0, suggestion: returned value, -1 is better, since some times the free space may be 0", + 0 != uiFreeSpace ); + } + +#if defined( UNX ) + void getFreeSpace_002( ) + { + sal_Int32 mask = VolumeInfoMask_FreeSpace; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL3, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo.isValid( mask ) ); + sal_uInt64 uiFreeSpace = aVolumeInfo.getFreeSpace( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFreeSpace function: get free space of /proc, it should be 0", + 0 == uiFreeSpace ); + } +#else /// Windows version, in Windows, there is no /proc directory + void getFreeSpace_002( ) + { + CPPUNIT_ASSERT_MESSAGE( "test for getFreeSpace function: not applicable for /proc( Windows version )", + 1 == 1 ); + } +#endif + + +#if defined(SOLARIS) + void getFreeSpace_003( ) + { + struct statvfs aStatFS; + static const sal_Char name[] = "/"; + + memset (&aStatFS, 0, sizeof(aStatFS)); + statvfs( name, &aStatFS); + sal_uInt64 FreeSpace = aStatFS.f_bfree * aStatFS.f_frsize ; + + sal_Int32 mask = VolumeInfoMask_FreeSpace; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo.isValid( mask ) ); + sal_uInt64 uiFreeSpace = aVolumeInfo.getFreeSpace( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFreeSpace function: get free space by hand, then compare with getFreeSpace, it did not pass", + uiFreeSpace == FreeSpace ); + } +#else //Windows version + void getFreeSpace_003( ) + { + CPPUNIT_ASSERT_MESSAGE( "test for getFreeSpace function: not implemented yet( Windows version )", + 1 == 1 ); + } +#endif + + + CPPUNIT_TEST_SUITE( getFreeSpace ); + CPPUNIT_TEST( getFreeSpace_001 ); + CPPUNIT_TEST( getFreeSpace_002 ); + CPPUNIT_TEST( getFreeSpace_003 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getFreeSpace + + //--------------------------------------------------------------------- + // testing the method + // inline sal_uInt64 getUsedSpace() const + //--------------------------------------------------------------------- + class getUsedSpace : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + + public: + // test code. + void getUsedSpace_001( ) + { + sal_Int32 mask = VolumeInfoMask_UsedSpace; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo.isValid( mask ) ); + sal_uInt64 uiUsedSpace = aVolumeInfo.getUsedSpace( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getUsedSpace function: get used space of Fixed disk volume mounted on /, it should not be 0, suggestion: returned value, -1 is better, since some times the used space may be 0", + 0 != uiUsedSpace ); + } + +#if defined( UNX ) + void getUsedSpace_002( ) + { + sal_Int32 mask = VolumeInfoMask_UsedSpace; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL3, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo.isValid( mask ) ); + sal_uInt64 uiUsedSpace = aVolumeInfo.getUsedSpace( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getUsedSpace function: get used space of /proc, it should be 0", + 0 == uiUsedSpace ); + } +#else /// Windows version, in Windows, there is no /proc directory + void getUsedSpace_002( ) + { + CPPUNIT_ASSERT_MESSAGE( "test for getUsedSpace function: not applicable for /proc( Windows version )", + 1 == 1 ); + } +#endif + + +#if defined(SOLARIS) + void getUsedSpace_003( ) + { + struct statvfs aStatFS; + static const sal_Char name[] = "/"; + + memset (&aStatFS, 0, sizeof(aStatFS)); + statvfs( name, &aStatFS); + sal_uInt64 UsedSpace = ( aStatFS.f_blocks - aStatFS.f_bavail ) * aStatFS.f_frsize; + + + sal_Int32 mask = VolumeInfoMask_UsedSpace; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo.isValid( mask ) ); + sal_uInt64 uiUsedSpace = aVolumeInfo.getUsedSpace( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getUsedSpace function: get used space by hand, then compare with getUsedSpace, it did not pass", + uiUsedSpace == UsedSpace ); + } +#else //Windows version + void getUsedSpace_003( ) + { + CPPUNIT_ASSERT_MESSAGE( "test for getUsedSpace function: not implemented yet( Windows version )", + 1 == 1 ); + } +#endif + + + CPPUNIT_TEST_SUITE( getUsedSpace ); + CPPUNIT_TEST( getUsedSpace_001 ); + CPPUNIT_TEST( getUsedSpace_002 ); + CPPUNIT_TEST( getUsedSpace_003 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getUsedSpace + + + //--------------------------------------------------------------------- + // testing the method + // inline sal_uInt32 getMaxNameLength() const + //--------------------------------------------------------------------- + class getMaxNameLength : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + + public: + // test code. + void getMaxNameLength_001( ) + { + sal_Int32 mask = VolumeInfoMask_MaxNameLength; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo.isValid( mask ) ); + sal_uInt32 uiMaxNameLength = aVolumeInfo.getMaxNameLength( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getMaxNameLength function: get max name length of Fixed disk volume mounted on /, it should not be 0", + 0 != uiMaxNameLength ); + } + + +#if ( defined UNX ) || ( defined OS2 ) + void getMaxNameLength_002( ) + { + struct statvfs aStatFS; + static const sal_Char name[] = "/"; + + memset (&aStatFS, 0, sizeof(aStatFS)); + statvfs( name, &aStatFS); + sal_uInt64 MaxNameLength = aStatFS.f_namemax; + + sal_Int32 mask = VolumeInfoMask_MaxNameLength; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo.isValid( mask ) ); + sal_uInt64 uiMaxNameLength = aVolumeInfo.getMaxNameLength( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getMaxNameLength function: get max name length by hand, then compare with getMaxNameLength", + uiMaxNameLength == MaxNameLength ); + } +#else //Windows version + void getMaxNameLength_002( ) + { + CPPUNIT_ASSERT_MESSAGE( "test for getMaxNameLength function: not implemented yet( Windows version )", + 1 == 1 ); + } +#endif + + CPPUNIT_TEST_SUITE( getMaxNameLength ); + CPPUNIT_TEST( getMaxNameLength_001 ); + CPPUNIT_TEST( getMaxNameLength_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getMaxNameLength + + + //--------------------------------------------------------------------- + // testing the method + // inline sal_uInt32 getMaxPathLength() const + //--------------------------------------------------------------------- + class getMaxPathLength : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + + public: + // test code. + void getMaxPathLength_001( ) + { + sal_Int32 mask = VolumeInfoMask_MaxPathLength; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo.isValid( mask ) ); + sal_uInt32 uiMaxPathLength = aVolumeInfo.getMaxPathLength( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getMaxPathLength function: get max path length of Fixed disk volume mounted on /, it should not be 0", + 0 != uiMaxPathLength ); + } + + +#if ( defined UNX ) || ( defined OS2 ) + void getMaxPathLength_002( ) + { + sal_Int32 mask = VolumeInfoMask_MaxPathLength; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo.isValid( mask ) ); + sal_uInt64 uiMaxPathLength = aVolumeInfo.getMaxPathLength( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getMaxPathLength function: get max path length by hand, then compare with getMaxPathLength", + uiMaxPathLength == PATH_MAX ); + } +#else //Windows version + void getMaxPathLength_002( ) + { + CPPUNIT_ASSERT_MESSAGE( "test for getMaxPathLength function: not implemented yet( Windows version )", + 1 == 1 ); + } +#endif + + + CPPUNIT_TEST_SUITE( getMaxPathLength ); + CPPUNIT_TEST( getMaxPathLength_001 ); + CPPUNIT_TEST( getMaxPathLength_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getMaxPathLength + + + //--------------------------------------------------------------------- + // testing the method + // inline ::rtl::OUString getFileSystemName() const + //--------------------------------------------------------------------- + class getFileSystemName : public CppUnit::TestFixture + { + ::rtl::OUString aUStr; + ::osl::FileBase::RC nError1; + + public: + // test code. + void getFileSystemName_001( ) + { + sal_Int32 mask = VolumeInfoMask_FileSystemName; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo.isValid( mask ) ); + aUStr = aVolumeInfo.getFileSystemName( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFileSystemName function: get file system name of Fixed disk volume mounted on /, it should not be empty string", + sal_False == compareFileName( aNullURL, aUStr ) ); + } + + +#if defined(SOLARIS) + void getFileSystemName_002( ) + { + struct statvfs aStatFS; + static const sal_Char name[] = "/"; + + memset (&aStatFS, 0, sizeof(aStatFS)); + statvfs( name, &aStatFS); + sal_Char * astrFileSystemName = aStatFS.f_basetype; + + sal_Int32 mask = VolumeInfoMask_FileSystemName; + ::osl::VolumeInfo aVolumeInfo( mask ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + CPPUNIT_ASSERT( sal_True == aVolumeInfo.isValid( mask ) ); + aUStr = aVolumeInfo.getFileSystemName( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFileSystemName function: get file system name by hand, then compare with getFileSystemName", + sal_True == compareFileName( aUStr, astrFileSystemName ) ); + } +#else //Windows version + void getFileSystemName_002( ) + { + CPPUNIT_ASSERT_MESSAGE( "test for getFileSystemName function: not implemented yet( Windows version )", + 1 == 1 ); + } +#endif + + + CPPUNIT_TEST_SUITE( getFileSystemName ); + CPPUNIT_TEST( getFileSystemName_001 ); + CPPUNIT_TEST( getFileSystemName_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getFileSystemName + + //--------------------------------------------------------------------- + // testing the method + // inline VolumeDevice getDeviceHandle() const + //--------------------------------------------------------------------- + class getDeviceHandle : public CppUnit::TestFixture + { + ::rtl::OUString aUStr; + ::osl::FileBase::RC nError1; + + public: + // test code. + void getDeviceHandle_001( ) + { + ::osl::VolumeInfo aVolumeInfo( VolumeInfoMask_Attributes ); + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + CPPUNIT_ASSERT( osl::FileBase::E_None == nError1 ); + + ::osl::VolumeDevice aVolumeDevice1( aVolumeInfo.getDeviceHandle( ) ); + sal_Bool bOk = compareFileName( aNullURL, aVolumeDevice1.getMountPath( ) ); + + CPPUNIT_ASSERT_MESSAGE( "test for getDeviceHandle function: get device handle of Fixed disk volume mounted on /, it should not be NULL, it did not pass in (W32) (UNX).", + ( sal_False == bOk ) ); + } + + CPPUNIT_TEST_SUITE( getDeviceHandle ); + CPPUNIT_TEST( getDeviceHandle_001 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getDeviceHandle + + + // ----------------------------------------------------------------------------- + /*CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_VolumeInfo::ctors, "osl_VolumeInfo" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_VolumeInfo::isValid, "osl_VolumeInfo" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_VolumeInfo::getRemoteFlag, "osl_VolumeInfo" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_VolumeInfo::getRemoveableFlag, "osl_VolumeInfo" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_VolumeInfo::getCompactDiscFlag, "osl_VolumeInfo" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_VolumeInfo::getFloppyDiskFlag, "osl_VolumeInfo" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_VolumeInfo::getFixedDiskFlag, "osl_VolumeInfo" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_VolumeInfo::getRAMDiskFlag, "osl_VolumeInfo" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_VolumeInfo::getTotalSpace, "osl_VolumeInfo" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_VolumeInfo::getFreeSpace, "osl_VolumeInfo" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_VolumeInfo::getUsedSpace, "osl_VolumeInfo" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_VolumeInfo::getMaxNameLength, "osl_VolumeInfo" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_VolumeInfo::getMaxPathLength, "osl_VolumeInfo" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_VolumeInfo::getFileSystemName, "osl_VolumeInfo" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_VolumeInfo::getDeviceHandle, "osl_VolumeInfo" );*/ +}// namespace osl_VolumeInfo + + + +//------------------------------------------------------------------------ +// Beginning of the test cases for VolumeDevice class +//------------------------------------------------------------------------ +namespace osl_FileStatus +{ + + //--------------------------------------------------------------------- + // testing the method + // FileStatus( sal_uInt32 nMask ): _nMask( nMask ) + //--------------------------------------------------------------------- + class ctors : public CppUnit::TestFixture + { + ::rtl::OUString aUStr; + ::osl::FileBase::RC nError1, nError2; + ::osl::DirectoryItem rItem; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + + ::std::auto_ptr<Directory> pDir( new Directory( aTmpName3 ) ); + nError1 = pDir->open( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = pDir->getNextItem( rItem, 0 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + pDir->close(); + /* + Directory aDir( aTmpName3 ); + nError1 = aDir.open(); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = aDir.getNextItem( rItem, 0 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + aDir.close(); + */ + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void ctors_001( ) + { + ::osl::FileStatus rFileStatus( FileStatusMask_All ); + nError1 = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + aUStr = rFileStatus.getFileName( ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors function: mask all and see the file name", + sal_True == compareFileName( aUStr, aTmpName2) ); + } + + void ctors_002( ) + { + ::osl::FileStatus rFileStatus( 0 ); + nError1 = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + aUStr = rFileStatus.getFileName( ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors function: mask is empty", + sal_True == compareFileName( aUStr, aNullURL) ); + } + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_001 ); + CPPUNIT_TEST( ctors_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class ctors + + + //--------------------------------------------------------------------- + // testing the method + // inline sal_Bool isValid( sal_uInt32 nMask ) const + //--------------------------------------------------------------------- + class isValid : public CppUnit::TestFixture + { + ::rtl::OUString aUStr; + ::osl::Directory *pDir; + ::osl::DirectoryItem rItem_file, rItem_link; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + + pDir = new Directory( aTmpName3 ); + //::std::auto_ptr<Directory> pDir( new Directory( aTmpName3 ) ); + ::osl::FileBase::RC nError1 = pDir->open( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = pDir->getNextItem( rItem_file, 1 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + } + + void tearDown( ) + { + ::osl::FileBase::RC nError1 = pDir->close( ); + delete pDir; + CPPUNIT_ASSERT_MESSAGE( errorToStr(nError1).getStr(), ::osl::FileBase::E_None == nError1 ); + + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void isValid_001( ) + { + sal_uInt32 mask = 0; + ::osl::FileStatus rFileStatus( mask ); + ::osl::FileBase::RC nError1 = rItem_file.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + sal_Bool bOk = rFileStatus.isValid( mask ); + + CPPUNIT_ASSERT_MESSAGE( "test for isValid function: no fields specified", + ( sal_True == bOk ) ); + } + + void check_FileStatus(::osl::FileStatus const& _aStatus) + { + rtl::OString sStat; + if (_aStatus.isValid(FileStatusMask_Type)) + { + sStat += "type "; + } + if (_aStatus.isValid(FileStatusMask_Attributes)) + { + sStat += "attributes "; + } + if (_aStatus.isValid(FileStatusMask_CreationTime)) + { + sStat += "ctime "; + } + if (_aStatus.isValid(FileStatusMask_AccessTime)) + { + sStat += "atime "; + } + if (_aStatus.isValid(FileStatusMask_ModifyTime)) + { + sStat += "mtime "; + } + if (_aStatus.isValid(FileStatusMask_FileSize)) + { + sStat += "filesize "; + } + if (_aStatus.isValid(FileStatusMask_FileName)) + { + sStat += "filename "; + } + if (_aStatus.isValid(FileStatusMask_FileURL)) + { + sStat += "fileurl "; + } + printf("mask: %s\n", sStat.getStr()); + } + + void isValid_002( ) + { + createTestFile( aTmpName6 ); + sal_uInt32 mask_file = ( FileStatusMask_Type | FileStatusMask_Attributes | + FileStatusMask_CreationTime | FileStatusMask_AccessTime | + FileStatusMask_ModifyTime | FileStatusMask_FileSize | + FileStatusMask_FileName | FileStatusMask_FileURL) ; + ::osl::FileStatus rFileStatus( mask_file ); + ::osl::FileBase::RC nError1 = ::osl::DirectoryItem::get( aTmpName6, rItem_file ); + nError1 = rItem_file.getFileStatus( rFileStatus ); + + CPPUNIT_ASSERT_MESSAGE( errorToStr(nError1).getStr(), ::osl::FileBase::E_None == nError1 ); + +// LLA: this is wrong, we never should try to check on all masks +// only on one. +// Second, it's not a bug, if a value is not valid, it's an unhandled feature. + +// sal_Bool bOk = rFileStatus.isValid( mask_file ); + + check_FileStatus(rFileStatus); + deleteTestFile( aTmpName6 ); + + // CPPUNIT_ASSERT_MESSAGE( "test for isValid function: regular file mask fields test, #FileStatusMask_CreationTime# should be valid field for regular file, but feedback is invalid", + // ( sal_True == bOk ) ); + } + + //Link is not defined in Windows, and on Linux, we can not get the directory item of the link file + // LLA: we have to differ to filesystems, normal filesystems support links (EXT2, ...) + // castrated filesystems don't (FAT, FAT32) + // Windows NT NTFS support links, but the windows api don't :-( + + void isValid_003( ) + { +#if defined ( UNX ) + // ::osl::FileBase::RC nError; + sal_Int32 fd; + + ::rtl::OUString aUStr_LnkFileSys( aTempDirectorySys ), aUStr_SrcFileSys( aTempDirectorySys ); + ( ( aUStr_LnkFileSys += aSlashURL ) += getCurrentPID( ) ) += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/tmpdir/link.file")); + ( ( aUStr_SrcFileSys += aSlashURL ) += getCurrentPID( ) ) += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/tmpdir/tmpname")); + + rtl::OString strLinkFileName; + rtl::OString strSrcFileName; + strLinkFileName = OUStringToOString( aUStr_LnkFileSys, RTL_TEXTENCODING_ASCII_US ); + strSrcFileName = OUStringToOString( aUStr_SrcFileSys, RTL_TEXTENCODING_ASCII_US ); + + //create a link file and link it to file "/tmp/PID/tmpdir/tmpname" + fd = symlink( strSrcFileName.getStr(), strLinkFileName.getStr() ); + CPPUNIT_ASSERT( fd == 0 ); + + // testDirectory is "/tmp/PID/tmpdir/" + ::osl::Directory testDirectory( aTmpName3 ); + ::osl::FileBase::RC nError1 = testDirectory.open( ); + ::rtl::OUString aFileName (RTL_CONSTASCII_USTRINGPARAM("link.file")); + sal_Bool bOk = sal_False; + while (1) { + nError1 = testDirectory.getNextItem( rItem_link, 4 ); + if (::osl::FileBase::E_None == nError1) { + sal_uInt32 mask_link = FileStatusMask_FileName | FileStatusMask_LinkTargetURL; + ::osl::FileStatus rFileStatus( mask_link ); + rItem_link.getFileStatus( rFileStatus ); + if ( compareFileName( rFileStatus.getFileName( ), aFileName) == sal_True ) + { + //printf("find the link file"); + if ( sal_True == rFileStatus.isValid( FileStatusMask_LinkTargetURL ) ) + { + bOk = sal_True; + break; + } + } + } + else + break; + }; + + fd = remove( strLinkFileName.getStr() ); + CPPUNIT_ASSERT( fd == 0 ); + + CPPUNIT_ASSERT_MESSAGE("test for isValid function: link file, check for LinkTargetURL", + ( sal_True == bOk ) ); +#endif + } + + void isValid_004( ) + { + sal_uInt32 mask_file_all = FileStatusMask_All; + ::osl::FileStatus rFileStatus_all( mask_file_all ); + ::osl::FileBase::RC nError1 = rItem_file.getFileStatus( rFileStatus_all ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + check_FileStatus(rFileStatus_all); +// LLA: this is wrong +// sal_Bool bOk1 = rFileStatus_all.isValid( mask_file_all ); + + sal_uInt32 mask_file_val = FileStatusMask_Validate; + ::osl::FileStatus rFileStatus_val( mask_file_val ); + nError1 = rItem_file.getFileStatus( rFileStatus_val ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + // sal_Bool bOk2 = rFileStatus_val.isValid( mask_file_val ); + + check_FileStatus(rFileStatus_val); + // CPPUNIT_ASSERT_MESSAGE( "test for isValid function: check for Mask_All and Validate, really not sure what validate used for and how to use it, help me. did not pass (W32)(UNX).", + // ( sal_False == bOk1 ) && ( sal_True == bOk2 ) ); + } + + + CPPUNIT_TEST_SUITE( isValid ); + CPPUNIT_TEST( isValid_001 ); + CPPUNIT_TEST( isValid_002 ); + CPPUNIT_TEST( isValid_003 ); + CPPUNIT_TEST( isValid_004 ); + CPPUNIT_TEST_SUITE_END( ); + };// class ctors + + + //--------------------------------------------------------------------- + // testing the method + // inline Type getFileType() const + //--------------------------------------------------------------------- + class getFileType : public CppUnit::TestFixture + { + ::rtl::OUString aUStr; + ::osl::FileBase::RC nError1, nError2; + + ::osl::DirectoryItem m_aItem_1, m_aItem_2, m_aVolumeItem, m_aFifoItem; + ::osl::DirectoryItem m_aLinkItem, m_aSocketItem, m_aSpecialItem; + + public: + // initialization + void setUp( ) + { + // create a tempfile: $TEMP/tmpdir/tmpname. + // a tempdirectory: $TEMP/tmpdir/tmpdir. + // use $ROOT/staroffice as volume ---> use dev/fd as volume. + // and get their directory item. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName3, aTmpName2 ); + createTestDirectory( aTmpName3, aTmpName1 ); + + ::std::auto_ptr<Directory> pDir( new Directory( aTmpName3 ) ); + nError1 = pDir->open( ); + CPPUNIT_ASSERT_MESSAGE("open aTmpName3 failed!", ::osl::FileBase::E_None == nError1 ); + //getNextItem can not assure which item retrieved + nError1 = pDir->getNextItem( m_aItem_1, 1 ); + CPPUNIT_ASSERT_MESSAGE("get first item failed!", ::osl::FileBase::E_None == nError1 ); + + nError1 = pDir->getNextItem( m_aItem_2 ); + CPPUNIT_ASSERT_MESSAGE("get second item failed!", ::osl::FileBase::E_None == nError1 ); + pDir->close(); + //mindy: failed on my RH9,so removed temporaly + //nError1 = ::osl::DirectoryItem::get( aVolURL2, m_aVolumeItem ); + //CPPUNIT_ASSERT_MESSAGE("get volume item failed!", ::osl::FileBase::E_None == nError1 ); + + } + + void tearDown( ) + { + // remove all in $TEMP/tmpdir. + deleteTestDirectory( aTmpName3, aTmpName1 ); + deleteTestFile( aTmpName3, aTmpName2 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void getFileType_001( ) + { + ::osl::FileStatus rFileStatus( FileStatusMask_Type | FileStatusMask_FileName ); + nError1 = m_aItem_1.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT_MESSAGE("getFileStatus failed", ::osl::FileBase::E_None == nError1 ); + + check_FileType(rFileStatus); + } + + void check_FileType(osl::FileStatus const& _rFileStatus ) + { + sal_Bool bOK = sal_False; + if ( _rFileStatus.isValid(FileStatusMask_FileName)) + { + rtl::OUString suFilename = _rFileStatus.getFileName(); + + if ( _rFileStatus.isValid(FileStatusMask_Type)) + { + osl::FileStatus::Type eType = _rFileStatus.getFileType( ); + + if ( compareFileName( suFilename, aTmpName2) == sal_True ) + { + // regular + bOK = ( eType == osl::FileStatus::Regular ); + } + if ( compareFileName( suFilename, aTmpName1) == sal_True ) + { + // directory + bOK = ( eType == ::osl::FileStatus::Directory ); + } + + CPPUNIT_ASSERT_MESSAGE( "test for getFileType function: ", + ( bOK == sal_True ) ); + } + } + // LLA: it's not a bug, if a FileStatus not exist, so no else + } + + void getFileType_002( ) + { + ::osl::FileStatus rFileStatus( FileStatusMask_Type | FileStatusMask_FileName ); + nError1 = m_aItem_2.getFileStatus( rFileStatus ); + + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + check_FileType(rFileStatus); + } + + void getFileType_003( ) + { + } + +/* + * LLA: removed, m_aSocketItem is wrong initialised. + */ + +// LLA: void getFileType_005( ) +// LLA: { +// LLA: #if defined ( SOLARIS ) //Socket file may differ in Windows +// LLA: // nError1 = ::osl::DirectoryItem::get( aTypeURL1, m_aSocketItem ); +// LLA: nError1 = ::osl::DirectoryItem::get( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/dev/null")), m_aSocketItem ); +// LLA: printError(nError1); +// LLA: CPPUNIT_ASSERT_MESSAGE("get Socket type file failed", ::osl::FileBase::E_None == nError1 ); +// LLA: +// LLA: //check for File type +// LLA: ::osl::FileStatus rFileStatus( FileStatusMask_Type ); +// LLA: +// LLA: nError1 = m_aSocketItem.getFileStatus( rFileStatus ); +// LLA: CPPUNIT_ASSERT_MESSAGE("getFileStatus failed", ::osl::FileBase::E_None == nError1 ); +// LLA: +// LLA: if (rFileStatus.isValid( FileStatusMask_Type )) +// LLA: { +// LLA: osl::FileStatus::Type eType = rFileStatus.getFileType( ); +// LLA: printFileType(eType); +// LLA: CPPUNIT_ASSERT_MESSAGE( "test for getFileType function: Socket, Solaris version ", +// LLA: ( eType == ::osl::FileStatus::Socket ) ); +// LLA: } +// LLA: #endif +// LLA: } + + +// deprecated since there is a same case Directory::getNextItem_004 +/*#if defined 0 //( UNX ) //( SOLARIS ) //Link file is not defined in Windows + void getFileType_006( ) + { + nError1 = ::osl::DirectoryItem::get( aTypeURL3, m_aLinkItem ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + //check for File type + ::osl::FileStatus rFileStatus( FileStatusMask_Type ); + nError1 = m_aLinkItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFileType function: Link, UNX version ", + ( ::osl::FileStatus::Link == rFileStatus.getFileType( ) ) ); + } +#endif */ + + void getFileType_007( ) + { +#if defined ( SOLARIS ) //Special file is differ in Windows + nError1 = ::osl::DirectoryItem::get( aTypeURL2, m_aSpecialItem ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + //check for File type + ::osl::FileStatus rFileStatus( FileStatusMask_Type ); + nError1 = m_aSpecialItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + if (rFileStatus.isValid(FileStatusMask_Type)) + { + osl::FileStatus::Type eType = rFileStatus.getFileType( ); + + + CPPUNIT_ASSERT_MESSAGE( "test for getFileType function: Special, Solaris version ", + ( eType == ::osl::FileStatus::Special ) ); + } +#endif + } + + CPPUNIT_TEST_SUITE( getFileType ); + CPPUNIT_TEST( getFileType_001 ); + CPPUNIT_TEST( getFileType_002 ); + CPPUNIT_TEST( getFileType_003 ); + // LLA: CPPUNIT_TEST( getFileType_005 ); + //CPPUNIT_TEST( getFileType_006 ); + CPPUNIT_TEST( getFileType_007 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getFileType + + //--------------------------------------------------------------------- + // testing the method + // inline sal_uInt64 getAttributes() const + //--------------------------------------------------------------------- + class getAttributes : public CppUnit::TestFixture + { + ::rtl::OUString aTypeURL, aTypeURL_Hid; + ::osl::FileBase::RC nError; + ::osl::DirectoryItem rItem, rItem_hidden; + + public: + // initialization + void setUp( ) + { + aTypeURL = aUserDirectoryURL.copy( 0 ); + concatURL( aTypeURL, aTmpName2 ); + createTestFile( aTypeURL ); + nError = ::osl::DirectoryItem::get( aTypeURL, rItem ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + + aTypeURL_Hid = aUserDirectoryURL.copy( 0 ); + concatURL( aTypeURL_Hid, aHidURL1 ); + createTestFile( aTypeURL_Hid ); + nError = ::osl::DirectoryItem::get( aTypeURL_Hid, rItem_hidden ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + } + + void tearDown( ) + { + deleteTestFile( aTypeURL ); + deleteTestFile( aTypeURL_Hid ); + } + + // test code. +#if ( defined UNX ) || ( defined OS2 ) +//windows only 3 file attributes: normal, readonly, hidden + void getAttributes_001( ) + { + changeFileMode( aTypeURL, S_IRUSR | S_IRGRP | S_IROTH ); + + ::osl::FileStatus rFileStatus( FileStatusMask_Attributes ); + nError = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + + CPPUNIT_ASSERT_MESSAGE( "test for getAttributes function: ReadOnly, GrpRead, OwnRead, OthRead( UNX version ) ", + ( Attribute_ReadOnly | Attribute_GrpRead | Attribute_OwnRead | Attribute_OthRead ) == + rFileStatus.getAttributes( ) ); + } +#else //Windows version + void getAttributes_001( ) + { + CPPUNIT_ASSERT_MESSAGE( "test for getAttributes function: ReadOnly, GrpRead, OwnRead, OthRead( Windows version )", + 1 == 1 ); + } +#endif + + + void getAttributes_002( ) + { +#if ( defined UNX ) || ( defined OS2 ) + changeFileMode( aTypeURL, S_IXUSR | S_IXGRP | S_IXOTH ); + + ::osl::FileStatus rFileStatus( FileStatusMask_Attributes ); + nError = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + + CPPUNIT_ASSERT_MESSAGE( "test for getAttributes function: Executable, GrpExe, OwnExe, OthExe, the result is Readonly, Executable, GrpExe, OwnExe, OthExe, it partly not pass( Solaris version )", + ( Attribute_ReadOnly | Attribute_Executable | Attribute_GrpExe | Attribute_OwnExe | Attribute_OthExe ) == + rFileStatus.getAttributes( ) ); +#endif + } + + +#if ( defined UNX ) || ( defined OS2 ) + void getAttributes_003( ) + { + changeFileMode( aTypeURL, S_IWUSR | S_IWGRP | S_IWOTH ); + + ::osl::FileStatus rFileStatus( FileStatusMask_Attributes ); + nError = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + + CPPUNIT_ASSERT_MESSAGE( "test for getAttributes function: GrpWrite, OwnWrite, OthWrite( Solaris version )", + ( Attribute_GrpWrite | Attribute_OwnWrite | Attribute_OthWrite ) == + rFileStatus.getAttributes( ) ); + } +#else //Windows version + void getAttributes_003( ) + { + CPPUNIT_ASSERT_MESSAGE( "test for getAttributes function: GrpWrite, OwnWrite, OthWrite( Windows version )", + 1 == 1 ); + } +#endif + +#if ( defined UNX ) || ( defined OS2 ) //hidden file definition may different in Windows + void getAttributes_004( ) + { + sal_Int32 test_Attributes = Attribute_Hidden; + ::osl::FileStatus rFileStatus( FileStatusMask_Attributes ); + nError = rItem_hidden.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + test_Attributes &= rFileStatus.getAttributes( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getAttributes function: Hidden files( Solaris version )", + test_Attributes == Attribute_Hidden ); + } +#else //Windows version + void getAttributes_004( ) + { + ::rtl::OUString aUserHiddenFileURL (RTL_CONSTASCII_USTRINGPARAM("file:///c:/AUTOEXEC.BAT")); + nError = ::osl::DirectoryItem::get( aUserHiddenFileURL, rItem_hidden ); + CPPUNIT_ASSERT_MESSAGE("get item fail", nError == FileBase::E_None ); + ::osl::FileStatus rFileStatus( FileStatusMask_Attributes ); + nError = rItem_hidden.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + + CPPUNIT_ASSERT_MESSAGE( "Hidden files(Windows version), please check if hidden file c:/AUTOEXEC.BAT exists ", + (rFileStatus.getAttributes( ) & Attribute_Hidden)!= 0 ); + } +#endif + + CPPUNIT_TEST_SUITE( getAttributes ); + CPPUNIT_TEST( getAttributes_001 ); + CPPUNIT_TEST( getAttributes_002 ); + CPPUNIT_TEST( getAttributes_003 ); + CPPUNIT_TEST( getAttributes_004 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getAttributes + + //--------------------------------------------------------------------- + // testing the method + // inline TimeValue getAccessTime() const + //--------------------------------------------------------------------- + class getAccessTime : public CppUnit::TestFixture + { + ::rtl::OUString aTypeURL; + ::osl::FileBase::RC nError; + ::osl::DirectoryItem rItem; + + public: + // initialization + void setUp( ) + { + aTypeURL = aUserDirectoryURL.copy( 0 ); + concatURL( aTypeURL, aTmpName2 ); + createTestFile( aTypeURL ); + nError = ::osl::DirectoryItem::get( aTypeURL, rItem ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + + } + + void tearDown( ) + { + deleteTestFile( aTypeURL ); + } + + // test code. + void getAccessTime_001( ) + { + TimeValue *pTV_current = NULL; + CPPUNIT_ASSERT( ( pTV_current = ( TimeValue* )malloc( sizeof( TimeValue ) ) ) != NULL ); + TimeValue *pTV_access = NULL; + CPPUNIT_ASSERT( ( pTV_access = ( TimeValue* )malloc( sizeof( TimeValue ) ) ) != NULL ); + + ::osl::FileStatus rFileStatus( FileStatusMask_AccessTime ); + nError = rItem.getFileStatus( rFileStatus ); + sal_Bool bOk = osl_getSystemTime( pTV_current ); + CPPUNIT_ASSERT( sal_True == bOk && nError == FileBase::E_None ); + + *pTV_access = rFileStatus.getAccessTime( ); + + sal_Bool bOK = t_compareTime( pTV_access, pTV_current, delta ); + free( pTV_current ); + free( pTV_access ); + + CPPUNIT_ASSERT_MESSAGE( "test for getAccessTime function: This test turns out that UNX pricision is no more than 1 sec, don't know how to test this function, in Windows test, it lost hour min sec, only have date time. ", + sal_True == bOK ); + } + + CPPUNIT_TEST_SUITE( getAccessTime ); + CPPUNIT_TEST( getAccessTime_001 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getAccessTime + + //--------------------------------------------------------------------- + // testing the method + // inline TimeValue getModifyTime() const + //--------------------------------------------------------------------- + class getModifyTime : public CppUnit::TestFixture + { + ::rtl::OUString aTypeURL; + ::osl::FileBase::RC nError; + ::osl::DirectoryItem rItem; + + public: + + // test code. + void getModifyTime_001( ) + { + TimeValue *pTV_current = NULL; + CPPUNIT_ASSERT( ( pTV_current = ( TimeValue* )malloc( sizeof( TimeValue ) ) ) != NULL ); + + //create file + aTypeURL = aUserDirectoryURL.copy( 0 ); + concatURL( aTypeURL, aTmpName2 ); + createTestFile( aTypeURL ); + + //get current time + sal_Bool bOk = osl_getSystemTime( pTV_current ); + CPPUNIT_ASSERT( sal_True == bOk ); + + //get instance item and filestatus + nError = ::osl::DirectoryItem::get( aTypeURL, rItem ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + ::osl::FileStatus rFileStatus( FileStatusMask_ModifyTime ); + nError = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + + //get modify time + TimeValue *pTV_modify = NULL; + CPPUNIT_ASSERT( ( pTV_modify = ( TimeValue* )malloc( sizeof( TimeValue ) ) ) != NULL ); + *pTV_modify = rFileStatus.getModifyTime( ); + + sal_Bool bOK = t_compareTime( pTV_modify, pTV_current, delta ); + //delete file + deleteTestFile( aTypeURL ); + free( pTV_current ); + + CPPUNIT_ASSERT_MESSAGE( "test for getModifyTime function: This test turns out that UNX pricision is no more than 1 sec, don't know how to improve this function. ", + sal_True == bOK ); + } + + CPPUNIT_TEST_SUITE( getModifyTime ); + CPPUNIT_TEST( getModifyTime_001 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getModifyTime + + + //--------------------------------------------------------------------- + // testing the method + // inline sal_uInt64 getFileSize() const + //--------------------------------------------------------------------- + class getFileSize : public CppUnit::TestFixture + { + ::rtl::OUString aTypeURL; + ::osl::FileBase::RC nError; + ::osl::DirectoryItem rItem; + + public: + // initialization + void setUp( ) + { + aTypeURL = aUserDirectoryURL.copy( 0 ); + concatURL( aTypeURL, aTmpName2 ); + createTestFile( aTypeURL ); + nError = ::osl::DirectoryItem::get( aTypeURL, rItem ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + } + + void tearDown( ) + { + deleteTestFile( aTypeURL ); + } + + // test code. + void getFileSize_001( ) + { + ::osl::FileStatus rFileStatus( FileStatusMask_FileSize ); + nError = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + + sal_uInt64 uFileSize = rFileStatus.getFileSize( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFileSize function: empty file ", + 0 == uFileSize ); + } + + void getFileSize_002( ) + { + ::osl::File testfile( aTypeURL ); + nError = testfile.open( osl_File_OpenFlag_Write | osl_File_OpenFlag_Read ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError ); + nError = testfile.setSize( TEST_FILE_SIZE ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError ); + + nError = ::osl::DirectoryItem::get( aTypeURL, rItem ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + ::osl::FileStatus rFileStatus( FileStatusMask_FileSize ); + nError = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + sal_uInt64 uFileSize = rFileStatus.getFileSize( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFileSize function: file with size of TEST_FILE_SIZE, did not pass in (W32). ", + TEST_FILE_SIZE == uFileSize ); + } + CPPUNIT_TEST_SUITE( getFileSize ); + CPPUNIT_TEST( getFileSize_001 ); + CPPUNIT_TEST( getFileSize_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getFileSize + + //--------------------------------------------------------------------- + // testing the method + // inline ::rtl::OUString getFileName() const + //--------------------------------------------------------------------- + class getFileName : public CppUnit::TestFixture + { + ::rtl::OUString aTypeURL; + ::osl::FileBase::RC nError; + ::osl::DirectoryItem rItem; + + public: + // initialization + void setUp( ) + { + aTypeURL = aUserDirectoryURL.copy( 0 ); + concatURL( aTypeURL, aTmpName2 ); + createTestFile( aTypeURL ); + nError = ::osl::DirectoryItem::get( aTypeURL, rItem ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + } + + void tearDown( ) + { + deleteTestFile( aTypeURL ); + } + + // test code. + void getFileName_001( ) + { + ::osl::FileStatus rFileStatus( FileStatusMask_FileName ); + nError = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + + ::rtl::OUString aFileName = rFileStatus.getFileName( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFileName function: name compare with specify", + sal_True == compareFileName( aFileName, aTmpName2 ) ); + } + + CPPUNIT_TEST_SUITE( getFileName ); + CPPUNIT_TEST( getFileName_001 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getFileName + + //--------------------------------------------------------------------- + // testing the method + // inline ::rtl::OUString getFileURL() const + //--------------------------------------------------------------------- + class getFileURL : public CppUnit::TestFixture + { + ::rtl::OUString aTypeURL; + ::osl::FileBase::RC nError; + ::osl::DirectoryItem rItem; + + public: + // initialization + void setUp( ) + { + createTestFile( aTmpName6 ); + nError = ::osl::DirectoryItem::get( aTmpName6, rItem ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + } + + void tearDown( ) + { + deleteTestFile( aTmpName6 ); + } + + // test code. + void getFileURL_001( ) + { + ::osl::FileStatus rFileStatus( FileStatusMask_FileURL ); + nError = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( nError == FileBase::E_None ); + + ::rtl::OUString aFileURL = rFileStatus.getFileURL( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFileURL function: ", + sal_True == compareFileName( aFileURL, aTmpName6 ) ); + } + + CPPUNIT_TEST_SUITE( getFileURL ); + CPPUNIT_TEST( getFileURL_001 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getFileURL + + //--------------------------------------------------------------------- + // testing the method + // inline ::rtl::OUString getLinkTargetURL() const + //--------------------------------------------------------------------- + class getLinkTargetURL : public CppUnit::TestFixture + { + ::rtl::OUString aTypeURL; + ::osl::FileBase::RC nError; + ::osl::DirectoryItem rItem; + + public: + // test code. + // initialization + void setUp( ) + { + aTypeURL = aUserDirectoryURL.copy( 0 ); + concatURL( aTypeURL, aTmpName2 ); + createTestFile( aTypeURL ); + } + + void tearDown( ) + { + deleteTestFile( aTypeURL ); + } + +#if ( defined UNX ) || ( defined OS2 ) //Link file is not define in Windows + void getLinkTargetURL_001( ) + { + //create a link file; + ::rtl::OUString aUStr_LnkFileSys( aTempDirectorySys ), aUStr_SrcFileSys( aTempDirectorySys ); + ( ( aUStr_LnkFileSys += aSlashURL ) += getCurrentPID( ) ) += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/link.file")); + ( ( aUStr_SrcFileSys += aSlashURL ) += getCurrentPID( ) ) += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/tmpname")); + + rtl::OString strLinkFileName, strSrcFileName; + strLinkFileName = OUStringToOString( aUStr_LnkFileSys, RTL_TEXTENCODING_ASCII_US ); + strSrcFileName = OUStringToOString( aUStr_SrcFileSys, RTL_TEXTENCODING_ASCII_US ); + + sal_Int32 fd; + fd = symlink( strSrcFileName.getStr(), strLinkFileName.getStr() ); + CPPUNIT_ASSERT_MESSAGE( "in creating link file", fd == 0 ); + + //get linkTarget URL + nError = ::osl::DirectoryItem::get( aLnkURL1, rItem ); + CPPUNIT_ASSERT_MESSAGE( "in getting link file item", nError == FileBase::E_None ); + + ::osl::FileStatus rFileStatus( FileStatusMask_LinkTargetURL ); + nError = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT_MESSAGE( "in getting link file status", nError == FileBase::E_None ); + ::rtl::OUString aFileURL = rFileStatus.getLinkTargetURL( ); + + //remove link file + fd = remove( strLinkFileName.getStr() ); + CPPUNIT_ASSERT_MESSAGE( "in deleting link file", fd == 0 ); + + CPPUNIT_ASSERT_MESSAGE( "test for getLinkTargetURL function: Solaris version, creat a file, and a link file link to it, get its LinkTargetURL and compare", + sal_True == compareFileName( aFileURL, aTypeURL ) ); + } +#else + void getLinkTargetURL_001( ) + { + CPPUNIT_ASSERT_MESSAGE( "test for getLinkTargetURL function: Windows version, not tested", + 1 ); + } +#endif + + CPPUNIT_TEST_SUITE( getLinkTargetURL ); + CPPUNIT_TEST( getLinkTargetURL_001 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getLinkTargetURL + + // ----------------------------------------------------------------------------- + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_FileStatus::ctors, "osl_FileStatus" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_FileStatus::isValid, "osl_FileStatus" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_FileStatus::getFileType, "osl_FileStatus" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_FileStatus::getAttributes, "osl_FileStatus" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_FileStatus::getAccessTime, "osl_FileStatus" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_FileStatus::getModifyTime, "osl_FileStatus" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_FileStatus::getFileSize, "osl_FileStatus" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_FileStatus::getFileName, "osl_FileStatus" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_FileStatus::getFileURL, "osl_FileStatus" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_FileStatus::getLinkTargetURL, "osl_FileStatus" ); +}// namespace osl_FileStatus + + + +//------------------------------------------------------------------------ +// Beginning of the test cases for File class +//------------------------------------------------------------------------ +namespace osl_File +{ + //--------------------------------------------------------------------- + // testing the method + // File( const ::rtl::OUString& ustrFileURL ) + //--------------------------------------------------------------------- + class ctors : public CppUnit::TestFixture + { + // ::osl::FileBase::RC nError1; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void ctors_001( ) + { + ::osl::File testFile( aTmpName4 ); + + ::osl::FileBase::RC nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + ::osl::FileBase::RC nError2 = testFile.close( ); + CPPUNIT_ASSERT_MESSAGE( "test for ctors function: initialize a File and test its open and close", + ( ::osl::FileBase::E_None == nError1 ) && ( ::osl::FileBase::E_None == nError2 ) ); + } + + void ctors_002( ) + { + ::osl::File testFile( aTmpName5 ); + sal_Char buffer[30] = "Test for File constructor"; + sal_uInt64 nCount; + + ::osl::FileBase::RC nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + ::osl::FileBase::RC nError2 = testFile.write( buffer, 30, nCount ); + testFile.close( ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors function: test relative file URL, this test show that relative file URL is also acceptable", + ( ::osl::FileBase::E_None == nError1 ) && ( ::osl::FileBase::E_None == nError2 ) ); + } + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_001 ); + CPPUNIT_TEST( ctors_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class ctors + + //--------------------------------------------------------------------- + // testing the method + // inline RC open( sal_uInt32 uFlags ) + //--------------------------------------------------------------------- + class open : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2, nError3; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void open_001( ) + { + ::osl::File testFile( aTmpName4 ); + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + nError2 = testFile.close( ); + CPPUNIT_ASSERT_MESSAGE("close error", ::osl::FileBase::E_None == nError2 ); + + CPPUNIT_ASSERT_MESSAGE( "test for open function: open a regular file", + ::osl::FileBase::E_None == nError1 ); + } + + void open_002( ) + { + ::osl::File testFile( aTmpName3 ); + + nError1 = testFile.open( osl_File_OpenFlag_Read ); + + CPPUNIT_ASSERT_MESSAGE( "test for open function: open a directory", + ( File::E_INVAL == nError1 ) || ( File::E_ACCES == nError1 ) ); + } + + void open_003( ) + { + ::osl::File testFile( aCanURL1 ); + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + + CPPUNIT_ASSERT_MESSAGE( "test for open function: open a non-exist file", + File::E_NOENT == nError1 ); + } + + void open_004( ) + { + ::rtl::OUString aTestFile( aRootURL ); + concatURL( aTestFile, aTmpName2 ); + ::osl::File testFile( aTestFile ); + + nError1 = testFile.open( osl_File_OpenFlag_Create ); + sal_Bool bOK = ( File::E_ACCES == nError1 ); +#if defined (WNT ) + bOK = sal_True; /// in Windows, you can create file in c:/ any way. + testFile.close( ); + deleteTestFile( aTestFile); +#endif + + CPPUNIT_ASSERT_MESSAGE( "test for open function: create an illegal file", + bOK == sal_True ); + } + + void open_005( ) + { + ::osl::File testFile( aTmpName4 ); + + nError1 = testFile.open( osl_File_OpenFlag_Create ); + + CPPUNIT_ASSERT_MESSAGE( "test for open function: create an exist file", + File::E_EXIST == nError1 ); + } + + void open_006( ) + { + ::osl::File testFile( aCanURL1 ); + sal_Char buffer_write[30] = "Test for File open"; + sal_Char buffer_read[30]; + sal_uInt64 nCount_write, nCount_read; + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write | osl_File_OpenFlag_Create ); + nError2 = testFile.write( buffer_write, 30, nCount_write ); + ::osl::FileBase::RC nError4 = testFile.setPos( Pos_Absolut, 0 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError4 ); + nError3 = testFile.read( buffer_read, 10, nCount_read ); + + ::osl::FileBase::RC nError5 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError5 ); + ::osl::FileBase::RC nError6 = testFile.remove( aCanURL1 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError6 ); + + CPPUNIT_ASSERT_MESSAGE( "test for open function: test for osl_File_OpenFlag_Read, osl_File_OpenFlag_Write and osl_File_OpenFlag_Create", + ( ::osl::FileBase::E_None == nError1 ) && + ( ::osl::FileBase::E_None == nError2 ) && + ( ::osl::FileBase::E_None == nError3 ) && + ( 30 == nCount_write ) && + ( 10 == nCount_read ) ); + } + + CPPUNIT_TEST_SUITE( open ); + CPPUNIT_TEST( open_001 ); + CPPUNIT_TEST( open_002 ); + CPPUNIT_TEST( open_003 ); + CPPUNIT_TEST( open_004 ); + CPPUNIT_TEST( open_005 ); + CPPUNIT_TEST( open_006 ); + CPPUNIT_TEST_SUITE_END( ); + };// class open + + //--------------------------------------------------------------------- + // testing the method + // inline RC close() + //--------------------------------------------------------------------- + class close : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2, nError3; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void close_001( ) + { + ::osl::File testFile( aTmpName4 ); + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + nError2 = testFile.close( ); + + CPPUNIT_ASSERT_MESSAGE( "test for close function: close a regular file", + ::osl::FileBase::E_None == nError2 ); + } + + void close_002( ) + { + ::osl::File testFile( aTmpName4 ); + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + nError2 = testFile.close( ); + + nError3 = testFile.setPos( Pos_Absolut, 0 ); + + CPPUNIT_ASSERT_MESSAGE( "test for close function: manipulate a file after it has been closed", + ( ::osl::FileBase::E_None == nError2 ) && + ( ::osl::FileBase::E_None != nError3 ) ); + } + + CPPUNIT_TEST_SUITE( close ); + CPPUNIT_TEST( close_001 ); + CPPUNIT_TEST( close_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class close + + + //--------------------------------------------------------------------- + // testing the method + // inline RC setPos( sal_uInt32 uHow, sal_Int64 uPos ) + //--------------------------------------------------------------------- + class setPos : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + sal_uInt64 nCount_write, nCount_read; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + + //write chars into the file. + ::osl::File testFile( aTmpName4 ); + + nError1 = testFile.open( osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.write( pBuffer_Char, sizeof( pBuffer_Char ), nCount_write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void setPos_001( ) + { + ::osl::File testFile( aTmpName4 ); + sal_Char buffer_read[2]; + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.setPos( Pos_Absolut, 26 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.read( buffer_read, 1, nCount_read ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for setPos function: test for Pos_Absolut, set the position to 26, test if the 26th char in file is correct", + buffer_read[0] == pBuffer_Char[26] ); + } + + void setPos_002( ) + { + ::osl::File testFile( aTmpName4 ); + sal_Char buffer_read[2]; + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.setPos( Pos_Absolut, sizeof( pBuffer_Char ) - 2 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.setPos( Pos_Current, 0); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.read( buffer_read, 1, nCount_read ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for setPos function: test for Pos_Current, set the position to end, test if the ( end -1 ) char in file is correct", + buffer_read[0] == pBuffer_Char[sizeof( pBuffer_Char ) - 2] ); + } + + void setPos_003( ) + { + ::osl::File testFile( aTmpName4 ); + sal_Char buffer_read[2]; + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + //the file size is smaller than 100 + nError1 = testFile.setPos( Pos_End, -100 ); + CPPUNIT_ASSERT_MESSAGE( "should return error", ::osl::FileBase::E_INVAL == nError1 ); + + nError1 = testFile.setPos( Pos_End, -53 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.read( buffer_read, 1, nCount_read ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for setPos function: test for Pos_End, set the position to end, test if the first char in file is correct", + buffer_read[0] == pBuffer_Char[0] ); + } + + CPPUNIT_TEST_SUITE( setPos ); + CPPUNIT_TEST( setPos_001 ); + CPPUNIT_TEST( setPos_002 ); + CPPUNIT_TEST( setPos_003 ); + CPPUNIT_TEST_SUITE_END( ); + };// class setPos + + //--------------------------------------------------------------------- + // testing the method + // inline RC getPos( sal_uInt64& uPos ) + //--------------------------------------------------------------------- + class getPos : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + sal_uInt64 nCount_write, nCount_read; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + + //write chars into the file. + ::osl::File testFile( aTmpName4 ); + + nError1 = testFile.open( osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.write( pBuffer_Char, sizeof( pBuffer_Char ), nCount_write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void getPos_001( ) + { + ::osl::File testFile( aTmpName4 ); + sal_uInt64 nFilePointer; + + nError1 = testFile.getPos( nFilePointer ); + CPPUNIT_ASSERT( ::osl::FileBase::E_INVAL == nError1 ); + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + nError1 = testFile.setPos( Pos_Absolut, 26 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.getPos( nFilePointer ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for getPos function: set the position to 26, get position and check if it is right", + 26 == nFilePointer ); + } + + CPPUNIT_TEST_SUITE( getPos ); + CPPUNIT_TEST( getPos_001 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getPos + + + //--------------------------------------------------------------------- + // testing the method + // inline RC isEndOfFile( sal_Bool *pIsEOF ) + //--------------------------------------------------------------------- + class isEndOfFile : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + sal_uInt64 nCount_write, nCount_read; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + + //write chars into the file. + ::osl::File testFile( aTmpName4 ); + + nError1 = testFile.open( osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.write( pBuffer_Char, sizeof( pBuffer_Char ), nCount_write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void isEndOfFile_001( ) + { + ::osl::File testFile( aTmpName4 ); + sal_Bool bEOF = sal_False; + sal_Bool *pEOF = &bEOF; + + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + nError1 = testFile.setPos( Pos_End, 0 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.isEndOfFile( pEOF ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for isEndOfFile function: set the position to end, check if reach end", + sal_True == *pEOF ); + } + + void isEndOfFile_002( ) + { + ::osl::File testFile( aTmpName4 ); + sal_Bool bEOF = sal_False; + sal_Bool *pEOF = &bEOF; + sal_uInt64 nFilePointer = 0; + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + nError1 = testFile.setPos( Pos_Absolut, 0 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + *pEOF = sal_False; + while ( !( *pEOF ) ) + { + nError1 = testFile.isEndOfFile( pEOF ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.setPos( Pos_Current, 1 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + } + nError1 = testFile.getPos( nFilePointer ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for isEndOfFile function: use isEndOfFile to move pointer step by step", + sizeof( pBuffer_Char ) + 1 == nFilePointer ); + } + CPPUNIT_TEST_SUITE( isEndOfFile ); + CPPUNIT_TEST( isEndOfFile_001 ); + CPPUNIT_TEST( isEndOfFile_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class isEndOfFile + + + //--------------------------------------------------------------------- + // testing the method + // inline RC setSize( sal_uInt64 uSize ) + //--------------------------------------------------------------------- + class setSize : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + sal_uInt64 nCount_write, nCount_read; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + + //write chars into the file. + ::osl::File testFile( aTmpName4 ); + + nError1 = testFile.open( osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.write( pBuffer_Char, sizeof( pBuffer_Char ), nCount_write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void setSize_001( ) + { + ::osl::File testFile( aTmpName4 ); + // sal_Bool bEOF = sal_False; + // sal_Bool *pEOF = &bEOF; + sal_uInt64 nFilePointer; + + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + //enlarge the file to size of 100; + nError1 = testFile.setSize( 100 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + //get the file size; + nError1 = testFile.setPos( Pos_End, 0 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.getPos( nFilePointer ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for setSize function: enlarge the file ", + 100 == nFilePointer ); + } + + void setSize_002( ) + { + ::osl::File testFile( aTmpName4 ); + // sal_Bool bEOF = sal_False; + // sal_Bool *pEOF = &bEOF; + sal_uInt64 nFilePointer; + + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + //enlarge the file to size of 100; + nError1 = testFile.setSize( 10 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + //get the file size; + nError1 = testFile.setPos( Pos_End, 0 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.getPos( nFilePointer ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for setSize function: truncate the file ", + 10 == nFilePointer ); + } + + CPPUNIT_TEST_SUITE( setSize ); + CPPUNIT_TEST( setSize_001 ); + CPPUNIT_TEST( setSize_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class setSize + + + //--------------------------------------------------------------------- + // testing the method + // inline RC read( void *pBuffer, sal_uInt64 uBytesRequested, sal_uInt64& rBytesRead ) + //--------------------------------------------------------------------- + class read : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + sal_uInt64 nCount_write, nCount_read; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + + //write chars into the file. + ::osl::File testFile( aTmpName4 ); + + nError1 = testFile.open( osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.write( pBuffer_Char, sizeof( pBuffer_Char ), nCount_write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void read_001( ) + { + ::osl::File testFile( aTmpName4 ); + sal_uInt64 nFilePointer; + sal_Char buffer_read[10]; + + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + nError1 = testFile.read( buffer_read, 10, nCount_read ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.getPos( nFilePointer ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for read function: read whole content in the file to a buffer", + ( 10 == nFilePointer ) && ( 0 == strncmp( buffer_read, pBuffer_Char, 10 ) ) ); + } + + void read_002( ) + { + ::osl::File testFile( aTmpName4 ); + sal_uInt64 nFilePointer; + sal_Char buffer_read[26]; + + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + nError1 = testFile.setPos( Pos_Absolut, 26 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.read( buffer_read, 26, nCount_read ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.getPos( nFilePointer ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for read function: read from a special positon in the file", + ( 52 == nFilePointer ) && ( 26 == nCount_read ) && ( 0 == strncmp( buffer_read, &pBuffer_Char[26], 26 ) ) ); + } + + CPPUNIT_TEST_SUITE( read ); + CPPUNIT_TEST( read_001 ); + CPPUNIT_TEST( read_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class read + + //--------------------------------------------------------------------- + // testing the method + // inline RC write(const void *pBuffer, sal_uInt64 uBytesToWrite, sal_uInt64& rBytesWritten) + //--------------------------------------------------------------------- + class write : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + sal_uInt64 nCount_write, nCount_read; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpname. + createTestFile( aTmpName6 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpname. + deleteTestFile( aTmpName6 ); + } + + // test code. + void write_001( ) + { + ::osl::File testFile( aTmpName6 ); + sal_uInt64 nFilePointer; + sal_Char buffer_read[10]; + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + //write chars into the file. + nError1 = testFile.write( pBuffer_Char, 10, nCount_write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + //get the current pointer; + nError1 = testFile.getPos( nFilePointer ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + //reset pointer to the begining; + nError1 = testFile.setPos( Pos_Absolut, 0 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.read( buffer_read, 10, nCount_read ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for write function: read whole content in the file to a buffer. Note, buffer size can not smaller than the read size", + ( 10 == nFilePointer ) && + ( 0 == strncmp( buffer_read, pBuffer_Char, 10 ) ) && + ( 10 == nCount_write ) ); + } + + CPPUNIT_TEST_SUITE( write ); + CPPUNIT_TEST( write_001 ); + CPPUNIT_TEST_SUITE_END( ); + };// class write + + //--------------------------------------------------------------------- + // testing the method + // inline RC readLine( ::rtl::ByteSequence& aSeq ) + //--------------------------------------------------------------------- + class readLine : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + sal_uInt64 nCount_write, nCount_read; + ::rtl::ByteSequence aSequence; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpname. + createTestFile( aTmpName6 ); + + //write some strings into the file. + ::osl::File testFile( aTmpName6 ); + sal_Char ppStrSeq[3][27] = { "abcde\n", + "1234567890\n", + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + }; + + nError1 = testFile.open( osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + for ( int nCount = 0; nCount < 3; nCount++ ) + { + nError1 = testFile.write( ppStrSeq[nCount], strlen( ppStrSeq[nCount] ), nCount_write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + } + + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpname. + deleteTestFile( aTmpName6 ); + } + + // test code. + void readLine_001( ) + { + ::osl::File testFile( aTmpName6 ); + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.readLine( aSequence ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for readLine function: read the first line of the file.", + ( ::osl::FileBase::E_None == nError1 ) && + ( 0 == strncmp( ( const char * )aSequence.getArray( ), pBuffer_Char, 5 ) ) ); + } + + void readLine_002( ) + { + ::osl::File testFile( aTmpName6 ); + sal_Bool bEOF = sal_False; + sal_Bool *pEOF = &bEOF; + + nError1 = testFile.open( osl_File_OpenFlag_Read | osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + for ( int nCount = 0; nCount < 3; nCount++ ) + { + nError1 = testFile.readLine( aSequence ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + } + nError1 = testFile.isEndOfFile( pEOF ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for readLine function: read three lines of the file and check the file pointer moving.", + *pEOF && + ( 0 == strncmp( ( const char * )aSequence.getArray( ), &pBuffer_Char[26], 26 ) ) ); + } + CPPUNIT_TEST_SUITE( readLine ); + CPPUNIT_TEST( readLine_001 ); + CPPUNIT_TEST( readLine_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class readLine + + //--------------------------------------------------------------------- + // testing the method + // inline static RC copy( const ::rtl::OUString& ustrSourceFileURL, const ::rtl::OUString& ustrDestFileURL ) + //--------------------------------------------------------------------- + class copy : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1; + sal_uInt64 nCount_write, nCount_read; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + + //write chars into the file. + ::osl::File testFile( aTmpName4 ); + + nError1 = testFile.open( osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.write( pBuffer_Char, sizeof( pBuffer_Char ), nCount_write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void copy_001( ) + { + ::osl::File testFile( aTmpName6 ); + + //copy $TEMP/tmpdir/tmpname to $TEMP/tmpname. + nError1 = ::osl::File::copy( aTmpName4, aTmpName6 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + //check + nError1 = testFile.open( osl_File_OpenFlag_Create ); + deleteTestFile( aTmpName6 ); + + CPPUNIT_ASSERT_MESSAGE( "test for copy function: copy file to upper directory", + ::osl::FileBase::E_EXIST == nError1 ); + } + + void copy_002( ) + { + //copy $TEMP/tmpdir/tmpname to $TEMP/tmpdir. + nError1 = ::osl::File::copy( aTmpName4, aTmpName3 ); + + CPPUNIT_ASSERT_MESSAGE( "test for copy function: use directory as destination", + ( ::osl::FileBase::E_ISDIR == nError1 ) ||( ::osl::FileBase::E_ACCES == nError1 ) ); + } + + void copy_003( ) + { + //copy $TEMP/tmpdir/tmpname to $ROOT/tmpname. + nError1 = ::osl::File::copy( aTmpName4, aTmpName7 ); +#if defined (WNT ) + nError1 = ::osl::FileBase::E_ACCES; /// for Windows, c:/ is writtenable any way. + deleteTestFile( aTmpName7); +#endif + CPPUNIT_ASSERT_MESSAGE( "test for copy function: copy to an illigal place", + ::osl::FileBase::E_ACCES == nError1 ); + } + + void copy_004( ) + { + //copy $TEMP/tmpname to $TEMP/tmpdir/tmpname. + nError1 = ::osl::File::copy( aTmpName6, aTmpName4 ); + + CPPUNIT_ASSERT_MESSAGE( "test for copy function: copy a not exist file", + ::osl::FileBase::E_NOENT == nError1 ); + } + + void copy_005( ) + { + //copy $TEMP/tmpname to $TEMP/system.path using system path. + nError1 = ::osl::File::copy( aTmpName6, aSysPath1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for copy function: copy a file using system file path", + ::osl::FileBase::E_INVAL == nError1 ); + } + void copy_006( ) + { + createTestFile( aTmpName6 ); + File tmpFile( aTmpName6 ); + FileBase::RC err = tmpFile.open( osl_File_OpenFlag_Write | osl_File_OpenFlag_Read ); + (void)err; + tmpFile.setSize( 200 ); + tmpFile.close(); + //copy to new path + nError1 = ::osl::File::copy( aTmpName6, aTmpName4 ); + CPPUNIT_ASSERT( nError1 == FileBase::E_None ); + + //check if is the new file + File newFile( aTmpName4 ); + newFile.open( osl_File_OpenFlag_Write | osl_File_OpenFlag_Read ); + newFile.setPos( Pos_End, 0 ); + // CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + sal_uInt64 nFilePointer; + nError1 = newFile.getPos( nFilePointer ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + newFile.close( ); + deleteTestFile( aTmpName6 ); + CPPUNIT_ASSERT_MESSAGE( "test for copy function: the dest file exist", + nFilePointer == 200 ); + } + //copyLink has not been impletmented yet + void copy_007( ) + { +#if ( defined UNX ) + + CPPUNIT_ASSERT_MESSAGE( "test for copy function: source file is link file", + ::osl::FileBase::E_INVAL == nError1 ); +#endif + } + + CPPUNIT_TEST_SUITE( copy ); + CPPUNIT_TEST( copy_001 ); + CPPUNIT_TEST( copy_002 ); + CPPUNIT_TEST( copy_003 ); + CPPUNIT_TEST( copy_004 ); + CPPUNIT_TEST( copy_005 ); + CPPUNIT_TEST( copy_006 ); + CPPUNIT_TEST_SUITE_END( ); + };// class copy + + //--------------------------------------------------------------------- + // testing the method + // inline static RC move( const ::rtl::OUString& ustrSourceFileURL, const ::rtl::OUString& ustrDestFileURL ) + //--------------------------------------------------------------------- + class move : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + sal_uInt64 nCount_write, nCount_read; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + + //write chars into the file. + ::osl::File testFile( aTmpName4 ); + + nError1 = testFile.open( osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.write( pBuffer_Char, sizeof( pBuffer_Char ), nCount_write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void move_001( ) + { + //rename $TEMP/tmpdir/tmpname to $TEMP/canonical.name. + nError1 = ::osl::File::move( aTmpName4, aCanURL1 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + //check + ::osl::File testFile( aCanURL1 ); + nError2 = testFile.open( osl_File_OpenFlag_Create ); + deleteTestFile( aCanURL1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for move function: rename file to another directory", + ::osl::FileBase::E_EXIST == nError2 ); + } + + void move_002( ) + { + //move $TEMP/tmpdir/tmpname to $TEMP/tmpdir. + nError1 = ::osl::File::move( aTmpName4, aTmpName3 ); + //returned ::osl::FileBase::E_ACCES on WNT + CPPUNIT_ASSERT_MESSAGE( "test for move function: use directory as destination", + ( ::osl::FileBase::E_ACCES == nError1 || ::osl::FileBase::E_ISDIR == nError1 ) ||( ::osl::FileBase::E_EXIST == nError1 ) ); + } + + void move_003( ) + { + //move $TEMP/tmpdir/tmpname to $ROOT/tmpname. + nError1 = ::osl::File::move( aTmpName4, aTmpName7 ); +#if defined (WNT ) + nError1 = ::osl::FileBase::E_ACCES; /// for Windows, c:/ is writtenable any way. + deleteTestFile( aTmpName7); +#endif + + CPPUNIT_ASSERT_MESSAGE( "test for move function: move to an illigal place", + ::osl::FileBase::E_ACCES == nError1 ); + } + + void move_004( ) + { + //move $TEMP/tmpname to $TEMP/tmpdir/tmpname. + nError1 = ::osl::File::move( aTmpName6, aTmpName4 ); + + CPPUNIT_ASSERT_MESSAGE( "test for move function: move a not exist file", + ::osl::FileBase::E_NOENT == nError1 ); + } + + void move_005( ) + { + //move $TEMP/tmpname to $TEMP/system.path using system path. + nError1 = ::osl::File::move( aTmpName6, aSysPath1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for move function: move a file using system file", + ::osl::FileBase::E_INVAL == nError1 ); + } + + void move_006( ) + { + //move directory $TEMP/tmpname to $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName6 ); + nError1 = ::osl::File::move( aTmpName6, aTmpName4 ); + //move file $TEMP/tmpdir/tmpname to $TEMP/tmpname + nError2 = ::osl::File::move( aTmpName4, aTmpName6 ); + deleteTestDirectory( aTmpName6 ); +#if defined ( WNT ) + deleteTestDirectory( aTmpName4 );// in Windows, it can be moved!!!!! this is only for not influence the following test. + deleteTestFile( aTmpName6 ); + nError1 = ::osl::FileBase::E_NOTDIR; + nError2 = ::osl::FileBase::E_ISDIR; +#endif + CPPUNIT_ASSERT_MESSAGE( "test for move function: move a directory to an exist file with same name, did not pass in (W32)", + ::osl::FileBase::E_NOTDIR == nError1 && ::osl::FileBase::E_ISDIR == nError2 ); + } + + void move_007( ) + { + //create directory $TEMP/tmpname. + createTestDirectory( aTmpName6 ); + //move directory $TEMP/tmpdir to $TEMP/tmpname/tmpdir + nError1 = ::osl::File::move( aTmpName3, aTmpName8 ); + //check + nError2 = ::osl::Directory::create( aTmpName8 ); + ::osl::File::move( aTmpName8, aTmpName3 ); + deleteTestDirectory( aTmpName6 ); + + CPPUNIT_ASSERT_MESSAGE( "test for move function: move a directory to an exist file with same name", + (::osl::FileBase::E_None == nError1 ) && + (::osl::FileBase::E_EXIST == nError2 ) ); + } + // oldpath and newpath are not on the same filesystem.EXDEV,no such error no on Solaris, only on linux + void move_008( ) + { + CPPUNIT_ASSERT_MESSAGE( "oldpath and newpath are not on the same filesystem, should error returns", + ::osl::FileBase::E_None == nError1 ); + } + //bugid# 115420, after the bug fix, add the case + void move_009( ) + { + //create directory $TEMP/tmpname. + createTestDirectory( aTmpName6 ); + //create directory $TEMP/tmpname/tmpdir + createTestDirectory( aTmpName8 ); + //move directory $TEMP/tmpname to $TEMP/tmpname/tmpdir/tmpname + rtl::OUString newName = aTmpName8 + OUString(RTL_CONSTASCII_USTRINGPARAM("/tmpname")); + nError1 = ::osl::File::move( aTmpName3, newName ); + //deleteTestDirectory( newName + OUString(RTL_CONSTASCII_USTRINGPARAM("/tmpname")) ); + //deleteTestDirectory( newName ); + deleteTestDirectory( aTmpName8 ); + deleteTestDirectory( aTmpName6 ); + CPPUNIT_ASSERT_MESSAGE( "test for move function: move a directory to it's subdirectory", + ::osl::FileBase::E_None != nError1 ); + } + + CPPUNIT_TEST_SUITE( move ); + CPPUNIT_TEST( move_001 ); + CPPUNIT_TEST( move_002 ); + CPPUNIT_TEST( move_003 ); + CPPUNIT_TEST( move_004 ); + CPPUNIT_TEST( move_005 ); + CPPUNIT_TEST( move_006 ); + CPPUNIT_TEST( move_007 ); + // CPPUNIT_TEST( move_008 ); + //CPPUNIT_TEST( move_009 ); + CPPUNIT_TEST_SUITE_END( ); + };// class move + + + //--------------------------------------------------------------------- + // testing the method + // inline static RC remove( const ::rtl::OUString& ustrFileURL ) + //--------------------------------------------------------------------- + class remove : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + sal_uInt64 nCount_write, nCount_read; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + + //write chars into the file. + ::osl::File testFile( aTmpName4 ); + + nError1 = testFile.open( osl_File_OpenFlag_Write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.write( pBuffer_Char, sizeof( pBuffer_Char ), nCount_write ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = testFile.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void remove_001( ) + { + //remove $TEMP/tmpdir/tmpname. + nError1 = ::osl::File::remove( aTmpName4 ); + //check + ::osl::File testFile( aTmpName4 ); + nError2 = testFile.open( osl_File_OpenFlag_Create ); + + CPPUNIT_ASSERT_MESSAGE( "test for remove function: remove a file", + ( ::osl::FileBase::E_None == nError1 ) && + ( ::osl::FileBase::E_EXIST != nError2 ) ); + } + + void remove_002( ) + { + //remove $TEMP/tmpname. + nError1 = ::osl::File::remove( aTmpName6 ); + + CPPUNIT_ASSERT_MESSAGE( "test for remove function: remove a file not exist", + ( ::osl::FileBase::E_NOENT == nError1 ) ); + } + + void remove_003( ) + { + //remove $TEMP/system/path. + nError1 = ::osl::File::remove( aSysPath2 ); + + CPPUNIT_ASSERT_MESSAGE( "test for remove function: removing a file not using full qualified URL", + ( ::osl::FileBase::E_INVAL == nError1 ) ); + } + + void remove_004( ) + { + //remove $TEMP/tmpdir. + nError1 = ::osl::File::remove( aTmpName3 ); + + CPPUNIT_ASSERT_MESSAGE( "test for remove function: remove a directory", + ( ::osl::FileBase::E_ISDIR == nError1 ) || ( ::osl::FileBase::E_ACCES == nError1 )); + } + + CPPUNIT_TEST_SUITE( remove ); + CPPUNIT_TEST( remove_001 ); + CPPUNIT_TEST( remove_002 ); + CPPUNIT_TEST( remove_003 ); + CPPUNIT_TEST( remove_004 ); + CPPUNIT_TEST_SUITE_END( ); + };// class remove + + + //--------------------------------------------------------------------- + // testing the method + // inline static RC setAttributes( const ::rtl::OUString& ustrFileURL, sal_uInt64 uAttributes ) + //--------------------------------------------------------------------- + class setAttributes : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + ::osl::DirectoryItem rItem, rItem_hidden; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestFile( aTmpName6 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName6 ); + } + + // test code. + void setAttributes_001( ) + { + //on windows, only can set 2 attributes: Attribute_ReadOnly, Attribute_HIDDEN +#ifdef UNX + //set the file to readonly + nError2 = ::osl::File::setAttributes( aTmpName6, Attribute_ReadOnly | Attribute_GrpRead | Attribute_OwnRead | Attribute_OthRead ); + CPPUNIT_ASSERT( nError2 == FileBase::E_None); + nError1 = ::osl::DirectoryItem::get( aTmpName6, rItem ); + CPPUNIT_ASSERT( nError1 == FileBase::E_None); + //get the file attributes + ::osl::FileStatus rFileStatus( FileStatusMask_Attributes ); + nError1 = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( nError1 == FileBase::E_None ); + + CPPUNIT_ASSERT_MESSAGE( "test for setAttributes function: set file attributes and get it to verify.", + ( Attribute_ReadOnly | Attribute_GrpRead | Attribute_OwnRead | Attribute_OthRead ) == + rFileStatus.getAttributes( ) ); +#else + //please see GetFileAttributes + nError2 = ::osl::File::setAttributes( aTmpName6, Attribute_ReadOnly ); + CPPUNIT_ASSERT( nError2 == FileBase::E_None); + nError1 = ::osl::DirectoryItem::get( aTmpName6, rItem ); + CPPUNIT_ASSERT( nError1 == FileBase::E_None); + //get the file attributes + ::osl::FileStatus rFileStatus( FileStatusMask_Attributes ); + nError1 = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( nError1 == FileBase::E_None ); + //here the file has 2 Attributes: FILE_ATTRIBUTE_READONLY and FILE_ATTRIBUTE_NORMAL, + // but FILE_ATTRIBUTE_NORMAL is valid only if used alone, so this is maybe a bug + /*::rtl::OString aString = ::rtl::OUStringToOString( aTmpName6, RTL_TEXTENCODING_ASCII_US ); + DWORD dwFileAttributes = GetFileAttributes( aString.getStr( ) ); + if (dwFileAttributes & FILE_ATTRIBUTE_NORMAL) + printf("has normal attribute"); + if (dwFileAttributes & FILE_ATTRIBUTE_READONLY) + printf("has readonly attribute"); + */ + CPPUNIT_ASSERT_MESSAGE( "test for setAttributes function: set file attributes READONLY and get it to verify.", + (Attribute_ReadOnly & rFileStatus.getAttributes( )) != 0 ); +#endif + } + void setAttributes_002( ) + { + //on UNX, can not set hidden attribute to file, rename file can set the attribute +#ifdef WNT + //set the file to hidden + nError2 = ::osl::File::setAttributes( aTmpName6, Attribute_Hidden); + + CPPUNIT_ASSERT( nError2 == FileBase::E_None); + nError1 = ::osl::DirectoryItem::get( aTmpName6, rItem ); + CPPUNIT_ASSERT( nError1 == FileBase::E_None); + //get the file attributes + ::osl::FileStatus rFileStatus( FileStatusMask_Attributes ); + nError1 = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( nError1 == FileBase::E_None ); + + CPPUNIT_ASSERT_MESSAGE( "test for setAttributes function: set file attributes and get it to verify.", + (Attribute_Hidden & rFileStatus.getAttributes( )) != 0 ); +#endif + } + + CPPUNIT_TEST_SUITE( setAttributes ); + CPPUNIT_TEST( setAttributes_001 ); + CPPUNIT_TEST( setAttributes_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class setAttributes + + + //--------------------------------------------------------------------- + // testing the method + // inline static RC setTime( + // const ::rtl::OUString& ustrFileURL, + // const TimeValue& rCreationTime, + // const TimeValue& rLastAccessTime, + // const TimeValue& rLastWriteTime ) + //--------------------------------------------------------------------- + class setTime : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + ::osl::DirectoryItem rItem; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestFile( aTmpName6 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName6 ); + } + + // test code. + void setTime_001( ) + { + TimeValue *pTV_current = NULL; + CPPUNIT_ASSERT( ( pTV_current = ( TimeValue* )malloc( sizeof( TimeValue ) ) ) != NULL ); + TimeValue *pTV_creation = NULL; + CPPUNIT_ASSERT( ( pTV_creation = ( TimeValue* )malloc( sizeof( TimeValue ) ) ) != NULL ); + TimeValue *pTV_access = NULL; + CPPUNIT_ASSERT( ( pTV_access = ( TimeValue* )malloc( sizeof( TimeValue ) ) ) != NULL ); + TimeValue *pTV_modify = NULL; + CPPUNIT_ASSERT( ( pTV_modify = ( TimeValue* )malloc( sizeof( TimeValue ) ) ) != NULL ); + + //get current time + sal_Bool bOk = osl_getSystemTime( pTV_current ); + CPPUNIT_ASSERT( sal_True == bOk ); + + //set the file time + nError2 = ::osl::File::setTime( aTmpName6, *pTV_current, *pTV_current, *pTV_current ); + CPPUNIT_ASSERT_MESSAGE( errorToStr( nError2 ).getStr(), nError2 == FileBase::E_None); + + //get the file access time, creation time, modify time + nError1 = ::osl::DirectoryItem::get( aTmpName6, rItem ); + CPPUNIT_ASSERT_MESSAGE( errorToStr( nError1 ).getStr(), nError1 == FileBase::E_None); + + ::osl::FileStatus rFileStatus( FileStatusMask_AccessTime ); + nError1 = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT_MESSAGE( errorToStr( nError1 ).getStr(),nError1 == FileBase::E_None ); + *pTV_access = rFileStatus.getAccessTime( ); + + ::osl::FileStatus rFileStatus1( FileStatusMask_CreationTime ); + nError1 = rItem.getFileStatus( rFileStatus1 ); + CPPUNIT_ASSERT_MESSAGE( errorToStr( nError1 ).getStr(), nError1 == FileBase::E_None ); + *pTV_creation = rFileStatus1.getCreationTime( ); + + ::osl::FileStatus rFileStatus2( FileStatusMask_ModifyTime ); + nError1 = rItem.getFileStatus( rFileStatus2 ); + CPPUNIT_ASSERT_MESSAGE( errorToStr( nError1 ).getStr(), nError1 == FileBase::E_None ); + *pTV_modify = rFileStatus2.getModifyTime( ); + + CPPUNIT_ASSERT_MESSAGE( "test for setTime function: set access time then get it. time precision is still a problem for it cut off the nanosec.", + sal_True == t_compareTime( pTV_access, pTV_current, delta ) ); +#if defined ( WNT ) + //Unfortunately there is no way to get the creation time of a file under Unix (its a Windows only feature). + //That means the flag osl_FileStatus_Mask_CreationTime should be deprecated under Unix. + CPPUNIT_ASSERT_MESSAGE( "test for setTime function: set creation time then get it. ", + sal_True == t_compareTime( pTV_creation, pTV_current, delta ) ) ; +#endif + CPPUNIT_ASSERT_MESSAGE( "test for setTime function: set modify time then get it. ", + sal_True == t_compareTime( pTV_modify, pTV_current, delta ) ); + free( pTV_current ); + free( pTV_creation ); + free( pTV_access ); + free( pTV_modify ); + } + + CPPUNIT_TEST_SUITE( setTime ); + CPPUNIT_TEST( setTime_001 ); + CPPUNIT_TEST_SUITE_END( ); + };// class setTime + + //--------------------------------------------------------------------- + // testing the method + // inline static RC sync() + //--------------------------------------------------------------------- + class sync : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + ::osl::DirectoryItem rItem; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestFile( aTmpName6 ); + + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName6 ); + } + + // test case: if The file is located on a read only file system. + void sync_001( ) + { +#ifdef UNX + nError1 = ::osl::DirectoryItem::get( aTmpName6, rItem ); + CPPUNIT_ASSERT( nError1 == FileBase::E_None); + + File tmp_file( aTmpName6 ); + FileBase::RC err = tmp_file.open(osl_File_OpenFlag_Write ); + + CPPUNIT_ASSERT_MESSAGE("File open failed", err == FileBase::E_None); + + char buffer[50000]; + sal_uInt64 written = 0; + nError1 = tmp_file.write((void*)buffer, sizeof(buffer), written); + CPPUNIT_ASSERT_MESSAGE("write failed!", nError1 == FileBase::E_None); + + //set the file to readonly + nError2 = ::osl::File::setAttributes( aTmpName6, Attribute_ReadOnly | Attribute_GrpRead | Attribute_OwnRead | Attribute_OthRead ); + CPPUNIT_ASSERT( nError2 == FileBase::E_None); + + nError2 = tmp_file.sync(); + + CPPUNIT_ASSERT_MESSAGE("can not sync to readonly file!", nError2 == FileBase::E_None); + + tmp_file.close(); +#endif + } + //test case:no enough space, how to create such case???see test_cpy_wrt_file.cxx::test_osl_writeFile + + + + CPPUNIT_TEST_SUITE( sync ); + CPPUNIT_TEST( sync_001 ); + CPPUNIT_TEST_SUITE_END( ); + };// class setTime + + // ----------------------------------------------------------------------------- + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_File::ctors, "osl_File" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_File::open, "osl_File" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_File::close, "osl_File" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_File::setPos, "osl_File" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_File::getPos, "osl_File" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_File::isEndOfFile, "osl_File" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_File::setSize, "osl_File" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_File::read, "osl_File" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_File::write, "osl_File" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_File::readLine, "osl_File" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_File::copy, "osl_File" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_File::move, "osl_File" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_File::remove, "osl_File" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_File::setAttributes, "osl_File" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_File::setTime, "osl_File" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_File::sync, "osl_File" ); + +}// namespace osl_File + + +//------------------------------------------------------------------------ +// Beginning of the test cases for DirectoryItem class +//------------------------------------------------------------------------ +namespace osl_DirectoryItem +{ + //--------------------------------------------------------------------- + // testing the method + // DirectoryItem(): _pData( NULL ) + //--------------------------------------------------------------------- + class ctors : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpname. + createTestFile( aTmpName6 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpname. + deleteTestFile( aTmpName6 ); + } + + // test code. + void ctors_001( ) + { + ::osl::File testFile( aTmpName6 ); + ::osl::DirectoryItem rItem; //constructor + + //get the DirectoryItem. + nError1 = ::osl::DirectoryItem::get( aTmpName6, rItem ); + CPPUNIT_ASSERT( FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors function: initialize a new instance of DirectoryItem and get an item to check.", + ::osl::FileBase::E_None == nError1 ); + } + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_001 ); + CPPUNIT_TEST_SUITE_END( ); + };// class ctors + + //--------------------------------------------------------------------- + // testing the method + // DirectoryItem( const DirectoryItem& rItem ): _pData( rItem._pData) + //--------------------------------------------------------------------- + class copy_assin_Ctors : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpname. + createTestFile( aTmpName6 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpname. + deleteTestFile( aTmpName6 ); + } + + // test code. + void copy_assin_Ctors_001( ) + { + ::osl::DirectoryItem rItem; //constructor + //get the DirectoryItem. + nError1 = ::osl::DirectoryItem::get( aTmpName6, rItem ); + CPPUNIT_ASSERT( FileBase::E_None == nError1 ); + + ::osl::DirectoryItem copyItem( rItem ); //copy constructor + ::osl::FileStatus rFileStatus( FileStatusMask_FileName ); + nError1 = copyItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( nError1 == FileBase::E_None ); + + CPPUNIT_ASSERT_MESSAGE( "test for copy_assin_Ctors function: use copy constructor to get an item and check filename.", + ( sal_True == compareFileName( rFileStatus.getFileName( ), aTmpName2 ) ) ); + } + + void copy_assin_Ctors_002( ) + { + ::osl::DirectoryItem rItem; //constructor + //get the DirectoryItem. + nError1 = ::osl::DirectoryItem::get( aTmpName6, rItem ); + CPPUNIT_ASSERT( FileBase::E_None == nError1 ); + + ::osl::DirectoryItem copyItem; + copyItem = rItem; //assinment operator + ::osl::FileStatus rFileStatus( FileStatusMask_FileName ); + nError1 = copyItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( nError1 == FileBase::E_None ); + + CPPUNIT_ASSERT_MESSAGE( "test for copy_assin_Ctors function: test assinment operator here since it is same as copy constructor in test way.", + ( sal_True == compareFileName( rFileStatus.getFileName( ), aTmpName2 ) ) ); + } + + CPPUNIT_TEST_SUITE( copy_assin_Ctors ); + CPPUNIT_TEST( copy_assin_Ctors_001 ); + CPPUNIT_TEST( copy_assin_Ctors_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class copy_assin_Ctors + + //--------------------------------------------------------------------- + // testing the method + // inline sal_Bool is() + //--------------------------------------------------------------------- + class is : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpname. + createTestFile( aTmpName6 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpname. + deleteTestFile( aTmpName6 ); + } + + // test code. + void is_001( ) + { + ::osl::DirectoryItem rItem; //constructor + + CPPUNIT_ASSERT_MESSAGE( "test for is function: use an uninitialized instance.", + !rItem.is( ) ); + } + + void is_002( ) + { + ::osl::DirectoryItem rItem; //constructor + //get the DirectoryItem. + nError1 = ::osl::DirectoryItem::get( aTmpName6, rItem ); + CPPUNIT_ASSERT( FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for is function: use an uninitialized instance.", + ( sal_True == rItem.is( ) ) ); + } + + CPPUNIT_TEST_SUITE( is ); + CPPUNIT_TEST( is_001 ); + CPPUNIT_TEST( is_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class is + + //--------------------------------------------------------------------- + // testing the method + // static inline RC get( const ::rtl::OUString& ustrFileURL, DirectoryItem& rItem ) + //--------------------------------------------------------------------- + class get : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpname. + createTestFile( aTmpName6 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpname. + deleteTestFile( aTmpName6 ); + } + + // test code. + void get_001( ) + { + ::osl::DirectoryItem rItem; //constructor + //get the DirectoryItem. + nError2 = ::osl::DirectoryItem::get( aTmpName6, rItem ); + + //check the file name + ::osl::FileStatus rFileStatus( FileStatusMask_FileName ); + nError1 = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( nError1 == FileBase::E_None ); + + CPPUNIT_ASSERT_MESSAGE( "test for get function: use copy constructor to get an item and check filename.", + ( ::osl::FileBase::E_None == nError2 ) && + ( sal_True == compareFileName( rFileStatus.getFileName( ), aTmpName2 ) ) ); + } + + void get_002( ) + { + ::osl::DirectoryItem rItem; + //get the DirectoryItem. + nError1 = ::osl::DirectoryItem::get( aSysPath1, rItem ); + + CPPUNIT_ASSERT_MESSAGE( "test for get function: use a system name instead of a URL.", + FileBase::E_INVAL == nError1 ); + } + + void get_003( ) + { + ::osl::DirectoryItem rItem; + //get the DirectoryItem. + nError1 = ::osl::DirectoryItem::get( aTmpName3, rItem ); + + CPPUNIT_ASSERT_MESSAGE( "test for get function: use a non existed file URL.", + FileBase::E_NOENT == nError1 ); + } + + CPPUNIT_TEST_SUITE( get ); + CPPUNIT_TEST( get_001 ); + CPPUNIT_TEST( get_002 ); + CPPUNIT_TEST( get_003 ); + CPPUNIT_TEST_SUITE_END( ); + };// class get + + //--------------------------------------------------------------------- + // testing the method + // inline RC getFileStatus( FileStatus& rStatus ) + //--------------------------------------------------------------------- + class getFileStatus : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void getFileStatus_001( ) + { + ::osl::DirectoryItem rItem; //constructor + //get the DirectoryItem. + nError1 = ::osl::DirectoryItem::get( aTmpName4, rItem ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + //check the file name + ::osl::FileStatus rFileStatus( FileStatusMask_FileName ); + nError2 = rItem.getFileStatus( rFileStatus ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFileStatus function: get file status and check filename", + ( ::osl::FileBase::E_None == nError2 ) && + ( sal_True == compareFileName( rFileStatus.getFileName( ), aTmpName2 ) ) ); + } + + void getFileStatus_002( ) + { + ::osl::DirectoryItem rItem; //constructor + //get the DirectoryItem. + nError1 = ::osl::DirectoryItem::get( aTmpName6, rItem ); + + //check the file name + ::osl::FileStatus rFileStatus( FileStatusMask_FileName ); + nError2 = rItem.getFileStatus( rFileStatus ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFileStatus function: file not existed", + ( ::osl::FileBase::E_INVAL == nError2 ) ); + } + + void getFileStatus_003( ) + { + ::osl::DirectoryItem rItem; //constructor + //get the DirectoryItem. + nError1 = ::osl::DirectoryItem::get( aTmpName3, rItem ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + //check the file name + ::osl::FileStatus rFileStatus( FileStatusMask_FileName ); + nError2 = rItem.getFileStatus( rFileStatus ); + + CPPUNIT_ASSERT_MESSAGE( "test for getFileStatus function: get directory information", + ( ::osl::FileBase::E_None == nError2 ) && + ( sal_True == compareFileName( rFileStatus.getFileName( ), aTmpName1 ) ) ); + } + + + CPPUNIT_TEST_SUITE( getFileStatus ); + CPPUNIT_TEST( getFileStatus_001 ); + CPPUNIT_TEST( getFileStatus_002 ); + CPPUNIT_TEST( getFileStatus_003 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getFileStatus + + + + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_DirectoryItem::ctors, "osl_DirectoryItem" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_DirectoryItem::copy_assin_Ctors, "osl_DirectoryItem" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_DirectoryItem::is, "osl_DirectoryItem" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_DirectoryItem::get, "osl_DirectoryItem" ); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_DirectoryItem::getFileStatus, "osl_DirectoryItem" ); +}// namespace osl_DirectoryItem + +//Use to deliberately silence warnings for a deliberate error +extern "C" void SAL_CALL suppressOslDebugMessage( const sal_Char *, sal_Int32, const sal_Char * ) +{ +} + +//------------------------------------------------------------------------ +// Beginning of the test cases for Directory class +//------------------------------------------------------------------------ +namespace osl_Directory +{ + //--------------------------------------------------------------------- + // testing the method + // Directory( const ::rtl::OUString& strPath ): _pData( 0 ), _aPath( strPath ) + //--------------------------------------------------------------------- + class ctors : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + // LLA: t_print("tearDown done.\n"); + } + + // test code. + void ctors_001( ) + { + ::osl::Directory testDirectory( aTmpName3 ); //constructor + + //open a directory + nError1 = testDirectory.open( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + //close a directory + nError2 = testDirectory.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError2 ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors function: create an instance and check open and close", + ( ::osl::FileBase::E_None == nError1 ) && + ( ::osl::FileBase::E_None == nError2 ) ); + } + + void ctors_002( ) + { + ::osl::Directory testDirectory( aTmpName9 ); //constructor + + //open a directory + nError1 = testDirectory.open( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + //close a directory + nError2 = testDirectory.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError2 ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors function: relative URL, :-), it is also worked", + ( ::osl::FileBase::E_None == nError1 ) && + ( ::osl::FileBase::E_None == nError2 ) ); + } + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_001 ); + CPPUNIT_TEST( ctors_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class ctors + + //--------------------------------------------------------------------- + // testing the method + // inline RC open() + //--------------------------------------------------------------------- + class open : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void open_001( ) + { + ::osl::Directory testDirectory( aTmpName3 ); //constructor + + //open a directory + nError1 = testDirectory.open( ); + //check if directory is opened. + sal_Bool bOk = testDirectory.isOpen( ); + //close a directory + nError2 = testDirectory.close( ); + + CPPUNIT_ASSERT_MESSAGE( "test for open function: open a directory and check for open", + ( sal_True == bOk ) && + ( ::osl::FileBase::E_None == nError1 ) && + ( ::osl::FileBase::E_None == nError2 ) ); + } + + void open_002( ) + { + ::osl::Directory testDirectory( aTmpName6 ); //constructor + + //open a directory + nError1 = testDirectory.open( ); + if ( ::osl::FileBase::E_None == nError1 ) + { + nError2 = testDirectory.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError2 ); + } + + CPPUNIT_ASSERT_MESSAGE( "test for open function: open a file that is not existed", + ( ::osl::FileBase::E_NOENT == nError1 ) ); + } + + void open_003( ) + { + ::osl::Directory testDirectory( aUserDirectorySys ); //constructor + + //open a directory + nError1 = testDirectory.open( ); + if ( ::osl::FileBase::E_None == nError1 ) + { + nError2 = testDirectory.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError2 ); + } + + CPPUNIT_ASSERT_MESSAGE( "test for open function: using system path", + ( ::osl::FileBase::E_INVAL == nError1 ) ); + } + + void open_004( ) + { + ::osl::Directory testDirectory( aTmpName4 ); //constructor + + //open a directory + nError1 = testDirectory.open( ); + if ( ::osl::FileBase::E_None == nError1 ) + { + nError2 = testDirectory.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError2 ); + } + + CPPUNIT_ASSERT_MESSAGE( "test for open function: open a file instead of a directory", + ( ::osl::FileBase::E_NOTDIR == nError1 ) || ( ::osl::FileBase::E_ACCES ) ); + } + + CPPUNIT_TEST_SUITE( open ); + CPPUNIT_TEST( open_001 ); + CPPUNIT_TEST( open_002 ); + CPPUNIT_TEST( open_003 ); + CPPUNIT_TEST( open_004 ); + CPPUNIT_TEST_SUITE_END( ); + };// class open + + //--------------------------------------------------------------------- + // testing the method + // inline sal_Bool isOpen() { return _pData != NULL; }; + //--------------------------------------------------------------------- + class isOpen : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + + public: + // initialization + void setUp( ) + { + // create a tempfile in $TEMP/tmpdir/tmpname. + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + } + + void tearDown( ) + { + // remove the tempfile in $TEMP/tmpdir/tmpname. + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void isOpen_001( ) + { + ::osl::Directory testDirectory( aTmpName3 ); //constructor + + //open a directory + nError1 = testDirectory.open( ); + //check if directory is opened. + sal_Bool bOk = testDirectory.isOpen( ); + //close a directory + nError2 = testDirectory.close( ); + + CPPUNIT_ASSERT_MESSAGE( "test for isOpen function: open a directory and check for open", + ( sal_True == bOk ) ); + } + + void isOpen_002( ) + { + ::osl::Directory testDirectory( aTmpName3 ); //constructor + + //check if directory is opened. + sal_Bool bOk = testDirectory.isOpen( ); + + CPPUNIT_ASSERT_MESSAGE( "test for isOpen function: do not open a directory and check for open", + !( sal_True == bOk ) ); + } + + CPPUNIT_TEST_SUITE( isOpen ); + CPPUNIT_TEST( isOpen_001 ); + CPPUNIT_TEST( isOpen_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class isOpen + + //--------------------------------------------------------------------- + // testing the method + // inline RC close() + //--------------------------------------------------------------------- + class close : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + + public: + // initialization + void setUp( ) + { + // create a tempdirectory : $TEMP/tmpdir. + createTestDirectory( aTmpName3 ); + } + + void tearDown( ) + { + // remove a tempdirectory : $TEMP/tmpdir. + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void close_001( ) + { + ::osl::Directory testDirectory( aTmpName3 ); //constructor + + //open a directory + nError1 = testDirectory.open( ); + //close a directory + nError2 = testDirectory.close( ); + //check if directory is opened. + sal_Bool bOk = testDirectory.isOpen( ); + + CPPUNIT_ASSERT_MESSAGE( "test for isOpen function: close a directory and check for open", + !( sal_True == bOk ) ); + } + + void close_002( ) + { + ::osl::Directory testDirectory( aTmpName3 ); //constructor + + //close a directory + nError1 = testDirectory.close( ); + + CPPUNIT_ASSERT_MESSAGE( "test for isOpen function: close a not opened directory", + ( ::osl::FileBase::E_BADF == nError1 ) ); + } + + + CPPUNIT_TEST_SUITE( close ); + CPPUNIT_TEST( close_001 ); + CPPUNIT_TEST( close_002 ); + CPPUNIT_TEST_SUITE_END( ); + };// class close + + //--------------------------------------------------------------------- + // testing the method + // inline RC reset() + //--------------------------------------------------------------------- + class reset : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + ::osl::DirectoryItem rItem; + + public: + // initialization + void setUp( ) + { + // create a tempdirectory : $TEMP/tmpdir. + createTestDirectory( aTmpName3 ); + // create three files : $TEMP/tmpdir/tmpname, $TEMP/tmpdir/tmpdir, $TEMP/tmpdir/hiddenfile, + createTestFile( aTmpName3, aTmpName2); + createTestFile( aTmpName3, aTmpName1); + createTestFile( aTmpName3, aHidURL1); + } + + void tearDown( ) + { + // remove three files : $TEMP/tmpdir/tmpname, $TEMP/tmpdir/tmpdir, $TEMP/tmpdir/hiddenfile, + deleteTestFile( aTmpName3, aHidURL1); + deleteTestFile( aTmpName3, aTmpName1); + deleteTestFile( aTmpName3, aTmpName2); + // remove a tempdirectory : $TEMP/tmpdir. + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void reset_001( ) + { + ::osl::Directory testDirectory( aTmpName3 ); //constructor + + //open a directory + nError1 = testDirectory.open( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + //get first Item + nError1 = testDirectory.getNextItem( rItem, 1 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + //check the file name of first Item + ::osl::FileStatus rFileStatusFirst( FileStatusMask_FileName ); + nError1 = rItem.getFileStatus( rFileStatusFirst ); + + //get second Item + //mindy: nError1 = testDirectory.getNextItem( rItem, 0 ); + //mindy: CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + //reset enumeration + nError2 = testDirectory.reset( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError2 ); + //get reseted Item, if reset does not work, getNextItem() should return the second Item (aTmpName1) + nError1 = testDirectory.getNextItem( rItem, 0 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + //check the file name again + ::osl::FileStatus rFileStatus( FileStatusMask_FileName ); + nError1 = rItem.getFileStatus( rFileStatus ); + //close a directory + nError1 = testDirectory.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + sal_Bool bOK1,bOK2,bOK3; + bOK1 = compareFileName( rFileStatus.getFileName( ), aTmpName2 ); + bOK2 = compareFileName( rFileStatus.getFileName( ), aHidURL1 ); + bOK3 = compareFileName( rFileStatus.getFileName( ), rFileStatusFirst.getFileName( ) ); + CPPUNIT_ASSERT_MESSAGE( "test for reset function: get two directory item, reset it, then get again, check the filename", + ( ::osl::FileBase::E_None == nError2 ) && + ( sal_True == bOK1 || bOK2 || bOK3 ) ); + } + + void reset_002( ) + { + ::osl::Directory testDirectory( aTmpName6 ); //constructor + + //close a directory + nError1 = testDirectory.reset( ); + + CPPUNIT_ASSERT_MESSAGE( "test for reset function: reset a non existed directory", + ( ::osl::FileBase::E_NOENT == nError1 ) ); + } + + + void reset_003( ) + { + ::osl::Directory testDirectory( aTmpName4 ); //constructor + + //close a directory + nError1 = testDirectory.reset( ); + + CPPUNIT_ASSERT_MESSAGE( "test for reset function: reset a file instead of a directory", + ( ::osl::FileBase::E_NOTDIR == nError1 ) || ( ::osl::FileBase::E_NOENT == nError1 ) ); + } + + void reset_004( ) + { + ::osl::Directory testDirectory( aUserDirectorySys ); //constructor + + //close a directory + nError1 = testDirectory.reset( ); + + CPPUNIT_ASSERT_MESSAGE( "test for reset function: use a system path", + ( ::osl::FileBase::E_INVAL == nError1 ) ); + } + + CPPUNIT_TEST_SUITE( reset ); + CPPUNIT_TEST( reset_001 ); + CPPUNIT_TEST( reset_002 ); + CPPUNIT_TEST( reset_003 ); + CPPUNIT_TEST( reset_004 ); + CPPUNIT_TEST_SUITE_END( ); + };// class reset + + //--------------------------------------------------------------------- + // testing the method + // inline RC getNextItem( DirectoryItem& rItem, sal_uInt32 nHint = 0 ) + //--------------------------------------------------------------------- + class getNextItem : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + ::osl::DirectoryItem rItem; + + public: + // initialization + void setUp( ) + { + // create a tempdirectory : $TEMP/tmpdir. + createTestDirectory( aTmpName3 ); + // create three files : $TEMP/tmpdir/tmpname, $TEMP/tmpdir/tmpdir, $TEMP/tmpdir/hiddenfile, + createTestFile( aTmpName3, aTmpName2 ); + createTestFile( aTmpName3, aTmpName1 ); + createTestFile( aTmpName3, aHidURL1 ); + + } + + void tearDown( ) + { + // remove three files : $TEMP/tmpdir/tmpname, $TEMP/tmpdir/tmpdir, $TEMP/tmpdir/hiddenfile, + deleteTestFile( aTmpName3, aHidURL1 ); + deleteTestFile( aTmpName3, aTmpName1 ); + deleteTestFile( aTmpName3, aTmpName2 ); + // remove a tempdirectory : $TEMP/tmpdir. + deleteTestDirectory( aTmpName3 ); + } + + // test code. + void getNextItem_001( ) + { + ::osl::Directory testDirectory( aTmpName3 ); //constructor + + //open a directory + nError1 = testDirectory.open( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + //check the file name + ::rtl::OUString strFilename; + sal_Bool bOk1 = sal_False; + sal_Bool bOk2 = sal_False; + sal_Bool bOk3 = sal_False; + ::osl::FileStatus rFileStatus( FileStatusMask_FileName ); + for ( int nCount = 0; nCount < 3; nCount++ ) + { + //get three Items + nError1 = testDirectory.getNextItem( rItem, 2 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + nError1 = rItem.getFileStatus( rFileStatus ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + // a special order is not guaranteed. So any file may occur on any time. + // But every file name should occur only once. + if ( bOk1 == sal_False && compareFileName( rFileStatus.getFileName( ), aTmpName1 ) ) + { + bOk1 = sal_True; + } + + if ( bOk2 == sal_False && compareFileName( rFileStatus.getFileName( ), aTmpName2 ) ) + { + bOk2 = sal_True; + } + + if ( bOk3 == sal_False && compareFileName( rFileStatus.getFileName( ), aHidURL1 ) ) + { + bOk3 = sal_True; + } + } + + //close a directory + nError1 = testDirectory.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for getNextItem function: retrive three items and check their names.", + ( sal_True == bOk1 ) && ( sal_True == bOk2 ) && ( sal_True == bOk3 ) ); + } + + void getNextItem_002( ) + { + ::osl::Directory testDirectory( aTmpName3 ); //constructor + //deliberate error, suppress run-time warning + pfunc_osl_printDetailedDebugMessage pOldDebugMessageFunc = osl_setDetailedDebugMessageFunc( &suppressOslDebugMessage ); + nError1 = testDirectory.getNextItem( rItem ); + osl_setDetailedDebugMessageFunc( pOldDebugMessageFunc ); + + CPPUNIT_ASSERT_MESSAGE( "test for getNextItem function: retrive an item in a directory which is not opened, also test for nHint's default value.", + ( ::osl::FileBase::E_INVAL == nError1 ) ); + } + + void getNextItem_003( ) + { + ::osl::Directory testDirectory( aTmpName3 ); //constructor + + //open a directory + nError1 = testDirectory.open( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + for ( int nCount = 0; nCount < 4; nCount++ ) + { + nError2 = testDirectory.getNextItem( rItem, 3 ); + } + + //close a directory + nError1 = testDirectory.close( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for getNextItem function: retrive 4 times in a directory which contain only 3 files.", + ( ::osl::FileBase::E_NOENT == nError2 ) ); + } + + void getNextItem_004( ) + { + //create a link file(can not on Windows), then check if getNextItem can get it. +#ifdef UNX + sal_Bool bLnkOK = sal_False; + sal_Bool bFoundOK = sal_False; + + ::rtl::OUString aUStr_LnkFileSys( aTempDirectorySys ), aUStr_SrcFileSys( aTempDirectorySys ); + ( aUStr_LnkFileSys += aSlashURL ) += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/tmpdir/link.file")); + ( aUStr_SrcFileSys += aSlashURL ) += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/tmpdir/tmpname")); + + ::rtl::OString strLinkFileName, strSrcFileName; + strLinkFileName = OUStringToOString( aUStr_LnkFileSys, RTL_TEXTENCODING_ASCII_US ); + strSrcFileName = OUStringToOString( aUStr_SrcFileSys, RTL_TEXTENCODING_ASCII_US ); + + // create a link file and link it to file "/tmp/PID/tmpdir/tmpname" + sal_Int32 fd = symlink( strSrcFileName.getStr(), strLinkFileName.getStr() ); + CPPUNIT_ASSERT( fd == 0 ); + ::osl::Directory testDirectory( aTmpName3 ); + + //open a directory + nError1 = testDirectory.open( ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + ::rtl::OUString aFileName (RTL_CONSTASCII_USTRINGPARAM("link.file")); + + while (1) { + nError1 = testDirectory.getNextItem( rItem, 4 ); + if (::osl::FileBase::E_None == nError1) { + ::osl::FileStatus rFileStatus( FileStatusMask_FileName | FileStatusMask_Type ); + rItem.getFileStatus( rFileStatus ); + if ( compareFileName( rFileStatus.getFileName( ), aFileName) == sal_True ) + { + bFoundOK = sal_True; + if ( FileStatus::Link == rFileStatus.getFileType( )) + { + bLnkOK = sal_True; + break; + } + } + } + else + break; + }; + fd = std::remove( strLinkFileName.getStr() ); + CPPUNIT_ASSERT_MESSAGE( "remove link file failed", fd == 0 ); + CPPUNIT_ASSERT_MESSAGE( "test for getNextItem function: check if can retrieve the link file name", + ( bFoundOK == sal_True ) ); + CPPUNIT_ASSERT_MESSAGE( "test for getNextItem function: check if link file has file type link", + ( bLnkOK == sal_True ) ); +#endif + } + + CPPUNIT_TEST_SUITE( getNextItem ); + CPPUNIT_TEST( getNextItem_001 ); + CPPUNIT_TEST( getNextItem_002 ); + CPPUNIT_TEST( getNextItem_003 ); + CPPUNIT_TEST( getNextItem_004 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getNextItem + + //--------------------------------------------------------------------- + // testing the method + // inline static RC getVolumeInfo( const ::rtl::OUString& ustrDirectoryURL, VolumeInfo& rInfo ) + //--------------------------------------------------------------------- + class getVolumeInfo : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + + public: + + // test code. + void checkValidMask(osl::VolumeInfo const& _aVolumeInfo, sal_Int32 _nMask) + { + if (_nMask == VolumeInfoMask_FileSystemName) + { + //get file system name + ::rtl::OUString aFileSysName( aNullURL ); + aFileSysName = _aVolumeInfo.getFileSystemName( ); + + sal_Bool bRes2 = compareFileName( aFileSysName, aNullURL ); + CPPUNIT_ASSERT_MESSAGE( "test for getVolumeInfo function: getVolumeInfo of root directory.", + ( osl::FileBase::E_None == nError1 ) && + ( sal_False == bRes2 ) ); + } + if (_nMask == VolumeInfoMask_Attributes) + { + sal_Bool b1 = _aVolumeInfo.getRemoteFlag(); + sal_Bool b2 = _aVolumeInfo.getRemoveableFlag(); + sal_Bool b3 = _aVolumeInfo.getCompactDiscFlag(); + sal_Bool b4 = _aVolumeInfo.getFloppyDiskFlag(); + sal_Bool b5 = _aVolumeInfo.getFixedDiskFlag(); + sal_Bool b6 = _aVolumeInfo.getRAMDiskFlag(); + + rtl::OString sAttr; + if (b1) sAttr = "Remote"; + if (b2) sAttr += " Removeable"; + if (b3) sAttr += " CDROM"; + if (b4) sAttr += " Floppy"; + if (b5) sAttr += " FixedDisk"; + if (b6) sAttr += " RAMDisk"; + + printf("Attributes: %s\n", sAttr.getStr() ); + } + if (_nMask == VolumeInfoMask_TotalSpace) + { + // within Linux, df / * 1024 bytes is the result + sal_uInt64 nSize = _aVolumeInfo.getTotalSpace(); + printf("Total space: %"SAL_PRIuUINT64"\n", nSize); + } + if (_nMask == VolumeInfoMask_UsedSpace) + { + sal_uInt64 nSize = _aVolumeInfo.getUsedSpace(); + printf(" Used space: %"SAL_PRIuUINT64"\n", nSize); + } + if (_nMask == VolumeInfoMask_FreeSpace) + { + sal_uInt64 nSize = _aVolumeInfo.getFreeSpace(); + printf(" Free space: %"SAL_PRIuUINT64"\n", nSize); + } + if (_nMask == VolumeInfoMask_MaxNameLength) + { + sal_uInt32 nLength = _aVolumeInfo.getMaxNameLength(); + printf("max name length: %"SAL_PRIuUINT32"\n", nLength); + } + if (_nMask == VolumeInfoMask_MaxPathLength) + { + sal_uInt32 nLength = _aVolumeInfo.getMaxPathLength(); + printf("max path length: %"SAL_PRIuUINT32"\n", nLength); + } + if (_nMask == VolumeInfoMask_FileSystemCaseHandling) + { + bool bIsCase = _aVolumeInfo.isCaseSensitiveFileSystem(); + printf("filesystem case sensitive: %s\n", bIsCase ? "yes" : "no"); + } + } + + void checkVolumeInfo(sal_Int32 _nMask) + { + ::osl::VolumeInfo aVolumeInfo( _nMask ); + //call getVolumeInfo here + nError1 = ::osl::Directory::getVolumeInfo( aVolURL1, aVolumeInfo ); + // LLA: IMHO it's not a bug, if VolumeInfo is not valid, it's a feature + // LLA: CPPUNIT_ASSERT_MESSAGE("mask is not valid", sal_True == aVolumeInfo.isValid( _nMask ) ); + if (aVolumeInfo.isValid( _nMask)) + { + checkValidMask(aVolumeInfo, _nMask); + } + } + + + void getVolumeInfo_001_1( ) + { + sal_Int32 mask = VolumeInfoMask_FileSystemName; + checkVolumeInfo(mask); + } + void getVolumeInfo_001_2( ) + { + sal_Int32 mask = VolumeInfoMask_Attributes; + checkVolumeInfo(mask); + } + void getVolumeInfo_001_3( ) + { + sal_Int32 mask = VolumeInfoMask_TotalSpace; + checkVolumeInfo(mask); + } + void getVolumeInfo_001_4( ) + { + sal_Int32 mask = VolumeInfoMask_UsedSpace; + checkVolumeInfo(mask); + } + void getVolumeInfo_001_5( ) + { + sal_Int32 mask = VolumeInfoMask_FreeSpace; + checkVolumeInfo(mask); + } + void getVolumeInfo_001_6( ) + { + sal_Int32 mask = VolumeInfoMask_MaxNameLength; + checkVolumeInfo(mask); + } + void getVolumeInfo_001_7( ) + { + sal_Int32 mask = VolumeInfoMask_MaxPathLength; + checkVolumeInfo(mask); + } + void getVolumeInfo_001_8( ) + { + sal_Int32 mask = VolumeInfoMask_FileSystemCaseHandling; + checkVolumeInfo(mask); + } + + void getVolumeInfo_002( ) + { + sal_Int32 mask = VolumeInfoMask_FileSystemName; + ::osl::VolumeInfo aVolumeInfo( mask ); + //call getVolumeInfo here + + // LLA: rtl::OUString aRootSysURL; + // LLA: nError1 = osl::File::getFileURLFromSystemPath(aRootSys, aRootSysURL); + // LLA: + // LLA: CPPUNIT_ASSERT_MESSAGE( "can't convert root path to file url", + // LLA: ( osl::FileBase::E_NONE == nError1 ) ); + + nError1 = ::osl::Directory::getVolumeInfo( aRootSys, aVolumeInfo ); + + CPPUNIT_ASSERT_MESSAGE( "test for getVolumeInfo function: use system path as parameter.", + ( osl::FileBase::E_INVAL == nError1 ) ); + } + + void getVolumeInfo_003( ) + { + sal_Int32 mask = VolumeInfoMask_FileSystemName; + ::osl::VolumeInfo aVolumeInfo( mask ); + //call getVolumeInfo here + nError1 = ::osl::Directory::getVolumeInfo( aTmpName3, aVolumeInfo ); + +// LLA: in Windows, it reply no error, it did not pass in (W32). +#ifdef UNX + CPPUNIT_ASSERT_MESSAGE( "test for getVolumeInfo function: non-existence test. ", + ( osl::FileBase::E_NOENT == nError1 ) ); +#endif + } + + CPPUNIT_TEST_SUITE( getVolumeInfo ); + CPPUNIT_TEST( getVolumeInfo_001_1 ); + CPPUNIT_TEST( getVolumeInfo_001_2 ); + CPPUNIT_TEST( getVolumeInfo_001_3 ); + CPPUNIT_TEST( getVolumeInfo_001_4 ); + CPPUNIT_TEST( getVolumeInfo_001_5 ); + CPPUNIT_TEST( getVolumeInfo_001_6 ); + CPPUNIT_TEST( getVolumeInfo_001_7 ); + CPPUNIT_TEST( getVolumeInfo_001_8 ); + CPPUNIT_TEST( getVolumeInfo_002 ); + CPPUNIT_TEST( getVolumeInfo_003 ); + CPPUNIT_TEST_SUITE_END( ); + };// class getVolumeInfo + + + //--------------------------------------------------------------------- + // testing the method + // inline static RC create( const ::rtl::OUString& ustrDirectoryURL ) + //--------------------------------------------------------------------- + class create : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + + public: + + // test code. + void create_001( ) + { + //create directory in $TEMP/tmpdir + nError1 = ::osl::Directory::create( aTmpName3 ); + //check for existence + nError2 = ::osl::Directory::create( aTmpName3 ); + //remove it + deleteTestDirectory( aTmpName3 ); + + CPPUNIT_ASSERT_MESSAGE( "test for create function: create a directory and check its existence.", + ( osl::FileBase::E_None == nError1 ) && + ( osl::FileBase::E_EXIST== nError2 ) ); + } + + void create_002( ) + { +#if !defined (WNT) && !defined (MACOSX) && defined (SAL_UNX) + if (geteuid() == 0) //don't test if building as root + return; + + rtl::OUString aTmpDir; + nError1 = FileBase::createTempFile(NULL, NULL, &aTmpDir); + CPPUNIT_ASSERT_MESSAGE("temp File creation failed", osl::FileBase::E_None == nError1); + + nError1 = ::osl::File::remove(aTmpDir); + CPPUNIT_ASSERT_MESSAGE("temp File removal failed", osl::FileBase::E_None == nError1); + + nError1 = ::osl::Directory::create(aTmpDir); + ::rtl::OString sError("test for create function: create a directory '"); + sError += ::rtl::OUStringToOString(aTmpDir, RTL_TEXTENCODING_ASCII_US); + sError += "' and check its existence."; + CPPUNIT_ASSERT_MESSAGE(sError.getStr(), osl::FileBase::E_None == nError1); + osl_setFileAttributes(aTmpDir.pData, 0); //no access allowed now + + //Shouldn't be possible now to create a dir underneath it + rtl::OUString aTmpSubLevel = aTmpDir + OUString(RTL_CONSTASCII_USTRINGPARAM("/notallowedhere")); + nError1 = ::osl::Directory::create(aTmpSubLevel); + + //allow removal + osl_setFileAttributes(aTmpDir.pData, + osl_File_Attribute_OwnRead | + osl_File_Attribute_OwnWrite | + osl_File_Attribute_OwnExe); + deleteTestDirectory(aTmpDir); + sError = ::rtl::OString("test for create function: create a directory under '"); + sError += ::rtl::OUStringToOString(aTmpDir, RTL_TEXTENCODING_ASCII_US); + sError += "' for access test."; + CPPUNIT_ASSERT_MESSAGE(sError.getStr(), osl::FileBase::E_ACCES == nError1); +#endif + } + + void create_003( ) + { + //create directory in /tmpname + nError1 = ::osl::Directory::create( aSysPath1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for create function: create a directory using system path.", + ( osl::FileBase::E_INVAL == nError1 ) ); + } + + CPPUNIT_TEST_SUITE( create ); + CPPUNIT_TEST( create_001 ); + CPPUNIT_TEST( create_002 ); + CPPUNIT_TEST( create_003 ); + CPPUNIT_TEST_SUITE_END( ); + };// class create + + //--------------------------------------------------------------------- + // testing the method + // inline static RC remove( const ::rtl::OUString& ustrDirectoryURL ) + //--------------------------------------------------------------------- + class remove : public CppUnit::TestFixture + { + ::osl::FileBase::RC nError1, nError2; + + public: + + // test code. + void remove_001( ) + { + //create directory in $TEMP/tmpdir + nError1 = ::osl::Directory::create( aTmpName3 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + //remove it + nError1 = ::osl::Directory::remove( aTmpName3 ); + //check for existence + ::osl::Directory rDirectory( aTmpName3 ); + nError2 = rDirectory.open( ); + + CPPUNIT_ASSERT_MESSAGE( "test for remove function: remove a directory and check its existence.", + ( osl::FileBase::E_None == nError1 ) && + ( osl::FileBase::E_NOENT == nError2 ) ); + } + + void remove_002( ) + { + //create directory in $TEMP/tmpdir + nError1 = ::osl::Directory::create( aTmpName3 ); + CPPUNIT_ASSERT( ::osl::FileBase::E_None == nError1 ); + //try to remove it by system path + nError1 = ::osl::Directory::remove( aSysPath3 ); + //check for existence + ::osl::Directory rDirectory( aTmpName3 ); + nError2 = rDirectory.open( ); + if ( osl::FileBase::E_NOENT != nError2 ) + ::osl::Directory::remove( aTmpName3 ); + + CPPUNIT_ASSERT_MESSAGE( "test for remove function: remove a directory by its system path, and check its existence.", + ( osl::FileBase::E_INVAL == nError1 ) ); + } + + void remove_003( ) + { + //try to remove a non-existed directory + nError1 = ::osl::Directory::remove( aTmpName6 ); + + CPPUNIT_ASSERT_MESSAGE( "test for remove function: try to remove a non-existed directory.", + ( osl::FileBase::E_NOENT == nError1 ) ); + } + + void remove_004( ) + { + createTestFile( aTmpName6 ); + sal_Bool bExist = ifFileExist( aTmpName6 ); + //try to remove file. + nError1 = ::osl::Directory::remove( aTmpName6 ); + deleteTestFile( aTmpName6 ); + + CPPUNIT_ASSERT_MESSAGE( "test for remove function: try to remove a file but not directory.", + bExist == sal_True &&(( osl::FileBase::E_NOTDIR == nError1 ) || ( osl::FileBase::E_NOENT == nError1 )) ); + } + + void remove_005( ) + { + createTestDirectory( aTmpName3 ); + createTestFile( aTmpName4 ); + nError1 = ::osl::Directory::remove( aTmpName3 ); + deleteTestFile( aTmpName4 ); + deleteTestDirectory( aTmpName3 ); + ::rtl::OString sError = "test for remove function: try to remove a directory that is not empty."; + sError += errorToStr( nError1 ).getStr(); +#if defined ( SOLARIS ) + //on UNX, the implementation uses rmdir(), which EEXIST is thrown on Solaris when the directory is not empty, refer to: 'man -s 2 rmdir', while on linux, ENOTEMPTY is thrown. + //EEXIST The directory contains entries other than those for "." and "..". + printf("#Solaris test\n"); + CPPUNIT_ASSERT_MESSAGE( sError.getStr(), ( osl::FileBase::E_EXIST == nError1 ) ); +#else + CPPUNIT_ASSERT_MESSAGE( sError.getStr(), ( osl::FileBase::E_NOTEMPTY == nError1 ) ); +#endif + } + + CPPUNIT_TEST_SUITE( remove ); + CPPUNIT_TEST( remove_001 ); + CPPUNIT_TEST( remove_002 ); + CPPUNIT_TEST( remove_003 ); + CPPUNIT_TEST( remove_004 ); + CPPUNIT_TEST( remove_005 ); + CPPUNIT_TEST_SUITE_END( ); + };// class remove + + //######################################## + // TEST Directory::createPath + //######################################## + + #ifdef WNT + # define PATH_BUFFER_SIZE MAX_PATH + #else + # define PATH_BUFFER_SIZE PATH_MAX + #endif + + char TEST_PATH_POSTFIX[] = "hello/world"; + + //######################################## + OUString get_test_path() + { + static OUString test_path; + if (test_path.isEmpty()) + { + OUString tmp; + FileBase::RC rc = FileBase::getTempDirURL(tmp); + + CPPUNIT_ASSERT_MESSAGE + ( + "Getting the location of TMP dir failed", + rc == FileBase::E_None + ); + + OUString system_path; + rc = FileBase::getSystemPathFromFileURL(tmp, system_path); + + CPPUNIT_ASSERT_MESSAGE + ( + "Cannot convert the TMP dir to system path", + rc == FileBase::E_None + ); + + OString tmp_x(rtl::OUStringToOString(system_path, RTL_TEXTENCODING_UTF8 )); + if (tmp_x.lastIndexOf('/') != (tmp_x.getLength() - 1)) + tmp_x += rtl::OString('/'); + +#ifndef WNT + // FIXME would be nice to create unique dir even on Windows + tmp_x += rtl::OString("XXXXXX"); + char *out = mkdtemp(const_cast<char*>(tmp_x.getStr())); + + CPPUNIT_ASSERT_MESSAGE + ( + "mkdtemp call failed", + out != NULL + ); + + tmp_x += rtl::OString('/'); +#endif + tmp_x += rtl::OString(TEST_PATH_POSTFIX); + + rc = FileBase::getFileURLFromSystemPath(rtl::OStringToOUString(tmp_x, RTL_TEXTENCODING_UTF8), test_path); + + CPPUNIT_ASSERT_MESSAGE + ( + "Cannot convert the system path back to an URL", + rc == FileBase::E_None + ); + } + return test_path; + } + + //######################################## + void rm_test_path(const OUString& path) + { + sal_Unicode buffer[PATH_BUFFER_SIZE]; + rtl_copyMemory(buffer, path.getStr(), (path.getLength() + 1) * sizeof(sal_Unicode)); + + sal_Int32 i = rtl_ustr_lastIndexOfChar(buffer, '/'); + if (i == path.getLength()) + buffer[i] = 0; + + Directory::remove(buffer); + + i = rtl_ustr_lastIndexOfChar(buffer, '/'); + buffer[i] = 0; + Directory::remove(buffer); + } + + //######################################## + class DirCreatedObserver : public DirectoryCreationObserver + { + public: + DirCreatedObserver() : i(0) + { + } + + virtual void DirectoryCreated(const rtl::OUString& /*aDirectoryUrl*/) + { + i++; + }; + + int number_of_dirs_created() const + { + return i; + } + + private: + int i; + }; + + + //######################################## + class createPath : public CppUnit::TestFixture + { + public: + //########################################## + createPath() + {} + + //########################################## + void with_relative_path() + { + FileBase::RC rc = Directory::createPath( + OUString(RTL_CONSTASCII_USTRINGPARAM(TEST_PATH_POSTFIX))); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_createDirectoryPath contract broken", + rc == FileBase::E_INVAL + ); + } + + //########################################## + void without_callback() + { + OUString tp_url = get_test_path(); + + rm_test_path(tp_url); + + FileBase::RC rc = Directory::createPath(tp_url); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_createDirectoryPath failed", + rc == FileBase::E_None + ); + } + + //########################################## + void with_callback() + { + OUString tp_url = get_test_path(); + + rm_test_path(tp_url); + + DirCreatedObserver* observer = new DirCreatedObserver; + FileBase::RC rc = Directory::createPath(tp_url, observer); + int nDirs = observer->number_of_dirs_created(); + delete observer; + CPPUNIT_ASSERT_MESSAGE + ( + "osl_createDirectoryPath failed", + (rc == FileBase::E_None) && (nDirs > 0) + ); + + } + +#ifdef WNT + + //########################################## + char* get_unused_drive_letter() + { + static char m_aBuff[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + DWORD ld = GetLogicalDrives(); + DWORD i = 4; + DWORD j = 2; + + while ((ld & i) && (i > 1)) + { i = i << 1; j++; } + + if (i > 2) + return m_aBuff + j; + + return NULL; + } + + //########################################## + void at_invalid_logical_drive() + { + char* drv = get_unused_drive_letter(); + char buff[PATH_BUFFER_SIZE]; + rtl_zeroMemory(buff, sizeof(buff)); + + strncpy(buff, drv, 1); + strcat(buff, ":\\"); + strcat(buff, TEST_PATH_POSTFIX); + + OUString path = OUString::createFromAscii(buff); + OUString tp_url; + FileBase::getFileURLFromSystemPath(path, tp_url); + + FileBase::RC rc = Directory::createPath(tp_url); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_createDirectoryPath doesn't fail on unused logical drive letters", + rc != FileBase::E_None + ); + } + + //########################################## + void with_UNC_path() + { + + OUString tp_unc (RTL_CONSTASCII_USTRINGPARAM("\\\\Tra-1\\TRA_D\\hello\\world\\")); + OUString tp_url; + FileBase::getFileURLFromSystemPath(tp_unc, tp_url); + + FileBase::RC rc = Directory::createPath(tp_url); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_createDirectoryPath fails with UNC path", + rc == FileBase::E_None + ); + } + +#endif /* WNT */ + + CPPUNIT_TEST_SUITE(createPath); + CPPUNIT_TEST(with_relative_path); + CPPUNIT_TEST(without_callback); + CPPUNIT_TEST(with_callback); +#ifdef WNT + CPPUNIT_TEST(at_invalid_logical_drive); + + // adapt the UNC path in method createDirectoryPath_with_UNC_path + // in order to run this test successfully + //CPPUNIT_TEST(with_UNC_path); +#endif + CPPUNIT_TEST_SUITE_END(); + + }; // class createPath + + // ----------------------------------------------------------------------------- + CPPUNIT_TEST_SUITE_REGISTRATION( osl_Directory::ctors ); + CPPUNIT_TEST_SUITE_REGISTRATION( osl_Directory::open ); + CPPUNIT_TEST_SUITE_REGISTRATION( osl_Directory::isOpen ); + CPPUNIT_TEST_SUITE_REGISTRATION( osl_Directory::close ); + CPPUNIT_TEST_SUITE_REGISTRATION( osl_Directory::reset ); + CPPUNIT_TEST_SUITE_REGISTRATION( osl_Directory::getNextItem ); + CPPUNIT_TEST_SUITE_REGISTRATION( osl_Directory::getVolumeInfo ); + CPPUNIT_TEST_SUITE_REGISTRATION( osl_Directory::create ); + CPPUNIT_TEST_SUITE_REGISTRATION( osl_Directory::remove ); + CPPUNIT_TEST_SUITE_REGISTRATION( osl_Directory::createPath ); +}// namespace osl_Directory + + + +CPPUNIT_PLUGIN_IMPLEMENT(); + + + +/** get Current PID. +*/ +inline ::rtl::OUString getCurrentPID( ) +{ + //~ Get current PID and turn it into OUString; + int nPID = 0; +#ifdef WNT + nPID = GetCurrentProcessId(); +#else + nPID = getpid(); +#endif + return ( ::rtl::OUString::valueOf( ( long )nPID ) ); +} + + +//~ do some clean up work after all test completed. +class GlobalObject +{ + public: + ~GlobalObject() + { + try + { + //~ special clean up task in Windows and Unix seperately; +#if ( defined UNX ) || ( defined OS2 ) + //~ some clean up task for UNIX OS + ; +#else + //~ some clean up task for Windows OS + //~ check if some files are in the way, remove them if necessary. + if ( ifFileExist( aTmpName6 ) == sal_True ) + deleteTestFile( aTmpName6 ); + if ( ifFileExist( aTmpName4 ) == sal_True ) + deleteTestFile( aTmpName4 ); + if ( checkDirectory( aTmpName4, osl_Check_Mode_Exist ) == sal_True ) + deleteTestDirectory( aTmpName4 ); + if ( ifFileExist( aTmpName3 ) == sal_True ) + deleteTestFile( aTmpName3 ); + if ( checkDirectory( aTmpName3, osl_Check_Mode_Exist ) == sal_True ) + deleteTestDirectory( aTmpName3 ); + + ::rtl::OUString aUStr( aUserDirectoryURL ); + concatURL( aUStr, aHidURL1 ); + if ( ifFileExist( aUStr ) == sal_True ) + deleteTestFile( aUStr ); + + ::rtl::OUString aUStr1( aRootURL ); + concatURL( aUStr1, aTmpName2 ); + if ( ifFileExist( aUStr1 ) == sal_True ) + deleteTestFile( aUStr1 ); +#endif + + } + catch (CppUnit::Exception &e) + { + printf("Exception caught in GlobalObject dtor(). Exception message: '%s'. Source line: %d\n", e.what(), e.sourceLine().lineNumber()); + } + catch (...) + { + printf("Exception caught (...) in GlobalObject dtor()\n"); + } + } +}; + +GlobalObject theGlobalObject; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/file/osl_File_Const.h b/sal/qa/osl/file/osl_File_Const.h new file mode 100644 index 000000000000..2e423b1622d7 --- /dev/null +++ b/sal/qa/osl/file/osl_File_Const.h @@ -0,0 +1,230 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _OSL_FILE_CONST_H_ +#define _OSL_FILE_CONST_H_ + +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <sal/types.h> +#include <rtl/textenc.h> + +#include <rtl/ustring.hxx> +#include <rtl/uri.hxx> + +#ifdef __cplusplus +extern "C" +{ +#endif + + + +//------------------------------------------------------------------------ +// common used string resource +// these common used string will be used as assist resource in test +// they are mostly OS independent, some of the resource can be reused +// so, acommon test data repository will be better since it can be +// shared among all test code +//------------------------------------------------------------------------ + +const sal_Char pBuffer_Char[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; +const sal_Char pBuffer_Number[] = "1234567890"; +const sal_Char pBuffer_Blank[] = ""; + +#define TRUNC_LEN 10; +#define ENLARG_LEN 100; + + + +//------------------------------------------------------------------------ +// OS dependent/independent definitions/includes +// we use FILE_PREFIX for URL prefix, +// TEST_PLATFORM for test platform initial, +// TEST_PLATFORM_ROOT for root dir in comrresponding platform, +// TEST_PLATFORM_TEMP for temp dir in comrresponding platform, +// PATH_LIST_DELIMITER for seperator of path list in comrresponding platform, +// PATH_SEPERATOR for seperator in URL or system path in comrresponding platform, +// PATH_MAX/MAX_PATH for max path length in comrresponding platform, +//------------------------------------------------------------------------ + +//------------------------------------------------------------------------ +// OS independent const definition +//------------------------------------------------------------------------ +# define FILE_PREFIX "file:///" +# define TEST_FILE_SIZE 1024 + +//------------------------------------------------------------------------ +// OS dependent declaration and includes +//------------------------------------------------------------------------ +#if ( defined UNX ) || ( defined OS2 ) //Unix +# include <unistd.h> +# include <limits.h> +# include <math.h> +# include <errno.h> +# include <fcntl.h> +# include <sys/stat.h> +# if !defined(MACOSX) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined (DRAGONFLY) +# include <sys/statfs.h> +# else +# include <sys/param.h> +# include <sys/mount.h> +# endif +# include <sys/statvfs.h> +# include <sys/types.h> +# define TEST_PLATFORM "" +# define TEST_PLATFORM_ROOT "/" +# define TEST_PLATFORM_TEMP "tmp" +# define PATH_LIST_DELIMITER ":" +# define PATH_SEPERATOR "/" +#endif + +#if (defined WNT ) // Windows +# include <tchar.h> +# include <io.h> +# include <stdio.h> +# include <stdlib.h> +# define PATH_MAX MAX_PATH +# define TEST_PLATFORM "c:/" +# define TEST_PLATFORM_ROOT "c:/" +# define TEST_PLATFORM_TEMP "temp" +# define PATH_LIST_DELIMITER ";" +# define PATH_SEPERATOR "/" +#endif + + +//------------------------------------------------------------------------ +// macro definition for the ASCII array/OUString declarations, +// we use p### for the ASCII array, +// a### for the OUString, +// n###Len for its length +//------------------------------------------------------------------------ + +#define OSLTEST_DECLARE( str_name, str_value ) \ + ::rtl::OUString a##str_name = rtl::OUString::createFromAscii( ( str_value ) ) + +#define OSLTEST_DECLARE_UTF8(str_name, str_value ) \ + ::rtl::OUString a##str_name = ::rtl::Uri::decode( ::rtl::OUString::createFromAscii( ( str_value ) ), rtl_UriDecodeToIuri, RTL_TEXTENCODING_UTF8) + +//------------------------------------------------------------------------ +// OS independent file definition +//------------------------------------------------------------------------ +OSLTEST_DECLARE( NullURL, "" ); +OSLTEST_DECLARE( SlashURL, PATH_SEPERATOR ); +OSLTEST_DECLARE( PreURL, FILE_PREFIX ); +OSLTEST_DECLARE( RootURL, FILE_PREFIX TEST_PLATFORM ); + +OSLTEST_DECLARE( TempDirectoryURL, FILE_PREFIX TEST_PLATFORM TEST_PLATFORM_TEMP ); +OSLTEST_DECLARE( TempDirectorySys, TEST_PLATFORM_ROOT TEST_PLATFORM_TEMP ); +OSLTEST_DECLARE( UserDirectoryURL, FILE_PREFIX TEST_PLATFORM TEST_PLATFORM_TEMP "" ); +OSLTEST_DECLARE( UserDirectorySys, TEST_PLATFORM_ROOT TEST_PLATFORM_TEMP "" ); + +//------------------------------------------------------------------------ +// common used URL:temp, canonical, root, relative, link,etc +//------------------------------------------------------------------------ +OSLTEST_DECLARE( CanURL1, FILE_PREFIX TEST_PLATFORM TEST_PLATFORM_TEMP "/canonical.name" ); +OSLTEST_DECLARE( CanURL2, "ca@#;+.,$///78no\0ni..name" ); +OSLTEST_DECLARE( CanURL3, "ca@#;+.,$//tmp/678nonical//name" ); +OSLTEST_DECLARE( CanURL4, "canonical.name" ); +OSLTEST_DECLARE( TmpName1, "tmpdir" ); +OSLTEST_DECLARE( TmpName2, "tmpname" ); +OSLTEST_DECLARE( TmpName3, FILE_PREFIX TEST_PLATFORM TEST_PLATFORM_TEMP "/tmpdir" ); +OSLTEST_DECLARE( TmpName4, FILE_PREFIX TEST_PLATFORM TEST_PLATFORM_TEMP "/tmpdir/tmpname" ); +OSLTEST_DECLARE( TmpName5, FILE_PREFIX TEST_PLATFORM TEST_PLATFORM_TEMP "/tmpdir/../tmpdir/./tmpname" ); +OSLTEST_DECLARE( TmpName6, FILE_PREFIX TEST_PLATFORM TEST_PLATFORM_TEMP "/tmpname" ); +OSLTEST_DECLARE( TmpName7, FILE_PREFIX TEST_PLATFORM TEST_PLATFORM_TEMP "/noaccess" ); +OSLTEST_DECLARE( TmpName8, FILE_PREFIX TEST_PLATFORM TEST_PLATFORM_TEMP "/tmpname/tmpdir" ); +OSLTEST_DECLARE( TmpName9, FILE_PREFIX TEST_PLATFORM TEST_PLATFORM_TEMP "/tmpdir/../tmpdir/./" ); +OSLTEST_DECLARE_UTF8( TmpName10, FILE_PREFIX TEST_PLATFORM TEST_PLATFORM_TEMP "/%E6%9C%AA%E5%91%BD%E5%90%8Dzhgb18030" ); + +OSLTEST_DECLARE( RelURL1, "relative/file1" ); +OSLTEST_DECLARE( RelURL2, "relative/./file2" ); +OSLTEST_DECLARE( RelURL3, "relative/../file3" ); +OSLTEST_DECLARE( RelURL4, "././relative/../file4" ); +OSLTEST_DECLARE( RelURL5, TEST_PLATFORM_TEMP "/./../" TEST_PLATFORM_TEMP ); +OSLTEST_DECLARE( LnkURL1, FILE_PREFIX TEST_PLATFORM TEST_PLATFORM_TEMP "/link.file" ); +OSLTEST_DECLARE( HidURL1, ".hiddenfile" ); + +//------------------------------------------------------------------------ +// common used System Path:temp, root,etc +//------------------------------------------------------------------------ +OSLTEST_DECLARE( RootSys, TEST_PLATFORM_ROOT ); +OSLTEST_DECLARE( SysPath1, TEST_PLATFORM_ROOT TEST_PLATFORM_TEMP "/system.path" ); +OSLTEST_DECLARE( SysPath2, TEST_PLATFORM_ROOT TEST_PLATFORM_TEMP "/system/path" ); +OSLTEST_DECLARE( SysPath3, TEST_PLATFORM_ROOT TEST_PLATFORM_TEMP "/tmpdir" ); +OSLTEST_DECLARE( SysPath4, TEST_PLATFORM_ROOT TEST_PLATFORM_TEMP "/tmpname" ); +OSLTEST_DECLARE_UTF8( SysPath5, TEST_PLATFORM_ROOT TEST_PLATFORM_TEMP "/%E6%9C%AA%E5%91%BD%E5%90%8Dzhgb18030" ); +OSLTEST_DECLARE( SysPathLnk, TEST_PLATFORM_ROOT TEST_PLATFORM_TEMP "/link.file" ); +OSLTEST_DECLARE( FifoSys, TEST_PLATFORM_ROOT TEST_PLATFORM_TEMP "/tmpdir/fifo" ); + +//------------------------------------------------------------------------ +// FileType URL, we pick some canonical file in corresponding system for test: +// socket, link, etc. +// Note that this may be changed in the different platform, so be careful to use. +//------------------------------------------------------------------------ +#if ( defined UNX ) || ( defined OS2 ) // Unix +OSLTEST_DECLARE( TypeURL1, FILE_PREFIX "dev/ccv"); //socket Solaris/Linux +OSLTEST_DECLARE( TypeURL2, FILE_PREFIX "devices/pseudo/tcp@0:tcp"); //special Solaris/Linux +OSLTEST_DECLARE( TypeURL3, FILE_PREFIX "lib" ); //link Solaris +#else // Windows +OSLTEST_DECLARE( TypeURL1, FILE_PREFIX "" ); +OSLTEST_DECLARE( TypeURL2, FILE_PREFIX "" ); +OSLTEST_DECLARE( TypeURL3, FILE_PREFIX "" ); +#endif + +//------------------------------------------------------------------------ +// Volume device URL, we pick some canonical volume device for test: +// UNIX file system, Floppy Disk, Proc file system, Temp file system, Compact Disk. +//------------------------------------------------------------------------ +#if ( defined UNX ) || ( defined OS2 ) // Unix +OSLTEST_DECLARE( VolURL1, FILE_PREFIX ""); //ufs Solaris/Linux +#ifdef SOLARIS +OSLTEST_DECLARE( VolURL2, FILE_PREFIX "dev/fd" ); //fd Solaris +#else +OSLTEST_DECLARE( VolURL2, FILE_PREFIX "dev/floppy/0u1440" ); //fd0 Linux +#endif +OSLTEST_DECLARE( VolURL3, FILE_PREFIX "proc" ); //proc Solaris/Linux +OSLTEST_DECLARE( VolURL4, FILE_PREFIX "staroffice" ); //nfs Solaris/Linux +OSLTEST_DECLARE( VolURL5, FILE_PREFIX "tmp" ); //tmpfs Solaris +OSLTEST_DECLARE( VolURL6, FILE_PREFIX "cdrom" ); //cd Solaris +#else // Windows +OSLTEST_DECLARE( VolURL1, FILE_PREFIX "c:/" ); +OSLTEST_DECLARE( VolURL2, FILE_PREFIX "a:/" ); +OSLTEST_DECLARE( VolURL3, FILE_PREFIX "" ); +OSLTEST_DECLARE( VolURL4, FILE_PREFIX "" ); +OSLTEST_DECLARE( VolURL5, FILE_PREFIX "c:/temp" ); +OSLTEST_DECLARE( VolURL6, FILE_PREFIX "e:/" ); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* _OSL_FILE_CONST_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/file/osl_old_test_file.cxx b/sal/qa/osl/file/osl_old_test_file.cxx new file mode 100644 index 000000000000..0b2f4d5664ca --- /dev/null +++ b/sal/qa/osl/file/osl_old_test_file.cxx @@ -0,0 +1,282 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +// LLA: +// this file is converted to use with testshl2 +// original was placed in sal/test/textenc.cxx + +#include <stdio.h> + +#include <osl/file.h> +#include <osl/process.h> +#include <rtl/ustring.hxx> +#ifdef SAL_UNX +#include <unistd.h> +#include <limits.h> +#include <string.h> +#include <sys/stat.h> +#define TEST_VOLUME "" +#else +// WINDOWS +#define TEST_VOLUME "c:/" +#endif + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> + +namespace osl_test_file +{ + +// ----------------------------------------------------------------------------- + +class oldtestfile : public CppUnit::TestFixture +{ +public: + void test_file_001(); + void test_file_002(); + void test_file_003(); + void test_file_004(); + + CPPUNIT_TEST_SUITE( oldtestfile ); + CPPUNIT_TEST( test_file_001 ); + CPPUNIT_TEST( test_file_002 ); + // so buggy!! CPPUNIT_TEST( test_file_003 ); + CPPUNIT_TEST( test_file_004 ); + CPPUNIT_TEST_SUITE_END( ); +}; + +const char * const aSource1[] = +{ + "a" , "file:///" TEST_VOLUME "bla/a", + ///TODO: check if last slash must be omitted in resolved path. +// "a/" , "file:///" TEST_VOLUME "bla/a", + "../a" , "file:///" TEST_VOLUME "a" , + "a/.." , "file:///" TEST_VOLUME "bla/", + "a/../b" , "file:///" TEST_VOLUME "bla/b", + ".." , "file:///" TEST_VOLUME "", + "a/b/c/d" , "file:///" TEST_VOLUME "bla/a/b/c/d", + "a/./c" , "file:///" TEST_VOLUME "bla/a/c", + "file:///bla/blub", "file:///" "bla/blub", + 0 , 0 +}; + +const char * const aSource2[ ] = +{ + "a" , "file:///" TEST_VOLUME "bla/blubs/schnubbel/a", + ///TODO: check if last slash must be omitted in resolved path. +// "a/", "file:///" TEST_VOLUME "bla/blubs/schnubbel/a", + "../a", "file:///" TEST_VOLUME "bla/blubs/a", + "../../a", "file:///" TEST_VOLUME "bla/a", + "../../../a", "file:///" TEST_VOLUME "a", + "../../../a/b/c/d", "file:///" TEST_VOLUME "a/b/c/d", + 0,0 +}; + +const char * const aSource3[ ] = +{ + ".." , "/a", + "../a" , "/a/a", + "e/f" , "/c/e/f", + "../..", "", + 0,0 +}; + +using ::rtl::OUString; +using ::rtl::OUStringToOString; +using ::rtl::OString; +void oldtestfile::test_file_001() +{ +#ifdef WIN32 + return; +#endif + + OUString base1( RTL_CONSTASCII_USTRINGPARAM( "file:///" TEST_VOLUME "bla" ) ); + int i; + for( i = 0 ; aSource1[i] ; i +=2 ) + { + OUString target; + OUString rel = OUString::createFromAscii( aSource1[i] ); + oslFileError e = osl_getAbsoluteFileURL( base1.pData, rel.pData , &target.pData ); + // printf("%d : %s -- %s -- %s\n", i, aSource1[i], aSource1[i+1], OUStringToOString(target , RTL_TEXTENCODING_ASCII_US ).getStr() ); + CPPUNIT_ASSERT_MESSAGE("failure #1", osl_File_E_None == e ); + if( osl_File_E_None == e ) + { + CPPUNIT_ASSERT_MESSAGE("failure #1.1", target.equalsAscii( aSource1[i+1] ) ); + } + OString o = OUStringToOString( target , RTL_TEXTENCODING_ASCII_US ); + OString obase = OUStringToOString( base1 , RTL_TEXTENCODING_ASCII_US ); + // fprintf( stderr, "%d %s + %s = %s\n" ,e, obase.getStr(), aSource1[i], o.pData->buffer ); + } + + OUString err1( RTL_CONSTASCII_USTRINGPARAM( "../.." ) ); + OUString target; + // CPPUNIT_ASSERT_MESSAGE("failure #11", osl_File_E_None != osl_getAbsoluteFileURL( base1.pData , err1.pData , &target.pData ) ); + +} + +void oldtestfile::test_file_002() +{ +#ifdef WIN32 + return; +#endif + + OUString base2( RTL_CONSTASCII_USTRINGPARAM( "file:///" TEST_VOLUME "bla/blubs/schnubbel" ) ); + int i; + for( i = 0 ; aSource2[i] ; i +=2 ) + { + OUString target; + OUString rel = OUString::createFromAscii( aSource2[i] ); + oslFileError e = osl_getAbsoluteFileURL( base2.pData, rel.pData , &target.pData ); + // printf("%d : %s -- %s -- %s\n", i, aSource2[i], aSource2[i+1], OUStringToOString(target , RTL_TEXTENCODING_ASCII_US ).getStr() ); + CPPUNIT_ASSERT_MESSAGE("failure #2", osl_File_E_None == e ); + if( osl_File_E_None == e ) + { + CPPUNIT_ASSERT_MESSAGE("failure #2.1", target.equalsAscii( aSource2[i+1] ) ); + } + OString o = OUStringToOString( target , RTL_TEXTENCODING_ASCII_US ); + OString obase = OUStringToOString( base2 , RTL_TEXTENCODING_ASCII_US ); +// fprintf( stderr, "%d %s + %s = %s\n" ,e, obase.getStr(), aSource2[i], o.pData->buffer ); + } +} + +void oldtestfile::test_file_003() +{ +#ifdef WIN32 + return; +#endif + + // links ! +#ifdef UNX + int i; + char buf[PATH_MAX]; + if( getcwd( buf, PATH_MAX -1 ) ) + { + char buf2[PATH_MAX]; + strcpy( buf2 , "/tmp" ); + strcat( buf2, "/a" ); + + if( 0 == mkdir( buf2 , S_IRWXG | S_IRWXO | S_IRWXU ) ) + { + strcat( buf2, "/b" ); + if( 0 == mkdir( buf2, S_IRWXU | S_IRWXO | S_IRWXU ) ) + { + if( 0 == symlink( buf2 , "/tmp/c" ) ) + { + OUString dir; + osl_getProcessWorkingDir( &(dir.pData) ); + + OUString base3 = dir; + base3 += OUString( RTL_CONSTASCII_USTRINGPARAM( "/c" ) ); + for( i = 0 ; aSource3[i] ; i +=2 ) + { + OUString target; + OUString rel = OUString::createFromAscii( aSource3[i] ); + oslFileError e = osl_getAbsoluteFileURL( base3.pData, rel.pData , &target.pData ); + CPPUNIT_ASSERT_MESSAGE("failure #3", osl_File_E_None == e ); + if( osl_File_E_None == e ) + { + CPPUNIT_ASSERT_MESSAGE("failure #4", target.getLength() >= dir.getLength() ); + if( target.getLength() >= dir.getLength() ) + { + int j; + for( j = dir.getLength() ; + j < target.getLength() && + aSource3[i+1][j-dir.getLength()] == target[j] ; j++ ); + CPPUNIT_ASSERT_MESSAGE("failure #5", j == target.getLength() ); + } + } + OString o = OUStringToOString( target , RTL_TEXTENCODING_ASCII_US ); + OString obase = OUStringToOString( base3 , RTL_TEXTENCODING_ASCII_US ); + //fprintf( stderr, "%d %s + %s = %s\n" ,e, obase.getStr(), aSource3[i], o.pData->buffer ); + } + unlink( "/tmp/c" ); + } + else + { + CPPUNIT_ASSERT_MESSAGE("failure #6", 0 ); + } + rmdir( "/tmp/a/b" ); + } + else + { + CPPUNIT_ASSERT_MESSAGE("failure #7", 0 ); + } + rmdir( "/tmp/a" ); + } + else + { + CPPUNIT_ASSERT_MESSAGE("failure #8", 0 ); + } + } + else + { + CPPUNIT_ASSERT_MESSAGE("failure #9", 0 ); + } +#endif +} + +void oldtestfile::test_file_004() +{ +#ifdef WIN32 + return; +#endif + + OUString base4( RTL_CONSTASCII_USTRINGPARAM( "file:///" TEST_VOLUME "bla/" ) ); + int i; + for( i = 0 ; aSource1[i] ; i +=2 ) + { + OUString target; + OUString rel = OUString::createFromAscii( aSource1[i] ); + oslFileError e = osl_getAbsoluteFileURL( base4.pData, rel.pData , &target.pData ); + CPPUNIT_ASSERT_MESSAGE("failure #10", osl_File_E_None == e ); + if( osl_File_E_None == e ) + { + CPPUNIT_ASSERT_MESSAGE("failure #10.1", target.equalsAscii( aSource1[i+1] ) ); + } + OString o = OUStringToOString( target , RTL_TEXTENCODING_ASCII_US ); + OString obase = OUStringToOString( base4 , RTL_TEXTENCODING_ASCII_US ); + //fprintf( stderr, "%d %s + %s = %s\n" ,e, obase.getStr(), aSource1[i], o.pData->buffer ); + } + + +// fprintf( stderr, "test_file done\n" ); +} + +} // namespace osl_test_file + +// ----------------------------------------------------------------------------- +CPPUNIT_TEST_SUITE_REGISTRATION( osl_test_file::oldtestfile); + +// ----------------------------------------------------------------------------- +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/file/test_cpy_wrt_file.cxx b/sal/qa/osl/file/test_cpy_wrt_file.cxx new file mode 100644 index 000000000000..891163120489 --- /dev/null +++ b/sal/qa/osl/file/test_cpy_wrt_file.cxx @@ -0,0 +1,104 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> +#include <osl/file.hxx> +#include <osl/thread.h> +#include <rtl/ustring.hxx> + +using namespace osl; + +using ::rtl::OUString; +using ::rtl::OUStringToOString; +using ::rtl::OString; + +//Use to silence OSL_ warnings for a deliberate error +extern "C" void SAL_CALL suppressOslDebugMessage( const sal_Char *, sal_Int32, const sal_Char * ) +{ +} + +class test_osl_writeFile : public CppUnit::TestFixture +{ +public: + void wrt_file() + { + FileBase::RC err; + + //create a tempfile + rtl::OUString aTmpFile; + err = FileBase::createTempFile(NULL, NULL, &aTmpFile); + CPPUNIT_ASSERT_MESSAGE("temp File creation failed", err == osl::FileBase::E_None); + + //now attempt to open with Create flag an existing file, should get E_EXIST + File tmp_file(aTmpFile); + err = tmp_file.open(osl_File_OpenFlag_Write | osl_File_OpenFlag_Create); + + rtl::OString sErrorMsg = "Expected that '"; + sErrorMsg += rtl::OUStringToOString(aTmpFile, RTL_TEXTENCODING_ASCII_US); + sErrorMsg += "' would exist!"; + CPPUNIT_ASSERT_MESSAGE(sErrorMsg.getStr(), err == FileBase::E_EXIST); + + //deliberate errors, suppress run-time warning for operations on + //un-opened File + pfunc_osl_printDetailedDebugMessage pOldDebugMessageFunc = + osl_setDetailedDebugMessageFunc( &suppressOslDebugMessage ); + + char buffer[1]; + sal_uInt64 written = 0; + err = tmp_file.write((void*)buffer, sizeof(buffer), written); + CPPUNIT_ASSERT_MESSAGE("write on unconnected file should fail", + err != osl::FileBase::E_None && written == 0); + + err = tmp_file.sync(); + CPPUNIT_ASSERT_MESSAGE("sync on unconnected file should fail", err != FileBase::E_None); + err = tmp_file.close(); + CPPUNIT_ASSERT_MESSAGE("close on unconnected file should fail", err != FileBase::E_None); + + osl_setDetailedDebugMessageFunc( pOldDebugMessageFunc ); + + err = ::osl::File::remove(aTmpFile); + CPPUNIT_ASSERT_MESSAGE("temp file should have existed", err == FileBase::E_None); + } + + CPPUNIT_TEST_SUITE(test_osl_writeFile); + CPPUNIT_TEST(wrt_file); + CPPUNIT_TEST_SUITE_END(); +}; + +//##################################### +// register test suites +CPPUNIT_TEST_SUITE_REGISTRATION(test_osl_writeFile); + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/module/export_dll.map b/sal/qa/osl/module/export_dll.map new file mode 100644 index 000000000000..879f246ebae1 --- /dev/null +++ b/sal/qa/osl/module/export_dll.map @@ -0,0 +1,35 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# <http://www.openoffice.org/license.html> +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +UDK_3_0_0 { + global: + firstfunc; + cppunitTestPlugIn; + + local: + *; +}; diff --git a/sal/qa/osl/module/makefile.mk b/sal/qa/osl/module/makefile.mk new file mode 100644 index 000000000000..df444788ea07 --- /dev/null +++ b/sal/qa/osl/module/makefile.mk @@ -0,0 +1,79 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# <http://www.openoffice.org/license.html> +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +PRJ=..$/..$/.. + +PRJNAME=sal +TARGET=qa_module + +ENABLE_EXCEPTIONS=TRUE + +# --- Settings ----------------------------------------------------- + +.INCLUDE : settings.mk + +CFLAGS+= $(LFS_CFLAGS) +CXXFLAGS+= $(LFS_CFLAGS) + +# BEGIN ---------------------------------------------------------------- + +# --- test dll ------------------------------------------------------ +SHL1TARGET = Module_DLL +SHL1OBJS = $(SLO)$/osl_Module_DLL.obj +SHL1STDLIBS = $(SALLIB) $(CPPUNITLIB) +SHL1IMPLIB = i$(SHL1TARGET) +SHL1DEF = $(MISC)$/$(SHL1TARGET).def +DEF1NAME = $(SHL1TARGET) +SHL1VERSIONMAP = export_dll.map + + +# --- main l ------------------------------------------------------ +SHL2OBJS= $(SLO)$/osl_Module.obj + +SHL2TARGET= osl_Module +SHL2STDLIBS= $(SALLIB) $(CPPUNITLIB) + +.IF "$(GUI)" == "WNT" +SHL2STDLIBS+=i$(SHL2TARGET).lib +.ENDIF +.IF "$(GUI)" == "UNX" +APP3STDLIBS+=-l$(SHL2TARGET) +.ENDIF + +SHL2DEPN= $(SHL1OBJS) +SHL2IMPLIB= i$(SHL2TARGET) +SHL2DEF= $(MISC)$/$(SHL2TARGET).def + +DEF2NAME =$(SHL2TARGET) +SHL2VERSIONMAP= $(PRJ)$/qa$/export.map +# END ------------------------------------------------------------------ + +# --- Targets ------------------------------------------------------ + +.INCLUDE : target.mk +.INCLUDE : $(PRJ)$/qa$/cppunit_local.mk + diff --git a/sal/qa/osl/module/osl_Module.cxx b/sal/qa/osl/module/osl_Module.cxx new file mode 100644 index 000000000000..dc8f562a1f86 --- /dev/null +++ b/sal/qa/osl/module/osl_Module.cxx @@ -0,0 +1,529 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ + /************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +//------------------------------------------------------------------------ +// include files +//------------------------------------------------------------------------ +#include <osl_Module_Const.h> + +using namespace osl; + +using ::rtl::OUString; +using ::rtl::OUStringToOString; +using ::rtl::OString; +//------------------------------------------------------------------------ +// helper functions and classes +//------------------------------------------------------------------------ + +/** print Boolean value. +*/ +inline void printBool( sal_Bool bOk ) +{ + printf("#printBool# " ); + ( sal_True == bOk ) ? printf( "TRUE!\n" ) + : printf( "FALSE!\n" ); +} + +/** print a UNI_CODE String. +*/ +inline void printUString( const ::rtl::OUString & str ) +{ + rtl::OString aString; + + printf("#printUString_u# " ); + aString = ::rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US ); + printf("%s\n", aString.getStr( ) ); +} + +/** get dll file URL. +*/ +inline ::rtl::OUString getDllURL( void ) +{ +#if ( defined WNT ) // lib in Unix and lib in Windows are not same in file name. + ::rtl::OUString libPath( RTL_CONSTASCII_USTRINGPARAM("Module_DLL.dll") ); +#else + ::rtl::OUString libPath( RTL_CONSTASCII_USTRINGPARAM("libModule_DLL.so") ); +#endif + + ::rtl::OUString dirPath, dllPath; + osl::Module::getUrlFromAddress( ( void* ) &getDllURL, dirPath ); + dirPath = dirPath.copy( 0, dirPath.lastIndexOf('/') + 1); + osl::FileBase::getAbsoluteFileURL( dirPath, libPath, dllPath ); + + return dllPath; +} + +inline sal_Bool isURL( const ::rtl::OUString pathname ) +{ + ::rtl::OUString aPreURL( RTL_CONSTASCII_USTRINGPARAM("file:///") ); + return ( ( pathname.indexOf( aPreURL ) == 0 ) ? sal_True : sal_False ); +} + +/** create a temp test directory using OUString name of full qualified URL or system path. +*/ +inline void createTestDirectory( const ::rtl::OUString dirname ) +{ + ::rtl::OUString aPathURL = dirname.copy( 0 ); + ::osl::FileBase::RC nError; + + if ( !isURL( dirname ) ) + ::osl::FileBase::getFileURLFromSystemPath( dirname, aPathURL ); //convert if not full qualified URL + nError = ::osl::Directory::create( aPathURL ); + CPPUNIT_ASSERT_MESSAGE( "In createTestDirectory Function: creation: ", ( ::osl::FileBase::E_None == nError ) || ( nError == ::osl::FileBase::E_EXIST ) ); +} + +/** delete a temp test directory using OUString name of full qualified URL or system path. +*/ +inline void deleteTestDirectory( const ::rtl::OUString dirname ) +{ + ::rtl::OUString aPathURL = dirname.copy( 0 ); + ::osl::FileBase::RC nError; + if ( !isURL( dirname ) ) + ::osl::FileBase::getFileURLFromSystemPath( dirname, aPathURL ); //convert if not full qualified URL + + ::osl::Directory testDir( aPathURL ); + if ( testDir.isOpen( ) == sal_True ) + { + testDir.close( ); //close if still open. + } + + nError = ::osl::Directory::remove( aPathURL ); + CPPUNIT_ASSERT_MESSAGE( "In deleteTestDirectory function: remove ", ( ::osl::FileBase::E_None == nError ) || ( nError == ::osl::FileBase::E_NOENT ) ); +} + +//check if the file exist +inline sal_Bool ifFileExist( const ::rtl::OUString & str ) +{ + ::rtl::OUString aUStr; + if ( isURL( str ) ) + ::osl::FileBase::getSystemPathFromFileURL( str, aUStr ); + else + return sal_False; + + ::osl::File strFile( aUStr ); + ::osl::FileBase::RC nError = strFile.open( osl_File_OpenFlag_Read ); + if ( ::File::E_NOENT == nError ) + return sal_False; + else{ + strFile.close( ); + return sal_True; + } +} + +/** detete a temp test file using OUString name. +*/ +inline void deleteTestFile( const ::rtl::OUString filename ) +{ + ::rtl::OUString aPathURL = filename.copy( 0 ); + ::osl::FileBase::RC nError; + + if ( !isURL( filename ) ) + ::osl::FileBase::getFileURLFromSystemPath( filename, aPathURL ); //convert if not full qualified URL + + nError = ::osl::File::setAttributes( aPathURL, Attribute_GrpWrite| Attribute_OwnWrite| Attribute_OthWrite ); // if readonly, make writtenable. + CPPUNIT_ASSERT_MESSAGE( "In deleteTestFile Function: set writtenable ", ( ::osl::FileBase::E_None == nError ) || ( ::osl::FileBase::E_NOENT == nError ) ); + + nError = ::osl::File::remove( aPathURL ); + CPPUNIT_ASSERT_MESSAGE( "In deleteTestFile Function: remove ", ( ::osl::FileBase::E_None == nError ) || ( nError == ::osl::FileBase::E_NOENT ) ); +} + + +//------------------------------------------------------------------------ +// test code start here +//------------------------------------------------------------------------ + +namespace osl_Module +{ + + /** class and member function that is available for module test : + */ + + class testClass + { + public: + static void myFunc() + { + printf("#Sun Microsystem\n"); + }; + }; + + + /** testing the methods: + Module(); + Module( const ::rtl::OUString& strModuleName, sal_Int32 nRtldMode = SAL_LOADMODULE_DEFAULT); + */ + class ctors : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void ctors_none( ) + { + ::osl::Module aMod; + bRes = aMod.is(); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test constructor without parameter.", + sal_False == bRes ); + } + + void ctors_name_mode( ) + { + OUString aFileURL; + bRes = osl::Module::getUrlFromAddress( ( void* ) &::osl_Module::testClass::myFunc, aFileURL ); + + if ( !( bRes ) ) + { + CPPUNIT_ASSERT_MESSAGE("Cannot locate current module.", sal_False ); + } + + ::osl::Module aMod( aFileURL ); + bRes = aMod.is( ); + aMod.unload( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test constructor with load action.", + sal_True == bRes ); + } + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_none ); + CPPUNIT_TEST( ctors_name_mode ); + CPPUNIT_TEST_SUITE_END( ); + }; // class ctors + + + /** testing the methods: + static sal_Bool getUrlFromAddress(void * addr, ::rtl::OUString & libraryUrl) + */ + class getUrlFromAddress : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void getUrlFromAddress_001( ) + { + OUString aFileURL; + bRes = osl::Module::getUrlFromAddress( ( void* ) &::osl_Module::testClass::myFunc, aFileURL ) ; + if ( !( bRes ) ) + { + CPPUNIT_ASSERT_MESSAGE("Cannot locate current module.", sal_False ); + } + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test get Module URL from address.", + sal_True == bRes && 0 < aFileURL.lastIndexOf('/') ); + } + + void getUrlFromAddress_002( ) + { +#if !defined( MACOSX ) + // TODO: Find out why this fails on Mac OS X + ::osl::Module aMod( getDllURL( ) ); + FuncPtr pFunc = ( FuncPtr ) aMod.getSymbol( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("firstfunc")) ); + + OUString aFileURL; + bRes = osl::Module::getUrlFromAddress( ( void* )pFunc, aFileURL ); + if ( !( bRes ) ) + { + CPPUNIT_ASSERT_MESSAGE("Cannot locate current module.", sal_False ); + } + aMod.unload( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: load an external library, get its function address and get its URL.", + sal_True == bRes && 0 < aFileURL.lastIndexOf('/') && aFileURL.equalsIgnoreAsciiCase( getDllURL( ) ) ); +#endif + } + + /* tester comments: another case is getFunctionSymbol_001*/ + + CPPUNIT_TEST_SUITE( getUrlFromAddress ); + CPPUNIT_TEST( getUrlFromAddress_001 ); + CPPUNIT_TEST( getUrlFromAddress_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class getUrlFromAddress + + + /** testing the method: + sal_Bool SAL_CALL load( const ::rtl::OUString& strModuleName, + sal_Int32 nRtldMode = SAL_LOADMODULE_DEFAULT) + */ + class load : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void load_001( ) + { + ::osl::Module aMod( getDllURL( ) ); + ::osl::Module aMod1; + + aMod1.load( getDllURL( ) ); + bRes = oslModule(aMod) == oslModule(aMod1); + aMod.unload( ); + aMod1.unload( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: load function should do the same thing as constructor with library name.", + sal_True == bRes ); + } + // load lib which is under a CJK directory + void load_002( ) + { +#if defined( UNX ) && !defined( MACOSX ) + // TODO: Find out why this fails on Mac OS X + //Can not get a CJK directory already exist, so here create one. Perhaps reason is encoding problem. + ::rtl::OUString aPidDirURL = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("file:///tmp/")) + ::rtl::OUString::valueOf( ( long )getpid( ) ); + ::rtl::OUString aMyDirURL = aPidDirURL + aKname; + createTestDirectory( aPidDirURL ); + createTestDirectory( aMyDirURL ); + + ::rtl::OUString aDLLURL = aMyDirURL + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/libModule_DLL.so")); + //check if the lib exist. + //FIXME: if assert condition is false, the case will return, so the directory will not be clean-up + CPPUNIT_ASSERT_MESSAGE( "#Source file is not exist. please manually clean-up directory and file under /tmp", ifFileExist( getDllURL( ) ) == sal_True ); + ::osl::FileBase::RC nError = ::osl::File::copy( getDllURL( ), aDLLURL ); + CPPUNIT_ASSERT_MESSAGE( "#copy failed. please manually clean-up directory and file under /tmp", nError == ::osl::FileBase::E_None ); + //ifFileExist returned false but the file exist + CPPUNIT_ASSERT_MESSAGE( "#This file is not exist, copy failed. please manually clean-up directory and file under /tmp", ifFileExist( aDLLURL ) == sal_True ); + + //test if can create a normal file + ::rtl::OUString aFileURL = aMyDirURL + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/test_file")); + ::osl::File testFile( aFileURL ); + nError = testFile.open( osl_File_OpenFlag_Create ); + CPPUNIT_ASSERT_MESSAGE( "#create failed. please manually clean-up directory and file under /tmp", nError == ::osl::FileBase::E_None ); + CPPUNIT_ASSERT_MESSAGE( "#This file is not exist, create failed. please manually clean-up directory and file under /tmp", ifFileExist( aFileURL ) == sal_True ); + + //load the copied dll + ::osl::Module aMod( aDLLURL ); + ::osl::Module aMod1; + + sal_Bool bOK = aMod1.load( aDLLURL ); + bRes = oslModule(aMod) == oslModule(aMod1); + aMod.unload( ); + aMod1.unload( ); + deleteTestFile( aFileURL ); + deleteTestFile( aDLLURL ); + deleteTestDirectory( aMyDirURL ); + deleteTestDirectory( aPidDirURL ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: load lib which is under a CJK directory.", + sal_True == bRes && bOK == sal_True ); +#endif + } + + CPPUNIT_TEST_SUITE( load ); + CPPUNIT_TEST( load_001 ); + CPPUNIT_TEST( load_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class load + + + /** testing the method: + void SAL_CALL unload() + */ + class unload : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void unload_001( ) + { + ::osl::Module aMod( getDllURL( ) ); + + aMod.unload( ); + bRes = oslModule(aMod) ==NULL; + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: unload function should do the same thing as destructor.", + sal_True == bRes ); + } + + CPPUNIT_TEST_SUITE( unload ); + CPPUNIT_TEST( unload_001 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class unload + + + /** testing the methods: + sal_Bool SAL_CALL is() const + */ + class is : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void is_001( ) + { + OUString aFileURL; + bRes = osl::Module::getUrlFromAddress( ( void* ) &::osl_Module::testClass::myFunc, aFileURL ); + if ( !( bRes ) ) + { + CPPUNIT_ASSERT_MESSAGE("Cannot locate current module - using executable instead", sal_False ); + } + + ::osl::Module aMod; + bRes = aMod.is( ); + aMod.load( aFileURL ); + bRes1 = aMod.is( ); + aMod.unload( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test if a module is a loaded module.", + sal_False == bRes && sal_True == bRes1); + } + CPPUNIT_TEST_SUITE( is ); + CPPUNIT_TEST( is_001 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class is + + + /** testing the methods: + void* SAL_CALL getSymbol( const ::rtl::OUString& strSymbolName) + */ + class getSymbol : public CppUnit::TestFixture + { + public: + sal_Bool bRes; + + void getSymbol_001( ) + { +#if !defined( MACOSX ) + // TODO: Find out why this fails on Mac OS X + ::osl::Module aMod( getDllURL( ) ); + FuncPtr pFunc = ( FuncPtr ) aMod.getSymbol( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("firstfunc")) ); + bRes = sal_False; + if ( pFunc ) + bRes = pFunc( bRes ); + aMod.unload(); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: load a dll and call one function in it.", + sal_True == bRes ); +#endif + } + + CPPUNIT_TEST_SUITE( getSymbol ); + CPPUNIT_TEST( getSymbol_001 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class getSymbol + + + /** testing the methods: + operator oslModule() const + */ + class optr_oslModule : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void optr_oslModule_001( ) + { +#if !defined( MACOSX ) + // TODO: Find out why this fails on Mac OS X + ::osl::Module aMod; + bRes = ( (oslModule)aMod == NULL ); + + aMod.load( getDllURL( ) ); + bRes1 = (oslModule)aMod != NULL; + + aMod.unload( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: the m_Module of a Module instance will be NULL when is not loaded, it will not be NULL after loaded.", + sal_True == bRes && sal_True == bRes1); +#endif + } + + void optr_oslModule_002( ) + { +#if !defined( MACOSX ) + // TODO: Find out why this fails on Mac OS X + ::osl::Module aMod( getDllURL( ) ); + ::rtl::OUString funcName( RTL_CONSTASCII_USTRINGPARAM("firstfunc") ); + + FuncPtr pFunc = ( FuncPtr ) osl_getSymbol( (oslModule)aMod, funcName.pData ); + bRes = sal_False; + if ( pFunc ) + bRes = pFunc( bRes ); + + aMod.unload(); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: use m_Module to call osl_getSymbol() function.", + sal_True == bRes ); +#endif + } + + CPPUNIT_TEST_SUITE( optr_oslModule ); + CPPUNIT_TEST( optr_oslModule_001 ); + CPPUNIT_TEST( optr_oslModule_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class optr_oslModule + + /** testing the methods: + oslGenericFunction SAL_CALL getFunctionSymbol( const ::rtl::OUString& ustrFunctionSymbolName ) + */ + class getFunctionSymbol : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void getFunctionSymbol_001( ) + { +#if !defined( MACOSX ) + // TODO: Find out why this fails on Mac OS X + ::osl::Module aMod( getDllURL( ) ); + oslGenericFunction oslFunc = aMod.getFunctionSymbol( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("firstfunc")) ); + ::rtl::OUString aLibraryURL; + bRes = ::osl::Module::getUrlFromAddress( oslFunc, aLibraryURL); + aMod.unload(); + CPPUNIT_ASSERT_MESSAGE( "#test comment#: load a dll and get its function addr and get its URL.", + sal_True == bRes && aLibraryURL.equalsIgnoreAsciiCase( getDllURL() ) ); +#endif + } + + CPPUNIT_TEST_SUITE( getFunctionSymbol ); + CPPUNIT_TEST( getFunctionSymbol_001 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class getFunctionSymbol + +// ----------------------------------------------------------------------------- +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Module::ctors); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Module::getUrlFromAddress); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Module::load); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Module::unload); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Module::is); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Module::getSymbol); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Module::optr_oslModule); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Module::getFunctionSymbol); +// ----------------------------------------------------------------------------- + +} // namespace osl_Module + +// ----------------------------------------------------------------------------- + +// this macro creates an empty function, which will called by the RegisterAllFunctions() +// to let the user the possibility to also register some functions by hand. +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/module/osl_Module_Const.h b/sal/qa/osl/module/osl_Module_Const.h new file mode 100644 index 000000000000..629d201f908e --- /dev/null +++ b/sal/qa/osl/module/osl_Module_Const.h @@ -0,0 +1,68 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _OSL_MODULE_CONST_H_ +#define _OSL_MODULE_CONST_H_ + + +#include <sal/types.h> +#include <rtl/ustring.hxx> +#include <osl/module.hxx> +#include <osl/file.hxx> + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> + +#if ( defined UNX ) || ( defined OS2 ) //Unix +# include <unistd.h> +#endif +#if ( defined WNT ) // Windows +# include <io.h> +#endif + +# define FILE_PREFIX "file:///" + +//Korea charactors +::rtl::OUString aKname( + RTL_CONSTASCII_STRINGPARAM( + "/\xEC\x95\x88\xEB\x85\x95\xED\x95\x98\xEC\x84\xB8\xEC\x9A\x94"), + RTL_TEXTENCODING_ISO_8859_1); + // zero-extend the individual byte-sized characters one-to-one to individual + // sal_Unicode-sized characters; not sure whether this is what was + // intended... + +//------------------------------------------------------------------------ +// function pointer type. +//------------------------------------------------------------------------ +typedef sal_Bool (* FuncPtr )( sal_Bool ); + + +#endif /* _OSL_MODULE_CONST_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/module/osl_Module_DLL.cxx b/sal/qa/osl/module/osl_Module_DLL.cxx new file mode 100644 index 000000000000..04c46143f809 --- /dev/null +++ b/sal/qa/osl/module/osl_Module_DLL.cxx @@ -0,0 +1,51 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +#include <osl_Module_Const.h> + +#include <stdio.h> +#include <sal/types.h> + +// This module contains no tests. It is loaded as a dynamic library by +// osl_Module. +// But we instatiate a test plugin to fake the build process. +CPPUNIT_PLUGIN_IMPLEMENT(); + +extern "C" sal_Bool SAL_CALL firstfunc( sal_Bool bRes ) +{ + return ( bRes = sal_True ); +} +extern "C" void SAL_CALL secondfunc() +{ + printf("second func called.\n"); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/mutex/osl_Mutex.cxx b/sal/qa/osl/mutex/osl_Mutex.cxx new file mode 100644 index 000000000000..80c2e69f2de7 --- /dev/null +++ b/sal/qa/osl/mutex/osl_Mutex.cxx @@ -0,0 +1,938 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +//------------------------------------------------------------------------ +// include files +//------------------------------------------------------------------------ +#include <sal/cppunit.h> + +#include <osl_Mutex_Const.h> + +using namespace osl; +using namespace rtl; + +//------------------------------------------------------------------------ +// helper functions +//------------------------------------------------------------------------ + +/** print a UNI_CODE String. +*/ +inline void printUString( const ::rtl::OUString & str ) +{ + rtl::OString aString; + + printf("#printUString_u# " ); + aString = ::rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US ); + printf("%s\n", aString.getStr( ) ); +} + +/** print Boolean value. +*/ +inline void printBool( sal_Bool bOk ) +{ + printf("#printBool# " ); + ( sal_True == bOk ) ? printf("YES!\n" ): printf("NO!\n" ); +} + +/** pause nSec seconds helper function. +*/ +namespace ThreadHelper +{ + void thread_sleep( sal_Int32 _nSec ) + { + /// print statement in thread process must use fflush() to force display. + // t_print("# wait %d seconds. ", _nSec ); + fflush(stdout); + +#ifdef WNT //Windows + Sleep( _nSec * 1000 ); +#endif +#if ( defined UNX ) || ( defined OS2 ) //Unix + sleep( _nSec ); +#endif + // printf("# done\n" ); + } + void thread_sleep_tenth_sec(sal_Int32 _nTenthSec) + { +#ifdef WNT //Windows + Sleep(_nTenthSec * 100 ); +#endif +#if ( defined UNX ) || ( defined OS2 ) //Unix + TimeValue nTV; + nTV.Seconds = static_cast<sal_uInt32>( _nTenthSec/10 ); + nTV.Nanosec = ( (_nTenthSec%10 ) * 100000000 ); + osl_waitThread(&nTV); +#endif + } +} + + +//------------------------------------------------------------------------ +// Beginning of the test cases for osl_Mutex class +//------------------------------------------------------------------------ + + +/** mutually exclusive data +*/ +struct resource { + sal_Int32 data1; + sal_Int32 data2; + Mutex lock; +}; + +/** IncreaseThread provide data. +*/ +class IncreaseThread : public Thread +{ +public: + IncreaseThread( struct resource *pData ): pResource( pData ) { } + + ~IncreaseThread( ) + { + CPPUNIT_ASSERT_MESSAGE( "#IncreaseThread does not shutdown properly.\n", sal_False == this -> isRunning( ) ); + } +protected: + struct resource *pResource; + + void SAL_CALL run( ) + { + pResource->lock.acquire( ); + for( sal_Int8 i = 0; i < 3; i++ ) + { + pResource->data1++; + yield( ); //yield() give CPU time to other thread, other thread if not block, they will change the data; + } + if ( pResource->data2 == 0 ) + pResource->data2 = ( pResource->data1 > 0 ? pResource->data1 : 0 - pResource->data1 ); + pResource->lock.release(); + } +}; + +/** DecreaseThread consume data. +*/ +class DecreaseThread : public Thread +{ +public: + DecreaseThread( struct resource *pData ): pResource( pData ) { } + + ~DecreaseThread( ) + { + CPPUNIT_ASSERT_MESSAGE( "#DecreaseThread does not shutdown properly.\n", sal_False == this -> isRunning( ) ); + } +protected: + struct resource *pResource; + + void SAL_CALL run( ) + { + pResource->lock.acquire( ); + for( sal_Int8 i = 0; i < 3; i++ ) + { + pResource->data1--; + yield( ); //yield() give CPU time to other thread, other thread if not block, they will change the data; + } + if ( pResource->data2 == 0 ) + pResource->data2 = ( pResource->data1 > 0 ? pResource->data1 : 0 - pResource->data1 ); + pResource->lock.release(); + } +}; + + +/** chain structure used in Threads as critical resource +*/ +struct chain { + sal_Int32 buffer[ BUFFER_SIZE ]; + Mutex lock; + sal_Int8 pos; +}; + +/** PutThread write to the chain structure in a mutex manner. +*/ +class PutThread : public Thread +{ +public: + //get the struct pointer to write data to buffer + PutThread( struct chain* pData ): pChain( pData ) { } + + ~PutThread( ) + { + CPPUNIT_ASSERT_MESSAGE( "#PutThread does not shutdown properly.\n", sal_False == this -> isRunning( ) ); + } +protected: + struct chain* pChain; + + void SAL_CALL run( ) + { + //block here if the mutex has been acquired + pChain->lock.acquire( ); + + //current position in buffer to write + sal_Int8 nPos = pChain->pos; + oslThreadIdentifier oId = getIdentifier( ); + //write data + sal_Int8 i; + for ( i = 0; i < 5; i++ ) + { + pChain->buffer[ nPos + i ] = oId; + yield( ); + } + //revise the position + pChain->pos = nPos + i; + + //finish writing, release the mutex + pChain->lock.release(); + } +}; + +/** thread for testing Mutex acquire. + */ +class HoldThread : public Thread +{ +public: + //get the Mutex pointer to operate + HoldThread( Mutex* pMutex ): pMyMutex( pMutex ) { } + + ~HoldThread( ) + { + CPPUNIT_ASSERT_MESSAGE( "#HoldThread does not shutdown properly.\n", sal_False == this -> isRunning( ) ); + } +protected: + Mutex* pMyMutex; + + void SAL_CALL run() + { + // block here if the mutex has been acquired + pMyMutex->acquire( ); + printf("# Mutex acquired. \n" ); + pMyMutex->release( ); + } +}; + +class WaitThread : public Thread +{ +public: + //get the Mutex pointer to operate + WaitThread( Mutex* pMutex ): pMyMutex( pMutex ) { } + + ~WaitThread( ) + { + CPPUNIT_ASSERT_MESSAGE( "#WaitThread does not shutdown properly.\n", sal_False == this -> isRunning( ) ); + } +protected: + Mutex* pMyMutex; + + void SAL_CALL run( ) + { + // block here if the mutex has been acquired + pMyMutex->acquire( ); + ThreadHelper::thread_sleep_tenth_sec( 2 ); + pMyMutex->release( ); + } +}; + +/** thread for testing getGlobalMutex. + */ +class GlobalMutexThread : public Thread +{ +public: + //get the Mutex pointer to operate + GlobalMutexThread( ){ } + + ~GlobalMutexThread( ) + { + CPPUNIT_ASSERT_MESSAGE( "#GlobalMutexThread does not shutdown properly.\n", sal_False == this -> isRunning( ) ); + } +protected: + void SAL_CALL run( ) + { + // block here if the mutex has been acquired + Mutex* pGlobalMutex; + pGlobalMutex = pGlobalMutex->getGlobalMutex( ); + pGlobalMutex->acquire( ); + printf("# Global Mutex acquired. \n" ); + pGlobalMutex->release( ); + } +}; + + +//-------------------------------------------------------------- +namespace osl_Mutex +{ + + /** Test of the osl::Mutex::constructor + */ + class ctor : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + struct chain m_Data; + struct resource m_Res; + + void setUp( ) + { + for ( sal_Int8 i=0; i < BUFFER_SIZE; i++ ) + m_Data.buffer[i] = 0; + m_Data.pos = 0; + + m_Res.data1 = 0; + m_Res.data2 = 0; + } + + void tearDown() + { + } + + /** Create two threads to write data to the same buffer, use Mutex to assure + during one thread write data five times, the other thread should not begin writing. + the two threads wrote two different datas: their thread ID, so we can check the datas + in buffer to know the order of the two threads writing + */ + void ctor_001() + { + PutThread myThread1( &m_Data ); + PutThread myThread2( &m_Data ); + + myThread1.create( ); + myThread2.create( ); + + //wait until the two threads terminate + myThread1.join( ); + myThread2.join( ); + + sal_Bool bRes = sal_False; + + // every 5 datas should the same + // LLA: this is not a good check, it's too fix + if (m_Data.buffer[0] == m_Data.buffer[1] && + m_Data.buffer[1] == m_Data.buffer[2] && + m_Data.buffer[2] == m_Data.buffer[3] && + m_Data.buffer[3] == m_Data.buffer[4] && + m_Data.buffer[5] == m_Data.buffer[6] && + m_Data.buffer[6] == m_Data.buffer[7] && + m_Data.buffer[7] == m_Data.buffer[8] && + m_Data.buffer[8] == m_Data.buffer[9]) + bRes = sal_True; + + /*for (sal_Int8 i=0; i<BUFFER_SIZE; i++) + printf("#data in buffer is %d\n", m_Data.buffer[i]); + */ + + CPPUNIT_ASSERT_MESSAGE("Mutex ctor", bRes == sal_True); + + } + + /** Create two threads to write data to operate on the same number , use Mutex to assure, + one thread increase data 3 times, the other thread decrease 3 times, store the operate + result when the first thread complete, if it is interrupt by the other thread, the stored + number will not be 3. + */ + void ctor_002() + { + IncreaseThread myThread1( &m_Res ); + DecreaseThread myThread2( &m_Res ); + + myThread1.create( ); + myThread2.create( ); + + //wait until the two threads terminate + myThread1.join( ); + myThread2.join( ); + + sal_Bool bRes = sal_False; + + // every 5 datas should the same + if ( ( m_Res.data1 == 0 ) && ( m_Res.data2 == 3 ) ) + bRes = sal_True; + + CPPUNIT_ASSERT_MESSAGE( "test Mutex ctor function: increase and decrease a number 3 times without interrupt.", bRes == sal_True ); + } + + CPPUNIT_TEST_SUITE( ctor ); + CPPUNIT_TEST( ctor_001 ); + CPPUNIT_TEST( ctor_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class ctor + + + /** Test of the osl::Mutex::acquire method + */ + class acquire : public CppUnit::TestFixture + { + public: + // acquire mutex in main thread, and then call acquire again in myThread, + // the child thread should block, wait 2 secs, it still block. + // Then release mutex in main thread, the child thread could return from acquire, + // and go to exec next statement, so could terminate quickly. + void acquire_001( ) + { + Mutex aMutex; + //acquire here + sal_Bool bRes = aMutex.acquire( ); + // pass the pointer of mutex to child thread + HoldThread myThread( &aMutex ); + myThread.create( ); + + ThreadHelper::thread_sleep_tenth_sec( 2 ); + // if acquire in myThread does not work, 2 secs is long enough, + // myThread should terminate now, and bRes1 should be sal_False + sal_Bool bRes1 = myThread.isRunning( ); + + aMutex.release( ); + ThreadHelper::thread_sleep_tenth_sec( 1 ); + // after release mutex, myThread stops blocking and will terminate immediately + sal_Bool bRes2 = myThread.isRunning( ); + myThread.join( ); + + CPPUNIT_ASSERT_MESSAGE( "Mutex acquire", + bRes == sal_True && bRes1 == sal_True && bRes2 == sal_False ); + } + + //in the same thread, acquire twice should success + void acquire_002() + { + Mutex aMutex; + //acquire here + sal_Bool bRes = aMutex.acquire(); + sal_Bool bRes1 = aMutex.acquire(); + + sal_Bool bRes2 = aMutex.tryToAcquire(); + + aMutex.release(); + + CPPUNIT_ASSERT_MESSAGE("Mutex acquire", + bRes == sal_True && bRes1 == sal_True && bRes2 == sal_True); + + } + + CPPUNIT_TEST_SUITE( acquire ); + CPPUNIT_TEST( acquire_001 ); + CPPUNIT_TEST( acquire_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class acquire + + + /** Test of the osl::Mutex::tryToAcquire method + */ + class tryToAcquire : public CppUnit::TestFixture + { + public: + // First let child thread acquire the mutex, and wait 2 secs, during the 2 secs, + // in main thread, tryToAcquire mutex should return False + // then after the child thread terminated, tryToAcquire should return True + void tryToAcquire_001() + { + Mutex aMutex; + WaitThread myThread(&aMutex); + myThread.create(); + + // ensure the child thread acquire the mutex + ThreadHelper::thread_sleep_tenth_sec(1); + + sal_Bool bRes1 = aMutex.tryToAcquire(); + + if (bRes1 == sal_True) + aMutex.release(); + // wait the child thread terminate + myThread.join(); + + sal_Bool bRes2 = aMutex.tryToAcquire(); + + if (bRes2 == sal_True) + aMutex.release(); + + CPPUNIT_ASSERT_MESSAGE("Try to acquire Mutex", + bRes1 == sal_False && bRes2 == sal_True); + } + + CPPUNIT_TEST_SUITE(tryToAcquire); + CPPUNIT_TEST(tryToAcquire_001); + CPPUNIT_TEST_SUITE_END(); + }; // class tryToAcquire + + /** Test of the osl::Mutex::release method + */ + class release : public CppUnit::TestFixture + { + public: + /** acquire/release are not used in pairs: after child thread acquired mutex, + the main thread release it, then any thread could acquire it. + */ + void release_001() + { + Mutex aMutex; + WaitThread myThread( &aMutex ); + myThread.create( ); + + // ensure the child thread acquire the mutex + ThreadHelper::thread_sleep_tenth_sec( 1 ); + + sal_Bool bRunning = myThread.isRunning( ); + sal_Bool bRes1 = aMutex.tryToAcquire( ); + // wait the child thread terminate + myThread.join( ); + + sal_Bool bRes2 = aMutex.tryToAcquire( ); + + if ( bRes2 == sal_True ) + aMutex.release( ); + + CPPUNIT_ASSERT_MESSAGE( "release Mutex: try to aquire before and after the mutex has been released", + bRes1 == sal_False && bRes2 == sal_True && bRunning == sal_True ); + + } + + // how about release twice? + void release_002() + { + } + + CPPUNIT_TEST_SUITE( release ); + CPPUNIT_TEST( release_001 ); + CPPUNIT_TEST( release_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class release + + + + /** Test of the osl::Mutex::getGlobalMutex method + */ + class getGlobalMutex : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + void getGlobalMutex_001() + { + Mutex* pGlobalMutex; + pGlobalMutex = pGlobalMutex->getGlobalMutex(); + pGlobalMutex->acquire(); + + GlobalMutexThread myThread; + myThread.create(); + + ThreadHelper::thread_sleep_tenth_sec(1); + sal_Bool bRes1 = myThread.isRunning(); + + pGlobalMutex->release(); + ThreadHelper::thread_sleep_tenth_sec(1); + // after release mutex, myThread stops blocking and will terminate immediately + sal_Bool bRes2 = myThread.isRunning(); + + CPPUNIT_ASSERT_MESSAGE("Global Mutex works", + bRes1 == sal_True && bRes2 == sal_False); + } + + void getGlobalMutex_002( ) + { + sal_Bool bRes; + + Mutex *pGlobalMutex; + pGlobalMutex = pGlobalMutex->getGlobalMutex( ); + pGlobalMutex->acquire( ); + { + Mutex *pGlobalMutex1; + pGlobalMutex1 = pGlobalMutex1->getGlobalMutex( ); + bRes = pGlobalMutex1->release( ); + } + + CPPUNIT_ASSERT_MESSAGE( "Global Mutex works: if the code between {} get the different mutex as the former one, it will return false when release.", + bRes == sal_True ); + } + + CPPUNIT_TEST_SUITE(getGlobalMutex); + CPPUNIT_TEST(getGlobalMutex_001); + CPPUNIT_TEST(getGlobalMutex_002); + CPPUNIT_TEST_SUITE_END(); + }; // class getGlobalMutex + +// ----------------------------------------------------------------------------- +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Mutex::ctor, "osl_Mutex"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Mutex::acquire, "osl_Mutex"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Mutex::tryToAcquire, "osl_Mutex"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Mutex::release, "osl_Mutex"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Mutex::getGlobalMutex, "osl_Mutex"); +} // namespace osl_Mutex + + +//------------------------------------------------------------------------ +// Beginning of the test cases for osl_Guard class +//------------------------------------------------------------------------ + +class GuardThread : public Thread +{ +public: + //get the Mutex pointer to operate + GuardThread( Mutex* pMutex ): pMyMutex( pMutex ) { } + + ~GuardThread( ) + { + CPPUNIT_ASSERT_MESSAGE( "#GuardThread does not shutdown properly.\n", sal_False == this -> isRunning( ) ); + } +protected: + Mutex* pMyMutex; + + void SAL_CALL run( ) + { + // block here if the mutex has been acquired + MutexGuard aGuard( pMyMutex ); + ThreadHelper::thread_sleep_tenth_sec( 2 ); + } +}; + + +namespace osl_Guard +{ + class ctor : public CppUnit::TestFixture + { + public: + // insert your test code here. + void ctor_001() + { + Mutex aMutex; + GuardThread myThread(&aMutex); + myThread.create(); + + ThreadHelper::thread_sleep_tenth_sec(1); + sal_Bool bRes = aMutex.tryToAcquire(); + // after 1 second, the mutex has been guarded, and the child thread should be running + sal_Bool bRes1 = myThread.isRunning(); + + myThread.join(); + sal_Bool bRes2 = aMutex.tryToAcquire(); + + CPPUNIT_ASSERT_MESSAGE("GuardThread constructor", + bRes == sal_False && bRes1 == sal_True && bRes2 == sal_True); + } + + void ctor_002( ) + { + Mutex aMutex; + + /// use reference constructor here + MutexGuard myGuard( aMutex ); + + /// the GuardThread will block here when it is initialised. + GuardThread myThread( &aMutex ); + myThread.create( ); + + /// is it still blocking? + ThreadHelper::thread_sleep_tenth_sec( 2 ); + sal_Bool bRes = myThread.isRunning( ); + + /// oh, release him. + aMutex.release( ); + myThread.join( ); + + CPPUNIT_ASSERT_MESSAGE("GuardThread constructor: reference initialization, aquire the mutex before running the thread, then check if it is blocking.", + bRes == sal_True); + } + + CPPUNIT_TEST_SUITE(ctor); + CPPUNIT_TEST(ctor_001); + CPPUNIT_TEST(ctor_002); + CPPUNIT_TEST_SUITE_END(); + }; // class ctor + +// ----------------------------------------------------------------------------- +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Guard::ctor, "osl_Guard"); +} // namespace osl_Guard + + +//------------------------------------------------------------------------ +// Beginning of the test cases for osl_ClearableGuard class +//------------------------------------------------------------------------ + +/** Thread for test ClearableGuard + */ +class ClearGuardThread : public Thread +{ +public: + //get the Mutex pointer to operate + ClearGuardThread( Mutex* pMutex ): pMyMutex( pMutex ) {} + + ~ClearGuardThread( ) + { + CPPUNIT_ASSERT_MESSAGE( "#ClearGuardThread does not shutdown properly.\n", sal_False == this -> isRunning( ) ); + } +protected: + Mutex* pMyMutex; + + void SAL_CALL run( ) + { + // acquire the mutex + // printf("# ClearGuardThread" ); + ClearableMutexGuard aGuard( pMyMutex ); + ThreadHelper::thread_sleep( 5 ); + + // release the mutex + aGuard.clear( ); + ThreadHelper::thread_sleep( 2 ); + } +}; + +// ----------------------------------------------------------------------------- +namespace osl_ClearableGuard +{ + + class ctor : public CppUnit::TestFixture + { + public: + void ctor_001() + { + Mutex aMutex; + + /// now, the aMutex has been guarded. + ClearableMutexGuard myMutexGuard( &aMutex ); + + /// it will return sal_False if the aMutex has not been Guarded. + sal_Bool bRes = aMutex.release( ); + + CPPUNIT_ASSERT_MESSAGE("ClearableMutexGuard constructor, test the aquire operation when initilized.", + bRes == sal_True ); + } + + void ctor_002( ) + { + Mutex aMutex; + + /// now, the aMutex has been guarded, this time, we use reference constructor. + ClearableMutexGuard myMutexGuard( aMutex ); + + /// it will return sal_False if the aMutex has not been Guarded. + sal_Bool bRes = aMutex.release( ); + + CPPUNIT_ASSERT_MESSAGE("ClearableMutexGuard constructor, test the aquire operation when initilized, we use reference constructor this time.", + bRes == sal_True ); + } + + CPPUNIT_TEST_SUITE(ctor); + CPPUNIT_TEST(ctor_001); + CPPUNIT_TEST(ctor_002); + CPPUNIT_TEST_SUITE_END(); + }; // class ctor + + class clear : public CppUnit::TestFixture + { + public: + void clear_001() + { + Mutex aMutex; + ClearGuardThread myThread(&aMutex); + myThread.create(); + + TimeValue aTimeVal_befor; + osl_getSystemTime( &aTimeVal_befor ); + // wait 1 second to assure the child thread has begun + ThreadHelper::thread_sleep(1); + + while (1) + { + if (aMutex.tryToAcquire() == sal_True) + { + break; + } + ThreadHelper::thread_sleep(1); + } + TimeValue aTimeVal_after; + osl_getSystemTime( &aTimeVal_after ); + sal_Int32 nSec = aTimeVal_after.Seconds - aTimeVal_befor.Seconds; + printf("nSec is %"SAL_PRIdINT32"\n", nSec); + + myThread.join(); + + CPPUNIT_ASSERT_MESSAGE("ClearableGuard method: clear", + nSec < 7 && nSec > 1); + } + + void clear_002( ) + { + Mutex aMutex; + + /// now, the aMutex has been guarded. + ClearableMutexGuard myMutexGuard( &aMutex ); + + /// launch the HoldThread, it will be blocked here. + HoldThread myThread( &aMutex ); + myThread.create( ); + + /// is it blocking? + ThreadHelper::thread_sleep_tenth_sec( 4 ); + sal_Bool bRes = myThread.isRunning( ); + + /// use clear to release. + myMutexGuard.clear( ); + myThread.join( ); + sal_Bool bRes1 = myThread.isRunning( ); + + CPPUNIT_ASSERT_MESSAGE( "ClearableGuard method: clear, control the HoldThread's running status!", + ( sal_True == bRes ) && ( sal_False == bRes1 ) ); + } + + CPPUNIT_TEST_SUITE( clear ); + CPPUNIT_TEST( clear_001 ); + CPPUNIT_TEST( clear_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class clear + +// ----------------------------------------------------------------------------- +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_ClearableGuard::ctor, "osl_ClearableGuard" ); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( osl_ClearableGuard::clear, "osl_ClearableGuard" ); +} // namespace osl_ClearableGuard + + +//------------------------------------------------------------------------ +// Beginning of the test cases for osl_ResettableGuard class +//------------------------------------------------------------------------ + +/** Thread for test ResettableGuard + */ +class ResetGuardThread : public Thread +{ +public: + //get the Mutex pointer to operate + ResetGuardThread( Mutex* pMutex ): pMyMutex( pMutex ) {} + + ~ResetGuardThread( ) + { + CPPUNIT_ASSERT_MESSAGE( "#ResetGuardThread does not shutdown properly.\n", sal_False == this -> isRunning( ) ); + } +protected: + Mutex* pMyMutex; + + void SAL_CALL run( ) + { + // acquire the mutex + printf("# ResettableGuard\n" ); + ResettableMutexGuard aGuard( pMyMutex ); + // release the mutex + aGuard.clear( ); + ThreadHelper::thread_sleep_tenth_sec( 2 ); + } +}; + +// ----------------------------------------------------------------------------- +namespace osl_ResettableGuard +{ + class ctor : public CppUnit::TestFixture + { + public: + void ctor_001() + { + Mutex aMutex; + + /// now, the aMutex has been guarded. + ResettableMutexGuard myMutexGuard( &aMutex ); + + /// it will return sal_False if the aMutex has not been Guarded. + sal_Bool bRes = aMutex.release( ); + + CPPUNIT_ASSERT_MESSAGE("ResettableMutexGuard constructor, test the aquire operation when initilized.", + bRes == sal_True ); + } + + void ctor_002( ) + { + Mutex aMutex; + + /// now, the aMutex has been guarded, this time, we use reference constructor. + ResettableMutexGuard myMutexGuard( aMutex ); + + /// it will return sal_False if the aMutex has not been Guarded. + sal_Bool bRes = aMutex.release( ); + + CPPUNIT_ASSERT_MESSAGE( "ResettableMutexGuard constructor, test the aquire operation when initilized, we use reference constructor this time.", + bRes == sal_True ); + } + + + CPPUNIT_TEST_SUITE(ctor); + CPPUNIT_TEST(ctor_001); + CPPUNIT_TEST(ctor_002); + CPPUNIT_TEST_SUITE_END(); + }; // class ctor + + class reset : public CppUnit::TestFixture + { + public: + void reset_001( ) + { + Mutex aMutex; + ResetGuardThread myThread( &aMutex ); + ResettableMutexGuard myMutexGuard( aMutex ); + myThread.create( ); + + /// is it running? and clear done? + sal_Bool bRes = myThread.isRunning( ); + myMutexGuard.clear( ); + ThreadHelper::thread_sleep_tenth_sec( 1 ); + + /// if reset is not success, the release will return sal_False + myMutexGuard.reset( ); + sal_Bool bRes1 = aMutex.release( ); + myThread.join( ); + + CPPUNIT_ASSERT_MESSAGE( "ResettableMutexGuard method: reset", + ( sal_True == bRes ) && ( sal_True == bRes1 ) ); + } + + void reset_002( ) + { + Mutex aMutex; + ResettableMutexGuard myMutexGuard( &aMutex ); + + /// shouldn't release after clear; + myMutexGuard.clear( ); + sal_Bool bRes = aMutex.release( ); + + /// can release after reset. + myMutexGuard.reset( ); + sal_Bool bRes1 = aMutex.release( ); + + CPPUNIT_ASSERT_MESSAGE( "ResettableMutexGuard method: reset, release after clear and reset, on Solaris, the mutex can be release without aquire, so it can not passed on (SOLARIS), but not the reason for reset_002", + ( sal_False == bRes ) && ( sal_True == bRes1 ) ); + } + + CPPUNIT_TEST_SUITE(reset); + CPPUNIT_TEST(reset_001); +#ifdef LINUX + CPPUNIT_TEST(reset_002); +#endif + CPPUNIT_TEST_SUITE_END(); + }; // class reset + +// ----------------------------------------------------------------------------- +CPPUNIT_TEST_SUITE_REGISTRATION(osl_ResettableGuard::ctor); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_ResettableGuard::reset); +} // namespace osl_ResettableGuard + +CPPUNIT_PLUGIN_IMPLEMENT(); + +// The following sets variables for GNU EMACS +// Local Variables: +// tab-width:4 +// End: + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/mutex/osl_Mutex_Const.h b/sal/qa/osl/mutex/osl_Mutex_Const.h new file mode 100644 index 000000000000..59c83c40eb87 --- /dev/null +++ b/sal/qa/osl/mutex/osl_Mutex_Const.h @@ -0,0 +1,53 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _OSL_MUTEX_CONST_H_ +#define _OSL_MUTEX_CONST_H_ + +#include <sal/types.h> +#include <rtl/ustring.hxx> + +#ifndef _OSL_THREAD_HXX +#include <osl/thread.hxx> +#endif + +#ifndef _OSL_MUTEX_HXX +#include <osl/mutex.hxx> +#endif +#include <osl/time.h> + +#ifdef UNX +#include <unistd.h> +#endif + +#define BUFFER_SIZE 16 + + +#endif /* _OSL_MUTEX_CONST_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/pipe/osl_Pipe.cxx b/sal/qa/osl/pipe/osl_Pipe.cxx new file mode 100644 index 000000000000..73544ba1dfe0 --- /dev/null +++ b/sal/qa/osl/pipe/osl_Pipe.cxx @@ -0,0 +1,1054 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +//------------------------------------------------------------------------ +// include files +//------------------------------------------------------------------------ + +#include <sal/cppunit.h> +#include "test/uniquepipename.hxx" +#include <sal/types.h> +#include <rtl/ustring.hxx> + +#include <osl/thread.hxx> + +#include <osl/mutex.hxx> + +#include <osl/pipe.hxx> +#include <osl/time.h> + +#ifdef UNX +#include <unistd.h> +#endif +#include <string.h> + +using namespace osl; + +using ::rtl::OUString; +using ::rtl::OUStringToOString; +using ::rtl::OString; + +//------------------------------------------------------------------------ +// helper functions +//------------------------------------------------------------------------ + +/** print Boolean value. + */ +inline void printBool( sal_Bool bOk ) +{ + printf("#printBool# " ); + ( sal_True == bOk ) ? printf("YES!\n" ): printf("NO!\n" ); +} + +/** print a UNI_CODE String. + */ +inline void printUString( const ::rtl::OUString & str ) +{ + rtl::OString aString; + + printf("#printUString_u# " ); + aString = ::rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US ); + printf("%s\n", aString.getStr( ) ); +} + +/** print last error of pipe system. + */ +inline void printPipeError( ::osl::Pipe aPipe ) +{ + oslPipeError nError = aPipe.getError( ); + printf("#printPipeError# " ); + switch ( nError ) { + case osl_Pipe_E_None: + printf("Success!\n" ); + break; + case osl_Pipe_E_NotFound: + printf("The returned error is: Not found!\n" ); + break; + case osl_Pipe_E_AlreadyExists: + printf("The returned error is: Already exist!\n" ); + break; + case osl_Pipe_E_NoProtocol: + printf("The returned error is: No protocol!\n" ); + break; + case osl_Pipe_E_NetworkReset: + printf("The returned error is: Network reset!\n" ); + break; + case osl_Pipe_E_ConnectionAbort: + printf("The returned error is: Connection aborted!\n" ); + break; + case osl_Pipe_E_ConnectionReset: + printf("The returned error is: Connection reset!\n" ); + break; + case osl_Pipe_E_NoBufferSpace: + printf("The returned error is: No buffer space!\n" ); + break; + case osl_Pipe_E_TimedOut: + printf("The returned error is: Timeout!\n" ); + break; + case osl_Pipe_E_ConnectionRefused: + printf("The returned error is: Connection refused!\n" ); + break; + case osl_Pipe_E_invalidError: + printf("The returned error is: Invalid error!\n" ); + break; + default: + printf("The returned error is: Number %d, Unknown Error\n", nError ); + break; + } +} + + + +//------------------------------------------------------------------------ +// pipe name and transfer contents +//------------------------------------------------------------------------ +const rtl::OUString aTestPipeName(RTL_CONSTASCII_USTRINGPARAM("testpipe2")); +const rtl::OUString aTestPipe1(RTL_CONSTASCII_USTRINGPARAM("testpipe1")); +const rtl::OUString aTestString(RTL_CONSTASCII_USTRINGPARAM("Sun Microsystems")); + +const OString m_pTestString1("Sun Microsystems"); +const OString m_pTestString2("test pipe PASS/OK"); + +//------------------------------------------------------------------------ +// test code start here +//------------------------------------------------------------------------ + +namespace osl_Pipe +{ + +//------------------------------------------------------------------------ +// most return value -1 denote a fail of operation. +//------------------------------------------------------------------------ +#define OSL_PIPE_FAIL -1 + + /** testing the methods: + inline Pipe(); + inline Pipe(const ::rtl::OUString& strName, oslPipeOptions Options); + inline Pipe(const ::rtl::OUString& strName, oslPipeOptions Options,const Security & rSecurity); + inline Pipe(const Pipe& pipe); + inline Pipe(oslPipe pipe, __sal_NoAcquire noacquire ); + inline Pipe(oslPipe Pipe); + */ + class ctors : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void setUp( ) + { + } + + void tearDown( ) + { + } + + void ctors_none( ) + { + ::osl::Pipe aPipe; + bRes = aPipe.is( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test constructor with no parameter, yet no case to test.", + sal_False == bRes ); + } + + void ctors_name_option( ) + { + /// create a named pipe. + ::osl::Pipe aPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + ::osl::Pipe aAssignPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_OPEN ); + + bRes = aPipe.is( ) && aAssignPipe.is( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test constructor with name and option.", + sal_True == bRes ); + } + + void ctors_name_option_security( ) + { + /// create a security pipe. + const ::osl::Security rSecurity; + ::osl::Pipe aSecurityPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE, rSecurity ); + + bRes = aSecurityPipe.is( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test constructor with name, option and security, the test of security is not implemented yet.", + sal_True == bRes ); + } + + void ctors_copy( ) + { + /// create a pipe. + ::osl::Pipe aPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + /// create a pipe using copy constructor. + ::osl::Pipe aCopyPipe( aPipe ); + + bRes = aCopyPipe.is( ) && aCopyPipe == aPipe; + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test copy constructor.", + sal_True == bRes ); + } + + /** tester comment: + + When test the following two constructors, don't know how to test the + acquire and no acquire action. possible plans: + 1.release one handle and check the other( did not success since the + other still exist and valid. ) + 2. release one handle twice to see getLastError( )(the getLastError + always returns invalidError(LINUX)). + */ + + void ctors_no_acquire( ) + { + /// create a pipe. + ::osl::Pipe aPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + /// constructs a pipe reference without acquiring the handle. + ::osl::Pipe aNoAcquirePipe( aPipe.getHandle( ), SAL_NO_ACQUIRE ); + + bRes = aNoAcquirePipe.is( ); + ///aPipe.clear( ); + ///bRes1 = aNoAcquirePipe.is( ); + + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test constructor with no aquire of handle, only validation test, do not know how to test no acquire.", + sal_True == bRes ); + } + + void ctors_acquire( ) + { + /// create a base pipe. + ::osl::Pipe aPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + /// constructs two pipes without acquiring the handle on the base pipe. + ::osl::Pipe aAcquirePipe( aPipe.getHandle( ) ); + ::osl::Pipe aAcquirePipe1( NULL ); + + bRes = aAcquirePipe.is( ); + bRes1 = aAcquirePipe1.is( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test constructor with no aquire of handle.only validation test, do not know how to test no acquire.", + sal_True == bRes && sal_False == bRes1 ); + } + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_none ); + CPPUNIT_TEST( ctors_name_option ); + CPPUNIT_TEST( ctors_name_option_security ); + CPPUNIT_TEST( ctors_copy ); + CPPUNIT_TEST( ctors_no_acquire ); + CPPUNIT_TEST( ctors_acquire ); + CPPUNIT_TEST_SUITE_END( ); + }; // class ctors + + + /** testing the method: + inline sal_Bool SAL_CALL is() const; + */ + class is : public CppUnit::TestFixture + { + public: + void is_001( ) + { + ::osl::Pipe aPipe; + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test is(), check if the pipe is a valid one.", sal_False == aPipe.is( ) ); + } + + void is_002( ) + { + ::osl::Pipe aPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test is(), a normal pipe creation.", sal_True == aPipe.is( ) ); + } + + void is_003( ) + { + ::osl::Pipe aPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + aPipe.clear( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test is(), an invalid case.", sal_False == aPipe.is( ) ); + } + + void is_004( ) + { + ::osl::Pipe aPipe( NULL ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test is(), an invalid constructor.", sal_False == aPipe.is( ) ); + } + + CPPUNIT_TEST_SUITE( is ); + CPPUNIT_TEST( is_001 ); + CPPUNIT_TEST( is_002 ); + CPPUNIT_TEST( is_003 ); + CPPUNIT_TEST( is_004 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class is + + + /** testing the methods: + inline sal_Bool create( const ::rtl::OUString & strName, + oslPipeOptions Options, const Security &rSec ); + nline sal_Bool create( const ::rtl::OUString & strName, + oslPipeOptions Options = osl_Pipe_OPEN ); + */ + class create : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + /** tester comment: + + security create only be tested creation, security section is + untested yet. + */ + + void create_named_security_001( ) + { + const Security rSec; + ::osl::Pipe aPipe; + bRes = aPipe.create( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE, rSec ); + bRes1 = aPipe.create( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE, rSec ); + aPipe.clear( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test creation.", + sal_True == bRes && sal_False == bRes1); + } + + void create_named_security_002( ) + { + const Security rSec; + ::osl::Pipe aPipe, aPipe1; + bRes = aPipe.create( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE, rSec ); + bRes1 = aPipe1.create( test::uniquePipeName(aTestPipeName), osl_Pipe_OPEN, rSec ); + aPipe.clear( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test creation and open.", + sal_True == bRes && sal_True == bRes1); + } + + void create_named_001( ) + { + ::osl::Pipe aPipe; + bRes = aPipe.create( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + bRes1 = aPipe.create( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + aPipe.clear( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test creation.", + sal_True == bRes && sal_False == bRes1); + } + + void create_named_002( ) + { + ::osl::Pipe aPipe, aPipe1; + bRes = aPipe.create( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + bRes1 = aPipe1.create( test::uniquePipeName(aTestPipeName), osl_Pipe_OPEN ); + aPipe.clear( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test creation and open.", + sal_True == bRes && sal_True == bRes1); + } + + void create_named_003( ) + { + ::osl::Pipe aPipe; + bRes = aPipe.create( test::uniquePipeName(aTestPipeName) ); + aPipe.clear( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test default option is open.", + sal_False == bRes ); + } + + CPPUNIT_TEST_SUITE( create ); + CPPUNIT_TEST( create_named_security_001 ); + CPPUNIT_TEST( create_named_security_002 ); + CPPUNIT_TEST( create_named_001 ); + CPPUNIT_TEST( create_named_002 ); + CPPUNIT_TEST( create_named_003 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class create + + + /** testing the method: + inline void SAL_CALL clear(); + */ + class clear : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void clear_001( ) + { + ::osl::Pipe aPipe; + aPipe.create( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + aPipe.clear( ); + bRes = aPipe.is( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test clear.", + sal_False == bRes ); + } + + CPPUNIT_TEST_SUITE( clear ); + CPPUNIT_TEST( clear_001 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class clear + + + /** testing the methods: + inline Pipe& SAL_CALL operator= (const Pipe& pipe); + inline Pipe& SAL_CALL operator= (const oslPipe pipe ); + */ + class assign : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void assign_ref( ) + { + ::osl::Pipe aPipe, aPipe1; + aPipe.create( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + aPipe1 = aPipe; + bRes = aPipe1.is( ); + bRes1 = aPipe == aPipe1; + aPipe.close( ); + aPipe1.close( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test assign with reference.", + sal_True == bRes && sal_True == bRes1 ); + } + + void assign_handle( ) + { + ::osl::Pipe aPipe, aPipe1; + aPipe.create( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + aPipe1 = aPipe.getHandle( ); + bRes = aPipe1.is( ); + bRes1 = aPipe == aPipe1; + aPipe.close( ); + aPipe1.close( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test assign with handle.", + sal_True == bRes && sal_True == bRes1 ); + } + + CPPUNIT_TEST_SUITE( assign ); + CPPUNIT_TEST( assign_ref ); + CPPUNIT_TEST( assign_handle ); + CPPUNIT_TEST_SUITE_END( ); + }; // class assign + + + /** testing the method: + inline sal_Bool SAL_CALL isValid() const; + isValid( ) has not been implemented under the following platforms, please refer to osl/pipe.hxx + */ + /*class isValid : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void isValid_001( ) + { + CPPUNIT_ASSERT_MESSAGE( "#test comment#: isValid() has not been implemented on all platforms.", + sal_False ); + } + + CPPUNIT_TEST_SUITE( isValid ); + CPPUNIT_TEST( isValid_001 ); + CPPUNIT_TEST_SUITE_END( ); + };*/ // class isValid + + + /** testing the method: + inline sal_Bool SAL_CALL operator==( const Pipe& rPipe ) const; + */ + class isEqual : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void isEqual_001( ) + { + ::osl::Pipe aPipe; + aPipe.create( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + bRes = aPipe == aPipe; + aPipe.close( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test isEqual(), compare its self.", + sal_True == bRes ); + } + + void isEqual_002( ) + { + ::osl::Pipe aPipe, aPipe1, aPipe2; + aPipe.create( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + + aPipe1 = aPipe; + aPipe2.create( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + + bRes = aPipe == aPipe1; + bRes1 = aPipe == aPipe2; + aPipe.close( ); + aPipe1.close( ); + aPipe2.close( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test isEqual(),create one copy instance, and compare.", + sal_True == bRes && sal_False == bRes1 ); + } + + CPPUNIT_TEST_SUITE( isEqual ); + CPPUNIT_TEST( isEqual_001 ); + CPPUNIT_TEST( isEqual_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class isEqual + + + /** testing the method: + inline void SAL_CALL close(); + */ + class close : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void close_001( ) + { + ::osl::Pipe aPipe( test::uniquePipeName(aTestPipe1), osl_Pipe_CREATE ); + aPipe.close( ); + bRes = aPipe.is( ); + + aPipe.clear( ); + bRes1 = aPipe.is( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: difference between close and clear.", + sal_True == bRes && sal_False == bRes1); + } + + void close_002( ) + { + ::osl::StreamPipe aPipe( test::uniquePipeName(aTestPipe1), osl_Pipe_CREATE ); + aPipe.close( ); + int nRet = aPipe.send( m_pTestString1.getStr(), 3 ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: use after close.", + OSL_PIPE_FAIL == nRet ); + } + + CPPUNIT_TEST_SUITE( close ); + CPPUNIT_TEST( close_001 ); + CPPUNIT_TEST( close_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class close + + + /** testing the method: + inline oslPipeError SAL_CALL accept(StreamPipe& Connection); + please refer to StreamPipe::recv + */ + /* class accept : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void accept_001( ) + { + + // CPPUNIT_ASSERT_MESSAGE( "#test comment#: accept, untested.", 1 == 1 ); + //CPPUNIT_ASSERT_STUB(); + } + + CPPUNIT_TEST_SUITE( accept ); + CPPUNIT_TEST( accept_001 ); + CPPUNIT_TEST_SUITE_END( ); + };*/ // class accept + + + /** testing the method: + inline oslPipeError SAL_CALL getError() const; + */ + class getError : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + /* + PipeError[]= { + { 0, osl_Pipe_E_None }, // no error + { EPROTOTYPE, osl_Pipe_E_NoProtocol }, // Protocol wrong type for socket + { ENOPROTOOPT, osl_Pipe_E_NoProtocol }, // Protocol not available + { EPROTONOSUPPORT, osl_Pipe_E_NoProtocol }, // Protocol not supported + { ESOCKTNOSUPPORT, osl_Pipe_E_NoProtocol }, // Socket type not supported + { EPFNOSUPPORT, osl_Pipe_E_NoProtocol }, // Protocol family not supported + { EAFNOSUPPORT, osl_Pipe_E_NoProtocol }, // Address family not supported by + // protocol family + { ENETRESET, osl_Pipe_E_NetworkReset }, // Network dropped connection because + // of reset + { ECONNABORTED, osl_Pipe_E_ConnectionAbort }, // Software caused connection abort + { ECONNRESET, osl_Pipe_E_ConnectionReset }, // Connection reset by peer + { ENOBUFS, osl_Pipe_E_NoBufferSpace }, // No buffer space available + { ETIMEDOUT, osl_Pipe_E_TimedOut }, // Connection timed out + { ECONNREFUSED, osl_Pipe_E_ConnectionRefused }, // Connection refused + { -1, osl_Pipe_E_invalidError } + }; + did not define osl_Pipe_E_NotFound, osl_Pipe_E_AlreadyExists + */ + + void getError_001( ) + { + ::osl::Pipe aPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_OPEN ); + oslPipeError nError = aPipe.getError( ); + printPipeError( aPipe ); + aPipe.clear( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: open a non-exist pipe.", + nError != osl_Pipe_E_None ); + } + + void getError_002( ) + { + ::osl::Pipe aPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + ::osl::Pipe aPipe1( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + oslPipeError nError = aPipe.getError( ); + printPipeError( aPipe ); + aPipe.clear( ); + aPipe1.clear( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: create an already exist pipe.", + nError != osl_Pipe_E_None ); + } + + CPPUNIT_TEST_SUITE( getError ); + CPPUNIT_TEST( getError_001 ); + CPPUNIT_TEST( getError_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class getError + + + /** testing the method: + inline oslPipe SAL_CALL getHandle() const; + */ + class getHandle : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void getHandle_001( ) + { + ::osl::Pipe aPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_OPEN ); + bRes = aPipe == aPipe.getHandle( ); + aPipe.clear( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: one pipe should equal to its handle.", + sal_True == bRes ); + } + + void getHandle_002( ) + { + ::osl::Pipe aPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + ::osl::Pipe aPipe1( aPipe.getHandle( ) ); + bRes = aPipe == aPipe1; + aPipe.clear( ); + aPipe1.clear( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: one pipe derived from another pipe's handle.", + sal_True == bRes ); + } + + CPPUNIT_TEST_SUITE( getHandle ); + CPPUNIT_TEST( getHandle_001 ); + CPPUNIT_TEST( getHandle_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class getHandle + + +// ----------------------------------------------------------------------------- + CPPUNIT_TEST_SUITE_REGISTRATION(osl_Pipe::ctors); + CPPUNIT_TEST_SUITE_REGISTRATION(osl_Pipe::is); + CPPUNIT_TEST_SUITE_REGISTRATION(osl_Pipe::create); + CPPUNIT_TEST_SUITE_REGISTRATION(osl_Pipe::clear); + CPPUNIT_TEST_SUITE_REGISTRATION(osl_Pipe::assign); +//CPPUNIT_TEST_SUITE_REGISTRATION(osl_Pipe::isValid); + CPPUNIT_TEST_SUITE_REGISTRATION(osl_Pipe::isEqual); + CPPUNIT_TEST_SUITE_REGISTRATION(osl_Pipe::close); + //CPPUNIT_TEST_SUITE_REGISTRATION(osl_Pipe::accept); + CPPUNIT_TEST_SUITE_REGISTRATION(osl_Pipe::getError); + CPPUNIT_TEST_SUITE_REGISTRATION(osl_Pipe::getHandle); +// ----------------------------------------------------------------------------- + +} // namespace osl_Pipe + + +namespace osl_StreamPipe +{ + + /** testing the methods: + inline StreamPipe(); + inline StreamPipe(oslPipe Pipe);; + inline StreamPipe(const StreamPipe& Pipe); + inline StreamPipe(const ::rtl::OUString& strName, oslPipeOptions Options = osl_Pipe_OPEN); + inline StreamPipe(const ::rtl::OUString& strName, oslPipeOptions Options, const Security &rSec ); + inline StreamPipe( oslPipe pipe, __sal_NoAcquire noacquire ); + */ + class ctors : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void ctors_none( ) + { + // create a pipe. + ::osl::StreamPipe aStreamPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + // create an unattached pipe. + ::osl::StreamPipe aStreamPipe1; + bRes = aStreamPipe1.is( ); + + // assign it and check. + aStreamPipe1 = aStreamPipe; + bRes1 = aStreamPipe1.is( ); + aStreamPipe.clear( ); + aStreamPipe1.clear( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test constructor with no parameter, before and after assign.", + sal_False == bRes && sal_True == bRes1 ); + } + + void ctors_handle( ) + { + // create a pipe. + ::osl::StreamPipe aStreamPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + // create a pipe with last handle. + ::osl::StreamPipe aStreamPipe1( aStreamPipe.getHandle( ) ); + bRes = aStreamPipe1.is( ) && aStreamPipe == aStreamPipe1; + aStreamPipe.clear( ); + aStreamPipe1.clear( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test constructor with other's handle.", + sal_True == bRes ); + } + + void ctors_copy( ) + { + // create a pipe. + ::osl::StreamPipe aStreamPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + // create an unattached pipe. + ::osl::StreamPipe aStreamPipe1( aStreamPipe ); + bRes = aStreamPipe1.is( ) && aStreamPipe == aStreamPipe1; + aStreamPipe.clear( ); + aStreamPipe1.clear( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test copy constructor.", + sal_True == bRes ); + } + + void ctors_name_option( ) + { + // create a pipe. + ::osl::StreamPipe aStreamPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + // create an unattached pipe. + ::osl::StreamPipe aStreamPipe1( test::uniquePipeName(aTestPipeName), osl_Pipe_OPEN ); + bRes = aStreamPipe1.is( ) && aStreamPipe.is( ); + aStreamPipe.clear( ); + aStreamPipe1.clear( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test constructor with name and option.", + sal_True == bRes ); + } + + void ctors_name_option_security( ) + { + /// create a security pipe. + const ::osl::Security rSecurity; + ::osl::StreamPipe aSecurityPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE, rSecurity ); + + bRes = aSecurityPipe.is( ); + aSecurityPipe.clear( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test constructor with name, option and security, the test of security is not implemented yet.", + sal_True == bRes ); + } + + /** tester comment: + + When test the following constructor, don't know how to test the + acquire and no acquire action. possible plans: + 1.release one handle and check the other( did not success since the + other still exist and valid. ) + 2. release one handle twice to see getLastError( )(the getLastError + always returns invalidError(LINUX)). + */ + + void ctors_no_acquire( ) + { + // create a pipe. + ::osl::StreamPipe aPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + // constructs a pipe reference without acquiring the handle. + ::osl::StreamPipe aNoAcquirePipe( aPipe.getHandle( ), SAL_NO_ACQUIRE ); + + bRes = aNoAcquirePipe.is( ); + aPipe.clear( ); + // bRes1 = aNoAcquirePipe.is( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test constructor with no aquire of handle, only validation test, do not know how to test no acquire.", + sal_True == bRes ); + } + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_none ); + CPPUNIT_TEST( ctors_handle ); + CPPUNIT_TEST( ctors_copy ); + CPPUNIT_TEST( ctors_name_option ); + CPPUNIT_TEST( ctors_name_option_security ); + CPPUNIT_TEST( ctors_no_acquire ); + CPPUNIT_TEST_SUITE_END( ); + }; // class ctors + + + /** testing the methods: + inline StreamPipe & SAL_CALL operator=(oslPipe Pipe); + inline StreamPipe& SAL_CALL operator=(const Pipe& pipe); + mindy: not implementated in osl/pipe.hxx, so remove the cases + */ + /* + class assign : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void assign_ref( ) + { + ::osl::StreamPipe aPipe, aPipe1; + aPipe.create( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + aPipe1 = aPipe; + bRes = aPipe1.is( ); + bRes1 = aPipe == aPipe1; + aPipe.close( ); + aPipe1.close( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test assign with reference.", + sal_True == bRes && sal_True == bRes1 ); + } + + void assign_handle( ) + { + ::osl::StreamPipe * pPipe = new ::osl::StreamPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + ::osl::StreamPipe * pAssignPipe = new ::osl::StreamPipe; + *pAssignPipe = pPipe->getHandle( ); + + bRes = pAssignPipe->is( ); + bRes1 = ( *pPipe == *pAssignPipe ); + pPipe->close( ); + + delete pAssignPipe; + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: test assign with handle., seems not implemented under (LINUX)(W32)", + sal_True == bRes && sal_True == bRes1 ); + } + + CPPUNIT_TEST_SUITE( assign ); + CPPUNIT_TEST( assign_ref ); + CPPUNIT_TEST( assign_handle ); + CPPUNIT_TEST_SUITE_END( ); + };*/ // class assign + + + /** wait _nSec seconds. + */ + void thread_sleep( sal_Int32 _nSec ) + { + /// print statement in thread process must use fflush() to force display. + // printf("wait %d seconds. ", _nSec ); + fflush(stdout); + +#ifdef WNT //Windows + Sleep( _nSec * 1000 ); +#endif +#if ( defined UNX ) || ( defined OS2 ) //Unix + sleep( _nSec ); +#endif + // printf("done\n" ); + } + // test read/write & send/recv data to pipe + // ----------------------------------------------------------------------------- + + class Pipe_DataSink_Thread : public Thread + { + public: + sal_Char buf[256]; + Pipe_DataSink_Thread( ) { } + + ~Pipe_DataSink_Thread( ) + { + } + protected: + void SAL_CALL run( ) + { + sal_Int32 nChars = 0; + + printf("open pipe\n"); + ::osl::StreamPipe aSenderPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_OPEN ); // test::uniquePipeName(aTestPipeName) is a string = "TestPipe" + if ( aSenderPipe.is() == sal_False ) + { + printf("pipe open failed! \n"); + } + else + { + printf("read\n"); + nChars = aSenderPipe.read( buf, m_pTestString1.getLength() + 1 ); + if ( nChars < 0 ) + { + printf("read failed! \n"); + return; + } + printf("buffer is %s \n", buf); + printf("send\n"); + nChars = aSenderPipe.send( m_pTestString2.getStr(), m_pTestString2.getLength() + 1 ); + if ( nChars < 0 ) + { + printf("client send failed! \n"); + return; + } + } + } + + }; + + // ----------------------------------------------------------------------------- + + class Pipe_DataSource_Thread : public Thread + { + public: + sal_Char buf[256]; + //::osl::StreamPipe aListenPipe; //( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + ::osl::Pipe aListenPipe; + ::osl::StreamPipe aConnectionPipe; + Pipe_DataSource_Thread( ) + { + printf("create pipe\n"); + aListenPipe.create( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + } + ~Pipe_DataSource_Thread( ) + { + aListenPipe.close(); + } + protected: + void SAL_CALL run( ) + { + //create pipe. + sal_Int32 nChars; + //::osl::StreamPipe aListenPipe( test::uniquePipeName(aTestPipeName), osl_Pipe_CREATE ); + printf("listen\n"); + if ( aListenPipe.is() == sal_False ) + { + printf("pipe create failed! \n"); + } + else + { + //::osl::StreamPipe aConnectionPipe; + + //start server and wait for connection. + printf("accept\n"); + if ( osl_Pipe_E_None != aListenPipe.accept( aConnectionPipe ) ) + { + printf("pipe accept failed!"); + return; + } + printf("write\n"); + // write to pipe + nChars = aConnectionPipe.write( m_pTestString1.getStr(), m_pTestString1.getLength() + 1 ); + if ( nChars < 0) + { + printf("server write failed! \n"); + return; + } + printf("recv\n"); + nChars = aConnectionPipe.recv( buf, 256 ); + + if ( nChars < 0) + { + printf("server receive failed! \n"); + return; + } + //thread_sleep( 2 ); + printf("received message is: %s\n", buf ); + //aConnectionPipe.close(); + } + } + }; + + /** testing the method: read/write/send/recv and Pipe::accept + */ + class recv : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void recv_001( ) + { + //launch threads. + Pipe_DataSource_Thread myDataSourceThread; + Pipe_DataSink_Thread myDataSinkThread; + myDataSourceThread.create( ); + thread_sleep( 1 ); + myDataSinkThread.create( ); + + //wait until the thread terminate + myDataSinkThread.join( ); + myDataSourceThread.join( ); + + int nCompare1 = strcmp( myDataSinkThread.buf, m_pTestString1.getStr() ); + int nCompare2 = strcmp( myDataSourceThread.buf, m_pTestString2.getStr() ); + CPPUNIT_ASSERT_MESSAGE( "test send/recv/write/read.", nCompare1 == 0 && nCompare2 == 0 ); + } + //close pipe when accept + void recv_002() + { + thread_sleep( 1 ); + + Pipe_DataSource_Thread myDataSourceThread; + Pipe_DataSink_Thread myDataSinkThread; + myDataSourceThread.create( ); + thread_sleep( 1 ); + myDataSourceThread.aListenPipe.close(); + myDataSourceThread.join( ); + //no condition judgement here, if the case could finish excuting within 1 or 2 seconds, it passes. + } + + CPPUNIT_TEST_SUITE( recv ); + CPPUNIT_TEST( recv_001 ); + CPPUNIT_TEST( recv_002 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class recv + +// ----------------------------------------------------------------------------- + CPPUNIT_TEST_SUITE_REGISTRATION(osl_StreamPipe::ctors); +//CPPUNIT_TEST_SUITE_REGISTRATION(osl_StreamPipe::assign); + CPPUNIT_TEST_SUITE_REGISTRATION(osl_StreamPipe::recv); +// ----------------------------------------------------------------------------- + +} // namespace osl_StreamPipe + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/process/batch.bat b/sal/qa/osl/process/batch.bat new file mode 100755 index 000000000000..7a47559e9b6e --- /dev/null +++ b/sal/qa/osl/process/batch.bat @@ -0,0 +1,2 @@ +@echo off +echo "Hello world"
\ No newline at end of file diff --git a/sal/qa/osl/process/batch.sh b/sal/qa/osl/process/batch.sh new file mode 100755 index 000000000000..fd3828c6ae42 --- /dev/null +++ b/sal/qa/osl/process/batch.sh @@ -0,0 +1,2 @@ +#!/bin/sh +echo "Hello world"
\ No newline at end of file diff --git a/sal/qa/osl/process/makefile.mk b/sal/qa/osl/process/makefile.mk new file mode 100644 index 000000000000..8e050cfbb46e --- /dev/null +++ b/sal/qa/osl/process/makefile.mk @@ -0,0 +1,98 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# <http://www.openoffice.org/license.html> +# for a copy of the LGPLv3 License. +# +#************************************************************************* +PRJ=..$/..$/.. + +PRJNAME=sal +TARGET=qa_osl_process + +ENABLE_EXCEPTIONS=TRUE + +# --- Settings ----------------------------------------------------- + +.INCLUDE : settings.mk + +CFLAGS+= $(LFS_CFLAGS) +CXXFLAGS+= $(LFS_CFLAGS) + +# BEGIN ---------------------------------------------------------------- +# auto generated Target:testjob by codegen.pl + +.IF "$(GUI)" == "WNT" + CFLAGS+=/Ob1 +.ENDIF + +SHL1OBJS=$(SLO)$/osl_Thread.obj +SHL1TARGET=osl_Thread +SHL1STDLIBS= $(SALLIB) $(CPPUNITLIB) +SHL1IMPLIB=i$(SHL1TARGET) +DEF1NAME=$(SHL1TARGET) +SHL1VERSIONMAP = $(PRJ)$/qa$/export.map + +# END ------------------------------------------------------------------ + +SHL2OBJS=$(SLO)$/osl_process.obj +SHL2TARGET=osl_process +SHL2STDLIBS= $(SALLIB) $(CPPUNITLIB) +SHL2IMPLIB=i$(SHL2TARGET) +DEF2NAME=$(SHL2TARGET) +SHL2VERSIONMAP = $(PRJ)$/qa$/export.map + +# END ------------------------------------------------------------------ + +OBJ3FILES=$(OBJ)$/osl_process_child.obj +APP3TARGET=osl_process_child +APP3OBJS=$(OBJ3FILES) +APP3STDLIBS=$(SALLIB) + +SHL2DEPN=$(APP3TARGETN) \ + $(BIN)/batch.sh \ + $(BIN)/batch.bat + +#------------------------------- All object files ------------------------------- +# do this here, so we get right dependencies + +.IF "$(GUI)" == "OS2" + +SLOFILES=$(SHL2OBJS) + +.ELSE + +SLOFILES=$(SHL1OBJS) $(SHL2OBJS) + +.ENDIF + +# --- Targets ------------------------------------------------------ + +.INCLUDE : target.mk + +$(BIN)/batch.sh: batch.sh + $(COPY) $< $@ + +$(BIN)/batch.bat: batch.bat + $(COPY) $< $@ + +.INCLUDE : $(PRJ)$/qa$/cppunit_local.mk diff --git a/sal/qa/osl/process/osl_Thread.cxx b/sal/qa/osl/process/osl_Thread.cxx new file mode 100644 index 000000000000..724cdbef2e10 --- /dev/null +++ b/sal/qa/osl/process/osl_Thread.cxx @@ -0,0 +1,2204 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +#ifdef WNT +#define NOMINMAX +#include <windows.h> +#else +#include <unistd.h> +#include <time.h> +#endif + +//------------------------------------------------------------------------ +// include files +//------------------------------------------------------------------------ +#include <sal/types.h> + +#include <rtl/string.hxx> + +#include <rtl/strbuf.hxx> + +#include <osl/thread.hxx> + +#include <osl/mutex.hxx> +#include <osl/time.h> + +#include <string.h> + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> + +#define t_print printf + +using namespace osl; + +using ::rtl::OString; + +// ----------------------------------------------------------------------------- +// Kleine Stopuhr +class StopWatch { + TimeValue t1,t2; // Start und Stopzeit + +protected: + sal_Int32 m_nNanoSec; + sal_Int32 m_nSeconds; + + bool m_bIsValid; // TRUE, wenn gestartet und gestoppt + bool m_bIsRunning; // TRUE, wenn gestartet. + +public: + StopWatch(); + ~StopWatch() {} + + void start(); // Startet Timer + void stop(); // Stoppt Timer + + double getSeconds() const; + double getTenthSec() const; +}; + +// ================================= Stop Watch ================================= + +// Eine kleine Stop-Uhr fuer den internen Gebrauch. +// (c) Lars Langhans 29.12.1996 22:10 + +StopWatch::StopWatch():m_bIsValid(false),m_bIsRunning(false) {} + +void StopWatch::start() +{ +// pre: % +// post: Start Timer + + m_bIsValid = false; + m_bIsRunning = true; + osl_getSystemTime( &t1 ); + t_print("# %u %u nsecs\n", (unsigned)t1.Seconds, (unsigned)t1.Nanosec); + // gettimeofday(&t1, 0); +} + +void StopWatch::stop() +{ +// pre: Timer should be started +// post: Timer will stopped + + // gettimeofday(&t2, 0); // Timer ausfragen + osl_getSystemTime( &t2 ); + t_print("# %u %u nsecs\n", (unsigned) t2.Seconds, (unsigned) t2.Nanosec); + + if (m_bIsRunning) + { // check ob gestartet. + m_nSeconds = static_cast<sal_Int32>(t2.Seconds) - static_cast<sal_Int32>(t1.Seconds); + if ( t2.Nanosec > t1.Nanosec ) + m_nNanoSec = static_cast<sal_Int32>(t2.Nanosec) - static_cast<sal_Int32>(t1.Nanosec); + else + { + m_nNanoSec = 1000000000 + static_cast<sal_Int32>(t2.Nanosec) - static_cast<sal_Int32>(t1.Nanosec); + m_nSeconds -= 1; + } + t_print("# %u %u nsecs\n", (unsigned) m_nSeconds, (unsigned) m_nNanoSec ); + //if (m_nNanoSec < 0) + //{ + //m_nNanoSec += 1000000000; + //m_nSeconds -= 1; + //} + m_bIsValid = true; + m_bIsRunning = false; + } +} + +double StopWatch::getSeconds() const +{ +// pre: gueltig = TRUE +// BACK: Zeit in Sekunden. + + double nValue = 0.0; + if (m_bIsValid) + { + nValue = double(m_nNanoSec) / 1000000000.0 + m_nSeconds; // milli micro nano + } + return nValue; +} + +double StopWatch::getTenthSec() const +{ + double nValue = 0.0; + if (m_bIsValid) + { + nValue = double(m_nNanoSec) / 100000000.0 + m_nSeconds * 10; + } + return nValue ; +} + +// ----------------------------------------------------------------------------- +template <class T> +class ThreadSafeValue +{ + T m_nFlag; + Mutex m_aMutex; +public: + ThreadSafeValue(T n = 0): m_nFlag(n) {} + T getValue() + { + //block if already acquired by another thread. + osl::MutexGuard g(m_aMutex); + return m_nFlag; + } + void addValue(T n) + { + //only one thread operate on the flag. + osl::MutexGuard g(m_aMutex); + m_nFlag += n; + } + void acquire() {m_aMutex.acquire();} + void release() {m_aMutex.release();} +}; + +// ----------------------------------------------------------------------------- +namespace ThreadHelper +{ + void thread_sleep_tenth_sec(sal_Int32 _nTenthSec) + { +#ifdef WNT + Sleep(_nTenthSec * 100 ); +#else + TimeValue nTV; + nTV.Seconds = static_cast<sal_uInt32>( _nTenthSec/10 ); + nTV.Nanosec = ( (_nTenthSec%10 ) * 100000000 ); + osl_waitThread(&nTV); +#endif + } + + void outputPriority(oslThreadPriority const& _aPriority) + { + // LLA: output the priority + if (_aPriority == osl_Thread_PriorityHighest) + { + t_print("Prio is High\n"); + } + else if (_aPriority == osl_Thread_PriorityAboveNormal) + { + t_print("Prio is above normal\n"); + } + else if (_aPriority == osl_Thread_PriorityNormal) + { + t_print("Prio is normal\n"); + } + else if (_aPriority == osl_Thread_PriorityBelowNormal) + { + t_print("Prio is below normal\n"); + } + else if (_aPriority == osl_Thread_PriorityLowest) + { + t_print("Prio is lowest\n"); + } + else + { + t_print("Prio is unknown\n"); + } + } +} + +/** Simple thread for testing Thread-create. + + Just add 1 of value 0, and after running, result is 1. + */ +class myThread : public Thread +{ + ThreadSafeValue<sal_Int32> m_aFlag; +public: + sal_Int32 getValue() { return m_aFlag.getValue(); } +protected: + /** guarded value which initialized 0 + + @see ThreadSafeValue + */ + void SAL_CALL run() + { + while(schedule()) + { + m_aFlag.addValue(1); + ThreadHelper::thread_sleep_tenth_sec(1); + } + } + +public: + + virtual void SAL_CALL suspend() + { + m_aFlag.acquire(); + ::osl::Thread::suspend(); + m_aFlag.release(); + } + + ~myThread() + { + if (isRunning()) + { + t_print("error: not terminated.\n"); + } + } + +}; + +// ----------------------------------------------------------------------------- +/** Thread which has a flag add 1 every second until 20 + */ +class OCountThread : public Thread +{ + ThreadSafeValue<sal_Int32> m_aFlag; +public: + OCountThread() + { + m_nWaitSec = 0; + t_print("new OCountThread thread %u!\n", (unsigned) getIdentifier()); + } + sal_Int32 getValue() { return m_aFlag.getValue(); } + + void setWait(sal_Int32 nSec) + { + m_nWaitSec = nSec; + //m_bWait = sal_True; + } + + virtual void SAL_CALL suspend() + { + m_aFlag.acquire(); + ::osl::Thread::suspend(); + m_aFlag.release(); + } + +protected: + //sal_Bool m_bWait; + sal_Int32 m_nWaitSec; + + void SAL_CALL run() + { + /// if the thread should terminate, schedule return false + while (m_aFlag.getValue() < 20 && schedule() == sal_True) + { + m_aFlag.addValue(1); + ThreadHelper::thread_sleep_tenth_sec(1); + + if (m_nWaitSec != 0) + { + TimeValue nTV; + nTV.Seconds = m_nWaitSec / 10 ; + nTV.Nanosec = ( m_nWaitSec%10 ) * 100000000 ; + wait( nTV ); + m_nWaitSec = 0; + } + } + } + void SAL_CALL onTerminated() + { + t_print("normally terminate this thread %u!\n", (unsigned) getIdentifier()); + } +public: + + ~OCountThread() + { + if (isRunning()) + { + t_print("error: not terminated.\n"); + } + } + +}; + +/** call suspend in the run method +*/ +class OSuspendThread : public Thread +{ + ThreadSafeValue<sal_Int32> m_aFlag; +public: + OSuspendThread(){ m_bSuspend = sal_False; } + sal_Int32 getValue() { return m_aFlag.getValue(); } + void setSuspend() + { + m_bSuspend = sal_True; + } + virtual void SAL_CALL suspend() + { + m_aFlag.acquire(); + ::osl::Thread::suspend(); + m_aFlag.release(); + } +protected: + sal_Bool m_bSuspend; + void SAL_CALL run() + { + //if the thread should terminate, schedule return false + while (schedule() == sal_True) + { + m_aFlag.addValue(1); + + ThreadHelper::thread_sleep_tenth_sec(1); + if (m_bSuspend == sal_True) + { + suspend(); + m_bSuspend = sal_False; + } + } + } +public: + + ~OSuspendThread() + { + if (isRunning()) + { + t_print("error: not terminated.\n"); + } + } + +}; + +/** no call schedule in the run method +*/ +class ONoScheduleThread : public Thread +{ + ThreadSafeValue<sal_Int32> m_aFlag; +public: + sal_Int32 getValue() { return m_aFlag.getValue(); } + + virtual void SAL_CALL suspend() + { + m_aFlag.acquire(); + ::osl::Thread::suspend(); + m_aFlag.release(); + } +protected: + void SAL_CALL run() + { + while (m_aFlag.getValue() < 10) + { + m_aFlag.addValue(1); + ThreadHelper::thread_sleep_tenth_sec(1); + } + } + void SAL_CALL onTerminated() + { + t_print("normally terminate this thread %u!\n", (unsigned) getIdentifier()); + } +public: + ONoScheduleThread() + { + t_print("new thread id %u!\n", (unsigned) getIdentifier()); + } + ~ONoScheduleThread() + { + if (isRunning()) + { + t_print("error: not terminated.\n"); + } + } + +}; + +/** +*/ +class OAddThread : public Thread +{ + ThreadSafeValue<sal_Int32> m_aFlag; +public: + //oslThreadIdentifier m_id, m_CurId; + OAddThread(){} + sal_Int32 getValue() { return m_aFlag.getValue(); } + + virtual void SAL_CALL suspend() + { + m_aFlag.acquire(); + ::osl::Thread::suspend(); + m_aFlag.release(); + } +protected: + void SAL_CALL run() + { + //if the thread should terminate, schedule return false + while (schedule() == sal_True) + { + m_aFlag.addValue(1); + } + } + void SAL_CALL onTerminated() + { + // t_print("normally terminate this thread %d!\n", getIdentifier()); + } +public: + + ~OAddThread() + { + if (isRunning()) + { + // t_print("error: not terminated.\n"); + } + } + +}; + +namespace osl_Thread +{ + + void resumeAndWaitThread(Thread* _pThread) + { + // This functions starts a thread, wait a second and suspends the thread + // Due to the fact, that a suspend and never run thread never really exists. + + // Note: on UNX, after createSuspended, and then terminate the thread, it performs well; + // while on Windows, after createSuspended, the thread can not terminate, wait endlessly, + // so here call resume at first, then call terminate. +#ifdef WNT + t_print("resumeAndWaitThread\n"); + _pThread->resume(); + ThreadHelper::thread_sleep_tenth_sec(1); +#else + _pThread->resume(); +#endif + } + + // kill a running thread and join it, if it has terminated, do nothing + void termAndJoinThread(Thread* _pThread) + { + _pThread->terminate(); + +// LLA: Windows feature???, a suspended thread can not terminated, so we have to weak it up +#ifdef WNT + _pThread->resume(); + ThreadHelper::thread_sleep_tenth_sec(1); +#endif + t_print("#wait for join.\n"); + _pThread->join(); + } +/** Test of the osl::Thread::create method + */ + + class create : public CppUnit::TestFixture + { + public: + + // initialise your test code values here. + void setUp() + { + } + + void tearDown() + { + } + + /** Simple create a thread. + + Create a simple thread, it just does add 1 to value(which initialized 0), + if the thread run, the value should be 1. + */ + void create_001() + { + myThread* newthread = new myThread(); + sal_Bool bRes = newthread->create(); + CPPUNIT_ASSERT_MESSAGE("Can not creates a new thread!\n", bRes == sal_True ); + + ThreadHelper::thread_sleep_tenth_sec(1); // wait short + sal_Bool isRunning = newthread->isRunning(); // check if thread is running + /// wait for the new thread to assure it has run + ThreadHelper::thread_sleep_tenth_sec(3); + sal_Int32 nValue = newthread->getValue(); + /// to assure the new thread has terminated + termAndJoinThread(newthread); + delete newthread; + + t_print(" nValue = %d\n", (int) nValue); + t_print("isRunning = %s\n", isRunning == sal_True ? "true" : "false"); + + CPPUNIT_ASSERT_MESSAGE( + "Creates a new thread", + nValue >= 1 && isRunning == sal_True + ); + + } + + /** only one running thread per instance, return false if create secondly + */ + void create_002() + { + myThread* newthread = new myThread(); + sal_Bool res1 = newthread->create(); + sal_Bool res2 = newthread->create(); + t_print("In non pro, an assertion should occurred. This behaviour is right.\n"); + termAndJoinThread(newthread); + delete newthread; + + CPPUNIT_ASSERT_MESSAGE( + "Creates a new thread: can not create two threads per instance", + res1 && !res2 + ); + + } + + CPPUNIT_TEST_SUITE(create); + CPPUNIT_TEST(create_001); + CPPUNIT_TEST(create_002); + CPPUNIT_TEST_SUITE_END(); + }; // class create + + + + /** Test of the osl::Thread::createSuspended method + */ + class createSuspended : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + void setUp() + { + } + + void tearDown() + { + } + + /** Create a suspended thread, use the same class as create_001 + + after create, wait enough time, check the value, if it's still the initial value, pass + */ + void createSuspended_001() + { + myThread* newthread = new myThread(); + sal_Bool bRes = newthread->createSuspended(); + CPPUNIT_ASSERT_MESSAGE("Can not creates a new thread!", bRes == sal_True ); + + ThreadHelper::thread_sleep_tenth_sec(1); + sal_Bool isRunning = newthread->isRunning(); + ThreadHelper::thread_sleep_tenth_sec(3); + sal_Int32 nValue = newthread->getValue(); + + resumeAndWaitThread(newthread); + + termAndJoinThread(newthread); + delete newthread; + + CPPUNIT_ASSERT_MESSAGE( + "Creates a new suspended thread", + nValue == 0 && isRunning + ); + } + + void createSuspended_002() + { + myThread* newthread = new myThread(); + sal_Bool res1 = newthread->createSuspended(); + sal_Bool res2 = newthread->createSuspended(); + + resumeAndWaitThread(newthread); + + termAndJoinThread(newthread); + + delete newthread; + + CPPUNIT_ASSERT_MESSAGE( + "Creates a new thread: can not create two threads per instance", + res1 && !res2 + ); + } + + CPPUNIT_TEST_SUITE(createSuspended); + CPPUNIT_TEST(createSuspended_001); + // LLA: Deadlocked!!! + CPPUNIT_TEST(createSuspended_002); + CPPUNIT_TEST_SUITE_END(); + }; // class createSuspended + + /** when the count value equal to or more than 3, suspend the thread. + */ + void suspendCountThread(OCountThread* _pCountThread) + { + sal_Int32 nValue = 0; + while (1) + { + nValue = _pCountThread->getValue(); + if (nValue >= 3) + { + _pCountThread->suspend(); + break; + } + } + } + + /** Test of the osl::Thread::suspend method + */ + class suspend : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + void setUp() + { + } + + void tearDown() + { + } + + /** Use a thread which has a flag added 1 every second + + ALGORITHM: + create the thread, after running special time, record value of flag, then suspend it, + wait a long time, check the flag, if it remains unchanged during suspending + */ + void suspend_001() + { + OCountThread* aCountThread = new OCountThread(); + sal_Bool bRes = aCountThread->create(); + CPPUNIT_ASSERT_MESSAGE ( "Can't start thread!", bRes == sal_True ); + // the thread run for some seconds, but not terminate + suspendCountThread( aCountThread ); + + // the value just after calling suspend + sal_Int32 nValue = aCountThread->getValue(); // (2) + + ThreadHelper::thread_sleep_tenth_sec(3); + + // the value after waiting 3 seconds + sal_Int32 nLaterValue = aCountThread->getValue(); // (3) + + resumeAndWaitThread(aCountThread); + termAndJoinThread(aCountThread); + delete aCountThread; + + CPPUNIT_ASSERT_MESSAGE( + "Suspend the thread", + bRes == sal_True && nValue == nLaterValue + ); + + } + /** suspend a thread in it's worker-function, the ALGORITHM is same as suspend_001 + reason of deadlocked I think: no schedule can schedule other threads to go on excuting + */ + void suspend_002() + { + OSuspendThread* aThread = new OSuspendThread(); + sal_Bool bRes = aThread->create(); + CPPUNIT_ASSERT_MESSAGE ( "Can't start thread!", bRes == sal_True ); + // first the thread run for some seconds, but not terminate + sal_Int32 nValue = 0; + //while (1) + //{ + ThreadHelper::thread_sleep_tenth_sec(3); + nValue = aThread->getValue(); // (1) + t_print(" getValue is %d !", (int) nValue ); + if (nValue >= 2) + { + aThread->setSuspend(); + //break; + } + //} + t_print(" after while!"); + // the value just after calling suspend + nValue = aThread->getValue(); // (2) + + ThreadHelper::thread_sleep_tenth_sec(3); + t_print(" after sleep!"); + // the value after waiting 3 seconds + sal_Int32 nLaterValue = aThread->getValue(); // (3) + + //resumeAndWaitThread(aThread); + aThread->resume(); + termAndJoinThread(aThread); + delete aThread; + + CPPUNIT_ASSERT_MESSAGE( + "Suspend the thread", + bRes == sal_True && nValue == nLaterValue + ); + } + + CPPUNIT_TEST_SUITE(suspend); + CPPUNIT_TEST(suspend_001); + // LLA: Deadlocked!!! + // CPPUNIT_TEST(createSuspended_002); + CPPUNIT_TEST_SUITE_END(); + }; // class suspend + + /** Test of the osl::Thread::resume method + */ + class resume : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + void setUp() + { + } + + void tearDown() + { + } + + /** check if the thread run samely as usual after suspend and resume + + ALGORITHM: + compare the values before and after suspend, they should be same, + then compare values before and after resume, the difference should be same as the sleep seconds number + */ + void resume_001() + { + OCountThread* pCountThread = new OCountThread(); + sal_Bool bRes = pCountThread->create(); + CPPUNIT_ASSERT_MESSAGE ( "Can't start thread!", bRes == sal_True ); + + suspendCountThread(pCountThread); + + sal_Int32 nSuspendValue = pCountThread->getValue(); // (2) + // suspend for 3 seconds + ThreadHelper::thread_sleep_tenth_sec(3); + pCountThread->resume(); + + ThreadHelper::thread_sleep_tenth_sec(3); + sal_Int32 nResumeValue = pCountThread->getValue(); + + ThreadHelper::thread_sleep_tenth_sec(3); + sal_Int32 nLaterValue = pCountThread->getValue(); + + termAndJoinThread(pCountThread); + delete pCountThread; + + t_print("SuspendValue: %d\n", (int) nSuspendValue); + t_print("ResumeValue: %d\n", (int) nResumeValue); + t_print("LaterValue: %d\n", (int) nLaterValue); + + /* LLA: this assumption is no longer relevant: nResumeValue == nSuspendValue && */ + CPPUNIT_ASSERT_MESSAGE( + "Suspend then resume the thread", + nLaterValue >= 9 && + nResumeValue > nSuspendValue && + nLaterValue > nResumeValue + ); + + } + + /** Create a suspended thread then resume, check if the thread has run + */ + void resume_002() + { + myThread* newthread = new myThread(); + sal_Bool bRes = newthread->createSuspended(); + CPPUNIT_ASSERT_MESSAGE ( "Can't create thread!", bRes == sal_True ); + + newthread->resume(); + ThreadHelper::thread_sleep_tenth_sec(2); + sal_Int32 nValue = newthread->getValue(); + + termAndJoinThread(newthread); + delete newthread; + + t_print(" nValue = %d\n", (int) nValue); + + CPPUNIT_ASSERT_MESSAGE( + "Creates a suspended thread, then resume", + nValue >= 1 + ); + } + + CPPUNIT_TEST_SUITE(resume); + CPPUNIT_TEST(resume_001); + CPPUNIT_TEST(resume_002); + CPPUNIT_TEST_SUITE_END(); + }; // class resume + + /** Test of the osl::Thread::terminate method + */ + class terminate : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + void setUp() + { + } + + void tearDown() + { + } + + /** Check after call terminate if the running thread running go on executing + + ALGORITHM: + before and after call terminate, the values should be the same + */ + void terminate_001() + { + OCountThread* aCountThread = new OCountThread(); + sal_Bool bRes = aCountThread->create(); + CPPUNIT_ASSERT_MESSAGE ( "Can't start thread!", bRes == sal_True ); + + ThreadHelper::thread_sleep_tenth_sec(2); + sal_Int32 nValue = aCountThread->getValue(); + aCountThread->terminate(); + ThreadHelper::thread_sleep_tenth_sec(2); + sal_Int32 nLaterValue = aCountThread->getValue(); + + // isRunning should be false after terminate + sal_Bool isRunning = aCountThread->isRunning(); + aCountThread->join(); + delete aCountThread; + + t_print(" nValue = %d\n", (int) nValue); + t_print("nLaterValue = %d\n", (int) nLaterValue); + + CPPUNIT_ASSERT_MESSAGE( + "Terminate the thread", + isRunning == sal_False && nLaterValue >= nValue + ); + } + /** Check if a suspended thread will terminate after call terminate, different on w32 and on UNX + */ + void terminate_002() + { + OCountThread* aCountThread = new OCountThread(); + sal_Bool bRes = aCountThread->create(); + CPPUNIT_ASSERT_MESSAGE ( "Can't start thread!", bRes == sal_True ); + + ThreadHelper::thread_sleep_tenth_sec(1); + suspendCountThread(aCountThread); + sal_Int32 nValue = aCountThread->getValue(); + + // seems a suspended thread can not be terminated on W32, while on Solaris can + resumeAndWaitThread(aCountThread); + + ThreadHelper::thread_sleep_tenth_sec(2); + + termAndJoinThread(aCountThread); + sal_Int32 nLaterValue = aCountThread->getValue(); + delete aCountThread; + + t_print(" nValue = %d\n", (int) nValue); + t_print("nLaterValue = %d\n", (int) nLaterValue); + + CPPUNIT_ASSERT_MESSAGE( + "Suspend then resume the thread", + nLaterValue > nValue ); + } + + CPPUNIT_TEST_SUITE(terminate); + CPPUNIT_TEST(terminate_001); + CPPUNIT_TEST(terminate_002); + CPPUNIT_TEST_SUITE_END(); + }; // class terminate + + /** Test of the osl::Thread::join method + */ + class join : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + void setUp() + { + } + + void tearDown() + { + } + + /** Check after call terminate if the thread running function will not go on executing + + the next statement after join will not exec before the thread terminate + ALGORITHM: + recode system time at the beginning of the thread run, call join, then record system time again, + the difference of the two time should be equal or more than 20 seconds, the CountThead normally terminate + */ + void join_001() + { + OCountThread *aCountThread = new OCountThread(); + sal_Bool bRes = aCountThread->create(); + CPPUNIT_ASSERT_MESSAGE ( "Can't start thread!", bRes == sal_True ); + + StopWatch aStopWatch; + aStopWatch.start(); + // TimeValue aTimeVal_befor; + // osl_getSystemTime( &aTimeVal_befor ); + //t_print("#join:the system time is %d,%d\n", pTimeVal_befor->Seconds,pTimeVal_befor->Nanosec); + + aCountThread->join(); + + //the below line will be executed after aCountThread terminate + // TimeValue aTimeVal_after; + // osl_getSystemTime( &aTimeVal_after ); + aStopWatch.stop(); + // sal_uInt32 nSec = aTimeVal_after.Seconds - aTimeVal_befor.Seconds; + double nSec = aStopWatch.getSeconds(); + t_print("join_001 nSec=%f\n", nSec); + delete aCountThread; + + CPPUNIT_ASSERT_MESSAGE( + "Join the thread: after the thread terminate", + nSec >= 2 + ); + + } + /** after terminated by another thread, join exited immediately + + ALGORITHM: + terminate the thread when value>=3, call join, check the beginning time and time after join, + the difference should be 3 seconds, join costs little time + */ + void join_002() + { + OCountThread *aCountThread = new OCountThread(); + sal_Bool bRes = aCountThread->create(); + CPPUNIT_ASSERT_MESSAGE ( "Can't start thread!", bRes == sal_True ); + + //record the time when the running begin + // TimeValue aTimeVal_befor; + // osl_getSystemTime( &aTimeVal_befor ); + StopWatch aStopWatch; + aStopWatch.start(); + + ThreadHelper::thread_sleep_tenth_sec(10); + termAndJoinThread(aCountThread); + + //the below line will be executed after aCountThread terminate + // TimeValue aTimeVal_after; + // osl_getSystemTime( &aTimeVal_after ); + // sal_uInt32 nSec = aTimeVal_after.Seconds - aTimeVal_befor.Seconds; + aStopWatch.stop(); + double nSec = aStopWatch.getSeconds(); + t_print("join_002 nSec=%f\n", nSec); + + delete aCountThread; + CPPUNIT_ASSERT_MESSAGE( + "Join the thread: after thread terminate by another thread", + nSec >= 1 + ); + } + + CPPUNIT_TEST_SUITE(join); + CPPUNIT_TEST(join_001); + CPPUNIT_TEST(join_002); + CPPUNIT_TEST_SUITE_END(); + }; // class join + + /** Test of the osl::Thread::isRunning method + */ + class isRunning : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + void setUp() + { + } + + void tearDown() + { + } + + /** + */ + void isRunning_001() + { + OCountThread *aCountThread = new OCountThread(); + sal_Bool bRes = aCountThread->create(); + CPPUNIT_ASSERT_MESSAGE ( "Can't start thread!", bRes == sal_True ); + + sal_Bool bRun = aCountThread->isRunning(); + + ThreadHelper::thread_sleep_tenth_sec(2); + termAndJoinThread(aCountThread); + sal_Bool bTer = aCountThread->isRunning(); + delete aCountThread; + + CPPUNIT_ASSERT_MESSAGE( + "Test isRunning", + bRun == sal_True && bTer == sal_False + ); + } + /** check the value of isRunning when suspending and after resume + */ + void isRunning_002() + { + OCountThread *aCountThread = new OCountThread(); + sal_Bool bRes = aCountThread->create(); + CPPUNIT_ASSERT_MESSAGE ( "Can't start thread!", bRes == sal_True ); + + // sal_Bool bRunning = aCountThread->isRunning(); + // sal_Int32 nValue = 0; + suspendCountThread(aCountThread); + + sal_Bool bRunning_sup = aCountThread->isRunning(); + ThreadHelper::thread_sleep_tenth_sec(2); + aCountThread->resume(); + ThreadHelper::thread_sleep_tenth_sec(2); + sal_Bool bRunning_res = aCountThread->isRunning(); + termAndJoinThread(aCountThread); + sal_Bool bRunning_ter = aCountThread->isRunning(); + delete aCountThread; + + CPPUNIT_ASSERT_MESSAGE( + "Test isRunning", + bRes == sal_True && + bRunning_sup == sal_True && + bRunning_res == sal_True && + bRunning_ter == sal_False + ); + + } + + CPPUNIT_TEST_SUITE(isRunning); + CPPUNIT_TEST(isRunning_001); + CPPUNIT_TEST(isRunning_002); + CPPUNIT_TEST_SUITE_END(); + }; // class isRunning + + + /// check osl::Thread::setPriority + class setPriority : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + void setUp() + { + } + + void tearDown() + { + } + + // insert your test code here. + rtl::OString getPrioName(oslThreadPriority _aPriority) + { + rtl::OString sPrioStr; + switch (_aPriority) + { + case osl_Thread_PriorityHighest: + sPrioStr = "Highest"; + break; + + case osl_Thread_PriorityAboveNormal: + sPrioStr = "AboveNormal"; + + case osl_Thread_PriorityNormal: + sPrioStr = "Normal"; + + case osl_Thread_PriorityBelowNormal: + sPrioStr = "BelowNormal"; + break; + + case osl_Thread_PriorityLowest: + sPrioStr = "Lowest"; + break; + default: + sPrioStr = "unknown"; + } + return sPrioStr; + } + + + /** check 2 threads. + + ALGORITHM: + Here the function should show, that 2 different threads, + which only increase a value, should run at the same time with same prio. + The test fails, if the difference between the two values is more than 5% + but IMHO this isn't a failure, it's only a feature of the OS. + */ + + void check2Threads(oslThreadPriority _aPriority) + { + // initial 5 threads with different priorities + OAddThread* pThread = new OAddThread(); + OAddThread* p2Thread = new OAddThread(); + + //Create them and start running at the same time + pThread->create(); + pThread->setPriority(_aPriority); + p2Thread->create(); + p2Thread->setPriority(_aPriority); + + ThreadHelper::thread_sleep_tenth_sec(5); + + pThread->terminate(); + p2Thread->terminate(); + + sal_Int32 nValueNormal = 0; + nValueNormal = pThread->getValue(); + + sal_Int32 nValueNormal2 = 0; + nValueNormal2 = p2Thread->getValue(); + + rtl::OString sPrio = getPrioName(_aPriority); + t_print("After 10 tenth seconds\n"); + + t_print("nValue in %s Prio Thread is %d\n",sPrio.getStr(), (int) nValueNormal); + t_print("nValue in %s Prio Thread is %d\n", sPrio.getStr(), (int) nValueNormal2); + + // ThreadHelper::thread_sleep_tenth_sec(1); + pThread->join(); + p2Thread->join(); + + delete pThread; + delete p2Thread; + + sal_Int32 nDelta = abs(nValueNormal - nValueNormal2); + double nQuotient = std::max(nValueNormal, nValueNormal2); + CPPUNIT_ASSERT_MESSAGE( + "Quotient is zero, which means, there exist no right values.", + nQuotient != 0 + ); + double nDeltaPercent = nDelta / nQuotient * 100; + + t_print("Delta value %d, percent %f\n", (int) nDelta, nDeltaPercent); + + // LLA: it's not a bug if the current OS is not able to handle thread scheduling right and good. + // like Windows XP + // LLA: CPPUNIT_ASSERT_MESSAGE( + // LLA: "Run 2 normal threads, the count diff more than 5 percent.", + // LLA: nDeltaPercent <= 5 + // LLA: ); + } + + void setPriority_001_1() + { + check2Threads(osl_Thread_PriorityHighest); + } + void setPriority_001_2() + { + check2Threads(osl_Thread_PriorityAboveNormal); + } + void setPriority_001_3() + { + check2Threads(osl_Thread_PriorityNormal); + } + void setPriority_001_4() + { + check2Threads(osl_Thread_PriorityBelowNormal); + } + void setPriority_001_5() + { + check2Threads(osl_Thread_PriorityLowest); + } + + void setPriority_002() + { + // initial 5 threads with different priorities + + OAddThread aHighestThread; + OAddThread aAboveNormalThread; + OAddThread aNormalThread; + //OAddThread *aBelowNormalThread = new OAddThread(); + //OAddThread *aLowestThread = new OAddThread(); + + //Create them and start running at the same time + aHighestThread.createSuspended(); + aHighestThread.setPriority(osl_Thread_PriorityHighest); + + aAboveNormalThread.createSuspended(); + aAboveNormalThread.setPriority(osl_Thread_PriorityAboveNormal); + + aNormalThread.createSuspended(); + aNormalThread.setPriority(osl_Thread_PriorityNormal); + /*aBelowNormalThread->create(); + aBelowNormalThread->setPriority(osl_Thread_PriorityBelowNormal); + aLowestThread->create(); + aLowestThread->setPriority(osl_Thread_PriorityLowest); + */ + + aHighestThread.resume(); + aAboveNormalThread.resume(); + aNormalThread.resume(); + + ThreadHelper::thread_sleep_tenth_sec(5); + + aHighestThread.suspend(); + aAboveNormalThread.suspend(); + aNormalThread.suspend(); + + termAndJoinThread(&aNormalThread); + termAndJoinThread(&aAboveNormalThread); + termAndJoinThread(&aHighestThread); + //aBelowNormalThread->terminate(); + //aLowestThread->terminate(); + + sal_Int32 nValueHighest = 0; + nValueHighest = aHighestThread.getValue(); + + sal_Int32 nValueAboveNormal = 0; + nValueAboveNormal = aAboveNormalThread.getValue(); + + sal_Int32 nValueNormal = 0; + nValueNormal = aNormalThread.getValue(); + + t_print("After 10 tenth seconds\n"); + t_print("nValue in Highest Prio Thread is %d\n", (int) nValueHighest); + t_print("nValue in AboveNormal Prio Thread is %d\n", (int) nValueAboveNormal); + t_print("nValue in Normal Prio Thread is %d\n", (int) nValueNormal); + +#ifndef WNT + CPPUNIT_ASSERT_MESSAGE( + "SetPriority", + nValueHighest > 0 && + nValueAboveNormal > 0 && + nValueNormal > 0 + ); +#endif + } + + void setPriority_003() + { + // initial 5 threads with different priorities + OAddThread *pHighestThread = new OAddThread(); + OAddThread *pAboveNormalThread = new OAddThread(); + OAddThread *pNormalThread = new OAddThread(); + OAddThread *pBelowNormalThread = new OAddThread(); + OAddThread *pLowestThread = new OAddThread(); + + //Create them and start running at the same time + pHighestThread->createSuspended(); + pHighestThread->setPriority(osl_Thread_PriorityHighest); + + pAboveNormalThread->createSuspended(); + pAboveNormalThread->setPriority(osl_Thread_PriorityAboveNormal); + + pNormalThread->createSuspended(); + pNormalThread->setPriority(osl_Thread_PriorityNormal); + + pBelowNormalThread->createSuspended(); + pBelowNormalThread->setPriority(osl_Thread_PriorityBelowNormal); + + pLowestThread->createSuspended(); + pLowestThread->setPriority(osl_Thread_PriorityLowest); + + pHighestThread->resume(); + pAboveNormalThread->resume(); + pNormalThread->resume(); + pBelowNormalThread->resume(); + pLowestThread->resume(); + + ThreadHelper::thread_sleep_tenth_sec(5); + + pHighestThread->suspend(); + pAboveNormalThread->suspend(); + pNormalThread->suspend(); + pBelowNormalThread->suspend(); + pLowestThread->suspend(); + + termAndJoinThread(pHighestThread); + termAndJoinThread(pAboveNormalThread); + termAndJoinThread(pNormalThread); + termAndJoinThread(pBelowNormalThread); + termAndJoinThread(pLowestThread); + + sal_Int32 nValueHighest = 0; + nValueHighest = pHighestThread->getValue(); + + sal_Int32 nValueAboveNormal = 0; + nValueAboveNormal = pAboveNormalThread->getValue(); + + sal_Int32 nValueNormal = 0; + nValueNormal = pNormalThread->getValue(); + + sal_Int32 nValueBelowNormal = 0; + nValueBelowNormal = pBelowNormalThread->getValue(); + + sal_Int32 nValueLowest = 0; + nValueLowest = pLowestThread->getValue(); + + t_print("After 10 tenth seconds\n"); + t_print("nValue in Highest Prio Thread is %d\n", (int) nValueHighest); + t_print("nValue in AboveNormal Prio Thread is %d\n", (int) nValueAboveNormal); + t_print("nValue in Normal Prio Thread is %d\n", (int) nValueNormal); + t_print("nValue in BelowNormal Prio Thread is %d\n", (int) nValueBelowNormal); + t_print("nValue in Lowest Prio Thread is %d\n", (int) nValueLowest); + + delete pHighestThread; + delete pAboveNormalThread; + delete pNormalThread; + delete pBelowNormalThread; + delete pLowestThread; + +#ifndef WNT + CPPUNIT_ASSERT_MESSAGE( + "SetPriority", + nValueHighest > 0 && + nValueAboveNormal > 0 && + nValueNormal > 0 && + nValueBelowNormal > 0 && + nValueLowest > 0 + ); +#endif + } + + void setPriority_004() + { + // initial 5 threads with different priorities + // OAddThread *pHighestThread = new OAddThread(); + OAddThread *pAboveNormalThread = new OAddThread(); + OAddThread *pNormalThread = new OAddThread(); + OAddThread *pBelowNormalThread = new OAddThread(); + OAddThread *pLowestThread = new OAddThread(); + + //Create them and start running at the same time + // pHighestThread->createSuspended(); + // pHighestThread->setPriority(osl_Thread_PriorityHighest); + + pAboveNormalThread->createSuspended(); + pAboveNormalThread->setPriority(osl_Thread_PriorityAboveNormal); + + pNormalThread->createSuspended(); + pNormalThread->setPriority(osl_Thread_PriorityNormal); + + pBelowNormalThread->createSuspended(); + pBelowNormalThread->setPriority(osl_Thread_PriorityBelowNormal); + + pLowestThread->createSuspended(); + pLowestThread->setPriority(osl_Thread_PriorityLowest); + + // pHighestThread->resume(); + pAboveNormalThread->resume(); + pNormalThread->resume(); + pBelowNormalThread->resume(); + pLowestThread->resume(); + + ThreadHelper::thread_sleep_tenth_sec(5); + + // pHighestThread->suspend(); + pAboveNormalThread->suspend(); + pNormalThread->suspend(); + pBelowNormalThread->suspend(); + pLowestThread->suspend(); + + // termAndJoinThread(pHighestThread); + termAndJoinThread(pAboveNormalThread); + termAndJoinThread(pNormalThread); + termAndJoinThread(pBelowNormalThread); + termAndJoinThread(pLowestThread); + + // sal_Int32 nValueHighest = 0; + // nValueHighest = pHighestThread->getValue(); + + sal_Int32 nValueAboveNormal = 0; + nValueAboveNormal = pAboveNormalThread->getValue(); + + sal_Int32 nValueNormal = 0; + nValueNormal = pNormalThread->getValue(); + + sal_Int32 nValueBelowNormal = 0; + nValueBelowNormal = pBelowNormalThread->getValue(); + + sal_Int32 nValueLowest = 0; + nValueLowest = pLowestThread->getValue(); + + t_print("After 5 tenth seconds\n"); + t_print("nValue in AboveNormal Prio Thread is %d\n", (int) nValueAboveNormal); + t_print("nValue in Normal Prio Thread is %d\n", (int) nValueNormal); + t_print("nValue in BelowNormal Prio Thread is %d\n", (int) nValueBelowNormal); + t_print("nValue in Lowest Prio Thread is %d\n", (int) nValueLowest); + + // delete pHighestThread; + delete pAboveNormalThread; + delete pNormalThread; + delete pBelowNormalThread; + delete pLowestThread; + +#ifndef WNT + CPPUNIT_ASSERT_MESSAGE( + "SetPriority", + /* nValueHighest > 0 && */ + nValueAboveNormal > 0 && + nValueNormal > 0 && + nValueBelowNormal > 0 && + nValueLowest > 0 + ); +#endif + } + void setPriority_005() + { + // initial 5 threads with different priorities + // OAddThread *pHighestThread = new OAddThread(); + // OAddThread *pAboveNormalThread = new OAddThread(); + OAddThread *pNormalThread = new OAddThread(); + OAddThread *pBelowNormalThread = new OAddThread(); + OAddThread *pLowestThread = new OAddThread(); + + //Create them and start running at the same time + // pHighestThread->createSuspended(); + // pHighestThread->setPriority(osl_Thread_PriorityHighest); + + // pAboveNormalThread->createSuspended(); + // pAboveNormalThread->setPriority(osl_Thread_PriorityAboveNormal); + + pNormalThread->createSuspended(); + pNormalThread->setPriority(osl_Thread_PriorityNormal); + + pBelowNormalThread->createSuspended(); + pBelowNormalThread->setPriority(osl_Thread_PriorityBelowNormal); + + pLowestThread->createSuspended(); + pLowestThread->setPriority(osl_Thread_PriorityLowest); + + // pHighestThread->resume(); + // pAboveNormalThread->resume(); + pNormalThread->resume(); + pBelowNormalThread->resume(); + pLowestThread->resume(); + + ThreadHelper::thread_sleep_tenth_sec(5); + + // pHighestThread->suspend(); + // pAboveNormalThread->suspend(); + pNormalThread->suspend(); + pBelowNormalThread->suspend(); + pLowestThread->suspend(); + + // termAndJoinThread(pHighestThread); + // termAndJoinThread(pAboveNormalThread); + termAndJoinThread(pNormalThread); + termAndJoinThread(pBelowNormalThread); + termAndJoinThread(pLowestThread); + + // sal_Int32 nValueHighest = 0; + // nValueHighest = pHighestThread->getValue(); + + // sal_Int32 nValueAboveNormal = 0; + // nValueAboveNormal = pAboveNormalThread->getValue(); + + sal_Int32 nValueNormal = 0; + nValueNormal = pNormalThread->getValue(); + + sal_Int32 nValueBelowNormal = 0; + nValueBelowNormal = pBelowNormalThread->getValue(); + + sal_Int32 nValueLowest = 0; + nValueLowest = pLowestThread->getValue(); + + t_print("After 5 tenth seconds\n"); + t_print("nValue in Normal Prio Thread is %d\n", (int) nValueNormal); + t_print("nValue in BelowNormal Prio Thread is %d\n", (int) nValueBelowNormal); + t_print("nValue in Lowest Prio Thread is %d\n", (int) nValueLowest); + + delete pNormalThread; + delete pBelowNormalThread; + delete pLowestThread; + +#ifndef WNT + CPPUNIT_ASSERT_MESSAGE( + "SetPriority", + /* nValueHighest > 0 && */ + /* nValueAboveNormal > 0 && */ + nValueNormal > 0 && + nValueBelowNormal > 0 && + nValueLowest > 0 + ); +#endif + } + + + CPPUNIT_TEST_SUITE(setPriority); +#ifndef SOLARIS + CPPUNIT_TEST(setPriority_002); + CPPUNIT_TEST(setPriority_003); + CPPUNIT_TEST(setPriority_004); + CPPUNIT_TEST(setPriority_005); +#endif + CPPUNIT_TEST(setPriority_001_1); + CPPUNIT_TEST(setPriority_001_2); + CPPUNIT_TEST(setPriority_001_3); + CPPUNIT_TEST(setPriority_001_4); + CPPUNIT_TEST(setPriority_001_5); + CPPUNIT_TEST_SUITE_END(); + }; // class setPriority + + /** Test of the osl::Thread::getPriority method + */ + class getPriority : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + void setUp() + { + } + + void tearDown() + { + } + + // insert your test code here. + void getPriority_001() + { + OAddThread *pHighestThread = new OAddThread(); + + //Create them and start running at the same time + pHighestThread->create(); + pHighestThread->setPriority(osl_Thread_PriorityHighest); + + oslThreadPriority aPriority = pHighestThread->getPriority(); + termAndJoinThread(pHighestThread); + delete pHighestThread; + + ThreadHelper::outputPriority(aPriority); + +// LLA: Priority settings may not work within some OS versions. +#if ( defined WNT ) || ( defined SOLARIS ) + CPPUNIT_ASSERT_MESSAGE( + "getPriority", + aPriority == osl_Thread_PriorityHighest + ); +#else +// LLA: Linux +// NO_PTHREAD_PRIORITY ??? + CPPUNIT_ASSERT_MESSAGE( + "getPriority", + aPriority == osl_Thread_PriorityNormal + ); +#endif + } + + void getPriority_002() + { + + } + + CPPUNIT_TEST_SUITE(getPriority); + CPPUNIT_TEST(getPriority_001); + CPPUNIT_TEST(getPriority_002); + CPPUNIT_TEST_SUITE_END(); + }; // class getPriority + + + class getIdentifier : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + void setUp() + { + } + + void tearDown() + { + } + + // insert your test code here. + void getIdentifier_001() + { + + } + + void getIdentifier_002() + { + + } + + CPPUNIT_TEST_SUITE(getIdentifier); + CPPUNIT_TEST(getIdentifier_001); + CPPUNIT_TEST(getIdentifier_002); + CPPUNIT_TEST_SUITE_END(); + }; // class getIdentifier + + /** Test of the osl::Thread::getCurrentIdentifier method + */ + class getCurrentIdentifier : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + void setUp() + { + } + + void tearDown() + { + } + + // insert your test code here. + void getCurrentIdentifier_001() + { + oslThreadIdentifier oId; + OCountThread* pCountThread = new OCountThread; + pCountThread->create(); + pCountThread->setWait(3); + oId = Thread::getCurrentIdentifier(); + oslThreadIdentifier oIdChild = pCountThread->getIdentifier(); + termAndJoinThread(pCountThread); + delete pCountThread; + + CPPUNIT_ASSERT_MESSAGE( + "Get the identifier for the current active thread.", + oId != oIdChild + ); + + } + + void getCurrentIdentifier_002() + { + } + + CPPUNIT_TEST_SUITE(getCurrentIdentifier); + CPPUNIT_TEST(getCurrentIdentifier_001); + //CPPUNIT_TEST(getCurrentIdentifier_002); + CPPUNIT_TEST_SUITE_END(); + }; // class getCurrentIdentifier + + /** Test of the osl::Thread::wait method + */ + class wait : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + void setUp() + { + } + + void tearDown() + { + } + + /** call wait in the run method + + ALGORITHM: + tested thread wait nWaitSec seconds, main thread sleep (2) seconds, + then terminate the tested thread, due to the fact that the thread do a sleep(1) + wait(5) + it's finish after 6 seconds. + */ + void wait_001() + { + OCountThread *aCountThread = new OCountThread(); + sal_Int32 nWaitSec = 5; + aCountThread->setWait(nWaitSec); + // thread runs at least 5 seconds. + sal_Bool bRes = aCountThread->create(); + CPPUNIT_ASSERT_MESSAGE ( "Can't start thread!", bRes == sal_True ); + + //record the time when the running begin + StopWatch aStopWatch; + aStopWatch.start(); + + // wait a little bit, to let the thread the time, to start + ThreadHelper::thread_sleep_tenth_sec( 4 ); + + // if wait works, + // this function returns, after 4 sec. later + termAndJoinThread(aCountThread); + + // value should be one. + sal_Int32 nValue = aCountThread->getValue(); + + aStopWatch.stop(); + + // sal_uInt32 nSec = aTimeVal_after.Seconds - aTimeVal_befor.Seconds; + double nTenthSec = aStopWatch.getTenthSec(); + double nSec = aStopWatch.getSeconds(); + delete aCountThread; + t_print("nTenthSec = %f \n", nTenthSec); + t_print("nSec = %f \n", nSec); + t_print("nValue = %d \n", (int) nValue); + + CPPUNIT_ASSERT_MESSAGE( + "Wait: Blocks the calling thread for the given number of time.", + nTenthSec >= 5 && nValue == 1 + ); + + } + + CPPUNIT_TEST_SUITE(wait); + CPPUNIT_TEST(wait_001); + CPPUNIT_TEST_SUITE_END(); + }; // class wait + + /** osl::Thread::yield method: can not design good test scenario to test up to now + */ + class yield : public CppUnit::TestFixture + { + public: + void setUp() + { + } + + void tearDown() + { + } + + // insert your test code here. + void yield_001() + { + } + + + CPPUNIT_TEST_SUITE(yield); + CPPUNIT_TEST(yield_001); + CPPUNIT_TEST_SUITE_END(); + }; // class yield + + /** Test of the osl::Thread::schedule method + */ + class schedule : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + void setUp() + { + } + + void tearDown() + { + } + + /** The requested thread will get terminate the next time schedule() is called. + + Note: on UNX, if call suspend thread is not the to be suspended thread, the to be + suspended thread will get suspended the next time schedule() is called, + while on w32, it's nothing with schedule. + + check if suspend and terminate work well via schedule + */ + void schedule_001() + { + OAddThread* aThread = new OAddThread(); + sal_Bool bRes = aThread->create(); + CPPUNIT_ASSERT_MESSAGE ( "Can't start thread!", bRes == sal_True ); + + ThreadHelper::thread_sleep_tenth_sec(2); + aThread->suspend(); + ThreadHelper::thread_sleep_tenth_sec(1); + sal_Int32 nValue = aThread->getValue(); + ThreadHelper::thread_sleep_tenth_sec(3); + sal_Int32 nLaterValue = aThread->getValue(); + // resumeAndWaitThread(aThread); + t_print(" value = %d\n", (int) nValue); + t_print("later value = %d\n", (int) nLaterValue); + // if value and latervalue not equal, than the thread would not suspended + + CPPUNIT_ASSERT_MESSAGE( + "Schedule: suspend works.", + nLaterValue == nValue + ); + + aThread->resume(); + ThreadHelper::thread_sleep_tenth_sec(2); + + aThread->terminate(); + sal_Int32 nValue_term = aThread->getValue(); + + aThread->join(); + sal_Int32 nValue_join = aThread->getValue(); + + t_print("value after term = %d\n", (int) nValue_term); + t_print("value after join = %d\n", (int) nValue_join); + + // nValue_term and nValue_join should be the same + // but should be differ from nValue + + delete aThread; + //check if thread really terminate after call terminate, if join immediatlly return + CPPUNIT_ASSERT_MESSAGE( + "Schedule: Returns False if the thread should terminate.", + nValue_join - nValue_term <= 1 && nValue_join - nValue_term >= 0 + ); + + } + + /** design a thread that has not call schedule in the workfunction--run method + */ + void schedule_002() + { + ONoScheduleThread aThread; // this thread runs 10 sec. (no schedule() used) + sal_Bool bRes = aThread.create(); + CPPUNIT_ASSERT_MESSAGE ( "Can't start thread!", bRes == sal_True ); + + ThreadHelper::thread_sleep_tenth_sec(2); + aThread.suspend(); + sal_Int32 nValue = aThread.getValue(); + + ThreadHelper::thread_sleep_tenth_sec(3); + sal_Int32 nLaterValue = aThread.getValue(); + ThreadHelper::thread_sleep_tenth_sec(5); + + resumeAndWaitThread(&aThread); + + t_print(" value = %d\n", (int) nValue); + t_print("later value = %d\n", (int) nLaterValue); + + //On windows, suspend works, so the values are same +#ifdef WNT + CPPUNIT_ASSERT_MESSAGE( + "Schedule: don't schedule in thread run method, suspend works.", + nLaterValue == nValue + ); +#endif + + //On UNX, suspend does not work, so the difference of the values equals to sleep seconds number +#ifdef UNX + aThread.resume(); + CPPUNIT_ASSERT_MESSAGE( + "Schedule: don't schedule in thread run method, suspend does not work too.", + nLaterValue > nValue + ); +#endif + + // terminate will not work if no schedule in thread's work function + termAndJoinThread(&aThread); + sal_Int32 nValue_term = aThread.getValue(); + + t_print(" value term = %d\n", (int) nValue_term); + + CPPUNIT_ASSERT_MESSAGE( + "Schedule: don't schedule in thread run method, terminate failed.", + nValue_term == 10 + ); + } + + CPPUNIT_TEST_SUITE(schedule); + CPPUNIT_TEST(schedule_001); + CPPUNIT_TEST(schedule_002); + CPPUNIT_TEST_SUITE_END(); + }; // class schedule + +// ----------------------------------------------------------------------------- + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Thread::create, "osl_Thread"); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Thread::createSuspended, "osl_Thread"); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Thread::suspend, "osl_Thread"); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Thread::resume, "osl_Thread"); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Thread::terminate, "osl_Thread"); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Thread::join, "osl_Thread"); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Thread::isRunning, "osl_Thread"); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Thread::setPriority, "osl_Thread"); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Thread::getPriority, "osl_Thread"); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Thread::getIdentifier, "osl_Thread"); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Thread::getCurrentIdentifier, "osl_Thread"); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Thread::wait, "osl_Thread"); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Thread::yield, "osl_Thread"); + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Thread::schedule, "osl_Thread"); +} // namespace osl_Thread + + +// ----------------------------------------------------------------------------- +// destroy function when the binding thread terminate +void SAL_CALL destroyCallback(void * data) +{ + delete[] (char *) data; +} + +static ThreadData myThreadData(destroyCallback); + +/** +*/ +class myKeyThread : public Thread +{ +public: + // a public char member for test result checking + char m_Char_Test; + // for pass thread-special data to thread + myKeyThread(const char cData) + { + m_nData = cData; + } +private: + char m_nData; + + void SAL_CALL run() + { + char * pc = new char[2]; +// strcpy(pc, &m_nData); + memcpy(pc, &m_nData, 1); + pc[1] = '\0'; + + myThreadData.setData(pc); + char* pData = (char*)myThreadData.getData(); + m_Char_Test = *pData; + // wait for long time to check the data value in main thread + ThreadHelper::thread_sleep_tenth_sec(3); + } +public: + ~myKeyThread() + { + if (isRunning()) + { + t_print("error: not terminated.\n"); + } + } +}; + +static ThreadData idData; + +class idThread: public Thread +{ +public: + oslThreadIdentifier m_Id; +private: + void SAL_CALL run() + { + oslThreadIdentifier* pId = new oslThreadIdentifier; + *pId = getIdentifier(); + idData.setData(pId); + oslThreadIdentifier* pIdData = (oslThreadIdentifier*)idData.getData(); + //t_print("Thread %d has Data %d\n", getIdentifier(), *pIdData); + m_Id = *pIdData; + delete pId; + } + +public: + ~idThread() + { + if (isRunning()) + { + t_print("error: not terminated.\n"); + } + } +}; + +namespace osl_ThreadData +{ + + class ctors : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + void setUp() + { + } + + void tearDown() + { + } + + // insert your test code here. + void ctor_001() + { + + } + + CPPUNIT_TEST_SUITE(ctors); + CPPUNIT_TEST(ctor_001); + CPPUNIT_TEST_SUITE_END(); + }; // class ctors + + + class setData : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + void setUp() + { + } + + void tearDown() + { + } + + /** the same instance of the class can have different values in different threads + */ + void setData_001() + { + idThread aThread1; + aThread1.create(); + idThread aThread2; + aThread2.create(); + + aThread1.join(); + aThread2.join(); + + oslThreadIdentifier aThreadId1 = aThread1.getIdentifier(); + oslThreadIdentifier aThreadId2 = aThread2.getIdentifier(); + + CPPUNIT_ASSERT_MESSAGE( + "ThreadData setData: ", + aThread1.m_Id == aThreadId1 && aThread2.m_Id == aThreadId2 + ); + + } + + void setData_002() + { + // at first, set the data a value + char* pc = new char[2]; + char m_nData = 'm'; +// LLA: this is a copy functions only and really only for \0 terminated strings +// m_nData is not a string, it's a character +// strcpy(pc, &m_nData); + memcpy(pc, &m_nData, 1); + pc[1] = '\0'; + + myThreadData.setData(pc); + + myKeyThread aThread1('a'); + aThread1.create(); + myKeyThread aThread2('b'); + aThread2.create(); + // aThread1 and aThread2 should have not terminated yet, check current data, not 'a' 'b' + char* pChar = (char*)myThreadData.getData(); + char aChar = *pChar; + + aThread1.join(); + aThread2.join(); + + // the saved thread data of aThread1 & aThread2, different + char cData1 = aThread1.m_Char_Test; + char cData2 = aThread2.m_Char_Test; + + CPPUNIT_ASSERT_MESSAGE( + "ThreadData setData: ", + cData1 == 'a' && cData2 == 'b' && aChar == 'm' + ); + + } + /** setData the second time, and then getData + */ + void setData_003() + { + // at first, set the data a value + char* pc = new char[2]; + char m_nData = 'm'; + memcpy(pc, &m_nData, 1); + pc[1] = '\0'; + myThreadData.setData(pc); + + myKeyThread aThread1('a'); + aThread1.create(); + myKeyThread aThread2('b'); + aThread2.create(); + // aThread1 and aThread2 should have not terminated yet + // setData the second time + char* pc2 = new char[2]; + m_nData = 'o'; + memcpy(pc2, &m_nData, 1); + pc2[1] = '\0'; + + myThreadData.setData(pc2); + char* pChar = (char*)myThreadData.getData(); + char aChar = *pChar; + + aThread1.join(); + aThread2.join(); + + // the saved thread data of aThread1 & aThread2, different + char cData1 = aThread1.m_Char_Test; + char cData2 = aThread2.m_Char_Test; + + CPPUNIT_ASSERT_MESSAGE( + "ThreadData setData: ", + cData1 == 'a' && cData2 == 'b' && aChar == 'o' + ); + + } + + CPPUNIT_TEST_SUITE(setData); + CPPUNIT_TEST(setData_001); + CPPUNIT_TEST(setData_002); + CPPUNIT_TEST(setData_003); + CPPUNIT_TEST_SUITE_END(); + }; // class setData + + class getData : public CppUnit::TestFixture + { + public: + // initialise your test code values here. + void setUp() + { + } + + void tearDown() + { + } + + // After setData in child threads, get Data in the main thread, should be independent + void getData_001() + { + char* pc = new char[2]; + char m_nData[] = "i"; + strcpy(pc, m_nData); + myThreadData.setData(pc); + + myKeyThread aThread1('c'); + aThread1.create(); + myKeyThread aThread2('d'); + aThread2.create(); + + aThread1.join(); + aThread2.join(); + + char cData1 = aThread1.m_Char_Test; + char cData2 = aThread2.m_Char_Test; + + char* pChar = (char*)myThreadData.getData(); + char aChar = *pChar; + + CPPUNIT_ASSERT_MESSAGE( + "ThreadData setData: ", + cData1 == 'c' && cData2 == 'd' && aChar == 'i' + ); + + } + + // setData then change the value in the address data pointer points, + // and then getData, should get the new value + void getData_002() + { + char* pc = new char[2]; + char m_nData = 'i'; + memcpy(pc, &m_nData, 1); + pc[1] = '\0'; + + myThreadData.setData(pc); + + myKeyThread aThread1('a'); + aThread1.create(); + myKeyThread aThread2('b'); + aThread2.create(); + + // change the value which pc points + char m_nData2 = 'j'; + memcpy(pc, &m_nData2, 1); + pc[1] = '\0'; + + void* pChar = myThreadData.getData(); + char aChar = *(char*)pChar; + + aThread1.join(); + aThread2.join(); + + char cData1 = aThread1.m_Char_Test; + char cData2 = aThread2.m_Char_Test; + + CPPUNIT_ASSERT_MESSAGE( + "ThreadData setData: ", + cData1 == 'a' && cData2 == 'b' && aChar == 'j' + ); + + } + + CPPUNIT_TEST_SUITE(getData); + CPPUNIT_TEST(getData_001); + CPPUNIT_TEST(getData_002); + CPPUNIT_TEST_SUITE_END(); + }; // class getData + +// ----------------------------------------------------------------------------- + CPPUNIT_TEST_SUITE_REGISTRATION(osl_ThreadData::ctors); + CPPUNIT_TEST_SUITE_REGISTRATION(osl_ThreadData::setData); + CPPUNIT_TEST_SUITE_REGISTRATION(osl_ThreadData::getData); +} // namespace osl_ThreadData + +// this macro creates an empty function, which will called by the RegisterAllFunctions() +// to let the user the possibility to also register some functions by hand. +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/process/osl_Thread.xsce b/sal/qa/osl/process/osl_Thread.xsce new file mode 100644 index 000000000000..42d9ef269178 --- /dev/null +++ b/sal/qa/osl/process/osl_Thread.xsce @@ -0,0 +1 @@ +osl_Thread.setPriority.setPriority_001_1 unxsols4 diff --git a/sal/qa/osl/process/osl_process.cxx b/sal/qa/osl/process/osl_process.cxx new file mode 100644 index 000000000000..1604a762c76f --- /dev/null +++ b/sal/qa/osl/process/osl_process.cxx @@ -0,0 +1,764 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> + +#define t_print printf + +#include <osl/process.h> +#include <osl/file.hxx> +#include <osl/thread.h> +#include <rtl/ustring.hxx> +#include <unistd.h> +#include <signal.h> + +#include <stdio.h> +#include <stdlib.h> +#include <osl/module.hxx> +#include <sal/macros.h> + +#if ( defined WNT ) // Windows +# include <windows.h> +# include <tchar.h> +#endif + +#include "rtl/allocator.hxx" + +#include <iostream> +#include <fstream> +#include <vector> +#include <algorithm> +#include <iterator> +#include <string> + +#ifdef UNX +#if defined( MACOSX ) +# include <crt_externs.h> +# define environ (*_NSGetEnviron()) +# else + extern char** environ; +# endif +#endif + +#if defined(WNT) || defined(OS2) + const rtl::OUString EXECUTABLE_NAME (RTL_CONSTASCII_USTRINGPARAM("osl_process_child.exe")); +#else + const rtl::OUString EXECUTABLE_NAME (RTL_CONSTASCII_USTRINGPARAM("osl_process_child")); +#endif + + +//######################################## +std::string OUString_to_std_string(const rtl::OUString& oustr) +{ + rtl::OString ostr = rtl::OUStringToOString(oustr, osl_getThreadTextEncoding()); + return std::string(ostr.getStr()); +} + +//######################################## +using namespace osl; + +using ::rtl::OUString; +using ::rtl::OUStringToOString; +using ::rtl::OString; + +/** print a UNI_CODE String. +*/ +inline void printUString( const ::rtl::OUString & str ) +{ + rtl::OString aString; + + t_print("#printUString_u# " ); + aString = ::rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US ); + t_print("%s\n", aString.getStr( ) ); +} + +/** get binary Path. +*/ +inline ::rtl::OUString getExecutablePath( void ) +{ + ::rtl::OUString dirPath; + osl::Module::getUrlFromAddress( ( void* ) &getExecutablePath, dirPath ); + dirPath = dirPath.copy( 0, dirPath.lastIndexOf('/') ); + dirPath = dirPath.copy( 0, dirPath.lastIndexOf('/') + 1); + dirPath += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("bin")); + return dirPath; +} + +//rtl::OUString CWD = getExecutablePath(); + +//######################################## +class Test_osl_joinProcess : public CppUnit::TestFixture +{ + const OUString join_param_; + const OUString wait_time_; + OUString suCWD; + OUString suExecutableFileURL; + + rtl_uString* parameters_[2]; + int parameters_count_; + +public: + + Test_osl_joinProcess() : + join_param_(OUString(RTL_CONSTASCII_USTRINGPARAM("-join"))), + wait_time_(OUString(RTL_CONSTASCII_USTRINGPARAM("1"))), + parameters_count_(2) + { + parameters_[0] = join_param_.pData; + parameters_[1] = wait_time_.pData; + suCWD = getExecutablePath(); + suExecutableFileURL = suCWD; + suExecutableFileURL += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/")); + suExecutableFileURL += EXECUTABLE_NAME; + } + + /*------------------------------------- + Start a process and join with this + process specify a timeout so that + osl_joinProcessWithTimeout returns + osl_Process_E_TimedOut + -------------------------------------*/ + + void osl_joinProcessWithTimeout_timeout_failure() + { + oslProcess process; + oslProcessError osl_error = osl_executeProcess( + suExecutableFileURL.pData, + parameters_, + parameters_count_, + osl_Process_NORMAL, + osl_getCurrentSecurity(), + suCWD.pData, + NULL, + 0, + &process); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_createProcess failed", + osl_error == osl_Process_E_None + ); + + TimeValue timeout; + timeout.Seconds = 1; + timeout.Nanosec = 0; + + osl_error = osl_joinProcessWithTimeout(process, &timeout); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_joinProcessWithTimeout returned without timeout failure", + osl_Process_E_TimedOut == osl_error + ); + + osl_error = osl_terminateProcess(process); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_terminateProcess failed", + osl_error == osl_Process_E_None + ); + + osl_freeProcessHandle(process); + } + + /*------------------------------------- + Start a process and join with this + process specify a timeout so that + osl_joinProcessWithTimeout returns + osl_Process_E_None + -------------------------------------*/ + + void osl_joinProcessWithTimeout_without_timeout_failure() + { + oslProcess process; + oslProcessError osl_error = osl_executeProcess( + suExecutableFileURL.pData, + parameters_, + parameters_count_, + osl_Process_NORMAL, + osl_getCurrentSecurity(), + suCWD.pData, + NULL, + 0, + &process); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_createProcess failed", + osl_error == osl_Process_E_None + ); + + TimeValue timeout; + timeout.Seconds = 10; + timeout.Nanosec = 0; + + osl_error = osl_joinProcessWithTimeout(process, &timeout); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_joinProcessWithTimeout returned with failure", + osl_Process_E_None == osl_error + ); + + osl_freeProcessHandle(process); + } + + /*------------------------------------- + Start a process and join with this + process specify an infinite timeout + -------------------------------------*/ + + void osl_joinProcessWithTimeout_infinite() + { + oslProcess process; + oslProcessError osl_error = osl_executeProcess( + suExecutableFileURL.pData, + parameters_, + parameters_count_, + osl_Process_NORMAL, + osl_getCurrentSecurity(), + suCWD.pData, + NULL, + 0, + &process); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_createProcess failed", + osl_error == osl_Process_E_None + ); + + osl_error = osl_joinProcessWithTimeout(process, NULL); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_joinProcessWithTimeout returned with failure", + osl_Process_E_None == osl_error + ); + + osl_freeProcessHandle(process); + } + + /*------------------------------------- + Start a process and join with this + process using osl_joinProcess + -------------------------------------*/ + + void osl_joinProcess() + { + oslProcess process; + oslProcessError osl_error = osl_executeProcess( + suExecutableFileURL.pData, + parameters_, + parameters_count_, + osl_Process_NORMAL, + osl_getCurrentSecurity(), + suCWD.pData, + NULL, + 0, + &process); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_createProcess failed", + osl_error == osl_Process_E_None + ); + + osl_error = ::osl_joinProcess(process); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_joinProcess returned with failure", + osl_Process_E_None == osl_error + ); + + osl_freeProcessHandle(process); + } + + CPPUNIT_TEST_SUITE(Test_osl_joinProcess); + CPPUNIT_TEST(osl_joinProcessWithTimeout_timeout_failure); + CPPUNIT_TEST(osl_joinProcessWithTimeout_without_timeout_failure); + CPPUNIT_TEST(osl_joinProcessWithTimeout_infinite); + CPPUNIT_TEST(osl_joinProcess); + CPPUNIT_TEST_SUITE_END(); +}; + +//######################################################### + +typedef std::vector<std::string, rtl::Allocator<std::string> > string_container_t; +typedef string_container_t::const_iterator string_container_const_iter_t; +typedef string_container_t::iterator string_container_iter_t; + +//######################################################### +class exclude : public std::unary_function<std::string, bool> +{ +public: + //------------------------------------------------ + exclude(const string_container_t& exclude_list) + { + string_container_const_iter_t iter = exclude_list.begin(); + string_container_const_iter_t iter_end = exclude_list.end(); + for (/**/; iter != iter_end; ++iter) + exclude_list_.push_back(env_var_name(*iter)); + } + + //------------------------------------------------ + bool operator() (const std::string& env_var) const + { + return (exclude_list_.end() != + std::find( + exclude_list_.begin(), + exclude_list_.end(), + env_var_name(env_var))); + } + +private: + //------------------------------------------------- + // extract the name from an environment variable + // that is given in the form "NAME=VALUE" + std::string env_var_name(const std::string& env_var) const + { + std::string::size_type pos_equal_sign = + env_var.find_first_of("="); + + if (std::string::npos != pos_equal_sign) + return std::string(env_var, 0, pos_equal_sign); + + return std::string(); + } + +private: + string_container_t exclude_list_; +}; + +namespace +{ + class starts_with + : public std::unary_function<const std::string&, bool> + { + private: + const std::string m_rString; + public: + starts_with(const char *pString) : m_rString(pString) {} + bool operator()(const std::string &rEntry) const + { + return rEntry.find(m_rString) == 0; + } + }; + + void tidy_container(string_container_t &env_container) + { + //sort them because there are no guarantees to ordering + std::sort(env_container.begin(), env_container.end()); + //remove LD_PRELOAD because valgrind injects that into the + //parent process + env_container.erase(std::remove_if(env_container.begin(), env_container.end(), + starts_with("LD_PRELOAD=")), env_container.end()); + } +} + +#ifdef WNT + void read_parent_environment(string_container_t* env_container) + { + LPTSTR env = reinterpret_cast<LPTSTR>(GetEnvironmentStrings()); + LPTSTR p = env; + + while (size_t l = _tcslen(p)) + { + env_container->push_back(std::string(p)); + p += l + 1; + } + FreeEnvironmentStrings(env); + tidy_container(*env_container); + } +#else + void read_parent_environment(string_container_t* env_container) + { + for (int i = 0; NULL != environ[i]; i++) + env_container->push_back(std::string(environ[i])); + tidy_container(*env_container); + } +#endif + +//######################################################### +class Test_osl_executeProcess : public CppUnit::TestFixture +{ + const OUString env_param_; + + OUString temp_file_url_; + OUString temp_file_path_; + rtl_uString* parameters_[2]; + int parameters_count_; + OUString suCWD; + OUString suExecutableFileURL; + +public: + + //------------------------------------------------ + // ctor + Test_osl_executeProcess() : + env_param_(OUString(RTL_CONSTASCII_USTRINGPARAM("-env"))), + parameters_count_(2) + { + parameters_[0] = env_param_.pData; + suCWD = getExecutablePath(); + suExecutableFileURL = suCWD; + suExecutableFileURL += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/")); + suExecutableFileURL += EXECUTABLE_NAME; + } + + //------------------------------------------------ + virtual void setUp() + { + temp_file_path_ = create_temp_file(temp_file_url_); + parameters_[1] = temp_file_path_.pData; + } + + virtual void tearDown() + { + osl::File::remove(temp_file_url_); + } + + //------------------------------------------------ + OUString create_temp_file(OUString &temp_file_url) + { + FileBase::RC rc = FileBase::createTempFile(0, 0, &temp_file_url); + CPPUNIT_ASSERT_MESSAGE("createTempFile failed", FileBase::E_None == rc); + + OUString temp_file_path; + rc = FileBase::getSystemPathFromFileURL(temp_file_url, temp_file_path); + CPPUNIT_ASSERT_MESSAGE("getSystemPathFromFileURL failed", FileBase::E_None == rc); + + return temp_file_path; + } + + //------------------------------------------------ + void read_child_environment(string_container_t* env_container) + { + OString temp_file_name = OUStringToOString(OUString( + parameters_[1]), osl_getThreadTextEncoding()); + std::ifstream file(temp_file_name.getStr()); + + CPPUNIT_ASSERT_MESSAGE + ( + "I/O error, cannot open child environment file", + file.is_open() + ); + + std::string line; + while (std::getline(file, line, '\0')) + env_container->push_back(line); + tidy_container(*env_container); + } + + //------------------------------------------------ + // environment of the child process that was + // started. The child process writes his + // environment into a file + bool compare_environments() + { + string_container_t parent_env; + read_parent_environment(&parent_env); + + string_container_t child_env; + read_child_environment(&child_env); + + return ((parent_env.size() == child_env.size()) && + (std::equal(child_env.begin(), child_env.end(), parent_env.begin()))); + } + + //------------------------------------------------ + // compare the equal environment parts and the + // different part of the child environment + bool compare_merged_environments(const string_container_t& different_env_vars) + { + string_container_t parent_env; + read_parent_environment(&parent_env); + +#if OSL_DEBUG_LEVEL > 1 + for (string_container_t::const_iterator iter = parent_env.begin(), end = parent_env.end(); iter != end; ++iter) + std::cerr << "initially parent env: " << *iter << std::endl; +#endif + + //remove the environment variables that we have changed + //in the child environment from the read parent environment + parent_env.erase( + std::remove_if(parent_env.begin(), parent_env.end(), exclude(different_env_vars)), + parent_env.end()); + +#if OSL_DEBUG_LEVEL > 1 + for (string_container_t::const_iterator iter = parent_env.begin(), end = parent_env.end(); iter != end; ++iter) + std::cerr << "stripped parent env: " << *iter << std::endl; +#endif + + //read the child environment and exclude the variables that + //are different + string_container_t child_env; + read_child_environment(&child_env); + +#if OSL_DEBUG_LEVEL > 1 + for (string_container_t::const_iterator iter = child_env.begin(), end = child_env.end(); iter != end; ++iter) + std::cerr << "initial child env: " << *iter << std::endl; +#endif + //partition the child environment into the variables that + //are different to the parent environment (they come first) + //and the variables that should be equal between parent + //and child environment + string_container_iter_t iter_logical_end = + std::stable_partition(child_env.begin(), child_env.end(), exclude(different_env_vars)); + + string_container_t different_child_env_vars(child_env.begin(), iter_logical_end); + child_env.erase(child_env.begin(), iter_logical_end); + +#if OSL_DEBUG_LEVEL > 1 + for (string_container_t::const_iterator iter = child_env.begin(), end = child_env.end(); iter != end; ++iter) + std::cerr << "stripped child env: " << *iter << std::endl; +#endif + + bool common_env_size_equals = (parent_env.size() == child_env.size()); + bool common_env_content_equals = std::equal(child_env.begin(), child_env.end(), parent_env.begin()); + +#if OSL_DEBUG_LEVEL > 1 + for (string_container_t::const_iterator iter = different_env_vars.begin(), end = different_env_vars.end(); iter != end; ++iter) + std::cerr << "different should be: " << *iter << std::endl; +#endif + + +#if OSL_DEBUG_LEVEL > 1 + for (string_container_t::const_iterator iter = different_child_env_vars.begin(), end = different_child_env_vars.end(); iter != end; ++iter) + std::cerr << "different are: " << *iter << std::endl; +#endif + + bool different_env_size_equals = (different_child_env_vars.size() == different_env_vars.size()); + bool different_env_content_equals = + std::equal(different_env_vars.begin(), different_env_vars.end(), different_child_env_vars.begin()); + + return (common_env_size_equals && common_env_content_equals && + different_env_size_equals && different_env_content_equals); + } + + //------------------------------------------------ + // test that parent and child process have the + // same environment when osl_executeProcess will + // be called with out setting new environment + // variables + void osl_execProc_parent_equals_child_environment() + { + oslProcess process; + oslProcessError osl_error = osl_executeProcess( + suExecutableFileURL.pData, + parameters_, + parameters_count_, + osl_Process_NORMAL, + NULL, + suCWD.pData, + NULL, + 0, + &process); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_createProcess failed", + osl_error == osl_Process_E_None + ); + + osl_error = ::osl_joinProcess(process); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_joinProcess returned with failure", + osl_Process_E_None == osl_error + ); + + osl_freeProcessHandle(process); + + CPPUNIT_ASSERT_MESSAGE + ( + "Parent and child environment not equal", + compare_environments() + ); + } + + //------------------------------------------------ + #define ENV1 "PAT=a:\\" + #define ENV2 "PATHb=b:\\" + #define ENV3 "Patha=c:\\" + #define ENV4 "Patha=d:\\" + + void osl_execProc_merged_child_environment() + { + rtl_uString* child_env[4]; + OUString env1(RTL_CONSTASCII_USTRINGPARAM(ENV1)); + OUString env2(RTL_CONSTASCII_USTRINGPARAM(ENV2)); + OUString env3(RTL_CONSTASCII_USTRINGPARAM(ENV3)); + OUString env4(RTL_CONSTASCII_USTRINGPARAM(ENV4)); + + child_env[0] = env1.pData; + child_env[1] = env2.pData; + child_env[2] = env3.pData; + child_env[3] = env4.pData; + + oslProcess process; + oslProcessError osl_error = osl_executeProcess( + suExecutableFileURL.pData, + parameters_, + parameters_count_, + osl_Process_NORMAL, + NULL, + suCWD.pData, + child_env, + SAL_N_ELEMENTS(child_env), + &process); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_createProcess failed", + osl_error == osl_Process_E_None + ); + + osl_error = ::osl_joinProcess(process); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_joinProcess returned with failure", + osl_Process_E_None == osl_error + ); + + osl_freeProcessHandle(process); + + string_container_t different_child_env_vars; + different_child_env_vars.push_back(ENV1); + different_child_env_vars.push_back(ENV2); + different_child_env_vars.push_back(ENV4); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_execProc_merged_child_environment", + compare_merged_environments(different_child_env_vars) + ); + } + + void osl_execProc_test_batch() + { + oslProcess process; +#if defined(WNT) || defined(OS2) + rtl::OUString suBatch = suCWD + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/")) + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("batch.bat")); +#else + rtl::OUString suBatch = suCWD + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/")) + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("batch.sh")); +#endif + oslProcessError osl_error = osl_executeProcess( + suBatch.pData, + NULL, + 0, + osl_Process_NORMAL, + NULL, + suCWD.pData, + NULL, + 0, + &process); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_createProcess failed", + osl_error == osl_Process_E_None + ); + + osl_error = ::osl_joinProcess(process); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_joinProcess returned with failure", + osl_Process_E_None == osl_error + ); + + osl_freeProcessHandle(process); + } + + void osl_execProc_exe_name_in_argument_list() + { + rtl_uString* params[3]; + + params[0] = suExecutableFileURL.pData; + params[1] = env_param_.pData; + params[2] = temp_file_path_.pData; + oslProcess process; + oslProcessError osl_error = osl_executeProcess( + NULL, + params, + 3, + osl_Process_NORMAL, + NULL, + suCWD.pData, + NULL, + 0, + &process); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_createProcess failed", + osl_error == osl_Process_E_None + ); + + osl_error = ::osl_joinProcess(process); + + CPPUNIT_ASSERT_MESSAGE + ( + "osl_joinProcess returned with failure", + osl_Process_E_None == osl_error + ); + + osl_freeProcessHandle(process); + } + + CPPUNIT_TEST_SUITE(Test_osl_executeProcess); + //TODO: Repair these under windows. +#ifndef WNT + CPPUNIT_TEST(osl_execProc_parent_equals_child_environment); + CPPUNIT_TEST(osl_execProc_merged_child_environment); +#endif + ///TODO: Repair makefile to get the batch.sh, batch.bat copied to $(BIN) for test execution + // CPPUNIT_TEST(osl_execProc_test_batch); + ///TODO: Repair test (or tested function ;-) - test fails. + // CPPUNIT_TEST(osl_execProc_exe_name_in_argument_list); + CPPUNIT_TEST_SUITE_END(); +}; + +//##################################### +// register test suites +//CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(Test_osl_joinProcess, "Test_osl_joinProcess"); +CPPUNIT_TEST_SUITE_REGISTRATION(Test_osl_executeProcess); + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/process/osl_process_child.cxx b/sal/qa/osl/process/osl_process_child.cxx new file mode 100644 index 000000000000..91addf9c1659 --- /dev/null +++ b/sal/qa/osl/process/osl_process_child.cxx @@ -0,0 +1,127 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +//######################################## +// includes + +#if ( defined WNT ) // Windows +# define UNICODE +# define _UNICODE +# define WIN32_LEAN_AND_MEAN +# include <windows.h> +# include <tchar.h> +#else +# include <unistd.h> +#endif + +#include <stdio.h> +#include <stdlib.h> +#include <iostream> +#include <fstream> +#include <string.h> + +#include <rtl/ustring.hxx> + +#ifdef UNX +#if defined( MACOSX ) +# include <crt_externs.h> +# define environ (*_NSGetEnviron()) +# else + extern char** environ; +# endif +#endif + +//######################################## +// defines + +#ifdef WNT +# define SLEEP(t) (Sleep((t)*1000)) +#else +# define SLEEP(t) (sleep((t))) +#endif + +//######################################## +void wait_for_seconds(char* time) +{ + SLEEP(atoi(time)); +} + +//######################################## + +#ifdef WNT +//######################################## +void w_to_a(LPCTSTR _strW, LPSTR strA, DWORD size) +{ + LPCWSTR strW = reinterpret_cast<LPCWSTR>(_strW); + WideCharToMultiByte(CP_ACP, 0, strW, -1, strA, size, NULL, NULL); +} +//######################################## + void dump_env(char* file_path) + { + LPTSTR env = reinterpret_cast<LPTSTR>( + GetEnvironmentStrings()); + LPTSTR p = env; + + std::ofstream file(file_path); + + char buffer[32767]; + while (size_t l = _tcslen(reinterpret_cast<wchar_t*>(p))) + { + w_to_a(p, buffer, sizeof(buffer)); + file << buffer << '\0'; + p += l + 1; + } + FreeEnvironmentStrings(env); + } +#else + void dump_env(char* file_path) + { + std::ofstream file(file_path); + for (int i = 0; NULL != environ[i]; ++i) + file << environ[i] << '\0'; + } +#endif + +//######################################## +int main(int argc, char* argv[]) +{ + if (argc > 2) + { + if (0 == strcmp("-join", argv[1])) + wait_for_seconds(argv[2]); + else if (0 == strcmp("-env", argv[1])) + dump_env(argv[2]); + } + + return 0; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/profile/osl_old_testprofile.cxx b/sal/qa/osl/profile/osl_old_testprofile.cxx new file mode 100644 index 000000000000..f2695a3084c1 --- /dev/null +++ b/sal/qa/osl/profile/osl_old_testprofile.cxx @@ -0,0 +1,96 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// LLA: +// this file is converted to use with testshl2 +// original was placed in sal/test/textenc.cxx + + +// ----------------------------------------------------------------------------- +#include <stdio.h> +#include <osl/profile.h> +#include <sal/cppunit.h> + + +//================================================================================================== +// ----------------------------------------------------------------------------- +namespace osl_Profile +{ + class oldtests : public CppUnit::TestFixture + { + public: + void test_profile(); + + CPPUNIT_TEST_SUITE( oldtests ); + CPPUNIT_TEST( test_profile ); + CPPUNIT_TEST_SUITE_END( ); + }; + +void oldtests::test_profile(void) +{ + oslProfile hProfile; + rtl_uString* ustrProfileName=0; + rtl_uString* ustrProfileName2=0; + + rtl_uString_newFromAscii(&ustrProfileName,"//./tmp/soffice.ini"); + rtl_uString_newFromAscii(&ustrProfileName2,"//./tmp/not_existing_path/soffice.ini"); + + + // successful write + hProfile = osl_openProfile( ustrProfileName, 0 ); + if (hProfile != 0) + { + if (! osl_writeProfileBool( hProfile, "testsection", "testbool", 1 )) + printf( "### cannot write into init file!\n" ); + + osl_closeProfile( hProfile ); + } + + // unsuccessful write + hProfile = osl_openProfile( ustrProfileName2, 0 ); + if (hProfile != 0) + { + if (osl_writeProfileBool( hProfile, "testsection", "testbool", 1 )) + printf( "### unexpected success writing into test2.ini!\n" ); + + osl_closeProfile( hProfile ); + } + + rtl_uString_release(ustrProfileName); + rtl_uString_release(ustrProfileName2); +} + +} // namespace osl_Profile + +// ----------------------------------------------------------------------------- +CPPUNIT_TEST_SUITE_REGISTRATION( osl_Profile::oldtests ); + +// ----------------------------------------------------------------------------- +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/security/makefile.mk b/sal/qa/osl/security/makefile.mk new file mode 100755 index 000000000000..9fc442fc1daa --- /dev/null +++ b/sal/qa/osl/security/makefile.mk @@ -0,0 +1,64 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# <http://www.openoffice.org/license.html> +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +PRJ=..$/..$/.. + +PRJNAME=sal +TARGET=qa_osl_security + +ENABLE_EXCEPTIONS=TRUE + +# --- Settings ----------------------------------------------------- + +.INCLUDE : settings.mk + +CFLAGS+= $(LFS_CFLAGS) +CXXFLAGS+= $(LFS_CFLAGS) + +# BEGIN ---------------------------------------------------------------- +# auto generated Target:Security by codegen.pl +SHL1OBJS= \ + $(SLO)$/osl_Security.obj + +SHL1TARGET= osl_Security +SHL1STDLIBS= $(SALLIB) $(CPPUNITLIB) +.IF "$(GUI)" == "WNT" +SHL1STDLIBS+= $(ADVAPI32LIB) +.ENDIF + +SHL1IMPLIB= i$(SHL1TARGET) +SHL1DEF= $(MISC)$/$(SHL1TARGET).def + +DEF1NAME =$(SHL1TARGET) +SHL1VERSIONMAP= $(PRJ)$/qa$/export.map +# auto generated Target:Security +# END ------------------------------------------------------------------ + +# --- Targets ------------------------------------------------------ + +.INCLUDE : target.mk +.INCLUDE : $(PRJ)$/qa$/cppunit_local.mk diff --git a/sal/qa/osl/security/osl_Security.cxx b/sal/qa/osl/security/osl_Security.cxx new file mode 100644 index 000000000000..9025e8fd9b22 --- /dev/null +++ b/sal/qa/osl/security/osl_Security.cxx @@ -0,0 +1,700 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ + /************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +//------------------------------------------------------------------------ +// header file +//------------------------------------------------------------------------ +#ifdef WNT +#include <windows.h> +#endif +#include <osl_Security_Const.h> + +using namespace osl; +using namespace rtl; + + +//------------------------------------------------------------------------ +// helper functions and classes +//------------------------------------------------------------------------ + +/** print Boolean value. +*/ +inline void printBool( sal_Bool bOk ) +{ + //t_print("#printBool# " ); + ( sal_True == bOk ) ? t_print("TRUE!\n" ): t_print("FALSE!\n" ); +} + +/** print a UNI_CODE String. +*/ +inline void printUString( const ::rtl::OUString & str ) +{ + rtl::OString aString; + + //t_print("#printUString_u# " ); + aString = ::rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US ); + t_print("%s\n", aString.getStr( ) ); +} + + +//------------------------------------------------------------------------ +// test code start here +//------------------------------------------------------------------------ + +namespace osl_Security +{ + + /** testing the method: + Security() + */ + class ctors : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void ctors_001( ) + { + ::osl::Security aSec; + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: create a security its handle should not be NULL.", + aSec.getHandle( ) != NULL ); + } + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_001 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class ctors + + + /** testing the methods: + inline sal_Bool SAL_CALL logonUser(const ::rtl::OUString& strName, + const ::rtl::OUString& strPasswd); + inline sal_Bool SAL_CALL logonUser(const ::rtl::OUString & strName, + const ::rtl::OUString & strPasswd, + const ::rtl::OUString & strFileServer); + */ + class logonUser : public CppUnit::TestFixture + { + public: + sal_Bool bRes; + + void logonUser_user_pwd( ) + { + ::osl::Security aSec; + bRes = aSec.logonUser( aLogonUser, aLogonPasswd ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: check logon user through forwarded user name, pwd, passed in (UNX), failed in (W32).", + ( sal_True == bRes ) ); + } + + void logonUser_user_pwd_server( ) + { + ::osl::Security aSec; + bRes = aSec.logonUser( aLogonUser, aLogonPasswd, aFileServer ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: check logon user through forwarded user name, pwd and server name, failed in (UNX)(W32).", + ( sal_True == bRes ) ); + } + + + CPPUNIT_TEST_SUITE( logonUser ); + if ( !aStringForward.equals( aNullURL ) && aStringForward.indexOf( (sal_Unicode)' ' ) != -1 && ( aStringForward.indexOf( ( sal_Unicode ) ' ' ) == aStringForward.lastIndexOf( ( sal_Unicode ) ' ' ) ) ) + /// if user name and passwd are forwarded + { + CPPUNIT_TEST( logonUser_user_pwd ); + } + if ( !aStringForward.equals( aNullURL ) && aStringForward.indexOf( (sal_Unicode)' ' ) != -1 && ( aStringForward.indexOf( ( sal_Unicode ) ' ' ) != aStringForward.lastIndexOf( ( sal_Unicode ) ' ' ) ) ) + /// if user name and passwd and file server are forwarded + { + CPPUNIT_TEST( logonUser_user_pwd_server ); + } + CPPUNIT_TEST_SUITE_END( ); + }; // class logonUser + + + /** testing the method: + inline sal_Bool Security::getUserIdent( rtl::OUString& strIdent) const + */ + class getUserIdent : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void getUserIdent_001( ) + { + ::osl::Security aSec; + ::rtl::OUString strID; + bRes = aSec.getUserIdent( strID ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: get UserID and compare it with names got at the beginning of the test.", + ( sal_True == strUserID.equals( strID ) ) && ( sal_True == bRes )); + } + + CPPUNIT_TEST_SUITE( getUserIdent ); + CPPUNIT_TEST( getUserIdent_001 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class getUserIdent + + + /** testing the method: + inline sal_Bool SAL_CALL getUserName( ::rtl::OUString& strName) const; + */ + class getUserName : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void getUserName_001( ) + { + ::osl::Security aSec; +#ifdef WNT + ::rtl::OUString strName( strUserName ), strGetName; +#else + ::rtl::OUString strName( strUserName ), strGetName; +#endif + bRes = aSec.getUserName( strGetName ); + + sal_Int32 nPos = -1; + if (strName.getLength() > 0) + { + nPos = strGetName.indexOf(strName); + } + CPPUNIT_ASSERT_MESSAGE( "#test comment#: get UserName and compare it with names got at the beginning of the test.", + ( nPos >= 0 ) && ( sal_True == bRes ) ); + } + + CPPUNIT_TEST_SUITE( getUserName ); + CPPUNIT_TEST( getUserName_001 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class getUserName + + + + /** testing the method: + inline sal_Bool SAL_CALL getHomeDir( ::rtl::OUString& strDirectory) const; + */ + class getHomeDir : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void getHomeDir_001( ) + { + ::osl::Security aSec; + ::rtl::OUString strHome; + bRes = aSec.getHomeDir( strHome ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: getHomeDir and compare it with the info we get at the beginning.", + ( sal_True == strHomeDirectory.equals( strHome ) ) && ( sal_True == bRes ) ); + } + + CPPUNIT_TEST_SUITE( getHomeDir ); + CPPUNIT_TEST( getHomeDir_001 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class getHomeDir + + /** testing the method: + inline sal_Bool Security::getConfigDir( rtl::OUString& strDirectory ) const + */ + class getConfigDir : public CppUnit::TestFixture + { + public: + sal_Bool bRes, bRes1; + + void getConfigDir_001( ) + { + ::osl::Security aSec; + ::rtl::OUString strConfig; + bRes = aSec.getConfigDir( strConfig ); + + CPPUNIT_ASSERT_MESSAGE( "failed to find a ConfigDir!", + ( sal_True == bRes )); + } + + CPPUNIT_TEST_SUITE( getConfigDir ); + CPPUNIT_TEST( getConfigDir_001 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class getConfigDir + + /** testing the method: + inline sal_Bool SAL_CALL isAdministrator() const; + */ + class isAdministrator : public CppUnit::TestFixture + { + public: + sal_Bool bRes; + + void isAdministrator_001( ) + { + ::osl::Security aSec; + bRes = aSec.isAdministrator( ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: check if the user is administrator at beginning, compare here.", + bRes == isAdmin ); + } + + CPPUNIT_TEST_SUITE( isAdministrator ); + CPPUNIT_TEST( isAdministrator_001 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class isAdministrator + + /** testing the method: + inline oslSecurity getHandle() const; + */ + class getHandle : public CppUnit::TestFixture + { + public: + sal_Bool bRes; + + void getHandle_001( ) + { + ::osl::Security aSec; + bRes = aSec.isAdministrator( ) == osl_isAdministrator( aSec.getHandle( ) ); + + CPPUNIT_ASSERT_MESSAGE( "#test comment#: use getHandle function to call C API.", + bRes == sal_True ); + } + + CPPUNIT_TEST_SUITE( getHandle ); + CPPUNIT_TEST( getHandle_001 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class getHandle + + + class UserProfile : public CppUnit::TestFixture + { + public: + + void loadUserProfile( ) + { + ::osl::Security aSec; + sal_Bool bValue = osl_loadUserProfile(aSec.getHandle()); + + CPPUNIT_ASSERT_MESSAGE( "empty function.", bValue == sal_False ); + } + + void unloadUserProfile( ) + { + ::osl::Security aSec; + osl_unloadUserProfile(aSec.getHandle()); + CPPUNIT_ASSERT_MESSAGE( "empty function.", sal_True ); + } + + CPPUNIT_TEST_SUITE( UserProfile ); + CPPUNIT_TEST( loadUserProfile ); + CPPUNIT_TEST( unloadUserProfile ); + CPPUNIT_TEST_SUITE_END( ); + }; // class UserProfile + + class loginUserOnFileServer : public CppUnit::TestFixture + { + public: + + void loginUserOnFileServer_001( ) + { + rtl::OUString suUserName; + rtl::OUString suPassword; + rtl::OUString suFileServer; + ::osl::Security aSec; + oslSecurity pSec = aSec.getHandle(); + + oslSecurityError erg = osl_loginUserOnFileServer(suUserName.pData, suPassword.pData, suFileServer.pData, &pSec); + + CPPUNIT_ASSERT_MESSAGE( "empty function.", erg == osl_Security_E_UserUnknown ); + } + + CPPUNIT_TEST_SUITE( loginUserOnFileServer ); + CPPUNIT_TEST( loginUserOnFileServer_001 ); + CPPUNIT_TEST_SUITE_END( ); + }; // class loginUserOnFileServer + +// ----------------------------------------------------------------------------- +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Security::ctors); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Security::logonUser); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Security::getUserIdent); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Security::getUserName); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Security::getHomeDir); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Security::getConfigDir); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Security::isAdministrator); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Security::getHandle); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Security::UserProfile); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Security::loginUserOnFileServer); + +// ----------------------------------------------------------------------------- + +} // namespace osl_Security + + +/* This defines an own TestPlugIn implementation with an own initialize() + method that will be called after loading the PlugIn + */ +#include <cppunit/plugin/TestPlugInDefaultImpl.h> + +class MyTestPlugInImpl: public CPPUNIT_NS::TestPlugInDefaultImpl +{ + public: + MyTestPlugInImpl() {}; + void initialize( CPPUNIT_NS::TestFactoryRegistry *registry, + const CPPUNIT_NS::PlugInParameters ¶meters ); +}; + + +void MyTestPlugInImpl::initialize( CPPUNIT_NS::TestFactoryRegistry *, + const CPPUNIT_NS::PlugInParameters & parameters) +{ + /// start message + t_print("#Initializing ...\n" ); + t_print("#\n#logonUser function need root/Administrator account to test.\n" ); + t_print("#You can test by login with root/Administrator, and excute:\n" ); + t_print("#testshl2 -forward \"username password\" ../../../wntmsci9/bin/Security.dll\n" ); + t_print("# where username and password are forwarded account info.\n" ); + t_print("#if no text forwarded, this function will be skipped.\n" ); + + /// get system information +#if ( defined UNX ) || ( defined OS2 ) + /// some initialization work for UNIX OS + + + struct passwd* pw; + CPPUNIT_ASSERT_MESSAGE( "getpwuid: no password entry\n",( pw = getpwuid( getuid() ) ) != NULL ); + + /// get user ID; + strUserID = ::rtl::OUString::valueOf( ( sal_Int32 )getuid( ) ); + + /// get user Name; + strUserName = ::rtl::OUString::createFromAscii( pw->pw_name ); + + /// get home directory; + char *pw_dir = pw->pw_dir; + if( getenv( "FAKEROOTKEY" ) ) + pw_dir = getenv("HOME"); + CPPUNIT_ASSERT_MESSAGE( "#Convert from system path to URL failed.", + ::osl::File::E_None == ::osl::File::getFileURLFromSystemPath( ::rtl::OUString::createFromAscii( pw_dir ), strHomeDirectory ) ); + + /// get config directory; + strConfigDirectory = strHomeDirectory.copy(0); + + /// is administrator; + if( !getuid( ) ) + isAdmin = sal_True; + +#endif +#if defined ( WNT ) + /// some initialization work for Windows OS + + + /// Get the user name, computer name, user home directory. + LPTSTR lpszSystemInfo; // pointer to system information string + DWORD cchBuff = BUFSIZE; // size of computer or user name + TCHAR tchBuffer[BUFSIZE]; // buffer for string + + lpszSystemInfo = tchBuffer; + cchBuff = BUFSIZE; + if( GetUserNameA(lpszSystemInfo, &cchBuff) ) + strUserName = ::rtl::OUString::createFromAscii( lpszSystemInfo ); + + if( GetComputerName(lpszSystemInfo, &cchBuff) ) + strComputerName = ::rtl::OUString::createFromAscii( lpszSystemInfo ); + + /// Get user home directory. + HKEY hRegKey; + sal_Char PathA[_MAX_PATH]; + ::rtl::OUString strHome; + if (RegOpenKey(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", &hRegKey) == ERROR_SUCCESS) + { + LONG lRet, lSize = sizeof(PathA); + DWORD Type; + + lRet = RegQueryValueEx(hRegKey, "AppData", NULL, &Type, ( unsigned char * )PathA, ( unsigned long * )&lSize); + if ( ( lRet == ERROR_SUCCESS ) && ( Type == REG_SZ ) && ( _access( PathA, 0 ) == 0 ) ) + { + CPPUNIT_ASSERT_MESSAGE( "#Convert from system path to URL failed.", + ::osl::File::E_None == ::osl::File::getFileURLFromSystemPath( ::rtl::OUString::createFromAscii( PathA ), strConfigDirectory ) ); + } + + lRet = RegQueryValueEx(hRegKey, "Personal", NULL, &Type, ( unsigned char * )PathA, ( unsigned long * )&lSize); + if ( ( lRet == ERROR_SUCCESS ) && ( Type == REG_SZ ) && ( _access( PathA, 0 ) == 0 ) ) + { + CPPUNIT_ASSERT_MESSAGE( "#Convert from system path to URL failed.", + ::osl::File::E_None == ::osl::File::getFileURLFromSystemPath( ::rtl::OUString::createFromAscii( PathA ), strHomeDirectory ) ); + } + + RegCloseKey(hRegKey); + } + + + /// Get user Security ID: + + // Create buffers that may be large enough. If a buffer is too small, the count parameter will be set to the size needed. + const DWORD INITIAL_SIZE = 32; + DWORD cbSid = 0; + DWORD dwSidBufferSize = INITIAL_SIZE; + DWORD cchDomainName = 0; + DWORD dwDomainBufferSize = INITIAL_SIZE; + WCHAR * wszDomainName = NULL; + SID_NAME_USE eSidType; + DWORD dwErrorCode = 0; + + LPCWSTR wszAccName = ( LPWSTR ) strUserName.getStr( ); + + // Create buffers for the SID and the domain name. + PSID pSid = (PSID) new BYTE[dwSidBufferSize]; + CPPUNIT_ASSERT_MESSAGE("# creating SID buffer failed.\n", pSid!= NULL ); + memset( pSid, 0, dwSidBufferSize); + + wszDomainName = new WCHAR[dwDomainBufferSize]; + CPPUNIT_ASSERT_MESSAGE("# creating Domain name buffer failed.\n", wszDomainName != NULL ); + memset(wszDomainName, 0, dwDomainBufferSize*sizeof(WCHAR)); + + // Obtain the SID for the account name passed. + for ( ; ; ) + { + // Set the count variables to the buffer sizes and retrieve the SID. + cbSid = dwSidBufferSize; + cchDomainName = dwDomainBufferSize; + if (LookupAccountNameW( + NULL, // Computer name. NULL for the local computer + wszAccName, + pSid, // Pointer to the SID buffer. Use NULL to get the size needed, + &cbSid, // Size of the SID buffer needed. + wszDomainName, // wszDomainName, + &cchDomainName, + &eSidType + )) + { + if (IsValidSid( pSid) == FALSE) + wprintf(L"# The SID for %s is invalid.\n", wszAccName); + break; + } + dwErrorCode = GetLastError(); + + // Check if one of the buffers was too small. + if (dwErrorCode == ERROR_INSUFFICIENT_BUFFER) + { + if (cbSid > dwSidBufferSize) + { + // Reallocate memory for the SID buffer. + wprintf(L"# The SID buffer was too small. It will be reallocated.\n"); + FreeSid( pSid); + pSid = (PSID) new BYTE[cbSid]; + CPPUNIT_ASSERT_MESSAGE("# re-creating SID buffer failed.\n", pSid!= NULL ); + memset( pSid, 0, cbSid); + dwSidBufferSize = cbSid; + } + if (cchDomainName > dwDomainBufferSize) + { + // Reallocate memory for the domain name buffer. + wprintf(L"# The domain name buffer was too small. It will be reallocated.\n"); + delete [] wszDomainName; + wszDomainName = new WCHAR[cchDomainName]; + CPPUNIT_ASSERT_MESSAGE("# re-creating domain name buffer failed.\n", wszDomainName!= NULL ); + memset(wszDomainName, 0, cchDomainName*sizeof(WCHAR)); + dwDomainBufferSize = cchDomainName; + } + } + else + { + wprintf(L"# LookupAccountNameW failed. GetLastError returned: %d\n", dwErrorCode); + break; + } + } + + // now got SID successfully, only need to compare SID, so I copied the rest lines from source to convert SID to OUString. + PSID_IDENTIFIER_AUTHORITY psia; + DWORD dwSubAuthorities; + DWORD dwSidRev=SID_REVISION; + DWORD dwCounter; + DWORD dwSidSize; + sal_Char *Ident; + + /* obtain SidIdentifierAuthority */ + psia=GetSidIdentifierAuthority(pSid); + + /* obtain sidsubauthority count */ + dwSubAuthorities=*GetSidSubAuthorityCount(pSid)<=5?*GetSidSubAuthorityCount(pSid):5; + + /* buffer length: S-SID_REVISION- + identifierauthority- + subauthorities- + NULL */ + Ident=(sal_Char * )malloc(88*sizeof(sal_Char)); + + /* prepare S-SID_REVISION- */ + dwSidSize=wsprintf(Ident, TEXT("S-%lu-"), dwSidRev); + + /* prepare SidIdentifierAuthority */ + if ((psia->Value[0] != 0) || (psia->Value[1] != 0)) + { + dwSidSize+=wsprintf(Ident + strlen(Ident), + TEXT("0x%02hx%02hx%02hx%02hx%02hx%02hx"), + (sal_uInt16)psia->Value[0], + (sal_uInt16)psia->Value[1], + (sal_uInt16)psia->Value[2], + (sal_uInt16)psia->Value[3], + (sal_uInt16)psia->Value[4], + (sal_uInt16)psia->Value[5]); + } + else + { + dwSidSize+=wsprintf(Ident + strlen(Ident), + TEXT("%lu"), + (sal_uInt32)(psia->Value[5] ) + + (sal_uInt32)(psia->Value[4] << 8) + + (sal_uInt32)(psia->Value[3] << 16) + + (sal_uInt32)(psia->Value[2] << 24) ); + } + + /* loop through SidSubAuthorities */ + for (dwCounter=0; dwCounter < dwSubAuthorities; dwCounter++) + { + dwSidSize+=wsprintf(Ident + dwSidSize, TEXT("-%lu"), + *GetSidSubAuthority(pSid, dwCounter) ); + } + + strUserID = ::rtl::OUString::createFromAscii( Ident ); + + free(Ident); + delete pSid; + delete [] wszDomainName; + + + /// check if logged in user is administrator: + + BOOL b; + SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY; + PSID AdministratorsGroup; + b = AllocateAndInitializeSid( + &NtAuthority, + 2, + SECURITY_BUILTIN_DOMAIN_RID, + DOMAIN_ALIAS_RID_ADMINS, + 0, 0, 0, 0, 0, 0, + &AdministratorsGroup); + if(b) + { + if (!CheckTokenMembership( NULL, AdministratorsGroup, &b)) + { + b = FALSE; + } + FreeSid(AdministratorsGroup); + } + + isAdmin = ( sal_Bool )b; + +#endif + + /// print the information. + t_print("#\n#Retrived system information is below:\n"); + + t_print("Computer Name: "); + if ( strComputerName == aNullURL ) + t_print("Not retrived\n" ); + else + printUString( strComputerName ); + + t_print("Current User Name: "); + if ( strUserName == aNullURL ) + t_print("Not retrived\n" ); + else + printUString( strUserName ); + + t_print("Current User Home Directory:"); + if ( strHomeDirectory == aNullURL ) + t_print("Not retrived\n" ); + else + printUString( strHomeDirectory ); + + t_print("Current Config Directory: "); + if ( strConfigDirectory == aNullURL ) + t_print("Not retrived\n" ); + else + printUString( strConfigDirectory ); + + t_print("Current UserID: "); + if ( strUserID == aNullURL ) + t_print("Not retrived\n" ); + else + printUString( strUserID ); + + t_print("Current User is: "); + if ( isAdmin == sal_False ) + t_print("NOT Administrator.\n" ); + else + t_print("Administrator.\n" ); + + /// get and display forwarded text if available. + aStringForward = ::rtl::OUString::createFromAscii( parameters.getCommandLine().c_str() ); + if ( !aStringForward.equals( aNullURL ) && aStringForward.indexOf( (sal_Unicode)' ' ) != -1 ) + { + sal_Int32 nFirstSpacePoint = aStringForward.indexOf( (sal_Unicode)' ' );; + sal_Int32 nLastSpacePoint = aStringForward.lastIndexOf( (sal_Unicode)' ' );; + if ( nFirstSpacePoint == nLastSpacePoint ) + /// only forwarded two parameters, username and password. + { + aLogonUser = aStringForward.copy( 0, nFirstSpacePoint ); + t_print("\n#Forwarded username: "); + printUString( aLogonUser); + + aLogonPasswd = aStringForward.copy( nFirstSpacePoint +1, aStringForward.getLength( ) - 1 ); + t_print("#Forwarded password: "); + for ( int i = nFirstSpacePoint +1; i <= aStringForward.getLength( ) - 1; i++, t_print("*") ); + t_print("\n" ); + } + else + /// forwarded three parameters, username, password and fileserver. + { + aLogonUser = aStringForward.copy( 0, nFirstSpacePoint ); + t_print("#Forwarded username: "); + printUString( aLogonUser); + + aLogonPasswd = aStringForward.copy( nFirstSpacePoint +1, nLastSpacePoint ); + t_print("#Forwarded password: "); + for ( int i = nFirstSpacePoint +1; i <= nLastSpacePoint; i++, t_print("*") ); + t_print("\n" ); + + aFileServer = aStringForward.copy( nLastSpacePoint +1, aStringForward.getLength( ) - 1 ); + t_print("#Forwarded FileServer: "); + printUString( aFileServer ); + + } + } + + t_print("#\n#Initialization Done.\n" ); + +} + +/* Instantiate and register the own TestPlugIn and instantiate the default + main() function. + (This is done by CPPUNIT_PLUGIN_IMPLEMENT() for TestPlugInDefaultImpl) + */ + +CPPUNIT_PLUGIN_EXPORTED_FUNCTION_IMPL( MyTestPlugInImpl ); +CPPUNIT_PLUGIN_IMPLEMENT_MAIN(); + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/security/osl_Security_Const.h b/sal/qa/osl/security/osl_Security_Const.h new file mode 100644 index 000000000000..e05018baa50d --- /dev/null +++ b/sal/qa/osl/security/osl_Security_Const.h @@ -0,0 +1,77 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _OSL_SECURITY_CONST_H_ +#define _OSL_SECURITY_CONST_H_ + +#if ( defined WNT ) // Windows +#include <io.h> +#endif + +#include <sal/types.h> +#include <rtl/ustring.hxx> +#include <osl/file.hxx> +#include <osl/security.hxx> + +#include <stdlib.h> +#include <stdio.h> + +#if ( defined UNX ) || ( defined OS2 ) +#include <unistd.h> +#include <pwd.h> +#endif + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> +#include <cppunit/plugin/TestPlugInDefaultImpl.h> + +#define t_print printf + +#define BUFSIZE 1024 +const char pTestString[17] = "Sun Microsystems"; + + +#define OSLTEST_DECLARE_USTRING( str_name, str_value ) \ + ::rtl::OUString a##str_name = rtl::OUString::createFromAscii( str_value ) + +//------------------------------------------------------------------------ +// condition names +//------------------------------------------------------------------------ +OSLTEST_DECLARE_USTRING( TestSec, "testsecurity" ); +OSLTEST_DECLARE_USTRING( NullURL, "" ); + +::rtl::OUString aLogonUser( aNullURL ), aLogonPasswd( aNullURL ), aFileServer( aNullURL ), aStringForward( aNullURL ); +::rtl::OUString strUserName( aNullURL ) , strComputerName( aNullURL ) , strHomeDirectory( aNullURL ); +::rtl::OUString strConfigDirectory( aNullURL ), strUserID( aNullURL ); + +sal_Bool isAdmin = sal_False; + +#endif /* _OSL_SECURITY_CONST_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/setthreadname/test-setthreadname.cxx b/sal/qa/osl/setthreadname/test-setthreadname.cxx new file mode 100644 index 000000000000..b969ad511913 --- /dev/null +++ b/sal/qa/osl/setthreadname/test-setthreadname.cxx @@ -0,0 +1,83 @@ +/************************************************************************* +* +* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +* +* Copyright 2000, 2011 Oracle and/or its affiliates. +* +* OpenOffice.org - a multi-platform office productivity suite +* +* This file is part of OpenOffice.org. +* +* OpenOffice.org is free software: you can redistribute it and/or modify +* it under the terms of the GNU Lesser General Public License version 3 +* only, as published by the Free Software Foundation. +* +* OpenOffice.org is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU Lesser General Public License version 3 for more details +* (a copy is included in the LICENSE file that accompanied this code). +* +* You should have received a copy of the GNU Lesser General Public License +* version 3 along with OpenOffice.org. If not, see +* <http://www.openoffice.org/license.html> +* for a copy of the LGPLv3 License. +* +************************************************************************/ + +#include "sal/config.h" +#include <sal/cppunit.h> + +#include <cstdlib> +#include <iostream> +#include <limits> + +#include "boost/noncopyable.hpp" +#include "osl/thread.hxx" + +namespace { + +class TestThread: public osl::Thread, private boost::noncopyable { +private: + virtual void SAL_CALL run(); +}; + +void TestThread::run() { +#if defined WNT + if (std::getenv("URE_TEST_SETTHREADNAME") != 0) { + // On Windows, setting thread names appears to only take effect when the + // process is being debugged, so attach a debugger now: + std::cout << "set: "; + std::cin.ignore(std::numeric_limits< int >::max(), '\n'); + } +#endif + setName("TestThread"); + if (std::getenv("URE_TEST_SETTHREADNAME") != 0) { + // On Linux, the thread name can now be observed with "ps -L"; on + // Windows with the Microsoft compiler, the thread name can now be + // observed in a debugger. + std::cout << "stop: "; + std::cin.ignore(std::numeric_limits< int >::max(), '\n'); + } +} + +class Test: public CppUnit::TestFixture { +private: + CPPUNIT_TEST_SUITE(Test); + CPPUNIT_TEST(test); + CPPUNIT_TEST_SUITE_END(); + + void test(); +}; + +void Test::test() { + TestThread t; + t.create(); + t.join(); +} + +CPPUNIT_TEST_SUITE_REGISTRATION(Test); + +} + +CPPUNIT_PLUGIN_IMPLEMENT(); diff --git a/sal/qa/osl/setthreadname/version.map b/sal/qa/osl/setthreadname/version.map new file mode 100644 index 000000000000..ef2ab497cb5e --- /dev/null +++ b/sal/qa/osl/setthreadname/version.map @@ -0,0 +1,34 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2000, 2011 Oracle and/or its affiliates. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# <http://www.openoffice.org/license.html> +# for a copy of the LGPLv3 License. +# +#***********************************************************************/ + +UDK_3_0_0 { + global: + cppunitTestPlugIn; + + local: + *; +}; diff --git a/sal/qa/osl/socket/export.exp b/sal/qa/osl/socket/export.exp new file mode 100755 index 000000000000..a13529da5876 --- /dev/null +++ b/sal/qa/osl/socket/export.exp @@ -0,0 +1 @@ +registerAllTestFunction diff --git a/sal/qa/osl/socket/makefile.mk b/sal/qa/osl/socket/makefile.mk new file mode 100755 index 000000000000..cdc268a2402a --- /dev/null +++ b/sal/qa/osl/socket/makefile.mk @@ -0,0 +1,223 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# <http://www.openoffice.org/license.html> +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +PRJ=..$/..$/.. + +PRJNAME=sal +TARGET=qa_osl_socket + +ENABLE_EXCEPTIONS=TRUE + +# --- Settings ----------------------------------------------------- + +.INCLUDE : settings.mk + +CFLAGS+= $(LFS_CFLAGS) +CXXFLAGS+= $(LFS_CFLAGS) + +# BEGIN ---------------------------------------------------------------- +# auto generated Target:Socket by codegen.pl +SHL1OBJS= \ + $(SLO)$/osl_Socket.obj + +SHL1TARGET=osl_SocketOld +SHL1STDLIBS= $(SALLIB) $(CPPUNITLIB) + +.IF "$(GUI)" == "WNT" +SHL1STDLIBS+= $(WS2_32LIB) +.ENDIF + +.IF "$(GUI)" == "UNX" +SHL1STDLIBS+= -ldl -lnsl +.ENDIF + +SHL1IMPLIB= i$(SHL1TARGET) +# SHL1DEF= $(MISC)$/$(SHL1TARGET).def +DEF1NAME=$(SHL1TARGET) +# DEF1EXPORTFILE= export.exp +SHL1VERSIONMAP = $(PRJ)$/qa$/export.map +# auto generated Target:Socket +# END ------------------------------------------------------------------ + +# --- BEGIN -------------------------------------------------------- +SHL2OBJS= \ + $(SLO)$/osl_Socket_tests.obj +SHL2TARGET= osl_Socket_tests +SHL2STDLIBS= $(SALLIB) $(CPPUNITLIB) + +SHL2IMPLIB= i$(SHL2TARGET) +DEF2NAME= $(SHL2TARGET) +SHL2VERSIONMAP = $(PRJ)$/qa$/export.map + +# END -------------------------------------------------------------- + +# BEGIN ---------------------------------------------------------------- +# auto generated Target:Socket by codegen.pl +SHL3OBJS= \ + $(SLO)$/sockethelper.obj \ + $(SLO)$/osl_StreamSocket.obj + +SHL3TARGET= osl_StreamSocket +SHL3STDLIBS= $(SALLIB) $(CPPUNITLIB) + +.IF "$(GUI)" == "WNT" +SHL3STDLIBS += $(WS2_32LIB) +.ENDIF + +.IF "$(GUI)" == "UNX" +SHL3STDLIBS += -ldl -lnsl +.ENDIF + +SHL3IMPLIB= i$(SHL3TARGET) +DEF3NAME= $(SHL3TARGET) +SHL3VERSIONMAP = $(PRJ)$/qa$/export.map +# auto generated Target:Socket +# END ------------------------------------------------------------------ + +# BEGIN ---------------------------------------------------------------- +# auto generated Target:Socket by codegen.pl +SHL4OBJS= \ + $(SLO)$/sockethelper.obj \ + $(SLO)$/osl_DatagramSocket.obj + +SHL4TARGET= osl_DatagramSocket +SHL4STDLIBS= $(SALLIB) $(CPPUNITLIB) + +.IF "$(GUI)" == "WNT" +SHL4STDLIBS += $(WS2_32LIB) +.ENDIF + +.IF "$(GUI)" == "UNX" +SHL4STDLIBS += -ldl -lnsl +.ENDIF + +SHL4IMPLIB= i$(SHL4TARGET) +DEF4NAME= $(SHL4TARGET) +SHL4VERSIONMAP = $(PRJ)$/qa$/export.map +# auto generated Target:Socket +# END ------------------------------------------------------------------ + +# BEGIN ---------------------------------------------------------------- +# auto generated Target:Socket by codegen.pl +SHL5OBJS= \ + $(SLO)$/sockethelper.obj \ + $(SLO)$/osl_SocketAddr.obj + +SHL5TARGET= osl_SocketAddr +SHL5STDLIBS= $(SALLIB) $(CPPUNITLIB) + +.IF "$(GUI)" == "WNT" +SHL5STDLIBS += $(WS2_32LIB) +.ENDIF + +.IF "$(GUI)" == "UNX" +SHL5STDLIBS += -ldl -lnsl +.ENDIF + +SHL5IMPLIB= i$(SHL5TARGET) +DEF5NAME= $(SHL5TARGET) +SHL5VERSIONMAP = $(PRJ)$/qa$/export.map +# auto generated Target:Socket +# END ------------------------------------------------------------------ + +# BEGIN ---------------------------------------------------------------- +# auto generated Target:Socket by codegen.pl +SHL6OBJS= \ + $(SLO)$/sockethelper.obj \ + $(SLO)$/osl_Socket2.obj + +SHL6TARGET= osl_Socket2 +SHL6STDLIBS= $(SALLIB) $(CPPUNITLIB) + +.IF "$(GUI)" == "WNT" +SHL6STDLIBS += $(WS2_32LIB) +.ENDIF + +.IF "$(GUI)" == "UNX" +SHL6STDLIBS += -ldl -lnsl +.ENDIF + +SHL6IMPLIB= i$(SHL6TARGET) +DEF6NAME= $(SHL6TARGET) +SHL6VERSIONMAP = $(PRJ)$/qa$/export.map +# auto generated Target:Socket +# END ------------------------------------------------------------------ + +# BEGIN ---------------------------------------------------------------- +# auto generated Target:Socket by codegen.pl +SHL7OBJS= \ + $(SLO)$/sockethelper.obj \ + $(SLO)$/osl_ConnectorSocket.obj + +SHL7TARGET= osl_ConnectorSocket +SHL7STDLIBS= $(SALLIB) $(CPPUNITLIB) + +.IF "$(GUI)" == "WNT" +SHL7STDLIBS += $(WS2_32LIB) +.ENDIF + +.IF "$(GUI)" == "UNX" +SHL7STDLIBS += -ldl -lnsl +.ENDIF + +SHL7IMPLIB= i$(SHL7TARGET) +DEF7NAME= $(SHL7TARGET) +SHL7VERSIONMAP = $(PRJ)$/qa$/export.map +# auto generated Target:Socket +# END ------------------------------------------------------------------ + +# BEGIN ---------------------------------------------------------------- +# auto generated Target:Socket by codegen.pl +SHL8OBJS= \ + $(SLO)$/sockethelper.obj \ + $(SLO)$/osl_AcceptorSocket.obj + +SHL8TARGET= osl_AcceptorSocket +SHL8STDLIBS= $(SALLIB) $(CPPUNITLIB) + +.IF "$(GUI)" == "WNT" +SHL8STDLIBS += $(WS2_32LIB) +.ENDIF + +.IF "$(GUI)" == "UNX" +SHL8STDLIBS += -ldl -lnsl +.ENDIF + +SHL8IMPLIB= i$(SHL8TARGET) +DEF8NAME= $(SHL8TARGET) +SHL8VERSIONMAP = $(PRJ)$/qa$/export.map +# auto generated Target:Socket +# END ------------------------------------------------------------------ + +#------------------------------- All object files ------------------------------- +# do this here, so we get right dependencies +# SLOFILES=$(SHL1OBJS) $(SHL2OBJS) + +# --- Targets ------------------------------------------------------ + +.INCLUDE : target.mk +.INCLUDE : $(PRJ)$/qa$/cppunit_local.mk diff --git a/sal/qa/osl/socket/osl_AcceptorSocket.cxx b/sal/qa/osl/socket/osl_AcceptorSocket.cxx new file mode 100644 index 000000000000..a648e475a725 --- /dev/null +++ b/sal/qa/osl/socket/osl_AcceptorSocket.cxx @@ -0,0 +1,266 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +/** test coder preface: + 1. the BSD socket function will meet "unresolved external symbol error" on Windows platform + if you are not including ws2_32.lib in makefile.mk, the including format will be like this: + + .IF "$(GUI)" == "WNT" + SHL1STDLIBS += $(SOLARLIBDIR)$/cppunit.lib + SHL1STDLIBS += ws2_32.lib + .ENDIF + + likewise on Solaris platform. + .IF "$(GUI)" == "UNX" + SHL1STDLIBS+=$(SOLARLIBDIR)$/libcppunit$(DLLPOSTFIX).a + SHL1STDLIBS += -lsocket -ldl -lnsl + .ENDIF + + 2. since the Socket implementation of osl is only IPv4 oriented, our test are mainly focus on IPv4 + category. + + 3. some fragment of Socket source implementation are lack of comment so it is hard for testers + guess what the exact functionality or usage of a member. Hope the Socket section's comment + will be added. + + 4. following functions are declared but not implemented: + inline sal_Bool SAL_CALL operator== (const SocketAddr & Addr) const; + */ + +//------------------------------------------------------------------------ +// include files +//------------------------------------------------------------------------ + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> + +#include "osl_Socket_Const.h" +#include "sockethelper.hxx" + +using namespace osl; +using ::rtl::OUString; + +#define IP_PORT_FTP 21 +#define IP_PORT_MYPORT9 8897 +#define IP_PORT_MYPORT4 8885 +#define IP_PORT_MYPORT3 8884 + +//------------------------------------------------------------------------ +// helper functions +//------------------------------------------------------------------------ + +// just used to test socket::close() when accepting +class AcceptorThread : public Thread +{ + ::osl::AcceptorSocket asAcceptorSocket; + ::rtl::OUString aHostIP; + sal_Bool bOK; +protected: + void SAL_CALL run( ) + { + ::osl::SocketAddr saLocalSocketAddr( aHostIP, IP_PORT_MYPORT9 ); + ::osl::StreamSocket ssStreamConnection; + + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //integer not sal_Bool : sal_True); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + if ( sal_True != bOK1 ) + { + t_print("# AcceptorSocket bind address failed.\n" ) ; + return; + } + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + if ( sal_True != bOK2 ) + { + t_print("# AcceptorSocket listen address failed.\n" ) ; + return; + } + + asAcceptorSocket.enableNonBlockingMode( sal_False ); + + oslSocketResult eResult = asAcceptorSocket.acceptConnection( ssStreamConnection ); + if (eResult != osl_Socket_Ok ) + { + bOK = sal_True; + t_print("AcceptorThread: acceptConnection failed! \n"); + } + } +public: + AcceptorThread(::osl::AcceptorSocket & asSocket, ::rtl::OUString const& aBindIP ) + : asAcceptorSocket( asSocket ), aHostIP( aBindIP ) + { + bOK = sal_False; + } + + sal_Bool isOK() { return bOK; } + + ~AcceptorThread( ) + { + if ( isRunning( ) ) + { + asAcceptorSocket.shutdown(); + t_print("# error: Acceptor thread not terminated.\n" ); + } + } +}; + +namespace osl_AcceptorSocket +{ + + /** testing the methods: + inline AcceptorSocket(oslAddrFamily Family = osl_Socket_FamilyInet, + oslProtocol Protocol = osl_Socket_ProtocolIp, + oslSocketType Type = osl_Socket_TypeStream); + */ + + class ctors : public CppUnit::TestFixture + { + public: + + void ctors_001() + { + /// Socket constructor. + ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors_001 constructor function: check if the acceptor socket was created successfully.", + osl_Socket_TypeStream == asSocket.getType( ) ); + } + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class ctors + + /** testing the method: + inline sal_Bool SAL_CALL listen(sal_Int32 MaxPendingConnections= -1); + inline oslSocketResult SAL_CALL acceptConnection( StreamSocket& Connection); + inline oslSocketResult SAL_CALL acceptConnection( StreamSocket& Connection, SocketAddr & PeerAddr); + */ + + class listen_accept : public CppUnit::TestFixture + { + public: + TimeValue *pTimeout; + ::osl::AcceptorSocket asAcceptorSocket; + ::osl::ConnectorSocket csConnectorSocket; + + + // initialization + void setUp( ) + { + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 3; + pTimeout->Nanosec = 0; + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1); + // sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + free( pTimeout ); + // sHandle = NULL; + asAcceptorSocket.close( ); + csConnectorSocket.close( ); + } + + + void listen_accept_001() + { + ::osl::SocketAddr saLocalSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT3 ); + ::osl::SocketAddr saTargetSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT3 ); + ::osl::StreamSocket ssConnection; + + /// launch server socket + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + asAcceptorSocket.enableNonBlockingMode( sal_True ); + + /// launch client socket + csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... + + oslSocketResult eResult = asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... + + CPPUNIT_ASSERT_MESSAGE( "test for listen_accept function: try to create a connection with remote host, using listen and accept.", + ( osl_Socket_Ok == eResult ) ); + } + + void listen_accept_002() + { + ::osl::SocketAddr saLocalSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT4 ); + ::osl::SocketAddr saTargetSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT4 ); + ::osl::SocketAddr saPeerSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.202")), IP_PORT_FTP ); + ::osl::StreamSocket ssConnection; + + /// launch server socket + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + asAcceptorSocket.enableNonBlockingMode( sal_True ); + + /// launch client socket + csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... + + oslSocketResult eResult = asAcceptorSocket.acceptConnection(ssConnection, saPeerSocketAddr); /// waiting for incoming connection... + + CPPUNIT_ASSERT_MESSAGE( "test for listen_accept function: try to create a connection with remote host, using listen and accept, accept with peer address.", + ( sal_True == bOK2 ) && + ( osl_Socket_Ok == eResult ) && + ( sal_True == compareSocketAddr( saPeerSocketAddr, saLocalSocketAddr ) ) ); + } + + + CPPUNIT_TEST_SUITE( listen_accept ); + CPPUNIT_TEST( listen_accept_001 ); + CPPUNIT_TEST( listen_accept_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class listen_accept + + +// ----------------------------------------------------------------------------- + +CPPUNIT_TEST_SUITE_REGISTRATION(osl_AcceptorSocket::ctors); +//CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_AcceptorSocket::operator_assign, "osl_AcceptorSocket"); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_AcceptorSocket::listen_accept); + +} // namespace osl_AcceptorSocket + +// ----------------------------------------------------------------------------- + +// this macro creates an empty function, which will called by the RegisterAllFunctions() +// to let the user the possibility to also register some functions by hand. +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/socket/osl_ConnectorSocket.cxx b/sal/qa/osl/socket/osl_ConnectorSocket.cxx new file mode 100644 index 000000000000..bf47ea327928 --- /dev/null +++ b/sal/qa/osl/socket/osl_ConnectorSocket.cxx @@ -0,0 +1,269 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +/** test coder preface: + 1. the BSD socket function will meet "unresolved external symbol error" on Windows platform + if you are not including ws2_32.lib in makefile.mk, the including format will be like this: + + .IF "$(GUI)" == "WNT" + SHL1STDLIBS += $(SOLARLIBDIR)$/cppunit.lib + SHL1STDLIBS += ws2_32.lib + .ENDIF + + likewise on Solaris platform. + .IF "$(GUI)" == "UNX" + SHL1STDLIBS+=$(SOLARLIBDIR)$/libcppunit$(DLLPOSTFIX).a + SHL1STDLIBS += -lsocket -ldl -lnsl + .ENDIF + + 2. since the Socket implementation of osl is only IPv4 oriented, our test are mainly focus on IPv4 + category. + + 3. some fragment of Socket source implementation are lack of comment so it is hard for testers + guess what the exact functionality or usage of a member. Hope the Socket section's comment + will be added. + + 4. following functions are declared but not implemented: + inline sal_Bool SAL_CALL operator== (const SocketAddr & Addr) const; + */ + +//------------------------------------------------------------------------ +// include files +//------------------------------------------------------------------------ + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> + +#include "osl_Socket_Const.h" +#include "sockethelper.hxx" + +using namespace osl; +using ::rtl::OUString; + +#define IP_PORT_MYPORT2 8883 +#define IP_PORT_FTP 21 +#define IP_PORT_MYPORT3 8884 + +//------------------------------------------------------------------------ +// helper functions +//------------------------------------------------------------------------ + +class CloseSocketThread : public Thread +{ + ::osl::Socket &m_sSocket; +protected: + void SAL_CALL run( ) + { + thread_sleep( 1 ); + m_sSocket.close( ); + } +public: + CloseSocketThread(::osl::Socket & sSocket ) + : m_sSocket( sSocket ) + { + } + + ~CloseSocketThread( ) + { + if ( isRunning( ) ) + { + t_print("# error: CloseSocketThread not terminated.\n" ); + } + } +}; + +namespace osl_ConnectorSocket +{ + + /** testing the method: + ConnectorSocket(oslAddrFamily Family = osl_Socket_FamilyInet, + oslProtocol Protocol = osl_Socket_ProtocolIp, + oslSocketType Type = osl_Socket_TypeStream); + */ + + class ctors : public CppUnit::TestFixture + { + public: + void ctors_001() + { + /// Socket constructor. + ::osl::ConnectorSocket csSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors_001 constructor function: check if the connector socket was created successfully.", + osl_Socket_TypeStream == csSocket.getType( ) ); + } + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class ctors + + /** testing the method: + oslSocketResult SAL_CALL connect(const SocketAddr& TargetHost, const TimeValue* pTimeout = 0); + */ + + class connect : public CppUnit::TestFixture + { + public: + TimeValue *pTimeout; + ::osl::AcceptorSocket asAcceptorSocket; + ::osl::ConnectorSocket csConnectorSocket; + + + // initialization + void setUp( ) + { + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 3; + pTimeout->Nanosec = 0; + // sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + free( pTimeout ); + // sHandle = NULL; + asAcceptorSocket.close( ); + csConnectorSocket.close( ); + } + + + void connect_001() + { + ::osl::SocketAddr saLocalSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT2 ); + ::osl::SocketAddr saTargetSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT2 ); + ::osl::SocketAddr saPeerSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.202")), IP_PORT_FTP ); + ::osl::StreamSocket ssConnection; + + /// launch server socket + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + + //asAcceptorSocket.enableNonBlockingMode( sal_True ); + //oslSocketResult eResultAccept = asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... + //CPPUNIT_ASSERT_MESSAGE( "accept failed.", osl_Socket_Ok == eResultAccept ); + /// launch client socket + oslSocketResult eResult = csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... + CPPUNIT_ASSERT_MESSAGE( "connect failed.", osl_Socket_Ok == eResult ); + + /// get peer information + csConnectorSocket.getPeerAddr( saPeerSocketAddr );/// connected. + + CPPUNIT_ASSERT_MESSAGE( "test for connect function: try to create a connection with remote host. and check the setup address.", + ( sal_True == compareSocketAddr( saPeerSocketAddr, saLocalSocketAddr ) ) && + ( osl_Socket_Ok == eResult )); + } + //non-blocking mode connect? + void connect_002() + { + ::osl::SocketAddr saLocalSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT3 ); + ::osl::SocketAddr saTargetSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT3 ); + ::osl::SocketAddr saPeerSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.202")), IP_PORT_FTP ); + + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + asAcceptorSocket.enableNonBlockingMode( sal_True ); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + + csConnectorSocket.enableNonBlockingMode( sal_True ); + + oslSocketResult eResult = csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... + CPPUNIT_ASSERT_MESSAGE( "connect failed.", osl_Socket_InProgress == eResult || osl_Socket_Ok == eResult ); + + /// get peer information + csConnectorSocket.getPeerAddr( saPeerSocketAddr ); + + CPPUNIT_ASSERT_MESSAGE( "test for connect function: try to create a connection with remote host. and check the setup address.", + sal_True == compareSocketAddr( saPeerSocketAddr, saLocalSocketAddr ) ) ; + } + // really an error or just delayed + // how to design senarios that will return osl_Socket_Interrupted, osl_Socket_TimedOut + void connect_003() + { + ::osl::SocketAddr saTargetSocketAddr1( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT3 ); + ::osl::SocketAddr saTargetSocketAddr2( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("123.345.67.89")), IP_PORT_MYPORT3 ); + + csConnectorSocket.enableNonBlockingMode( sal_False ); + + oslSocketResult eResult1 = csConnectorSocket.connect( saTargetSocketAddr1, pTimeout ); + oslSocketResult eResult2 = csConnectorSocket.connect( saTargetSocketAddr2, pTimeout ); + CloseSocketThread myCloseThread( csConnectorSocket ); + oslSocketResult eResult3 = csConnectorSocket.connect( saTargetSocketAddr2, pTimeout ); + myCloseThread.join(); + CPPUNIT_ASSERT_MESSAGE( "connect should failed.", osl_Socket_Error == eResult1 && + osl_Socket_Error == eResult2 && osl_Socket_Error == eResult3 ); + + } + + // really an error in non-blocking mode + void connect_004() + { + ::osl::SocketAddr saTargetSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("123.345.67.89")), IP_PORT_MYPORT3 ); + + csConnectorSocket.enableNonBlockingMode( sal_True ); + + oslSocketResult eResult = csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... + CPPUNIT_ASSERT_MESSAGE( "connect should failed.", osl_Socket_Error == eResult ); + } + /** here need a case: immediate connection, say in non-blocking mode connect return osl_Socket_Ok + */ + + CPPUNIT_TEST_SUITE( connect ); + CPPUNIT_TEST( connect_001 ); + CPPUNIT_TEST( connect_002 ); + CPPUNIT_TEST( connect_003 ); + CPPUNIT_TEST( connect_004 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class connect + + +// ----------------------------------------------------------------------------- + +CPPUNIT_TEST_SUITE_REGISTRATION(osl_ConnectorSocket::ctors); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_ConnectorSocket::connect); + +} // namespace osl_ConnectorSocket + +// ----------------------------------------------------------------------------- + +// this macro creates an empty function, which will called by the RegisterAllFunctions() +// to let the user the possibility to also register some functions by hand. +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/socket/osl_ConnectorSocket.xsce b/sal/qa/osl/socket/osl_ConnectorSocket.xsce new file mode 100644 index 000000000000..6c04ae2eb6f3 --- /dev/null +++ b/sal/qa/osl/socket/osl_ConnectorSocket.xsce @@ -0,0 +1 @@ +osl_ConnectorSocket.connect.connect_003 wntmsci diff --git a/sal/qa/osl/socket/osl_DatagramSocket.cxx b/sal/qa/osl/socket/osl_DatagramSocket.cxx new file mode 100644 index 000000000000..111c690439fe --- /dev/null +++ b/sal/qa/osl/socket/osl_DatagramSocket.cxx @@ -0,0 +1,320 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +/** test coder preface: + 1. the BSD socket function will meet "unresolved external symbol error" on Windows platform + if you are not including ws2_32.lib in makefile.mk, the including format will be like this: + + .IF "$(GUI)" == "WNT" + SHL1STDLIBS += $(SOLARLIBDIR)$/cppunit.lib + SHL1STDLIBS += ws2_32.lib + .ENDIF + + likewise on Solaris platform. + .IF "$(GUI)" == "UNX" + SHL1STDLIBS+=$(SOLARLIBDIR)$/libcppunit$(DLLPOSTFIX).a + SHL1STDLIBS += -lsocket -ldl -lnsl + .ENDIF + + 2. since the Socket implementation of osl is only IPv4 oriented, our test are mainly focus on IPv4 + category. + + 3. some fragment of Socket source implementation are lack of comment so it is hard for testers + guess what the exact functionality or usage of a member. Hope the Socket section's comment + will be added. + + 4. following functions are declared but not implemented: + inline sal_Bool SAL_CALL operator== (const SocketAddr & Addr) const; + */ + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> + +#include "sockethelper.hxx" + +using namespace osl; + +using ::rtl::OUString; + +#define IP_PORT_MYPORT9 8897 +#define IP_PORT_MYPORT10 8898 + +const char * pTestString1 = "test socket"; +const char * pTestString2 = " Passed#OK"; + +//------------------------------------------------------------------------ +// helper functions +//------------------------------------------------------------------------ + +class CloseSocketThread : public Thread +{ + ::osl::Socket m_sSocket; +protected: + void SAL_CALL run( ) + { + thread_sleep( 1 ); + m_sSocket.close( ); + } +public: + CloseSocketThread(::osl::Socket & sSocket ) + : m_sSocket( sSocket ) + { + } + + ~CloseSocketThread( ) + { + if ( isRunning( ) ) + { + t_print("# error: CloseSocketThread not terminated.\n" ); + } + } +}; + +//------------------------------------------------------------------------ +// tests cases begins here +//------------------------------------------------------------------------ + +namespace osl_DatagramSocket +{ + + /** testing the methods: + inline DatagramSocket(oslAddrFamily Family= osl_Socket_FamilyInet, + oslProtocol Protocol= osl_Socket_ProtocolIp, + oslSocketType Type= osl_Socket_TypeDgram); + */ + + class ctors : public CppUnit::TestFixture + { + public: + + void ctors_001() + { + /// Socket constructor. + ::osl::DatagramSocket dsSocket; + + CPPUNIT_ASSERT_MESSAGE( "test for ctors_001 constructor function: check if the datagram socket was created successfully.", + osl_Socket_TypeDgram == dsSocket.getType( ) ); + } + + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class ctors + +/**thread do sendTo, refer to http://www.coding-zone.co.uk/cpp/articles/140101networkprogrammingv.shtml +*/ +class TalkerThread : public Thread +{ +protected: + ::osl::SocketAddr saTargetSocketAddr; + ::osl::DatagramSocket dsSocket; + + void SAL_CALL run( ) + { + dsSocket.sendTo( saTargetSocketAddr, pTestString1, strlen( pTestString1 ) + 1 ); // "test socket" + dsSocket.shutdown(); + } + + void SAL_CALL onTerminated( ) + { + } + +public: + TalkerThread( ): + saTargetSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT9 ) + { + } + + ~TalkerThread( ) + { + if ( isRunning( ) ) + t_print("# error: TalkerThread not terminated normally.\n" ); + } +}; + +/**thread do listen, refer to http://www.coding-zone.co.uk/cpp/articles/140101networkprogrammingv.shtml +*/ +class ListenerThread : public Thread +{ +protected: + ::osl::SocketAddr saTargetSocketAddr; + ::osl::DatagramSocket dsSocket; + + void SAL_CALL run( ) + { + ::osl::SocketAddr saLocalSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT10 ); + dsSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); + if ( dsSocket.bind( saLocalSocketAddr ) == sal_False ) + { + t_print("DatagramSocket bind failed \n"); + return; + } + //blocking mode: default +#if !SILENT_TEST + sal_Int32 nRecv = +#endif + dsSocket.recvFrom( pRecvBuffer, 30, &saTargetSocketAddr); //strlen( pTestString2 ) + 1 + t_print("After recvFrom, nRecv is %d\n", (int) nRecv); + } + + void SAL_CALL onTerminated( ) + { + } + +public: + sal_Char pRecvBuffer[30]; + ListenerThread( ): + saTargetSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT10 ) + { + pRecvBuffer[0] = '\0'; + } + + ~ListenerThread( ) + { + if ( isRunning( ) ) + t_print("# error: ListenerThread not terminated normally.\n" ); + } + +}; + + /** testing the methods: + inline sal_Int32 DatagramSocket::recvFrom(void* pBuffer, sal_uInt32 BufferSize, + SocketAddr* pSenderAddr, oslSocketMsgFlag Flag ) + inline sal_Int32 DatagramSocket::sendTo( const SocketAddr& ReceiverAddr, + const void* pBuffer, sal_uInt32 BufferSize, oslSocketMsgFlag Flag ) + */ + + class sendTo_recvFrom : public CppUnit::TestFixture + { + public: + + void sr_001() + { + ::osl::SocketAddr saLocalSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT9 ); + ::osl::DatagramSocket dsSocket; + dsSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); + dsSocket.bind( saLocalSocketAddr ); + + sal_Char pReadBuffer[30]; + TalkerThread myTalkThread; + myTalkThread.create(); + sal_Int32 nRecv = dsSocket.recvFrom( pReadBuffer, 30, &saLocalSocketAddr); + myTalkThread.join(); + //t_print("#received buffer is %s# \n", pReadBuffer); + + sal_Bool bOk = ( strcmp(pReadBuffer, pTestString1) == 0 ); + + CPPUNIT_ASSERT_MESSAGE( "test for sendTo/recvFrom function: create a talker thread and recvFrom in the main thread, check if the datagram socket can communicate successfully.", + nRecv > 0 && bOk == sal_True ); + } + + void sr_002() + { + ::osl::SocketAddr saListenSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT10 ); + ::osl::DatagramSocket dsSocket; + + //listener thread construct a DatagramSocket, recvFrom waiting for data, then main thread sendto data + ListenerThread myListenThread; + myListenThread.create(); + //to grantee the recvFrom is before sendTo + thread_sleep( 1 ); + + sal_Int32 nSend = dsSocket.sendTo( saListenSocketAddr, pTestString2, strlen( pTestString2 ) + 1 ); + + CPPUNIT_ASSERT_MESSAGE( "DatagramSocket sendTo failed: nSend <= 0.", nSend > 0); + + myListenThread.join(); + //t_print("#received buffer is %s# \n", myListenThread.pRecvBuffer); + + sal_Bool bOk = ( strcmp( myListenThread.pRecvBuffer, pTestString2) == 0 ); + + CPPUNIT_ASSERT_MESSAGE( "test for sendTo/recvFrom function: create a listener thread and sendTo in the main thread, check if the datagram socket can communicate successfully.", + bOk == sal_True ); + } + + //sendTo error, return -1; recvFrom error, return -1 + void sr_003() + { + ::osl::SocketAddr saListenSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("123.345.67.89")), IP_PORT_MYPORT10 ); + ::osl::DatagramSocket dsSocket; + // Transport endpoint is not connected + sal_Int32 nSend = dsSocket.sendTo( saListenSocketAddr, pTestString2, strlen( pTestString2 ) + 1 ); + CPPUNIT_ASSERT_MESSAGE( "DatagramSocket sendTo should fail: nSend <= 0.", + nSend == -1 ); + } + + void sr_004() + { + ::osl::SocketAddr saListenSocketAddr1( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("123.345.67.89")), IP_PORT_MYPORT10 ); + ::osl::SocketAddr saListenSocketAddr2( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.202")), IP_PORT_MYPORT10 ); + ::osl::DatagramSocket dsSocket; + + dsSocket.enableNonBlockingMode( sal_True ); + + sal_Char pReadBuffer[30]; + //sal_Int32 nRecv1 = dsSocket.recvFrom( pReadBuffer, 30, &saListenSocketAddr1 ); + + // will block ? + CloseSocketThread myThread( dsSocket ); + myThread.create(); + sal_Int32 nRecv2 = dsSocket.recvFrom( pReadBuffer, 30, &saListenSocketAddr1 ); + myThread.join(); + //t_print("#nRecv1 is %d nRecv2 is %d\n", nRecv1, nRecv2 ); + CPPUNIT_ASSERT_MESSAGE( "DatagramSocket sendTo should fail: nSend <= 0.", + nRecv2 == -1 ); + } + + CPPUNIT_TEST_SUITE( sendTo_recvFrom ); + CPPUNIT_TEST( sr_001 ); + CPPUNIT_TEST( sr_002 ); + CPPUNIT_TEST( sr_003 ); + CPPUNIT_TEST( sr_004 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class sendTo_recvFrom + +// ----------------------------------------------------------------------------- + +CPPUNIT_TEST_SUITE_REGISTRATION(osl_DatagramSocket::ctors); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_DatagramSocket::sendTo_recvFrom); + +} // namespace osl_DatagramSocket + +// ----------------------------------------------------------------------------- + +// this macro creates an empty function, which will called by the RegisterAllFunctions() +// to let the user the possibility to also register some functions by hand. +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/socket/osl_Socket.cxx b/sal/qa/osl/socket/osl_Socket.cxx new file mode 100644 index 000000000000..47ae4d0cef32 --- /dev/null +++ b/sal/qa/osl/socket/osl_Socket.cxx @@ -0,0 +1,3720 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +/** test coder preface: + 1. the BSD socket function will meet "unresolved external symbol error" on Windows platform + if you are not including ws2_32.lib in makefile.mk, the including format will be like this: + + .IF "$(GUI)" == "WNT" + SHL1STDLIBS += $(SOLARLIBDIR)$/cppunit.lib + SHL1STDLIBS += ws2_32.lib + .ENDIF + + likewise on Solaris platform. + .IF "$(GUI)" == "UNX" + SHL1STDLIBS+=$(SOLARLIBDIR)$/libcppunit$(DLLPOSTFIX).a + SHL1STDLIBS += -lsocket -ldl -lnsl + .ENDIF + + 2. since the Socket implementation of osl is only IPv4 oriented, our test are mainly focus on IPv4 + category. + + 3. some fragment of Socket source implementation are lack of comment so it is hard for testers + guess what the exact functionality or usage of a member. Hope the Socket section's comment + will be added. + + 4. following functions are declared but not implemented: + inline sal_Bool SAL_CALL operator== (const SocketAddr & Addr) const; + */ + + +//------------------------------------------------------------------------ +// include files +//------------------------------------------------------------------------ + +#include <osl_Socket_Const_orig.h> + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> + +/** test output if SILENT_TEST is 0 +*/ +#if OSL_DEBUG_LEVEL > 0 +# define SILENT_TEST 0 +#else +# define SILENT_TEST 1 +#endif + +#if SILENT_TEST +# define t_print(...) { } +#else +# define t_print printf +#endif + +/** convert UString and OUString to std::string +*/ +#define STD_STRING(s) (std::string((const char *)s.getStr())) + +using namespace osl; + +using ::rtl::OUString; +using ::rtl::OUStringToOString; +using ::rtl::OString; + +//------------------------------------------------------------------------ +// helper functions +//------------------------------------------------------------------------ + +/** compare two OUString. +*/ +inline sal_Bool compareUString( const ::rtl::OUString & ustr1, const ::rtl::OUString & ustr2 ) +{ + sal_Bool bOk = ustr1.equalsIgnoreAsciiCase( ustr2 ); + + return bOk; +} + +/** compare a OUString and an ASCII string. +*/ +inline sal_Bool compareUString( const ::rtl::OUString & ustr, const sal_Char *astr ) +{ + ::rtl::OUString ustr2 = rtl::OUString::createFromAscii( astr ); + sal_Bool bOk = ustr.equalsIgnoreAsciiCase( ustr2 ); + + return bOk; +} + +/** compare two socket address. +*/ +inline sal_Bool compareSocketAddr( const ::osl::SocketAddr & addr1 , const ::osl::SocketAddr & addr2 ) +{ + return ( ( sal_True == compareUString( addr1.getHostname( 0 ), addr2.getHostname( 0 ) ) ) && ( addr2.getPort( ) == addr2.getPort( ) ) ); +} + +inline char * oustring2char( const ::rtl::OUString & str ) +{ + rtl::OString aString; + aString = ::rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US ); + return (char *)aString.getStr( ); +} + +/** print a UNI_CODE String. And also print some comments of the string. +*/ +inline void printUString( const ::rtl::OUString & str, const sal_Char * msg = "" ) +{ +#if SILENT_TEST + (void)str; + (void)msg; +#else + t_print("#%s #printUString_u# ", msg ); + t_print("%s\n", oustring2char( str ) ); +#endif +} + +/** get the local host name. + mindy: gethostbyname( "localhost" ), on Linux, it returns the hostname in /etc/hosts + domain name, + if no entry in /etc/hosts, it returns "localhost" + domain name +*/ +inline ::rtl::OUString getHost( void ) +{ + struct hostent *hptr; + + hptr = gethostbyname( "localhost" ); + CPPUNIT_ASSERT_MESSAGE( "#In getHostname function, error on gethostbyname()", hptr != NULL ); + ::rtl::OUString aUString = ::rtl::OUString::createFromAscii( (const sal_Char *) hptr->h_name ); + + return aUString; +} + +/** get the full host name of the current processor, such as "aegean.prc.sun.com" --mindyliu +*/ +inline ::rtl::OUString getThisHostname( void ) +{ + ::rtl::OUString aUString; +#ifdef WNT + struct hostent *hptr; + hptr = gethostbyname( "localhost" ); + CPPUNIT_ASSERT_MESSAGE( "#In getHostname function, error on gethostbyname()", hptr != NULL ); + aUString = ::rtl::OUString::createFromAscii( (const sal_Char *) hptr->h_name ); +#else + char hostname[255]; + CPPUNIT_ASSERT_MESSAGE( "#Error: gethostname failed.", gethostname(hostname, 255) == 0 ); + + struct hostent *hptr; + //first search /ets/hosts, then search from dns + hptr = gethostbyname( hostname); + if ( hptr != NULL ) + { + strcpy( hostname, hptr->h_name ); + } + + t_print("hostname is %s \n", hostname ); + aUString = ::rtl::OUString::createFromAscii( (const sal_Char *) hostname ); +#endif + return aUString; +} + +/** get IP by name, search /etc/hosts first, then search from dns, fail return OUString("") +*/ +inline ::rtl::OUString getIPbyName( rtl::OString const& str_name ) +{ + ::rtl::OUString aUString; + struct hostent *hptr; + //first search /ets/hosts, then search from dns + hptr = gethostbyname( str_name.getStr()); + if ( hptr != NULL ) + { + struct in_addr ** addrptr; + addrptr = (struct in_addr **) hptr->h_addr_list ; + //if there are more than one IPs on the same machine, we select one + for (; *addrptr; addrptr++) + { + t_print("#Local IP Address: %s\n", inet_ntoa(**addrptr)); + aUString = ::rtl::OUString::createFromAscii( (sal_Char *) (inet_ntoa(**addrptr)) ); + } + } + return aUString; +} + +/** get local ethernet IP +*/ +inline ::rtl::OUString getLocalIP( ) +{ + char hostname[255]; + gethostname(hostname, 255); + + return getIPbyName( hostname ); +} + +/** construct error message +*/ +inline ::rtl::OUString outputError( const ::rtl::OUString & returnVal, const ::rtl::OUString & rightVal, const sal_Char * msg = "") +{ + ::rtl::OUString aUString; + if ( returnVal.equals( rightVal ) ) + return aUString; + aUString += ::rtl::OUString::createFromAscii(msg); + aUString += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(": the returned value is '")); + aUString += returnVal; + aUString += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("', but the value should be '")); + aUString += rightVal; + aUString += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("'.")); + return aUString; +} + +/** wait _nSec seconds. +*/ +void thread_sleep( sal_Int32 _nSec ) +{ + /// print statement in thread process must use fflush() to force display. + t_print("# wait %d seconds. ", (int) _nSec ); + fflush(stdout); + +#ifdef WNT //Windows + Sleep( _nSec * 100 ); +#endif +#if ( defined UNX ) || ( defined OS2 ) //Unix + usleep(_nSec * 100000); +#endif + t_print("# done\n" ); +} + +/** print Boolean value. +*/ +inline void printBool( sal_Bool bOk ) +{ +#if SILENT_TEST + (void)bOk; +#else + t_print("#printBool# " ); + t_print ("%s", (sal_True == bOk) ? "YES!\n" : "NO!\n"); +#endif +} + +/** print content of a ByteSequence. +*/ +inline void printByteSequence_IP( const ::rtl::ByteSequence & bsByteSeq, sal_Int32 nLen ) +{ +#if SILENT_TEST + (void)bsByteSeq; + (void)nLen; +#else + t_print("#ByteSequence is: " ); + for ( int i = 0; i < nLen; i++ ){ + if ( bsByteSeq[i] < 0 ) + t_print("%d ", 256 + bsByteSeq[i] ); + else + t_print("%d ", bsByteSeq[i] ); + } + t_print(" .\n" ); +#endif +} + +/** convert an IP which is stored as a UString format to a ByteSequence array for later use. +*/ +inline ::rtl::ByteSequence UStringIPToByteSequence( ::rtl::OUString aUStr ) +{ + + rtl::OString aString = ::rtl::OUStringToOString( aUStr, RTL_TEXTENCODING_ASCII_US ); + const sal_Char *pChar = aString.getStr( ) ; + sal_Char tmpBuffer[4]; + sal_Int32 nCharCounter = 0; + ::rtl::ByteSequence bsByteSequence( IP_VER ); + sal_Int32 nByteSeqCounter = 0; + + for ( int i = 0; i < aString.getLength( ) + 1 ; i++ ) + { + if ( ( *pChar != '.' ) && ( i !=aString.getLength( ) ) ) + tmpBuffer[nCharCounter++] = *pChar; + else + { + tmpBuffer[nCharCounter] = '\0'; + nCharCounter = 0; + bsByteSequence[nByteSeqCounter++] = static_cast<sal_Int8>( atoi( tmpBuffer ) ); + } + pChar++; + } + return bsByteSequence; +} + +/** print a socket result name. +*/ +inline void printSocketResult( oslSocketResult eResult ) +{ + t_print("#printSocketResult# " ); + if (!eResult) + switch (eResult) + { + case osl_Socket_Ok: + t_print("client connected\n"); + break; + case osl_Socket_Error: + t_print("got an error ... exiting\r\n\r\n" ); + break; + case osl_Socket_TimedOut: + t_print("timeout\n"); + break; + + case osl_Socket_FORCE_EQUAL_SIZE: + t_print("FORCE EQUAL SIZE\n"); + break; + case osl_Socket_InProgress: + t_print("In Progress\n"); + break; + case osl_Socket_Interrupted: + t_print("Interrupted\n"); + break; + } +} + +/** Client Socket Thread, served as a temp little client to communicate with server. +*/ +class ClientSocketThread : public Thread +{ +protected: + oslThreadIdentifier m_id; + ::osl::SocketAddr saTargetSocketAddr; + ::osl::ConnectorSocket csConnectorSocket; + + void SAL_CALL run( ) + { + TimeValue *pTimeout; + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 5; + pTimeout->Nanosec = 0; + + /// if the thread should terminate, schedule return false + //while ( schedule( ) == sal_True ) + //{ + if ( osl_Socket_Ok == csConnectorSocket.connect( saTargetSocketAddr, pTimeout )) + { + csConnectorSocket.send( pTestString1, 11 ); // "test socket" + csConnectorSocket.send( pTestString2, 10); + } + else + t_print("# ClientSocketThread: connect failed! \n"); + // terminate(); + //} + csConnectorSocket.close(); + free( pTimeout ); + } + + void SAL_CALL onTerminated( ) + { + //t_print("# normally terminate this thread %d!\n", m_id ); + } + +public: + ClientSocketThread( ): + saTargetSocketAddr( aHostIp1, IP_PORT_MYPORT9 ), + csConnectorSocket( ) + { + m_id = getIdentifier( ); + //t_print("# successfully creat this client thread %d!\n", m_id ); + } + + ~ClientSocketThread( ) + { + if ( isRunning( ) ) + t_print("# error: client thread not terminated.\n" ); + } + +}; + + +/** Server Socket Thread, served as a temp little server to communicate with client. +*/ +class ServerSocketThread : public Thread +{ +protected: + oslThreadIdentifier m_id; + + void SAL_CALL run( ) + { + ::osl::AcceptorSocket asAcceptorSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + ::osl::SocketAddr saLocalSocketAddr( aHostIp1, IP_PORT_MYPORT9 ); + ::osl::StreamSocket ssStreamConnection; + + //if has not set this option, socket addr can not be binded in some time(maybe 2 minutes) by another socket + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //integer not sal_Bool : sal_True); + while ( schedule( ) == sal_True ) + { + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + if ( sal_True != bOK1 ) + { + t_print("# ServerSocketThread: AcceptorSocket bind address failed.\n" ) ; + break; + } + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + if ( sal_True != bOK2 ) + { + t_print("# ServerSocketThread: AcceptorSocket listen address failed.\n" ) ; + break; + } + + asAcceptorSocket.enableNonBlockingMode( sal_False ); + + oslSocketResult eResult = asAcceptorSocket.acceptConnection( ssStreamConnection ); + if (eResult != osl_Socket_Ok ) + { + t_print("ServerSocketThread: acceptConnection failed! \n"); + break; + } + sal_Int32 nReadNumber1 = ssStreamConnection.recv( pReadBuffer, 11 ); + sal_Int32 nReadNumber2 = ssStreamConnection.recv( pReadBuffer + nReadNumber1, 11 ); + pReadBuffer[nReadNumber1 + nReadNumber2] = '\0'; + //t_print("# read buffer content: %s\n", pReadBuffer ); + break; + } + ssStreamConnection.close(); + asAcceptorSocket.close(); + + } + + void SAL_CALL onTerminated( ) + { + //t_print("# normally terminate this server thread %d!\n", m_id ); + } + +public: + // public to check if data transmition is OK + sal_Char pReadBuffer[30]; + ServerSocketThread( ) + { + m_id = getIdentifier( ); + //t_print("# successfully creat this server thread %d!\n", m_id ); + } + + ~ServerSocketThread( ) + { + if ( isRunning( ) ) + t_print("# error: server thread not terminated.\n" ); + } +}; + +// ----------------------------------------------------------------------------- +// Helper functions, to create buffers, check buffers +class ValueCheckProvider +{ + bool m_bFoundFailure; + char *m_pBuffer; + sal_Int32 m_nBufferSize; + +public: + ValueCheckProvider() + : + m_bFoundFailure(false), + m_pBuffer(NULL), + m_nBufferSize(0) + { + } + + bool isFailure() {return m_bFoundFailure;} + + const char* getBuffer() {return m_pBuffer;} + char* getWriteBuffer() {return m_pBuffer;} + + sal_Int32 getBufferSize() {return m_nBufferSize;} + + bool checkValues(sal_Int32 _nLength, int _nValue) + { + m_bFoundFailure = false; + for(sal_Int32 i=0;i<_nLength;i++) + { + if (m_pBuffer[i] != _nValue) + { + m_bFoundFailure = true; + } + } + return m_bFoundFailure; + } + + void createBuffer(sal_Int32 _nLength, int _nValue) + { + m_nBufferSize = _nLength; + m_pBuffer = (char*) malloc(m_nBufferSize); + if (m_pBuffer) + { + memset(m_pBuffer, _nValue, m_nBufferSize); + } + } + + void freeBuffer() + { + if (m_pBuffer) free(m_pBuffer); + } + +}; + +// ----------------------------------------------------------------------------- +/** Client Socket Thread, served as a temp little client to communicate with server. +*/ + +class ReadSocketThread : public Thread +{ + int m_nValue; + ValueCheckProvider m_aValues; + +protected: + oslThreadIdentifier m_id; + ::osl::SocketAddr saTargetSocketAddr; + ::osl::ConnectorSocket csConnectorSocket; + + void SAL_CALL run( ) + { + TimeValue *pTimeout; + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 5; + pTimeout->Nanosec = 0; + + /// if the thread should terminate, schedule return false + //while ( schedule( ) == sal_True ) + //{ + if ( osl_Socket_Ok == csConnectorSocket.connect( saTargetSocketAddr, pTimeout )) + { + sal_Int32 nReadCount = csConnectorSocket.read( m_aValues.getWriteBuffer(), m_aValues.getBufferSize() ); + m_aValues.checkValues(nReadCount, m_nValue); + } + else + { + t_print("# ReadSocketThread: connect failed! \n"); + } + // terminate(); + //} + //remove this line for deadlock on solaris( margritte.germany ) + csConnectorSocket.close(); + free( pTimeout ); + } + + void SAL_CALL onTerminated( ) + { + //t_print("# normally terminate this thread %d!\n", m_id ); + } + +public: + sal_Int32 getCount() {return m_aValues.getBufferSize();} + bool isOk() {return m_aValues.isFailure() == true ? false : true;} + + ReadSocketThread(sal_Int32 _nBufferSize, int _nValue ) + : + m_nValue( _nValue ), + saTargetSocketAddr( aHostIp1, IP_PORT_MYPORT10 ), + csConnectorSocket( ) + { + m_id = getIdentifier( ); + //t_print("# successfully creat this client thread %d!\n", m_id ); + m_aValues.createBuffer(_nBufferSize, 0); + } + + ~ReadSocketThread( ) + { + if ( isRunning( ) ) + t_print("# error: client thread not terminated.\n" ); + m_aValues.freeBuffer(); + } + +}; + +/** Server Socket Thread, write a file which is large +*/ +class WriteSocketThread : public Thread +{ + ValueCheckProvider m_aValues; + +protected: + oslThreadIdentifier m_id; + + void SAL_CALL run( ) + { + ::osl::AcceptorSocket asAcceptorSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + ::osl::SocketAddr saLocalSocketAddr( aHostIp1, IP_PORT_MYPORT10 ); + ::osl::StreamSocket ssStreamConnection; + + //if has not set this option, socket addr can not be binded in some time(maybe 2 minutes) by another socket + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + + /// if the thread should terminate, schedule return false + while ( schedule( ) == sal_True ) + { + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + if ( sal_True != bOK1 ) + { + t_print("# WriteSocketThread: AcceptorSocket bind address failed. \n" ) ; + break; + } + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + if ( sal_True != bOK2 ) + { + t_print("# WriteSocketThread: AcceptorSocket listen address failed. \n" ) ; + break; + } + // blocking mode, if read/recv failed, block until success + asAcceptorSocket.enableNonBlockingMode( sal_False); + + oslSocketResult eResult = asAcceptorSocket.acceptConnection( ssStreamConnection ); + if (eResult != osl_Socket_Ok ) + { + t_print("WriteSocketThread: acceptConnection failed! \n"); + break; + } + + ssStreamConnection.write( m_aValues.getBuffer(), m_aValues.getBufferSize() ); + break; + } + ssStreamConnection.close(); + asAcceptorSocket.close(); + } + + void SAL_CALL onTerminated( ) + { + //t_print("# normally terminate this server thread %d!\n", m_id ); + } + +public: + // public to check if data transmition is OK + WriteSocketThread(sal_Int32 _nBufferSize, int _nValue ) + { + m_id = getIdentifier( ); + //t_print("# successfully creat this server thread %d!\n", m_id ); + + m_aValues.createBuffer(_nBufferSize, _nValue); + } + + ~WriteSocketThread( ) + { + if ( isRunning( ) ) + t_print("# error: server thread not terminated.\n" ); + m_aValues.freeBuffer(); + } + +}; + +// ----------------------------------------------------------------------------- +// just used to test socket::close() when accepting +class AcceptorThread : public Thread +{ + ::osl::AcceptorSocket asAcceptorSocket; + ::rtl::OUString aHostIP; + sal_Bool bOK; +protected: + void SAL_CALL run( ) + { + ::osl::SocketAddr saLocalSocketAddr( aHostIP, IP_PORT_MYPORT9 ); + ::osl::StreamSocket ssStreamConnection; + + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //integer not sal_Bool : sal_True); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + if ( sal_True != bOK1 ) + { + t_print("# AcceptorSocket bind address failed.\n" ) ; + return; + } + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + if ( sal_True != bOK2 ) + { + t_print("# AcceptorSocket listen address failed.\n" ) ; + return; + } + + asAcceptorSocket.enableNonBlockingMode( sal_False ); + + oslSocketResult eResult = asAcceptorSocket.acceptConnection( ssStreamConnection ); + if (eResult != osl_Socket_Ok ) + { + bOK = sal_True; + t_print("AcceptorThread: acceptConnection failed! \n"); + } + } +public: + AcceptorThread(::osl::AcceptorSocket & asSocket, ::rtl::OUString & aBindIP ) + : asAcceptorSocket( asSocket ), aHostIP( aBindIP ) + { + bOK = sal_False; + } + + sal_Bool isOK() { return bOK; } + + ~AcceptorThread( ) + { + if ( isRunning( ) ) + { + asAcceptorSocket.shutdown(); + t_print("# error: Acceptor thread not terminated.\n" ); + } + } +}; + +class CloseSocketThread : public Thread +{ + ::osl::Socket m_sSocket; +protected: + void SAL_CALL run( ) + { + thread_sleep( 1 ); + m_sSocket.close( ); + } +public: + CloseSocketThread(::osl::Socket & sSocket ) + : m_sSocket( sSocket ) + { + } + + ~CloseSocketThread( ) + { + if ( isRunning( ) ) + { + t_print("# error: CloseSocketThread not terminated.\n" ); + } + } +}; + +//------------------------------------------------------------------------ +// tests cases begins here +//------------------------------------------------------------------------ + +namespace osl_SocketAddr +{ + + /** testing the methods: + inline SocketAddr(); + inline SocketAddr(const SocketAddr& Addr); + inline SocketAddr(const oslSocketAddr , __osl_socket_NoCopy nocopy ); + inline SocketAddr(oslSocketAddr Addr); + inline SocketAddr( const ::rtl::OUString& strAddrOrHostName, sal_Int32 nPort ); + */ + + class ctors : public CppUnit::TestFixture + { + public: + + void ctors_none() + { + /// SocketAddr constructor. + ::osl::SocketAddr saSocketAddr; + + // oslSocketResult aResult; + // rtl::OUString suHost = saSocketAddr.getLocalHostname( &aResult); + + // rtl::OUString suHost2 = getThisHostname(); + + CPPUNIT_ASSERT_MESSAGE("test for none parameter constructor function: check if the socket address was created successfully", + sal_True == saSocketAddr.is( ) ); + } + + void ctors_none_000() + { + /// SocketAddr constructor. + ::osl::SocketAddr saSocketAddr; + + oslSocketResult aResult; + rtl::OUString suHost = saSocketAddr.getLocalHostname( &aResult); + rtl::OUString suHost2 = getThisHostname(); + + sal_Bool bOk = compareUString(suHost, suHost2); + + rtl::OUString suError (RTL_CONSTASCII_USTRINGPARAM("Host names should be the same. From SocketAddr.getLocalHostname() it is'")); + suError += suHost; + suError += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("', from getThisHostname() it is '")); + suError += suHost2; + suError += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("'.")); + + CPPUNIT_ASSERT_MESSAGE(STD_STRING(suError), sal_True == bOk); + } + + void ctors_copy() + { + /// SocketAddr copy constructor. + ::osl::SocketAddr saSocketAddr( aHostName1, IP_PORT_HTTP1 ); + ::osl::SocketAddr saCopySocketAddr( saSocketAddr ); + + sal_Int32 nPort = saCopySocketAddr.getPort( ); + + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr copy constructor function: copy constructor, do an action of copy construction then check the port with original set.", + ( sal_True == saCopySocketAddr.is( ) ) && ( nPort == IP_PORT_HTTP1 ) ); + } + + void ctors_copy_no_001() + { + + ::osl::SocketAddr* pSocketAddr = new ::osl::SocketAddr( aHostName1, IP_PORT_HTTP1 ); + CPPUNIT_ASSERT_MESSAGE("check for new SocketAddr", pSocketAddr != NULL); + + oslSocketAddr psaOSLSocketAddr = pSocketAddr->getHandle( ); + + ::osl::SocketAddr* pSocketAddrCopy = new ::osl::SocketAddr( psaOSLSocketAddr, SAL_NO_COPY ); + + pSocketAddrCopy->setPort( IP_PORT_HTTP2 ); + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr no copy constructor function: do a no copy constructor on a given SocketAddr instance, modify the new instance's port, check the original one.", + pSocketAddr->getPort( ) == IP_PORT_HTTP2 ); + + delete pSocketAddrCopy; + // LLA: don't do this also: delete pSocketAddr; + } + + void ctors_copy_no_002() + { + ::osl::SocketAddr* pSocketAddr = new ::osl::SocketAddr( aHostName1, IP_PORT_HTTP1 ); + CPPUNIT_ASSERT_MESSAGE("check for new SocketAddr", pSocketAddr != NULL); + oslSocketAddr psaOSLSocketAddr = pSocketAddr->getHandle( ); + ::osl::SocketAddr* pSocketAddrCopy = new ::osl::SocketAddr( psaOSLSocketAddr, SAL_NO_COPY ); + + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr no copy constructor function: do a no copy constructor on a given SocketAddr instance, modify the new instance's port, check the original one.", + pSocketAddr->getHandle( ) == pSocketAddrCopy->getHandle( ) ); + + delete pSocketAddrCopy; + } + + void ctors_copy_handle_001() + { + ::osl::SocketAddr saSocketAddr( aHostName1, IP_PORT_HTTP1 ); + ::osl::SocketAddr saSocketAddrCopy( saSocketAddr.getHandle( ) ); + + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr copy handle constructor function: copy another Socket's handle, get its port to check copy effect.", + saSocketAddrCopy.getPort( ) == IP_PORT_HTTP1 ); + } + + void ctors_copy_handle_002() + { + ::osl::SocketAddr saSocketAddr( aHostName1, IP_PORT_HTTP1 ); + ::osl::SocketAddr saSocketAddrCopy( saSocketAddr.getHandle( ) ); + saSocketAddrCopy.setPort( IP_PORT_HTTP2 ); + + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr copy handle constructor function: copy another Socket's handle, the original one should not be changed.", + saSocketAddr.getPort( ) != IP_PORT_HTTP2 ); + } + + void ctors_hostname_port_001() + { + /// tcpip-specif constructor. + ::osl::SocketAddr saSocketAddr( aHostIp1, IP_PORT_FTP ); + printUString(saSocketAddr.getHostname( ), "ctors_hostname_port_001:getHostname"); + + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr tcpip specif constructor function: do a constructor using tcpip spec, check the result.", + saSocketAddr.is( ) == sal_True && + ( saSocketAddr.getPort( ) == IP_PORT_FTP )/*&& + ( sal_True == compareUString( saSocketAddr.getHostname( ), aHostName1 ) ) */); + } + + //same as is_002 + void ctors_hostname_port_002() + { + /// tcpip-specif constructor. + ::osl::SocketAddr saSocketAddr( aHostIpInval1, IP_PORT_MYPORT2 ); + + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr tcpip specif constructor function: using an invalid IP address, the socketaddr ctors should fail", sal_False == saSocketAddr.is( )); + } + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_none ); + CPPUNIT_TEST( ctors_none_000 ); + CPPUNIT_TEST( ctors_copy ); + CPPUNIT_TEST( ctors_copy_no_001 ); + CPPUNIT_TEST( ctors_copy_no_002 ); + CPPUNIT_TEST( ctors_copy_handle_001 ); + CPPUNIT_TEST( ctors_copy_handle_002 ); + CPPUNIT_TEST( ctors_hostname_port_001 ); + CPPUNIT_TEST( ctors_hostname_port_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class ctors + + + /** testing the method: + inline sal_Bool is() const; + */ + + class is : public CppUnit::TestFixture + { + public: + void is_001() + { + ::osl::SocketAddr saSocketAddr; + + CPPUNIT_ASSERT_MESSAGE("test for is() function: create an unknown type socket, it should be True when call is.", + sal_True == saSocketAddr.is( ) ); + } + // refer to setPort_003() + void is_002() + { + ::osl::SocketAddr saSocketAddr( aHostIp1, IP_PORT_INVAL ); + + CPPUNIT_ASSERT_MESSAGE("test for is() function: create a tcp-ip socket using invalid port number", + sal_True == saSocketAddr.is( ) ); + } + + void is_003() + { + ::osl::SocketAddr saSocketAddr( aHostIpInval1, IP_PORT_MYPORT ); + + CPPUNIT_ASSERT_MESSAGE("test for is() function: create a tcp-ip socket using invalid Ip number", + sal_True != saSocketAddr.is( ) ); + } + + CPPUNIT_TEST_SUITE( is ); + CPPUNIT_TEST( is_001 ); + CPPUNIT_TEST( is_002 ); + CPPUNIT_TEST( is_003 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class is + + + /** testing the method: + inline ::rtl::OUString SAL_CALL getHostname( oslSocketResult *pResult = 0 ) const; + */ + + class getHostname : public CppUnit::TestFixture + { + public: + void setUp() + { + } + + void tearDown() + { + } + + void getHostname_000() + { + ::osl::SocketAddr saSocketAddr( aHostIp4, IP_PORT_FTP ); + + } + + /** it will search the Ip in current machine's /etc/hosts at first, if find, then return the + mapped hostname, otherwise, it will search via DNS server, and often return hostname+ Domain name + like "sceri.PRC.Sun.COM" + The process is same as Socket::getLocalHost(), but getLocalHost can only return hostname of the current machine. + */ + void getHostname_001() + { + ::osl::SocketAddr saSocketAddr( aHostIp4, IP_PORT_FTP ); + rtl::OUString suResult = saSocketAddr.getHostname( 0 ); + rtl::OUString suError = outputError(suResult, aHostName4, "test for getHostname(0)"); + sal_Bool bOK = compareUString( suResult, aHostName4 ); + // search the returned hostname in /etc/hosts, if find, and the IP in the row is same as IP + // in the Addr, it's right also. + if ( bOK == sal_False) + { + if ( compareUString( getIPbyName( oustring2char( suResult ) ), aHostIp4 ) == sal_True ) + bOK = sal_True; + } + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError), sal_True == bOK); + } + +// LLA: now we have to control, if this behaviour is right. +// LLA: this function does not work in company (Linux, Windows) but at home + void getHostname_002() + { + rtl::OUString suHostname (RTL_CONSTASCII_USTRINGPARAM("cn-1.germany.sun.com")); + rtl::OUString aHostIP = getIPbyName( oustring2char( suHostname ) ); + + ::osl::SocketAddr saSocketAddr( aHostName1, IP_PORT_FTP ); + sal_Bool bOK = saSocketAddr.setHostname( suHostname ); + CPPUNIT_ASSERT_MESSAGE("#SocketAddr.setHostname failed", sal_True == bOK ); + oslSocketResult aResult; + rtl::OUString suResult = saSocketAddr.getHostname( &aResult ); + CPPUNIT_ASSERT_MESSAGE("SocketAddr.getHostname failed.", aResult == osl_Socket_Ok); + + rtl::OUString suError = outputError(suResult, suHostname, "test for getHostname(0)"); + bOK = compareUString( suResult, suHostname ); + if ( bOK == sal_False) + { + rtl::OString aString = ::rtl::OUStringToOString( suResult, RTL_TEXTENCODING_ASCII_US ); + if ( compareUString( getIPbyName( aString) , aHostIp6 ) == sal_True ) + { + bOK = sal_True; + } + } + + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError), sal_True == bOK ); + } + + + CPPUNIT_TEST_SUITE( getHostname ); + CPPUNIT_TEST( getHostname_001 ); + CPPUNIT_TEST( getHostname_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getHostname + + + /** testing the method: + inline sal_Int32 SAL_CALL getPort() const; + */ + + class getPort : public CppUnit::TestFixture + { + public: + void getPort_001() + { + ::osl::SocketAddr saSocketAddr( aHostIp1, IP_PORT_FTP ); + + CPPUNIT_ASSERT_MESSAGE( "test for getPort() function: get a normal port number.", + IP_PORT_FTP == saSocketAddr.getPort( ) ); + } + + void getPort_002() + { + ::osl::SocketAddr saSocketAddr( aHostIp2, IP_PORT_INVAL ); + + //t_print("#getPort_002: Port number is %d \n", saSocketAddr.getPort( )); + + CPPUNIT_ASSERT_MESSAGE( "test for getPort( ) function: give an invalid port to a SocketAddr, get the port to see if it can detect. it did not pass in (W32).", + saSocketAddr.getPort( )>=1 && saSocketAddr.getPort( ) <= 65535 ); + } + //two cases will return OSL_INVALID_PORT: 1. not valid SocketAddr + //2. SocketAddr family is not osl_Socket_FamilyInet, but case 2 could not be constructed + void getPort_003() + { + ::osl::SocketAddr saSocketAddr( aHostIpInval1, IP_PORT_MYPORT ); + + CPPUNIT_ASSERT_MESSAGE( "test for getPort( ) function: give an invalid IP to a SocketAddr, get the port to see returned value. ", + saSocketAddr.getPort( ) == OSL_INVALID_PORT ); + } + + CPPUNIT_TEST_SUITE( getPort ); + CPPUNIT_TEST( getPort_001 ); + CPPUNIT_TEST( getPort_002 ); + CPPUNIT_TEST( getPort_003 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class getPort + + + /** testing the method: + inline sal_Bool SAL_CALL setPort( sal_Int32 nPort ); + rfc1413.txt: TCP port numbers are from 1-65535 + rfc1700.txt: 0/tcp Reserved ; 0/udp Reserved + */ + + class setPort : public CppUnit::TestFixture + { + public: + void setPort_001() + { + ::osl::SocketAddr saSocketAddr( aHostIp1, IP_PORT_FTP ); + sal_Bool bOK = saSocketAddr.setPort( IP_PORT_TELNET ); + + CPPUNIT_ASSERT_MESSAGE( "test for setPort() function: modify a port number setting, and check it.", + ( sal_True == bOK ) && + ( IP_PORT_TELNET == saSocketAddr.getPort( ) ) ); + } + + /** 0 to 1024 is known as the reserved port range (traditionally only root can assign programs to ports in + this range) and the ephemeral port range from 1025 to 65535. + As many of you programmers will know, when you specify the source port of 0 when you connect to a host, + the OS automatically reassigns the port number to high numbered ephemeral port. The same happens if you + try to bind a listening socket to port 0. + http://www.securiteam.com/securityreviews/5XP0Q2AAKS.html + another: http://www.muq.org/~cynbe/muq/mufref_564.html + */ + void setPort_002() + { + ::osl::SocketAddr saSocketAddr( aHostIp1, IP_PORT_FTP ); + sal_Bool bOK = saSocketAddr.setPort( IP_PORT_ZERO ); + + oslSocket sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + ::osl::Socket sSocket(sHandle); + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 );//sal_True); + sal_Bool bOK1 = sSocket.bind( saSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "bind SocketAddr failed", bOK1 == sal_True ); + + sal_Int32 newPort = sSocket.getLocalPort(); + //t_print("#new port is %d\n", newPort ); + + CPPUNIT_ASSERT_MESSAGE( "test for setPort() function: port number should be in 1 ~ 65535, set port 0, it should be converted to a port number between 1024~65535.", + ( 1024 <= newPort ) && ( 65535 >= newPort ) && ( bOK == sal_True ) ); + + } + + void setPort_003() + { + ::osl::SocketAddr saSocketAddr( aHostIp1, IP_PORT_FTP); + sal_Bool bOK = saSocketAddr.setPort( IP_PORT_INVAL ); + //on Linux, getPort return 34463 + //t_print("#Port number is %d \n", saSocketAddr.getPort( )); + + CPPUNIT_ASSERT_MESSAGE( "test for setPort( ) function: set an address with invalid port. it should return error or convert it to a valid port.", + ( ( 1 <= saSocketAddr.getPort( ) ) && ( 65535 >= saSocketAddr.getPort( ) ) &&( bOK == sal_True ) ) || + bOK == sal_False); + } + + /* this is not a inet-addr => can't set port */ + void setPort_004() + { + ::osl::SocketAddr saSocketAddr( aHostIpInval1, IP_PORT_FTP); + sal_Bool bOK = saSocketAddr.setPort( IP_PORT_MYPORT ); + + CPPUNIT_ASSERT_MESSAGE( "test for setPort( ) function: set an invalid address with valid port. it should return error.", + bOK == sal_False); + } + + + CPPUNIT_TEST_SUITE( setPort ); + CPPUNIT_TEST( setPort_001 ); + CPPUNIT_TEST( setPort_002 ); + CPPUNIT_TEST( setPort_003 ); + CPPUNIT_TEST( setPort_004 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class setPort + + + /** tester comment: + + In the following two functions, it use ::rtl::ByteSequence as an intermediate storage for address, + the ByteSequence object can hold sal_Int8 arrays, which is raged [-127, 127], in case of IP addr + that is greater than 127, say 129.158.217.202, it will stored as -127, -98, -39, -54, it is unique + in the range of sal_Int8, but lack of readability. + so may be a sal_uInt8 array is better. + */ + + + /** testing the method: + inline sal_Bool SAL_CALL setAddr( const ::rtl::ByteSequence & address ); + */ + + class setAddr : public CppUnit::TestFixture + { + public: + void setAddr_001() + { + ::osl::SocketAddr saSocketAddr( aHostIp2, IP_PORT_FTP ); + saSocketAddr.setAddr( UStringIPToByteSequence( aHostIp1 ) ); + ::rtl::ByteSequence bsSocketAddr = saSocketAddr.getAddr( 0 ); + sal_Bool bOK = sal_False; + + if ( ( bsSocketAddr[0] == 127 ) && ( bsSocketAddr[1] == 0 ) && ( bsSocketAddr[2] == 0 ) && ( bsSocketAddr[3] == 1 ) ) + bOK = sal_True; + + CPPUNIT_ASSERT_MESSAGE( "test for setAddr() function: construct Addr with \"129.158.217.202\", set it to \"127.0.0.1\", and check the correctness ", + sal_True == bOK ); + } + + + CPPUNIT_TEST_SUITE( setAddr ); + CPPUNIT_TEST( setAddr_001 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class setAddr + + + /** testing the method: + inline ::rtl::ByteSequence SAL_CALL getAddr( oslSocketResult *pResult = 0 ) const; + */ + + class getAddr : public CppUnit::TestFixture + { + public: + void getAddr_001() + { + oslSocketResult SocketResult; + ::osl::SocketAddr saSocketAddr( aHostIp1, IP_PORT_FTP ); + ::rtl::ByteSequence bsSocketAddr = saSocketAddr.getAddr( &SocketResult ); + + sal_Bool bOK = sal_False; + + if ( ( osl_Socket_Ok == SocketResult ) &&( bsSocketAddr[0] == 127 ) && ( bsSocketAddr[1] == 0 ) &&( bsSocketAddr[2] == 0 ) && ( bsSocketAddr[3] == 1 ) ) + bOK = sal_True; + + CPPUNIT_ASSERT_MESSAGE( "test for getAddr() function: construct a socketaddr with IP assigned, get the address to check correctness.Caught unknown exception on (Win32)", + sal_True == bOK && SocketResult == osl_Socket_Ok); + } + + CPPUNIT_TEST_SUITE( getAddr ); + CPPUNIT_TEST( getAddr_001 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class getAddr + + + /** testing the methods: + inline SocketAddr & SAL_CALL operator= (oslSocketAddr Addr); + inline SocketAddr & SAL_CALL operator= (const SocketAddr& Addr); + inline SocketAddr & SAL_CALL assign( oslSocketAddr Addr, __osl_socket_NoCopy nocopy ); + inline sal_Bool SAL_CALL operator== (oslSocketAddr Addr) const; + inline sal_Bool SAL_CALL operator== (const SocketAddr & Addr) const; /// not implemented. + */ + + class operator_equal : public CppUnit::TestFixture + { + public: + void operator_equal_001() + { + ::osl::SocketAddr saSocketAddr( aHostIp1, IP_PORT_TELNET); + ::osl::SocketAddr saSocketAddrEqual( aHostIp2, IP_PORT_FTP ); + + saSocketAddrEqual = saSocketAddr; + sal_Bool bOK = sal_False; + ::rtl::ByteSequence bsSocketAddr = saSocketAddrEqual.getAddr( 0 ); + + if ( ( IP_PORT_TELNET == saSocketAddrEqual.getPort( ) ) &&( bsSocketAddr[0] == 127 ) && ( bsSocketAddr[1] == 0 ) &&( bsSocketAddr[2] == 0 ) && ( bsSocketAddr[3] == 1 ) ) + bOK = sal_True; + + CPPUNIT_ASSERT_MESSAGE( "test for operator_equal() function: use operator= to assign Ip1 to Ip2, check its modification.", + sal_True == bOK ); + } + + + void operator_equal_002() + { + ::osl::SocketAddr saSocketAddr( aHostIp3, IP_PORT_TELNET); + ::osl::SocketAddr saSocketAddrEqual( aHostIp2, IP_PORT_FTP ); + + saSocketAddrEqual = saSocketAddr; + CPPUNIT_ASSERT_MESSAGE( "after assign, the assigned SocketAddr is not same as the original Addr", + IP_PORT_TELNET == saSocketAddrEqual.getPort( ) ); + saSocketAddrEqual.setPort( IP_PORT_MYPORT3 ); + saSocketAddr.setPort( IP_PORT_HTTP2 ); + + CPPUNIT_ASSERT_MESSAGE( "test for operator_equal() function: perform an equal action, then try to change the original address's port. it should not be changed ( handle released), it did not pass in (W32), this is under discussion.", + IP_PORT_MYPORT3 == saSocketAddrEqual.getPort( ) ); + } + + void operator_equal_const_001() + { + const ::osl::SocketAddr saSocketAddr( aHostIp1, IP_PORT_TELNET); + ::osl::SocketAddr saSocketAddrEqual( aHostIp2, IP_PORT_FTP ); + + saSocketAddrEqual = saSocketAddr; + sal_Bool bOK = sal_False; + ::rtl::ByteSequence bsSocketAddr = saSocketAddrEqual.getAddr( 0 ); + + if ( ( IP_PORT_TELNET == saSocketAddrEqual.getPort( ) ) &&( bsSocketAddr[0] == 127 ) && ( bsSocketAddr[1] == 0 ) &&( bsSocketAddr[2] == 0 ) && ( bsSocketAddr[3] == 1 ) ) + bOK = sal_True; + + CPPUNIT_ASSERT_MESSAGE( "test for operator_equal_const() function: use operator= const to assign Ip1 to Ip2, verify the change on the second one.", + sal_True == bOK ); + } + + void operator_equal_const_002() + { + const ::osl::SocketAddr saSocketAddr( aHostIp1, IP_PORT_TELNET); + ::osl::SocketAddr saSocketAddrEqual( aHostIp2, IP_PORT_FTP ); + + saSocketAddrEqual = saSocketAddr; + saSocketAddrEqual.setPort( IP_PORT_HTTP1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for operator_equal_const() function: change the second instance, the first one should not be altered, since it does not released the handle.", + IP_PORT_HTTP1 != saSocketAddr.getPort( ) ); + } + + void operator_equal_assign_001() + { + ::osl::SocketAddr* pSocketAddr = new ::osl::SocketAddr( aHostIp1, IP_PORT_TELNET ); + CPPUNIT_ASSERT_MESSAGE("check for new SocketAddr", pSocketAddr != NULL); + ::osl::SocketAddr* pSocketAddrAssign = new ::osl::SocketAddr( aHostIp2, IP_PORT_FTP ); + oslSocketAddr poslSocketAddr = pSocketAddr->getHandle( ); + //if( m_handle ) osl_destroySocketAddr( m_handle ); so pSocketAddrAssign had been destroyed and then point to pSocketAddr + pSocketAddrAssign->assign(poslSocketAddr, SAL_NO_COPY); + + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr no copy constructor function: do a no copy constructor on a given SocketAddr instance, modify the new instance's port, check the original one.", + pSocketAddrAssign->getPort( ) == IP_PORT_TELNET ); + + delete pSocketAddrAssign; + } + + void operator_is_equal_001() + { + ::osl::SocketAddr saSocketAddr( aHostIp1, IP_PORT_TELNET); + ::osl::SocketAddr saSocketAddrequal( aHostIp1, IP_PORT_TELNET ); + + CPPUNIT_ASSERT_MESSAGE( "test for operator_equal_equal() function: check two identical Address.", + sal_True == ( saSocketAddrequal == saSocketAddr.getHandle( ) ) ); + } + + void operator_is_equal_002() + { + ::osl::SocketAddr saSocketAddr( aHostIp2, IP_PORT_FTP); + ::osl::SocketAddr saSocketAddrequal( aHostIp1, IP_PORT_TELNET ); + + CPPUNIT_ASSERT_MESSAGE( "test for operator_equal_equal() function: check two different Address.", + sal_False == ( saSocketAddrequal == saSocketAddr.getHandle( ) ) ); + } + + CPPUNIT_TEST_SUITE( operator_equal ); + CPPUNIT_TEST( operator_equal_001 ); + CPPUNIT_TEST( operator_equal_002 ); + CPPUNIT_TEST( operator_equal_const_001 ); + CPPUNIT_TEST( operator_equal_const_002 ); + CPPUNIT_TEST( operator_equal_assign_001 ); + CPPUNIT_TEST( operator_is_equal_001 ); + CPPUNIT_TEST( operator_is_equal_002 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class operator_equal + + + + /** testing the method: + inline oslSocketAddr SAL_CALL getHandle() const; + */ + + class getSocketAddrHandle : public CppUnit::TestFixture + { + public: + + void getSocketAddrHandle_001() + { + ::osl::SocketAddr* pSocketAddr = new ::osl::SocketAddr( aHostName1, IP_PORT_HTTP1 ); + CPPUNIT_ASSERT_MESSAGE("check for new SocketAddr", pSocketAddr != NULL); + oslSocketAddr psaOSLSocketAddr = pSocketAddr->getHandle( ); + ::osl::SocketAddr* pSocketAddrCopy = new ::osl::SocketAddr( psaOSLSocketAddr, SAL_NO_COPY ); + + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr no copy constructor function: do a no copy constructor on a given SocketAddr instance, modify the new instance's port, check the original one.", + pSocketAddr->getHandle( ) == pSocketAddrCopy->getHandle( ) ); + + delete pSocketAddrCopy; + } + + void getSocketAddrHandle_002() + { + ::osl::SocketAddr saSocketAddr( aHostName3, IP_PORT_MYPORT4 ); + oslSocketAddr poslSocketAddr = saSocketAddr.getHandle( ); + + sal_Bool bOK = ( saSocketAddr == poslSocketAddr ); + //t_print("getSocketAddrHandle_002\n"); + CPPUNIT_ASSERT_MESSAGE( "test for getHandle() function: use getHandle() function as an intermediate way to create identical address.", + sal_True == bOK ); + } + + CPPUNIT_TEST_SUITE( getSocketAddrHandle ); + CPPUNIT_TEST( getSocketAddrHandle_001 ); + CPPUNIT_TEST( getSocketAddrHandle_002 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class getSocketAddrHandle + + + /** testing the method: + static inline ::rtl::OUString SAL_CALL getLocalHostname( oslSocketResult *pResult = 0); + */ + + class getLocalHostname : public CppUnit::TestFixture + { + public: + /* the process of getLocalHostname: 1.gethostname (same as /bin/hostname) returned name A + 2. search A in /etc/hosts, if there is an alias name is A, return the name in the same row + */ + + void getLocalHostname_000() + { + // _osl_getFullQualifiedDomainName( ); + oslSocketResult aResult = osl_Socket_Error; + rtl::OUString suHostname = osl::SocketAddr::getLocalHostname(&aResult); + CPPUNIT_ASSERT_MESSAGE("getLocalHostname failed", aResult == osl_Socket_Ok); + } + + void getLocalHostname_001() + { + oslSocketResult *pResult = NULL; + //printSocketResult(*pResult); + ::rtl::OUString suResult = ::osl::SocketAddr::getLocalHostname( pResult ); + + // LLA: IMHO localhost, or hostname by itself should be ok. + rtl::OUString suThisHost = getThisHostname( ); + bool bOk = false; + if (suThisHost.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("localhost")))) + { + bOk = true; + } + else + { + if (suThisHost.equals(suResult)) + { + bOk = true; + } + } + + ::rtl::OUString suError; + suError = outputError(suResult, getThisHostname( ), "test for getLocalHostname() function"); + + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError), bOk == true ); + } + + CPPUNIT_TEST_SUITE( getLocalHostname ); + CPPUNIT_TEST( getLocalHostname_000 ); + CPPUNIT_TEST( getLocalHostname_001 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class getLocalHostname + + + /** testing the method: + static inline void SAL_CALL resolveHostname( const ::rtl::OUString & strHostName , SocketAddr & Addr ); + */ + + class resolveHostname : public CppUnit::TestFixture + { + public: + void resolveHostname_001() + { + ::osl::SocketAddr saSocketAddr; + ::osl::SocketAddr::resolveHostname( aHostIp1, saSocketAddr ); + ::rtl::ByteSequence bsSocketAddr = saSocketAddr.getAddr( 0 ); + sal_Bool bOK = sal_False; + + if ( ( bsSocketAddr[0] == 127 ) && ( bsSocketAddr[1] == 0 ) &&( bsSocketAddr[2] == 0 ) && ( bsSocketAddr[3] == 1 ) ) + bOK = sal_True; + + CPPUNIT_ASSERT_MESSAGE( "test for resolveHostname() function: try to resolve localhost to 127.0.0.1.", + sal_True == bOK ); + } + + CPPUNIT_TEST_SUITE( resolveHostname ); + CPPUNIT_TEST( resolveHostname_001 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class resolveHostname + + + /** testing the method: + static inline sal_Int32 SAL_CALL getServicePort( + const ::rtl::OUString& strServiceName, + const ::rtl::OUString & strProtocolName= ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("tcp")) ); + */ + + class gettheServicePort : public CppUnit::TestFixture + { + public: + void gettheServicePort_001() + { + CPPUNIT_ASSERT_MESSAGE( "test for getServicePort() function: try to get ftp service port on TCP protocol.", + IP_PORT_FTP== ::osl::SocketAddr::getServicePort( aServiceFTP, aProtocolTCP ) ); + } + + void gettheServicePort_002() + { + CPPUNIT_ASSERT_MESSAGE( "test for getServicePort() function: try to get telnet service port on TCP protocol.", + IP_PORT_TELNET== ::osl::SocketAddr::getServicePort( aServiceTELNET, aProtocolTCP ) ); + } + + void gettheServicePort_003() + { + //Solaris has no service called "https", please see /etc/services + CPPUNIT_ASSERT_MESSAGE( "test for getServicePort() function: try to get netbios-ssn service port on UDP protocol.", + IP_PORT_NETBIOS_DGM == ::osl::SocketAddr::getServicePort( aServiceNETBIOS, aProtocolUDP ) ); + } + + void gettheServicePort_004() + { + CPPUNIT_ASSERT_MESSAGE( "test for getServicePort() function: try to get a service port which is not exist.", + OSL_INVALID_PORT == ::osl::SocketAddr::getServicePort( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("notexist")), aProtocolUDP ) ); + } + + CPPUNIT_TEST_SUITE( gettheServicePort ); + CPPUNIT_TEST( gettheServicePort_001 ); + CPPUNIT_TEST( gettheServicePort_002 ); + CPPUNIT_TEST( gettheServicePort_003 ); + CPPUNIT_TEST( gettheServicePort_004 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class gettheServicePort + +// ----------------------------------------------------------------------------- + + +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_SocketAddr::ctors, "osl_SocketAddr"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_SocketAddr::is, "osl_SocketAddr"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_SocketAddr::getHostname, "osl_SocketAddr"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_SocketAddr::getPort, "osl_SocketAddr"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_SocketAddr::setPort, "osl_SocketAddr"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_SocketAddr::setAddr, "osl_SocketAddr"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_SocketAddr::getAddr, "osl_SocketAddr"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_SocketAddr::operator_equal, "osl_SocketAddr"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_SocketAddr::getSocketAddrHandle, "osl_SocketAddr"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_SocketAddr::getLocalHostname, "osl_SocketAddr"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_SocketAddr::resolveHostname, "osl_SocketAddr"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_SocketAddr::gettheServicePort, "osl_SocketAddr"); + + +} // namespace osl_SocketAddr + + + +namespace osl_Socket +{ + + /** testing the methods: + inline Socket( ); + inline Socket( const Socket & socket ); + inline Socket( oslSocket socketHandle ); + inline Socket( oslSocket socketHandle, __sal_NoAcquire noacquire ); + */ + + /** test writer's comment: + + class Socket can not be initialized by its protected constructor, though the protected + constructor is the most convenient way to create a new socket. + it only allow the method of C function osl_createSocket like: + ::osl::Socket sSocket( osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, + osl_Socket_ProtocolIp ) ); + the use of C method lost some of the transparent of tester using C++ wrapper. + */ + + + class ctors : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void ctors_none() + { + /// Socket constructor. + // ::osl::Socket sSocket; + + CPPUNIT_ASSERT_MESSAGE( "test for ctors_none constructor function: check if the socket was created successfully, if no exception occurred", + 1 == 1 ); + } + + void ctors_acquire() + { + /// Socket constructor. + ::osl::Socket sSocket( sHandle ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors_acquire constructor function: check if the socket was created successfully", + osl_Socket_TypeStream == sSocket.getType( ) ); + } + + void ctors_no_acquire() + { + /// Socket constructor. + ::osl::Socket sSocket( sHandle, SAL_NO_ACQUIRE ); + + CPPUNIT_ASSERT_MESSAGE(" test for ctors_no_acquire constructor function: check if the socket was created successfully", + osl_Socket_TypeStream == sSocket.getType( ) ); + } + + void ctors_copy_ctor() + { + ::osl::Socket sSocket( sHandle ); + /// Socket copy constructor. + ::osl::Socket copySocket( sSocket ); + + CPPUNIT_ASSERT_MESSAGE(" test for ctors_copy_ctor constructor function: create new Socket instance using copy constructor", + osl_Socket_TypeStream == copySocket.getType( ) ); + } + + void ctors_TypeRaw() + { +#ifdef WNT + oslSocket sHandleRaw = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeRaw, osl_Socket_ProtocolIp ); +// LLA: ? ::osl::Socket sSocket( sHandleRaw ); + CPPUNIT_ASSERT_MESSAGE( " type osl_Socket_TypeRaw socket create failed on UNX ", sHandleRaw != NULL); +#else + oslSocket sHandleRaw = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeRaw, osl_Socket_ProtocolIp ); + CPPUNIT_ASSERT_MESSAGE( " can't create socket with type osl_Socket_TypeRaw within UNX is ok.", sHandleRaw == NULL); +#endif + } + + void ctors_family_Ipx() + { + oslSocket sHandleIpx = osl_createSocket( osl_Socket_FamilyIpx, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + CPPUNIT_ASSERT_MESSAGE( " family osl_Socket_FamilyIpx socket create failed! ", sHandleIpx != NULL); + ::osl::Socket sSocket( sHandleIpx ); //, SAL_NO_ACQUIRE ); + t_print("#Type is %d \n", sSocket.getType( ) ); + + CPPUNIT_ASSERT_MESSAGE(" test for create new Socket instance that family is osl_Socket_FamilyIpx", + osl_Socket_TypeStream == sSocket.getType( ) ); + } + + + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_none ); + CPPUNIT_TEST( ctors_acquire ); + CPPUNIT_TEST( ctors_no_acquire ); + CPPUNIT_TEST( ctors_copy_ctor ); + CPPUNIT_TEST( ctors_TypeRaw ); + CPPUNIT_TEST( ctors_family_Ipx ); + CPPUNIT_TEST_SUITE_END(); + + }; // class ctors + + + /** testing the methods: + inline Socket& SAL_CALL operator= ( oslSocket socketHandle); + inline Socket& SAL_CALL operator= (const Socket& sock); + inline sal_Bool SAL_CALL operator==( const Socket& rSocket ) const ; + inline sal_Bool SAL_CALL operator==( const oslSocket socketHandle ) const; + */ + + class operators : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + /** test writer's comment: + + the assignment operator does not support direct assinment like: + ::osl::Socket sSocket = sHandle. + */ + void operators_assignment_handle() + { + ::osl::Socket sSocket(sHandle); + ::osl::Socket assignSocket = sSocket.getHandle(); + + CPPUNIT_ASSERT_MESSAGE( "test for operators_assignment_handle function: test the assignment operator.", + osl_Socket_TypeStream == assignSocket.getType( ) ); + } + + void operators_assignment() + { + ::osl::Socket sSocket( sHandle ); + ::osl::Socket assignSocket = sSocket; + + CPPUNIT_ASSERT_MESSAGE( "test for operators_assignment function: assignment operator", + osl_Socket_TypeStream == assignSocket.getType( ) ); + } + + void operators_equal_handle_001() + { + /// Socket constructor. + ::osl::Socket sSocket( sHandle ); + ::osl::Socket equalSocket = sSocket; + + CPPUNIT_ASSERT_MESSAGE(" test for operators_equal_handle_001 function: check equal.", + equalSocket == sHandle ); + } + + void operators_equal_handle_002() + { + /// Socket constructor. + ::osl::Socket equalSocket( osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ) ); + + CPPUNIT_ASSERT_MESSAGE(" test for operators_equal_handle_001 function: check unequal.", + !( equalSocket == sHandle ) ); + } + + void operators_equal_001() + { + ::osl::Socket sSocket( sHandle ); + /// Socket copy constructor. + ::osl::Socket equalSocket( sSocket ); + + CPPUNIT_ASSERT_MESSAGE(" test for operators_equal function: check equal.", + equalSocket == sSocket ); + } + + void operators_equal_002() + { + ::osl::Socket sSocket( sHandle ); + /// Socket copy constructor. + ::osl::Socket equalSocket( osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ) ); + + CPPUNIT_ASSERT_MESSAGE(" test for operators_equal_002 function: check unequal.", + !( equalSocket == sSocket ) ); + } + + CPPUNIT_TEST_SUITE( operators ); + CPPUNIT_TEST( operators_assignment_handle ); + CPPUNIT_TEST( operators_assignment ); + CPPUNIT_TEST( operators_equal_handle_001 ); + CPPUNIT_TEST( operators_equal_handle_002 ); + CPPUNIT_TEST( operators_equal_001 ); + CPPUNIT_TEST( operators_equal_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class operators + + + /** testing the methods: + inline void SAL_CALL shutdown( oslSocketDirection Direction = osl_Socket_DirReadWrite ); + inline void SAL_CALL close(); + */ + + class close : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void close_001() + { + ::osl::Socket sSocket(sHandle); + sSocket.close(); + + CPPUNIT_ASSERT_MESSAGE( "test for close_001 function: this function is reserved for test.", + sSocket.getHandle() == sHandle ); + } + + void close_002() + { +//#if defined(LINUX) + ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + AcceptorThread myAcceptorThread( asSocket, aHostIp1 ); + myAcceptorThread.create(); + + thread_sleep( 1 ); + //when accepting, close the socket, the thread will not block for accepting + //man close:Any locks held on the file it was associated with, and owned by the process, are removed + asSocket.close(); + //thread_sleep( 2 ); + myAcceptorThread.join(); + + CPPUNIT_ASSERT_MESSAGE( "test for close when is accepting: the socket will quit accepting status.", + myAcceptorThread.isOK() == sal_True ); +//#endif + } + + // to cover "if ( pSockAddrIn->sin_addr.s_addr == htonl(INADDR_ANY) )" in osl_closeSocket( ) + void close_003() + { + ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + AcceptorThread myAcceptorThread( asSocket, aHostIpZero ); + myAcceptorThread.create(); + + thread_sleep( 1 ); + asSocket.close(); + myAcceptorThread.join(); + + CPPUNIT_ASSERT_MESSAGE( "test for close when is accepting: the socket will quit accepting status.", + myAcceptorThread.isOK() == sal_True ); + } + + CPPUNIT_TEST_SUITE( close ); + CPPUNIT_TEST( close_001 ); + CPPUNIT_TEST( close_002 ); + CPPUNIT_TEST( close_003 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class close + + /** testing the method: + inline void SAL_CALL getLocalAddr( SocketAddr &Addr ) const; + */ + + class getLocalAddr : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + // get the Address of the local end of the socket + void getLocalAddr_001() + { + ::osl::Socket sSocket(sHandle); + ::osl::SocketAddr saBindSocketAddr( aHostIp1, IP_PORT_MYPORT8 ); + ::osl::SocketAddr saLocalSocketAddr; + + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + + sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); + ::rtl::OUString suError1 = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Socket bind fail:")) + sSocket.getErrorAsString(); + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError1), sal_True == bOK1 ); + + sSocket.getLocalAddr( saLocalSocketAddr ); + + sal_Bool bOK = compareUString( saLocalSocketAddr.getHostname( 0 ), sSocket.getLocalHost() ) ; + + CPPUNIT_ASSERT_MESSAGE( "test for getLocalAddr function: first create a new socket, then a socket address, bind them, and check the address.", + sal_True == bOK ); + } + + + CPPUNIT_TEST_SUITE( getLocalAddr ); + CPPUNIT_TEST( getLocalAddr_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getLocalAddr + + + /** testing the method: + inline sal_Int32 SAL_CALL getLocalPort() const; + */ + + class getLocalPort : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void getLocalPort_001() + { + ::osl::Socket sSocket(sHandle); + ::osl::SocketAddr saBindSocketAddr( aHostIp1, IP_PORT_MYPORT7 ); // aHostIp1 localhost + ::osl::SocketAddr saLocalSocketAddr; + + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + + sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); + ::rtl::OUString suError1 = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Socket bind fail:")) + sSocket.getErrorAsString(); + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError1), sal_True == bOK1 ); + sal_Bool bOK = ( IP_PORT_MYPORT7 == sSocket.getLocalPort( ) ); + + CPPUNIT_ASSERT_MESSAGE( "test for getLocalPort function: first create a new socket, then a socket address, bind them, and check the port.", + sal_True == bOK ); + } + + /** test writer's comment: + + the invalid port number can not be set by giving invalid port number + such as 99999 or -1, it will convert to ( x mod 65535 ), so it will always be + valid, the only instance that the getLocalPort returns OSL_INVALID_PORT + is when saSocketAddr itself is an invalid one, that is , the IP or host name + can not be found, then the created socket address is not valid. + */ + void getLocalPort_002() + { + ::osl::SocketAddr saBindSocketAddr( aHostIpInval, IP_PORT_TELNET); +#ifdef WNT + ::osl::Socket sSocket(sHandle); + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); // sal_True); + sSocket.bind( saBindSocketAddr ); + //Invalid IP, so bind should fail + ::rtl::OUString suError = outputError(::rtl::OUString::valueOf(sSocket.getLocalPort( )), + ::rtl::OUString::valueOf((sal_Int32)OSL_INVALID_PORT), + "test for getLocalPort function: first create a new socket, then an invalid socket address, bind them, and check the port assigned."); + sal_Bool bOK = ( OSL_INVALID_PORT == sSocket.getLocalPort( ) ); + (void)bOK; +#else + //on Unix, if Addr is not an address of type osl_Socket_FamilyInet, it returns OSL_INVALID_PORT + ::rtl::OUString suError (RTL_CONSTASCII_USTRINGPARAM("on Unix, if Addr is not an address of type osl_Socket_FamilyInet, it returns OSL_INVALID_PORT, but can not create Addr of that case")); +#endif + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError), sal_False ); + + } + + void getLocalPort_003() + { + ::osl::Socket sSocket(sHandle); + ::osl::SocketAddr saBindSocketAddr( getLocalIP(), IP_PORT_INVAL); + + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + + sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); + ::rtl::OUString suError1 = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Socket bind fail:")) + sSocket.getErrorAsString(); + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError1), sal_True == bOK1 ); + ::rtl::OUString suError = outputError(::rtl::OUString::valueOf(sSocket.getLocalPort( )), + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("34463")), + "test for getLocalPort function: first create a new socket, then an invalid socket address, bind them, and check the port assigned"); + sal_Bool bOK = ( sSocket.getLocalPort( ) >= 1 && sSocket.getLocalPort( ) <= 65535); + + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError), sal_True == bOK ); + } + + CPPUNIT_TEST_SUITE( getLocalPort ); + CPPUNIT_TEST( getLocalPort_001 ); +// LLA: CPPUNIT_TEST( getLocalPort_002 ); + CPPUNIT_TEST( getLocalPort_003 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getLocalPort + + + /** testing the method: + inline ::rtl::OUString SAL_CALL getLocalHost() const; + + Mindyliu: on Linux, at first it will check the binded in /etc/hosts, if it has the binded IP, it will return the hostname in it; + else if the binded IP is "127.0.0.1", it will return "localhost", if it's the machine's ethernet ip such as "129.158.217.90", it + will return hostname of current processor such as "aegean.PRC.Sun.COM" + */ + + class getLocalHost : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void getLocalHost_001() + { + ::osl::Socket sSocket(sHandle); + //port number from IP_PORT_HTTP1 to IP_PORT_MYPORT6, mindyliu + ::osl::SocketAddr saBindSocketAddr( aHostIp1, IP_PORT_MYPORT6 ); + + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + + sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); + ::rtl::OUString suError1 = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Socket bind fail:")) + sSocket.getErrorAsString(); + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError1), sal_True == bOK1 ); + sal_Bool bOK; + ::rtl::OUString suError; +#ifdef WNT + bOK = compareUString( sSocket.getLocalHost( ), getThisHostname( ) ) ; + suError = outputError(sSocket.getLocalHost( ), getThisHostname( ), +"test for getLocalHost function: create localhost socket and check name"); +#else + ::rtl::OUString aUString = ::rtl::OUString::createFromAscii( (const sal_Char *) "localhost" ); + sal_Bool bRes1, bRes2; + bRes1 = compareUString( sSocket.getLocalHost( ), aUString ) ; + bRes2 = compareUString( sSocket.getLocalHost( ), saBindSocketAddr.getHostname(0) ) ; + bOK = bRes1 || bRes2; + suError = outputError(sSocket.getLocalHost( ), aUString, "test for getLocalHost function: create localhost socket and check name"); +#endif + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError), sal_True == bOK ); + } + + void getLocalHost_002() + { + ::osl::Socket sSocket(sHandle); + ::osl::SocketAddr saBindSocketAddr( aHostIpInval, IP_PORT_POP3); + ::osl::SocketAddr saLocalSocketAddr; + + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + sSocket.bind( saBindSocketAddr ); + //Invalid IP, so bind should fail + sal_Bool bOK = compareUString( sSocket.getLocalHost( ), aNullURL ) ; + ::rtl::OUString suError = outputError(sSocket.getLocalHost( ), aNullURL, "test for getLocalHost function: getLocalHost with invalid SocketAddr"); + + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError), sal_True == bOK ); + } + + CPPUNIT_TEST_SUITE( getLocalHost ); + CPPUNIT_TEST( getLocalHost_001 ); + CPPUNIT_TEST( getLocalHost_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getLocalHost + + + /** testing the methods: + inline void SAL_CALL getPeerAddr( SocketAddr & Addr) const; + inline sal_Int32 SAL_CALL getPeerPort() const; + inline ::rtl::OUString SAL_CALL getPeerHost() const; + */ + class getPeer : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + TimeValue *pTimeout; + ::osl::AcceptorSocket asAcceptorSocket; + ::osl::ConnectorSocket csConnectorSocket; + + + // initialization + void setUp( ) + { + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 3; + pTimeout->Nanosec = 0; + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + free( pTimeout ); + sHandle = NULL; + asAcceptorSocket.close( ); + csConnectorSocket.close( ); + } + + + void getPeer_001() + { + ::osl::SocketAddr saLocalSocketAddr( aHostIp1, IP_PORT_MYPORT ); + ::osl::SocketAddr saTargetSocketAddr( aHostIp1, IP_PORT_MYPORT ); + ::osl::SocketAddr saPeerSocketAddr( aHostIp2, IP_PORT_FTP ); + ::osl::StreamSocket ssConnection; + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + /// launch server socket + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind '127.0.0.1' address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + + asAcceptorSocket.enableNonBlockingMode( sal_True ); + asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... + + /// launch client socket + csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... + + /// get peer information + csConnectorSocket.getPeerAddr( saPeerSocketAddr );/// connected. + sal_Int32 peerPort = csConnectorSocket.getPeerPort( ); + ::rtl::OUString peerHost = csConnectorSocket.getPeerHost( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getPeer function: setup a connection and then get the peer address, port and host from client side.", + ( sal_True == compareSocketAddr( saPeerSocketAddr, saLocalSocketAddr ) )&& + ( sal_True == compareUString( peerHost, saLocalSocketAddr.getHostname( 0 ) ) ) && + ( peerPort == saLocalSocketAddr.getPort( ) )); + } + + + CPPUNIT_TEST_SUITE( getPeer ); + CPPUNIT_TEST( getPeer_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getPeer + + + /** testing the methods: + inline sal_Bool SAL_CALL bind(const SocketAddr& LocalInterface); + */ + + + class bind : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void bind_001() + { + ::osl::Socket sSocket(sHandle); + //bind must use local IP address ---mindyliu + ::osl::SocketAddr saBindSocketAddr( getLocalIP(), IP_PORT_MYPORT5 ); + + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "Socket bind fail.", sal_True == bOK1 ); + + sal_Bool bOK2 = compareUString( sSocket.getLocalHost( ), saBindSocketAddr.getHostname( ) ) ; + + sSocket.close(); + CPPUNIT_ASSERT_MESSAGE( "test for bind function: bind a valid address.", sal_True == bOK2 ); + } + + void bind_002() + { + ::osl::Socket sSocket(sHandle); + ::osl::SocketAddr saBindSocketAddr( aHostIpInval, IP_PORT_NETBIOS ); + ::osl::SocketAddr saLocalSocketAddr; + + sSocket.setOption( osl_Socket_OptionReuseAddr, 1); // sal_True); + sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); + sal_Bool bOK2 = compareUString( sSocket.getLocalHost( ), getThisHostname( ) ) ; + + CPPUNIT_ASSERT_MESSAGE( "test for bind function: bind a valid address.", + ( sal_False == bOK1 ) && ( sal_False == bOK2 ) ); + } + + CPPUNIT_TEST_SUITE( bind ); + CPPUNIT_TEST( bind_001 ); + CPPUNIT_TEST( bind_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class bind + + + /** testing the methods: + inline sal_Bool SAL_CALL isRecvReady(const TimeValue *pTimeout = 0) const; + + */ + class isRecvReady : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + TimeValue *pTimeout; + ::osl::AcceptorSocket asAcceptorSocket; + ::osl::ConnectorSocket csConnectorSocket; + + + // initialization + void setUp( ) + { + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 3; + pTimeout->Nanosec = 0; + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + free( pTimeout ); + sHandle = NULL; + asAcceptorSocket.close( ); + csConnectorSocket.close( ); + } + + + void isRecvReady_001() + { + ::osl::SocketAddr saLocalSocketAddr( aHostIp1, IP_PORT_MYPORT1 ); + ::osl::SocketAddr saTargetSocketAddr( aHostIp1, IP_PORT_MYPORT1 ); + ::osl::SocketAddr saPeerSocketAddr( aHostIp2, IP_PORT_FTP ); + ::osl::StreamSocket ssConnection; + /// launch server socket + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); // sal_True); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + asAcceptorSocket.enableNonBlockingMode( sal_True ); + asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... + + /// launch client socket + csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... + + /// is receive ready? + sal_Bool bOK3 = asAcceptorSocket.isRecvReady( pTimeout ); + + CPPUNIT_ASSERT_MESSAGE( "test for isRecvReady function: setup a connection and then check if it can transmit data.", + ( sal_True == bOK3 ) ); + } + + + CPPUNIT_TEST_SUITE( isRecvReady ); + CPPUNIT_TEST( isRecvReady_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class isRecvReady + + + /** testing the methods: + inline sal_Bool SAL_CALL isSendReady(const TimeValue *pTimeout = 0) const; + */ + class isSendReady : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + TimeValue *pTimeout; + ::osl::AcceptorSocket asAcceptorSocket; + ::osl::ConnectorSocket csConnectorSocket; + + + // initialization + void setUp( ) + { + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 3; + pTimeout->Nanosec = 0; + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + free( pTimeout ); + sHandle = NULL; + asAcceptorSocket.close( ); + csConnectorSocket.close( ); + } + + + void isSendReady_001() + { + ::osl::SocketAddr saLocalSocketAddr( aHostIp1, IP_PORT_MYPORT ); + ::osl::SocketAddr saTargetSocketAddr( aHostIp1, IP_PORT_MYPORT ); + ::osl::SocketAddr saPeerSocketAddr( aHostIp2, IP_PORT_FTP ); + ::osl::StreamSocket ssConnection; + + /// launch server socket + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + asAcceptorSocket.enableNonBlockingMode( sal_True ); + asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... + + /// launch client socket + csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... + + /// is send ready? + sal_Bool bOK3 = csConnectorSocket.isSendReady( pTimeout ); + + CPPUNIT_ASSERT_MESSAGE( "test for isSendReady function: setup a connection and then check if it can transmit data.", + ( sal_True == bOK3 ) ); + } + + + CPPUNIT_TEST_SUITE( isSendReady ); + CPPUNIT_TEST( isSendReady_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class isSendReady + + + /** testing the methods: + inline oslSocketType SAL_CALL getType() const; + + */ + + class getType : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void getType_001() + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + ::osl::Socket sSocket(sHandle); + + CPPUNIT_ASSERT_MESSAGE( "test for getType function: get type of socket.", + osl_Socket_TypeStream == sSocket.getType( ) ); + } + + void getType_002() + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ); + ::osl::Socket sSocket(sHandle); + + CPPUNIT_ASSERT_MESSAGE( "test for getType function: get type of socket.", + osl_Socket_TypeDgram == sSocket.getType( ) ); + } + +#ifdef UNX + // mindy: since on LINUX and SOLARIS, Raw type socket can not be created, so do not test getType() here + // mindy: and add one test case to test creating Raw type socket--> ctors_TypeRaw() + void getType_003() + { + CPPUNIT_ASSERT_MESSAGE( "test for getType function: get type of socket.this is not passed in (LINUX, SOLARIS), the osl_Socket_TypeRaw, type socket can not be created.", + sal_True); + } +#else + void getType_003() + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeRaw, osl_Socket_ProtocolIp ); + ::osl::Socket sSocket(sHandle); + + CPPUNIT_ASSERT_MESSAGE( "test for getType function: get type of socket.", + osl_Socket_TypeRaw == sSocket.getType( ) ); + } +#endif + + CPPUNIT_TEST_SUITE( getType ); + CPPUNIT_TEST( getType_001 ); + CPPUNIT_TEST( getType_002 ); + CPPUNIT_TEST( getType_003 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getType + + + + /** testing the methods: + inline sal_Int32 SAL_CALL getOption( + oslSocketOption Option, + void* pBuffer, + sal_uInt32 BufferLen, + oslSocketOptionLevel Level= osl_Socket_LevelSocket) const; + + inline sal_Int32 getOption( oslSocketOption option ) const; + + */ + + class getOption : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + + } + + void tearDown( ) + { + sHandle = NULL; + } + + /** test writer's comment: + + in oslSocketOption, the osl_Socket_OptionType denote 1 as osl_Socket_TypeStream. + 2 as osl_Socket_TypeDgram, etc which is not mapping the oslSocketType enum. differ + in 1. + */ + + void getOption_001() + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + ::osl::Socket sSocket(sHandle); + sal_Int32 * pType = ( sal_Int32 * )malloc( sizeof ( sal_Int32 ) ); + *pType = 0; + sSocket.getOption( osl_Socket_OptionType, pType, sizeof ( sal_Int32 ) ); + sal_Bool bOK = ( SOCK_STREAM == *pType ); + // there is a TypeMap(socket.c) which map osl_Socket_TypeStream to SOCK_STREAM on UNX, and SOCK_STREAM != osl_Socket_TypeStream + //sal_Bool bOK = ( TYPE_TO_NATIVE(osl_Socket_TypeStream) == *pType ); + free( pType ); + + CPPUNIT_ASSERT_MESSAGE( "test for getOption function: get type option of socket.", + sal_True == bOK ); + } + + // getsockopt error + void getOption_004() + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ); + ::osl::Socket sSocket(sHandle); + + sal_Bool * pbDontRoute = ( sal_Bool * )malloc( sizeof ( sal_Bool ) ); + sal_Int32 nRes = sSocket.getOption( osl_Socket_OptionInvalid, pbDontRoute, sizeof ( sal_Bool ) ); + free( pbDontRoute ); + + CPPUNIT_ASSERT_MESSAGE( "test for getOption function: get invalid option of socket, should return -1.", + nRes == -1 ); + } + + void getOption_simple_001() + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ); + ::osl::Socket sSocket(sHandle); + + sal_Bool bOK = ( sal_False == sSocket.getOption( osl_Socket_OptionDontRoute ) ); + + CPPUNIT_ASSERT_MESSAGE( "test for getOption function: get debug option of socket.", + sal_True == bOK ); + } + + void getOption_simple_002() + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ); + ::osl::Socket sSocket(sHandle); + + sal_Bool bOK = ( sal_False == sSocket.getOption( osl_Socket_OptionDebug ) ); + + CPPUNIT_ASSERT_MESSAGE( "test for getOption function: get debug option of socket.", + sal_True == bOK ); + } + + CPPUNIT_TEST_SUITE( getOption ); + CPPUNIT_TEST( getOption_001 ); + CPPUNIT_TEST( getOption_004 ); + CPPUNIT_TEST( getOption_simple_001 ); + CPPUNIT_TEST( getOption_simple_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getOption + + + /** testing the methods: + inline sal_Bool SAL_CALL setOption( oslSocketOption Option, + void* pBuffer, + sal_uInt32 BufferLen, + oslSocketOptionLevel Level= osl_Socket_LevelSocket ) const; + */ + + class setOption : public CppUnit::TestFixture + { + public: + TimeValue *pTimeout; +// LLA: maybe there is an error in the source, +// as long as I remember, if a derived class do not overload all ctors there is a problem. + + ::osl::AcceptorSocket asAcceptorSocket; + + void setUp( ) + { + + } + + void tearDown( ) + { + asAcceptorSocket.close( ); + } + + + // LLA: + // getSocketOption returns BufferLen, or -1 if something failed + + // setSocketOption returns sal_True, if option could stored + // else sal_False + + void setOption_001() + { + /// set and get option. + int nBufferLen = sizeof ( sal_Int32); + // LLA: SO_DONTROUTE expect an integer boolean, what ever it is, it's not sal_Bool! + + sal_Int32 * pbDontRouteSet = ( sal_Int32 * )malloc( sizeof ( sal_Int32 ) ); + *pbDontRouteSet = 1; // sal_True; + + sal_Int32 * pGetBuffer = ( sal_Int32 * )malloc( sizeof ( sal_Int32 ) ); + *pGetBuffer = 0; + + // maybe asAcceptorSocket is not right initialized + sal_Bool b1 = asAcceptorSocket.setOption( osl_Socket_OptionDontRoute, pbDontRouteSet, nBufferLen ); + CPPUNIT_ASSERT_MESSAGE( "setOption function failed.", ( sal_True == b1 ) ); + sal_Int32 n2 = asAcceptorSocket.getOption( osl_Socket_OptionDontRoute, pGetBuffer, nBufferLen ); + CPPUNIT_ASSERT_MESSAGE( "getOption function failed.", ( n2 == nBufferLen ) ); + + // on Linux, the value of option is 1, on Solaris, it's 16, but it's not important the exact value, + // just judge it is zero or not! + sal_Bool bOK = ( 0 != *pGetBuffer ); + t_print("#setOption_001: getOption is %"SAL_PRIdINT32" \n", *pGetBuffer); + + // toggle check, set to 0 + *pbDontRouteSet = 0; + + sal_Bool b3 = asAcceptorSocket.setOption( osl_Socket_OptionDontRoute, pbDontRouteSet, sizeof ( sal_Int32 ) ); + CPPUNIT_ASSERT_MESSAGE( "setOption function failed.", ( sal_True == b3 ) ); + sal_Int32 n4 = asAcceptorSocket.getOption( osl_Socket_OptionDontRoute, pGetBuffer, nBufferLen ); + CPPUNIT_ASSERT_MESSAGE( "getOption (DONTROUTE) function failed.", ( n4 == nBufferLen ) ); + + sal_Bool bOK2 = ( 0 == *pGetBuffer ); + + t_print("#setOption_001: getOption is %"SAL_PRIdINT32" \n", *pGetBuffer); + +// LLA: sal_Bool * pbDontTouteSet = ( sal_Bool * )malloc( sizeof ( sal_Bool ) ); +// LLA: *pbDontTouteSet = sal_True; +// LLA: sal_Bool * pbDontTouteGet = ( sal_Bool * )malloc( sizeof ( sal_Bool ) ); +// LLA: *pbDontTouteGet = sal_False; +// LLA: asAcceptorSocket.setOption( osl_Socket_OptionDontRoute, pbDontTouteSet, sizeof ( sal_Bool ) ); +// LLA: asAcceptorSocket.getOption( osl_Socket_OptionDontRoute, pbDontTouteGet, sizeof ( sal_Bool ) ); +// LLA: ::rtl::OUString suError = outputError(::rtl::OUString::valueOf((sal_Int32)*pbDontTouteGet), +// LLA: ::rtl::OUString::valueOf((sal_Int32)*pbDontTouteSet), +// LLA: "test for setOption function: set osl_Socket_OptionDontRoute and then check"); +// LLA: +// LLA: sal_Bool bOK = ( sal_True == *pbDontTouteGet ); +// LLA: free( pbDontTouteSet ); +// LLA: free( pbDontTouteGet ); + + CPPUNIT_ASSERT_MESSAGE( "test for setOption function: set option of a socket and then check.", + ( sal_True == bOK ) && (sal_True == bOK2) ); + + free( pbDontRouteSet ); + free( pGetBuffer ); +// LLA: CPPUNIT_ASSERT_MESSAGE( suError, sal_True == bOK ); + } + + void setOption_002() + { + /// set and get option. + + // sal_Int32 * pbLingerSet = ( sal_Int32 * )malloc( nBufferLen ); + // *pbLingerSet = 7; + // sal_Int32 * pbLingerGet = ( sal_Int32 * )malloc( nBufferLen ); + /* struct */linger aLingerSet; + sal_Int32 nBufferLen = sizeof( struct linger ); + aLingerSet.l_onoff = 1; + aLingerSet.l_linger = 7; + + linger aLingerGet; + + asAcceptorSocket.setOption( osl_Socket_OptionLinger, &aLingerSet, nBufferLen ); + + sal_Int32 n1 = asAcceptorSocket.getOption( osl_Socket_OptionLinger, &aLingerGet, nBufferLen ); + CPPUNIT_ASSERT_MESSAGE( "getOption (SO_LINGER) function failed.", ( n1 == nBufferLen ) ); + + //t_print("#setOption_002: getOption is %d \n", aLingerGet.l_linger); + sal_Bool bOK = ( 7 == aLingerGet.l_linger ); + CPPUNIT_ASSERT_MESSAGE( "test for setOption function: set option of a socket and then check. ", + sal_True == bOK ); + + } + + void setOption_003() + { + linger aLingerSet; + aLingerSet.l_onoff = 1; + aLingerSet.l_linger = 7; + + sal_Bool b1 = asAcceptorSocket.setOption( osl_Socket_OptionLinger, &aLingerSet, 0 ); + printUString( asAcceptorSocket.getErrorAsString() ); + CPPUNIT_ASSERT_MESSAGE( "setOption (SO_LINGER) function failed for optlen is 0.", + ( b1 == sal_False ) ); + } + + void setOption_simple_001() + { + /// set and get option. + asAcceptorSocket.setOption( osl_Socket_OptionDontRoute, 1 ); //sal_True ); + sal_Bool bOK = ( 0 != asAcceptorSocket.getOption( osl_Socket_OptionDontRoute ) ); + + t_print("setOption_simple_001(): getoption is %d \n", (int) asAcceptorSocket.getOption( osl_Socket_OptionDontRoute ) ); + CPPUNIT_ASSERT_MESSAGE( "test for setOption function: set option of a socket and then check.", + ( sal_True == bOK ) ); + } + + void setOption_simple_002() + { + /// set and get option. + // LLA: this does not work, due to the fact that SO_LINGER is a structure +// LLA: asAcceptorSocket.setOption( osl_Socket_OptionLinger, 7 ); +// LLA: sal_Bool bOK = ( 7 == asAcceptorSocket.getOption( osl_Socket_OptionLinger ) ); + +// LLA: CPPUNIT_ASSERT_MESSAGE( "test for setOption function: set option of a socket and then check.", +// LLA: ( sal_True == bOK ) ); + } + + CPPUNIT_TEST_SUITE( setOption ); + CPPUNIT_TEST( setOption_001 ); + CPPUNIT_TEST( setOption_002 ); + CPPUNIT_TEST( setOption_003 ); + CPPUNIT_TEST( setOption_simple_001 ); +// LLA: CPPUNIT_TEST( setOption_simple_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class setOption + + + + /** testing the method: + inline sal_Bool SAL_CALL enableNonBlockingMode( sal_Bool bNonBlockingMode); + */ + class enableNonBlockingMode : public CppUnit::TestFixture + { + public: + ::osl::AcceptorSocket asAcceptorSocket; + + void enableNonBlockingMode_001() + { + ::osl::SocketAddr saLocalSocketAddr( aHostIp1, IP_PORT_MYPORT ); + ::osl::StreamSocket ssConnection; + + /// launch server socket + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + asAcceptorSocket.enableNonBlockingMode( sal_True ); + asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... + + /// if reach this statement, it is non-blocking mode, since acceptConnection will blocked by default. + sal_Bool bOK = sal_True; + asAcceptorSocket.close( ); + + CPPUNIT_ASSERT_MESSAGE( "test for enableNonBlockingMode function: launch a server socket and make it non blocking. if it can pass the acceptConnection statement, it is non-blocking", + ( sal_True == bOK ) ); + } + + + CPPUNIT_TEST_SUITE( enableNonBlockingMode ); + CPPUNIT_TEST( enableNonBlockingMode_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class enableNonBlockingMode + + + /** testing the method: + inline sal_Bool SAL_CALL isNonBlockingMode() const; + */ + class isNonBlockingMode : public CppUnit::TestFixture + { + public: + ::osl::AcceptorSocket asAcceptorSocket; + + void isNonBlockingMode_001() + { + ::osl::SocketAddr saLocalSocketAddr( aHostIp1, IP_PORT_MYPORT ); + ::osl::StreamSocket ssConnection; + + /// launch server socket + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); // sal_True); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + + sal_Bool bOK3 = asAcceptorSocket.isNonBlockingMode( ); + asAcceptorSocket.enableNonBlockingMode( sal_True ); + asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... + + /// if reach this statement, it is non-blocking mode, since acceptConnection will blocked by default. + sal_Bool bOK4 = asAcceptorSocket.isNonBlockingMode( ); + asAcceptorSocket.close( ); + + CPPUNIT_ASSERT_MESSAGE( "test for isNonBlockingMode function: launch a server socket and make it non blocking. it is expected to change from blocking mode to non-blocking mode.", + ( sal_False == bOK3 ) && ( sal_True == bOK4 ) ); + } + + + CPPUNIT_TEST_SUITE( isNonBlockingMode ); + CPPUNIT_TEST( isNonBlockingMode_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class isNonBlockingMode + + /** testing the method: + inline void SAL_CALL clearError() const; + */ + class clearError : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void clearError_001() + { + ::osl::Socket sSocket(sHandle); + ::osl::SocketAddr saBindSocketAddr( aHostIpInval, IP_PORT_HTTP2 ); + ::osl::SocketAddr saLocalSocketAddr; + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + sSocket.bind( saBindSocketAddr );//build an error "osl_Socket_E_AddrNotAvail" + oslSocketError seBind = sSocket.getError( ); + sSocket.clearError( ); + + CPPUNIT_ASSERT_MESSAGE( "test for clearError function: trick an error called sSocket.getError( ), and then clear the error states, check the result.", + osl_Socket_E_None == sSocket.getError( ) && seBind != osl_Socket_E_None ); + } + + + CPPUNIT_TEST_SUITE( clearError ); + CPPUNIT_TEST( clearError_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class clearError + + + /** testing the methods: + inline oslSocketError getError() const; + inline ::rtl::OUString getErrorAsString( ) const; + */ + class getError : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void getError_001() + { + ::osl::Socket sSocket(sHandle); + ::osl::SocketAddr saBindSocketAddr( aHostIp1, IP_PORT_FTP ); + ::osl::SocketAddr saLocalSocketAddr; + + CPPUNIT_ASSERT_MESSAGE( "test for getError function: should get no error.", + osl_Socket_E_None == sSocket.getError( ) ); + } + + void getError_002() + { + ::osl::Socket sSocket(sHandle); + ::osl::SocketAddr saBindSocketAddr( aHostIpInval, IP_PORT_FTP ); + ::osl::SocketAddr saLocalSocketAddr; + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + sSocket.bind( saBindSocketAddr );//build an error "osl_Socket_E_AddrNotAvail" + //on Solaris, the error no is EACCES, but it has no mapped value, so getError() returned osl_Socket_E_InvalidError. +#if defined(SOLARIS) + CPPUNIT_ASSERT_MESSAGE( "trick an error called sSocket.getError( ), check the getError result.Failed on Solaris, returned osl_Socket_E_InvalidError because no entry to map the errno EACCES. ", + osl_Socket_E_InvalidError == sSocket.getError( ) ); +#else + //while on Linux & Win32, the errno is EADDRNOTAVAIL, getError returned osl_Socket_E_AddrNotAvail. + + CPPUNIT_ASSERT_MESSAGE( "trick an error called sSocket.getError( ), check the getError result.Failed on Solaris, returned osl_Socket_E_InvalidError because no entry to map the errno EACCES. Passed on Linux & Win32", + osl_Socket_E_AddrNotAvail == sSocket.getError( ) ); +#endif + } + + CPPUNIT_TEST_SUITE( getError ); + CPPUNIT_TEST( getError_001 ); + CPPUNIT_TEST( getError_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getError + + + + /** testing the methods: + inline oslSocket getHandle() const; + */ + + class getHandle : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + void getHandle_001() + { + ::osl::Socket sSocket(sHandle); + ::osl::Socket assignSocket = sSocket.getHandle(); + + CPPUNIT_ASSERT_MESSAGE( "test for operators_assignment_handle function: test the assignment operator.", + osl_Socket_TypeStream == assignSocket.getType( ) ); + } + + void getHandle_002() + { + ::osl::Socket sSocket( sHandle ); + ::osl::Socket assignSocket ( sSocket.getHandle( ) ); + + CPPUNIT_ASSERT_MESSAGE( "test for operators_assignment function: assignment operator", + osl_Socket_TypeStream == assignSocket.getType( ) ); + } + + CPPUNIT_TEST_SUITE( getHandle ); + CPPUNIT_TEST( getHandle_001 ); + CPPUNIT_TEST( getHandle_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getHandle + + +// ----------------------------------------------------------------------------- + + +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::ctors, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::operators, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::close, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::getLocalAddr, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::getLocalPort, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::getLocalHost, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::getPeer, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::bind, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::isRecvReady, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::isSendReady, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::getType, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::getOption, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::setOption, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::enableNonBlockingMode, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::isNonBlockingMode, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::clearError, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::getError, "osl_Socket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::getHandle, "osl_Socket"); + +} // namespace osl_Socket + + + +namespace osl_StreamSocket +{ + + /** testing the methods: + inline StreamSocket(oslAddrFamily Family = osl_Socket_FamilyInet, + oslProtocol Protocol = osl_Socket_ProtocolIp, + oslSocketType Type = osl_Socket_TypeStream); + + inline StreamSocket( const StreamSocket & ); + + inline StreamSocket( oslSocket Socket , __sal_NoAcquire noacquire ); + + inline StreamSocket( oslSocket Socket ); + */ + + class ctors : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void ctors_none() + { + /// Socket constructor. + ::osl::StreamSocket ssSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors_none constructor function: check if the stream socket was created successfully.", + osl_Socket_TypeStream == ssSocket.getType( ) ); + } + + void ctors_acquire() + { + /// Socket constructor. + ::osl::StreamSocket ssSocket( sHandle ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors_acquire constructor function: check if the socket was created successfully", + osl_Socket_TypeStream == ssSocket.getType( ) ); + } + + void ctors_no_acquire() + { + /// Socket constructor. + ::osl::StreamSocket ssSocket( sHandle, SAL_NO_ACQUIRE ); + + CPPUNIT_ASSERT_MESSAGE(" test for ctors_no_acquire constructor function: check if the socket was created successfully", + osl_Socket_TypeStream == ssSocket.getType( ) ); + } + + void ctors_copy_ctor() + { + /// Socket constructor. + ::osl::StreamSocket ssSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + /// Socket copy constructor. + ::osl::StreamSocket copySocket( ssSocket ); + + CPPUNIT_ASSERT_MESSAGE(" test for ctors_copy_ctor constructor function: create new Socket instance using copy constructor", + osl_Socket_TypeStream == copySocket.getType( ) ); + } + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_none ); + CPPUNIT_TEST( ctors_acquire ); + CPPUNIT_TEST( ctors_no_acquire ); + CPPUNIT_TEST( ctors_copy_ctor ); + CPPUNIT_TEST_SUITE_END(); + + }; // class ctors + + class send_recv: public CppUnit::TestFixture + { + public: + // initialization + void setUp( ) + { + } + + void tearDown( ) + { + + } + + void send_recv1() + { + //client sent two strings, and server received, check the order and value + ServerSocketThread myServerThread; + ClientSocketThread myClientThread; + myServerThread.create( ); + myClientThread.create( ); + + //wait until the thread terminate + myClientThread.join( ); + myServerThread.join( ); + sal_Char myStr[30] = ""; + strcat( myStr, pTestString1 ); + strcat( myStr, pTestString2 ); + sal_Int32 nRes = strcmp( myServerThread.pReadBuffer, myStr ); + CPPUNIT_ASSERT_MESSAGE(" test for send/recv with two threads: launch Server/Client threads, send data from client, check received data in Server thread.", + nRes == 0 ); + } + + // error when recv + void send_recv2() + { + ::osl::AcceptorSocket asAcceptorSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + ::osl::SocketAddr saLocalSocketAddr( aHostIp1, IP_PORT_MYPORT9 ); + ::osl::StreamSocket ssStreamConnection; + sal_Char pReadBuffer[30] = ""; + + ClientSocketThread myClientThread; + myClientThread.create( ); + + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); + + asAcceptorSocket.bind( saLocalSocketAddr ); + asAcceptorSocket.listen( 1 ); + asAcceptorSocket.enableNonBlockingMode( sal_True ); + asAcceptorSocket.acceptConnection( ssStreamConnection ); + sal_Int32 nReadNumber = ssStreamConnection.recv( pReadBuffer, 11 ); + + myClientThread.join( ) ; + ssStreamConnection.close(); + asAcceptorSocket.close(); + CPPUNIT_ASSERT_MESSAGE(" test for send/recv, recv error!", nReadNumber == -1 ); + } + + void write_read(sal_Int32 _nBufferSize, int _nValue) + { + //client sent two strings, and server received, check the order and value + WriteSocketThread myServerThread(_nBufferSize, _nValue); + ReadSocketThread myClientThread(_nBufferSize, _nValue); + myServerThread.create( ); +// thread_sleep( 1 ); + myClientThread.create( ); + + //wait until the thread terminate + myClientThread.join( ); + myServerThread.join( ); + + //Maximum Packet Size is ( ARPANET, MILNET = 1007 Ethernet (10Mb) = 1500 + // Proteon PRONET = 2046), so here test read 4000 bytes + sal_Int32 nLength = myClientThread.getCount(); + bool bIsOk = myClientThread.isOk(); // check if the values are right. + + t_print("Length:=%d\n", (int) nLength); + t_print(" bIsOk:=%d\n", bIsOk); + + CPPUNIT_ASSERT_MESSAGE(" test for write/read values with two threads: send data from server, check readed data in client.", + nLength == _nBufferSize && bIsOk == true); + } + + void write_read_001() + { + write_read(50, 10); + } + void write_read_002() + { + write_read(1024, 20); + } + void write_read_003() + { + write_read(4000, 1); + } + void write_read_004() + { + write_read(8192, 3); + } + + CPPUNIT_TEST_SUITE( send_recv ); + CPPUNIT_TEST( write_read_001 ); + CPPUNIT_TEST( write_read_002 ); + CPPUNIT_TEST( write_read_003 ); + CPPUNIT_TEST( write_read_004 ); + CPPUNIT_TEST( send_recv1 ); + CPPUNIT_TEST( send_recv2 ); +// CPPUNIT_TEST( write_read ); + CPPUNIT_TEST_SUITE_END(); + }; // class send_recv + +class SendClientThread : public ClientSocketThread +{ +protected: + + void SAL_CALL run( ) + { + TimeValue *pTimeout; + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 5; + pTimeout->Nanosec = 0; + + if ( osl_Socket_Ok == csConnectorSocket.connect( saTargetSocketAddr, pTimeout )) + { +#if !SILENT_TEST + sal_Int32 nWrite1 = +#endif + csConnectorSocket.write( pTestString1, 11 ); // "test socket" + +#if !SILENT_TEST + sal_Int32 nWrite2 = +#endif + csConnectorSocket.write( pTestString2, strlen( pTestString2 ) + 1 ); + thread_sleep( 2 ); + csConnectorSocket.write( pTestString2, strlen( pTestString2 ) + 1 ); + t_print("nWrite1 is %d, nWrite2 is %d\n", (int)nWrite1, (int)nWrite2 ); + //thread_sleep( 1 ); + } + else + t_print("# SendClientThread: connect failed! \n"); + + csConnectorSocket.close(); + free( pTimeout ); + } + +}; + + class shutdown: public CppUnit::TestFixture + { + public: + // initialization + void setUp( ) + { + } + + void tearDown( ) + { + + } + + // similar to close_002 + void shutdown_001() + { +#if defined(LINUX) + ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + AcceptorThread myAcceptorThread( asSocket, aHostIp1 ); + myAcceptorThread.create(); + + thread_sleep( 1 ); + + //when accepting, shutdown the socket, the thread will not block for accepting + asSocket.shutdown(); + myAcceptorThread.join(); + + CPPUNIT_ASSERT_MESSAGE( "test for close when is accepting: the socket will quit accepting status.", + myAcceptorThread.isOK( ) == sal_True ); +#endif + } + + void shutdown_002() + { + ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + ::osl::SocketAddr saLocalSocketAddr( aHostIp1, IP_PORT_MYPORT9); + asSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); + CPPUNIT_ASSERT_MESSAGE("shutdown_002: bind fail", asSocket.bind( saLocalSocketAddr ) == sal_True); + CPPUNIT_ASSERT_MESSAGE("shutdown_002: listen fail", asSocket.listen( 1 ) == sal_True ); + sal_Char pReadBuffer[40]; + SendClientThread mySendThread; + mySendThread.create(); + + asSocket.enableNonBlockingMode( sal_False ); + ::osl::StreamSocket ssConnectionSocket; + oslSocketResult eResult = asSocket.acceptConnection( ssConnectionSocket ); + CPPUNIT_ASSERT_MESSAGE("shutdown_002: acceptConnection fail", eResult == osl_Socket_Ok ); + + /* set socket option SO_LINGER 0, so close immediatly */ + linger aLingerSet; + sal_Int32 nBufferLen = sizeof( struct linger ); + aLingerSet.l_onoff = 0; + aLingerSet.l_linger = 0; + + ssConnectionSocket.setOption( osl_Socket_OptionLinger, &aLingerSet, nBufferLen ); + thread_sleep( 1 ); + //sal_uInt32 nRecv1 = 0; + sal_Int32 nRead1 = ssConnectionSocket.read( pReadBuffer, 11 ); + + //shutdown read after client the first send complete + ssConnectionSocket.shutdown( osl_Socket_DirRead ); + + sal_Int32 nRead2 = ssConnectionSocket.read( pReadBuffer + nRead1, 12 ); + sal_Int32 nRead3 = ssConnectionSocket.read( pReadBuffer + nRead1 + nRead2, 12 ); + t_print("after read 2, nRead1 is %d, nRead2 is %d, nRead3 is %d \n", (int) nRead1, (int) nRead2, (int) nRead3 ); + mySendThread.join(); + + ssConnectionSocket.close(); + asSocket.close(); + + /* on Linux, if send is before shutdown(DirRead), can read, nRecv2 still > 0, + http://dbforums.com/arch/186/2002/12/586417 + While on Solaris, after shutdown(DirRead), all read will return 0 + */ +#ifdef LINUX + CPPUNIT_ASSERT_MESSAGE( "test for shutdown read direction: the socket can not read(recv).", + nRead1 > 0 && nRead3 == 0 ); +#else + CPPUNIT_ASSERT_MESSAGE( "test for shutdown read direction: the socket can not read(recv).", + nRead1 > 0 && nRead2 == 0 && nRead3 == 0 ); +#endif + + } + + void shutdown_003() + { + ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + ::osl::SocketAddr saLocalSocketAddr( aHostIp1, IP_PORT_MYPORT9); + asSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); + CPPUNIT_ASSERT_MESSAGE("shutdown_002: bind fail", asSocket.bind( saLocalSocketAddr ) == sal_True); + CPPUNIT_ASSERT_MESSAGE("shutdown_002: listen fail", asSocket.listen( 1 ) == sal_True ); + sal_Char pReadBuffer[40]; + SendClientThread mySendThread; + mySendThread.create(); + + asSocket.enableNonBlockingMode( sal_False ); + ::osl::StreamSocket ssConnectionSocket; + oslSocketResult eResult = asSocket.acceptConnection( ssConnectionSocket ); + CPPUNIT_ASSERT_MESSAGE("shutdown_002: acceptConnection fail", eResult == osl_Socket_Ok ); + + thread_sleep( 1 ); + //shutdown write after client the first send complete + ssConnectionSocket.shutdown( osl_Socket_DirWrite ); + + // recv should not shutdown + sal_Int32 nRead1 = ssConnectionSocket.read( pReadBuffer, 11 ); + + sal_Int32 nWrite = ssConnectionSocket.write( pReadBuffer, 11 ); + // still can read + sal_Int32 nRead3 = ssConnectionSocket.read( pReadBuffer + nRead1 , 12 ); + t_print("after read 2, nRead1 is %d, nWrite is %d, nRead3 is %d\n", (int) nRead1, (int) nWrite, (int) nRead3 ); + mySendThread.join(); + ssConnectionSocket.close(); + asSocket.close(); + + CPPUNIT_ASSERT_MESSAGE( "test for shutdown read direction: the socket can not send(write).", + nRead1 > 0 && nWrite == 0 && nRead3 > 0); + + } + + CPPUNIT_TEST_SUITE( shutdown ); + CPPUNIT_TEST( shutdown_001 ); + CPPUNIT_TEST( shutdown_002 ); + CPPUNIT_TEST( shutdown_003 ); + CPPUNIT_TEST_SUITE_END(); + }; // class shutdown + + class isExceptionPending: public CppUnit::TestFixture + { + public: + void isExPending_001() + { + ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + TimeValue *pTimeout; + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 3; + pTimeout->Nanosec = 0; + sal_Bool bOk = asSocket.isExceptionPending( pTimeout ); + free( pTimeout ); + + CPPUNIT_ASSERT_MESSAGE( "test for isExceptionPending.", + bOk == sal_False ); + } + + /**tester's comments: lack of a case that return sal_True, do not know when it will return sal_True*/ + + + CPPUNIT_TEST_SUITE( isExceptionPending ); + CPPUNIT_TEST( isExPending_001 ); + CPPUNIT_TEST_SUITE_END(); + }; // class isExceptionPending + +// ----------------------------------------------------------------------------- + +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_StreamSocket::ctors, "osl_StreamSocket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_StreamSocket::send_recv, "osl_StreamSocket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_StreamSocket::shutdown, "osl_StreamSocket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_StreamSocket::isExceptionPending, "osl_StreamSocket"); + +} // namespace osl_StreamSocket + + +namespace osl_ConnectorSocket +{ + + /** testing the method: + ConnectorSocket(oslAddrFamily Family = osl_Socket_FamilyInet, + oslProtocol Protocol = osl_Socket_ProtocolIp, + oslSocketType Type = osl_Socket_TypeStream); + */ + + class ctors : public CppUnit::TestFixture + { + public: + void ctors_001() + { + /// Socket constructor. + ::osl::ConnectorSocket csSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors_001 constructor function: check if the connector socket was created successfully.", + osl_Socket_TypeStream == csSocket.getType( ) ); + } + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class ctors + + /** testing the method: + oslSocketResult SAL_CALL connect(const SocketAddr& TargetHost, const TimeValue* pTimeout = 0); + */ + + class connect : public CppUnit::TestFixture + { + public: + TimeValue *pTimeout; + ::osl::AcceptorSocket asAcceptorSocket; + ::osl::ConnectorSocket csConnectorSocket; + + + // initialization + void setUp( ) + { + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 3; + pTimeout->Nanosec = 0; + // sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + free( pTimeout ); + // sHandle = NULL; + asAcceptorSocket.close( ); + csConnectorSocket.close( ); + } + + + void connect_001() + { + ::osl::SocketAddr saLocalSocketAddr( aHostIp1, IP_PORT_MYPORT2 ); + ::osl::SocketAddr saTargetSocketAddr( aHostIp1, IP_PORT_MYPORT2 ); + ::osl::SocketAddr saPeerSocketAddr( aHostIp2, IP_PORT_FTP ); + ::osl::StreamSocket ssConnection; + + /// launch server socket + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + + //asAcceptorSocket.enableNonBlockingMode( sal_True ); + //oslSocketResult eResultAccept = asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... + //CPPUNIT_ASSERT_MESSAGE( "accept failed.", osl_Socket_Ok == eResultAccept ); + /// launch client socket + oslSocketResult eResult = csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... + CPPUNIT_ASSERT_MESSAGE( "connect failed.", osl_Socket_Ok == eResult ); + + /// get peer information + csConnectorSocket.getPeerAddr( saPeerSocketAddr );/// connected. + + CPPUNIT_ASSERT_MESSAGE( "test for connect function: try to create a connection with remote host. and check the setup address.", + ( sal_True == compareSocketAddr( saPeerSocketAddr, saLocalSocketAddr ) ) && + ( osl_Socket_Ok == eResult )); + } + //non-blocking mode connect? + void connect_002() + { + ::osl::SocketAddr saLocalSocketAddr( aHostIp1, IP_PORT_MYPORT3 ); + ::osl::SocketAddr saTargetSocketAddr( aHostIp1, IP_PORT_MYPORT3 ); + ::osl::SocketAddr saPeerSocketAddr( aHostIp2, IP_PORT_FTP ); + + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + asAcceptorSocket.enableNonBlockingMode( sal_True ); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + + csConnectorSocket.enableNonBlockingMode( sal_True ); + + oslSocketResult eResult = csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... + CPPUNIT_ASSERT_MESSAGE( "connect failed.", osl_Socket_InProgress == eResult || osl_Socket_Ok == eResult ); + + /// get peer information + csConnectorSocket.getPeerAddr( saPeerSocketAddr ); + + CPPUNIT_ASSERT_MESSAGE( "test for connect function: try to create a connection with remote host. and check the setup address.", + sal_True == compareSocketAddr( saPeerSocketAddr, saLocalSocketAddr ) ) ; + } + // really an error or just delayed + // how to design senarios that will return osl_Socket_Interrupted, osl_Socket_TimedOut + void connect_003() + { + ::osl::SocketAddr saTargetSocketAddr1( aHostIp1, IP_PORT_MYPORT3 ); + ::osl::SocketAddr saTargetSocketAddr2( aHostIpInval1, IP_PORT_MYPORT3 ); + + csConnectorSocket.enableNonBlockingMode( sal_False ); + + oslSocketResult eResult1 = csConnectorSocket.connect( saTargetSocketAddr1, pTimeout ); + oslSocketResult eResult2 = csConnectorSocket.connect( saTargetSocketAddr2, pTimeout ); + CloseSocketThread myCloseThread( csConnectorSocket ); + oslSocketResult eResult3 = csConnectorSocket.connect( saTargetSocketAddr2, pTimeout ); + myCloseThread.join(); + CPPUNIT_ASSERT_MESSAGE( "connect should failed.", osl_Socket_Error == eResult1 && + osl_Socket_Error == eResult2 && osl_Socket_Error == eResult3 ); + + } + + // really an error in non-blocking mode + void connect_004() + { + ::osl::SocketAddr saTargetSocketAddr( aHostIpInval1, IP_PORT_MYPORT3 ); + + csConnectorSocket.enableNonBlockingMode( sal_True ); + + oslSocketResult eResult = csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... + CPPUNIT_ASSERT_MESSAGE( "connect should failed.", osl_Socket_Error == eResult ); + } + /** here need a case: immediate connection, say in non-blocking mode connect return osl_Socket_Ok + */ + + CPPUNIT_TEST_SUITE( connect ); + CPPUNIT_TEST( connect_001 ); + CPPUNIT_TEST( connect_002 ); + CPPUNIT_TEST( connect_003 ); + CPPUNIT_TEST( connect_004 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class connect + + +// ----------------------------------------------------------------------------- + +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_ConnectorSocket::ctors, "osl_ConnectorSocket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_ConnectorSocket::connect, "osl_ConnectorSocket"); + +} // namespace osl_ConnectorSocket + + + +namespace osl_AcceptorSocket +{ + + /** testing the methods: + inline AcceptorSocket(oslAddrFamily Family = osl_Socket_FamilyInet, + oslProtocol Protocol = osl_Socket_ProtocolIp, + oslSocketType Type = osl_Socket_TypeStream); + */ + + class ctors : public CppUnit::TestFixture + { + public: + + void ctors_001() + { + /// Socket constructor. + ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors_001 constructor function: check if the acceptor socket was created successfully.", + osl_Socket_TypeStream == asSocket.getType( ) ); + } + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class ctors + + /** testing the method: + inline sal_Bool SAL_CALL listen(sal_Int32 MaxPendingConnections= -1); + inline oslSocketResult SAL_CALL acceptConnection( StreamSocket& Connection); + inline oslSocketResult SAL_CALL acceptConnection( StreamSocket& Connection, SocketAddr & PeerAddr); + */ + + class listen_accept : public CppUnit::TestFixture + { + public: + TimeValue *pTimeout; + ::osl::AcceptorSocket asAcceptorSocket; + ::osl::ConnectorSocket csConnectorSocket; + + + // initialization + void setUp( ) + { + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 3; + pTimeout->Nanosec = 0; + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1); + // sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + free( pTimeout ); + // sHandle = NULL; + asAcceptorSocket.close( ); + csConnectorSocket.close( ); + } + + + void listen_accept_001() + { + ::osl::SocketAddr saLocalSocketAddr( aHostIp1, IP_PORT_MYPORT3 ); + ::osl::SocketAddr saTargetSocketAddr( aHostIp1, IP_PORT_MYPORT3 ); + ::osl::StreamSocket ssConnection; + + /// launch server socket + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + asAcceptorSocket.enableNonBlockingMode( sal_True ); + + /// launch client socket + csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... + + oslSocketResult eResult = asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... + + CPPUNIT_ASSERT_MESSAGE( "test for listen_accept function: try to create a connection with remote host, using listen and accept.", + ( osl_Socket_Ok == eResult ) ); + } + + void listen_accept_002() + { + ::osl::SocketAddr saLocalSocketAddr( aHostIp1, IP_PORT_MYPORT4 ); + ::osl::SocketAddr saTargetSocketAddr( aHostIp1, IP_PORT_MYPORT4 ); + ::osl::SocketAddr saPeerSocketAddr( aHostIp2, IP_PORT_FTP ); + ::osl::StreamSocket ssConnection; + + /// launch server socket + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + asAcceptorSocket.enableNonBlockingMode( sal_True ); + + /// launch client socket + csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... + + oslSocketResult eResult = asAcceptorSocket.acceptConnection(ssConnection, saPeerSocketAddr); /// waiting for incoming connection... + + CPPUNIT_ASSERT_MESSAGE( "test for listen_accept function: try to create a connection with remote host, using listen and accept, accept with peer address.", + ( sal_True == bOK2 ) && + ( osl_Socket_Ok == eResult ) && + ( sal_True == compareSocketAddr( saPeerSocketAddr, saLocalSocketAddr ) ) ); + } + + void listen_accept_003() + { + + } + + CPPUNIT_TEST_SUITE( listen_accept ); + CPPUNIT_TEST( listen_accept_001 ); + CPPUNIT_TEST( listen_accept_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class listen_accept + + +// ----------------------------------------------------------------------------- + +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_AcceptorSocket::ctors, "osl_AcceptorSocket"); +//CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_AcceptorSocket::operator_assign, "osl_AcceptorSocket"); +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_AcceptorSocket::listen_accept, "osl_AcceptorSocket"); + +} // namespace osl_AcceptorSocket + + +namespace osl_DatagramSocket +{ + + /** testing the methods: + inline DatagramSocket(oslAddrFamily Family= osl_Socket_FamilyInet, + oslProtocol Protocol= osl_Socket_ProtocolIp, + oslSocketType Type= osl_Socket_TypeDgram); + */ + + class ctors : public CppUnit::TestFixture + { + public: + + void ctors_001() + { + /// Socket constructor. + ::osl::DatagramSocket dsSocket; + + CPPUNIT_ASSERT_MESSAGE( "test for ctors_001 constructor function: check if the datagram socket was created successfully.", + osl_Socket_TypeDgram == dsSocket.getType( ) ); + } + + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class ctors + +/**thread do sendTo, refer to http://www.coding-zone.co.uk/cpp/articles/140101networkprogrammingv.shtml +*/ +class TalkerThread : public Thread +{ +protected: + ::osl::SocketAddr saTargetSocketAddr; + ::osl::DatagramSocket dsSocket; + + void SAL_CALL run( ) + { + dsSocket.sendTo( saTargetSocketAddr, pTestString1, strlen( pTestString1 ) + 1 ); // "test socket" + dsSocket.shutdown(); + } + + void SAL_CALL onTerminated( ) + { + } + +public: + TalkerThread( ): + saTargetSocketAddr( aHostIp1, IP_PORT_MYPORT9 ) + { + } + + ~TalkerThread( ) + { + if ( isRunning( ) ) + t_print("# error: TalkerThread not terminated normally.\n" ); + } +}; + +/**thread do listen, refer to http://www.coding-zone.co.uk/cpp/articles/140101networkprogrammingv.shtml +*/ +class ListenerThread : public Thread +{ +protected: + ::osl::SocketAddr saTargetSocketAddr; + ::osl::DatagramSocket dsSocket; + + void SAL_CALL run( ) + { + ::osl::SocketAddr saLocalSocketAddr( aHostIp1, IP_PORT_MYPORT10 ); + dsSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); + if ( dsSocket.bind( saLocalSocketAddr ) == sal_False ) + { + t_print("DatagramSocket bind failed \n"); + return; + } + //blocking mode: default +#if !SILENT_TEST + sal_Int32 nRecv = +#endif + dsSocket.recvFrom( pRecvBuffer, 30, &saTargetSocketAddr); + t_print("After recvFrom, nRecv is %d\n", (int) nRecv); + } + + void SAL_CALL onTerminated( ) + { + } + +public: + sal_Char pRecvBuffer[30]; + ListenerThread( ): + saTargetSocketAddr( aHostIp1, IP_PORT_MYPORT10 ) + { + pRecvBuffer[0] = '\0'; + } + + ~ListenerThread( ) + { + if ( isRunning( ) ) + t_print("# error: ListenerThread not terminated normally.\n" ); + } + +}; + + /** testing the methods: + inline sal_Int32 DatagramSocket::recvFrom(void* pBuffer, sal_uInt32 BufferSize, + SocketAddr* pSenderAddr, oslSocketMsgFlag Flag ) + inline sal_Int32 DatagramSocket::sendTo( const SocketAddr& ReceiverAddr, + const void* pBuffer, sal_uInt32 BufferSize, oslSocketMsgFlag Flag ) + */ + + class sendTo_recvFrom : public CppUnit::TestFixture + { + public: + + void sr_001() + { + ::osl::SocketAddr saLocalSocketAddr( aHostIp1, IP_PORT_MYPORT9 ); + ::osl::DatagramSocket dsSocket; + dsSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); + dsSocket.bind( saLocalSocketAddr ); + + sal_Char pReadBuffer[30]; + TalkerThread myTalkThread; + myTalkThread.create(); + sal_Int32 nRecv = dsSocket.recvFrom( pReadBuffer, 30, &saLocalSocketAddr); + myTalkThread.join(); + //t_print("#received buffer is %s# \n", pReadBuffer); + + sal_Bool bOk = ( strcmp(pReadBuffer, pTestString1) == 0 ); + + CPPUNIT_ASSERT_MESSAGE( "test for sendTo/recvFrom function: create a talker thread and recvFrom in the main thread, check if the datagram socket can communicate successfully.", + nRecv > 0 && bOk == sal_True ); + } + + void sr_002() + { + ::osl::SocketAddr saListenSocketAddr( aHostIp1, IP_PORT_MYPORT10 ); + ::osl::DatagramSocket dsSocket; + + //listener thread construct a DatagramSocket, recvFrom waiting for data, then main thread sendto data + ListenerThread myListenThread; + myListenThread.create(); + //to grantee the recvFrom is before sendTo + thread_sleep( 1 ); + + sal_Int32 nSend = dsSocket.sendTo( saListenSocketAddr, pTestString2, strlen( pTestString2 ) + 1 ); + + CPPUNIT_ASSERT_MESSAGE( "DatagramSocket sendTo failed: nSend <= 0.", nSend > 0); + + myListenThread.join(); + //t_print("#received buffer is %s# \n", myListenThread.pRecvBuffer); + + sal_Bool bOk = ( strcmp( myListenThread.pRecvBuffer, pTestString2) == 0 ); + + CPPUNIT_ASSERT_MESSAGE( "test for sendTo/recvFrom function: create a listener thread and sendTo in the main thread, check if the datagram socket can communicate successfully.", + bOk == sal_True ); + } + + //sendTo error, return -1; recvFrom error, return -1 + void sr_003() + { + ::osl::SocketAddr saListenSocketAddr( aHostIpInval1, IP_PORT_MYPORT10 ); + ::osl::DatagramSocket dsSocket; + // Transport endpoint is not connected + sal_Int32 nSend = dsSocket.sendTo( saListenSocketAddr, pTestString2, strlen( pTestString2 ) + 1 ); + CPPUNIT_ASSERT_MESSAGE( "DatagramSocket sendTo should fail: nSend <= 0.", + nSend == -1 ); + } + + void sr_004() + { + ::osl::SocketAddr saListenSocketAddr1( aHostIpInval1, IP_PORT_MYPORT10 ); + ::osl::SocketAddr saListenSocketAddr2( aHostIp2, IP_PORT_MYPORT10 ); + ::osl::DatagramSocket dsSocket; + + dsSocket.enableNonBlockingMode( sal_True ); + + sal_Char pReadBuffer[30]; + //sal_Int32 nRecv1 = dsSocket.recvFrom( pReadBuffer, 30, &saListenSocketAddr1 ); + + // will block ? + CloseSocketThread myThread( dsSocket ); + myThread.create(); + sal_Int32 nRecv2 = dsSocket.recvFrom( pReadBuffer, 30, &saListenSocketAddr1 ); + myThread.join(); + //t_print("#nRecv1 is %d nRecv2 is %d\n", nRecv1, nRecv2 ); + CPPUNIT_ASSERT_MESSAGE( "DatagramSocket sendTo should fail: nSend <= 0.", + nRecv2 == -1 ); + } + + CPPUNIT_TEST_SUITE( sendTo_recvFrom ); + CPPUNIT_TEST( sr_001 ); + CPPUNIT_TEST( sr_002 ); + CPPUNIT_TEST( sr_003 ); + CPPUNIT_TEST( sr_004 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class sendTo_recvFrom + +// ----------------------------------------------------------------------------- + +CPPUNIT_TEST_SUITE_REGISTRATION(osl_DatagramSocket::ctors); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_DatagramSocket::sendTo_recvFrom); + +} // namespace osl_DatagramSocket + + +// ----------------------------------------------------------------------------- + +// this macro creates an empty function, which will called by the RegisterAllFunctions() +// to let the user the possibility to also register some functions by hand. +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/socket/osl_Socket.xsce b/sal/qa/osl/socket/osl_Socket.xsce new file mode 100644 index 000000000000..38c02c8c75a3 --- /dev/null +++ b/sal/qa/osl/socket/osl_Socket.xsce @@ -0,0 +1,5 @@ +osl_Socket.ctors.ctors_family_Ipx +osl_SocketAddr.getHostname.getHostname_002 + +osl_StreamSocket.send_recv.write_read_003 unxsols +osl_StreamSocket.send_recv.write_read_004 unxsols diff --git a/sal/qa/osl/socket/osl_Socket2.cxx b/sal/qa/osl/socket/osl_Socket2.cxx new file mode 100644 index 000000000000..bee02b978f4c --- /dev/null +++ b/sal/qa/osl/socket/osl_Socket2.cxx @@ -0,0 +1,1470 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +/** test coder preface: + 1. the BSD socket function will meet "unresolved external symbol error" on Windows platform + if you are not including ws2_32.lib in makefile.mk, the including format will be like this: + + .IF "$(GUI)" == "WNT" + SHL1STDLIBS += $(SOLARLIBDIR)$/cppunit.lib + SHL1STDLIBS += ws2_32.lib + .ENDIF + + likewise on Solaris platform. + .IF "$(GUI)" == "UNX" + SHL1STDLIBS+=$(SOLARLIBDIR)$/libcppunit$(DLLPOSTFIX).a + SHL1STDLIBS += -lsocket -ldl -lnsl + .ENDIF + + 2. since the Socket implementation of osl is only IPv4 oriented, our test are mainly focus on IPv4 + category. + + 3. some fragment of Socket source implementation are lack of comment so it is hard for testers + guess what the exact functionality or usage of a member. Hope the Socket section's comment + will be added. + + 4. following functions are declared but not implemented: + inline sal_Bool SAL_CALL operator== (const SocketAddr & Addr) const; + */ + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> + +#include "sockethelper.hxx" + +using namespace osl; +using ::rtl::OUString; + +#define IP_PORT_FTP 21 +#define IP_PORT_TELNET 23 +#define IP_PORT_HTTP2 8080 +#define IP_PORT_INVAL 99999 +#define IP_PORT_POP3 110 +#define IP_PORT_NETBIOS 139 +#define IP_PORT_MYPORT 8881 +#define IP_PORT_MYPORT1 8882 +#define IP_PORT_MYPORT5 8886 +#define IP_PORT_MYPORT6 8887 +#define IP_PORT_MYPORT7 8895 +#define IP_PORT_MYPORT8 8896 +#define IP_PORT_MYPORT9 8897 + +//------------------------------------------------------------------------ +// helper functions +//------------------------------------------------------------------------ + +// just used to test socket::close() when accepting +class AcceptorThread : public Thread +{ + ::osl::AcceptorSocket asAcceptorSocket; + ::rtl::OUString aHostIP; + sal_Bool bOK; +protected: + void SAL_CALL run( ) + { + ::osl::SocketAddr saLocalSocketAddr( aHostIP, IP_PORT_MYPORT9 ); + ::osl::StreamSocket ssStreamConnection; + + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //integer not sal_Bool : sal_True); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + if ( sal_True != bOK1 ) + { + t_print("# AcceptorSocket bind address failed.\n" ) ; + return; + } + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + if ( sal_True != bOK2 ) + { + t_print("# AcceptorSocket listen address failed.\n" ) ; + return; + } + + asAcceptorSocket.enableNonBlockingMode( sal_False ); + + oslSocketResult eResult = asAcceptorSocket.acceptConnection( ssStreamConnection ); + if (eResult != osl_Socket_Ok ) + { + bOK = sal_True; + t_print("AcceptorThread: acceptConnection failed! \n"); + } + } +public: + AcceptorThread(::osl::AcceptorSocket & asSocket, ::rtl::OUString const& aBindIP ) + : asAcceptorSocket( asSocket ), aHostIP( aBindIP ) + { + bOK = sal_False; + } + + sal_Bool isOK() { return bOK; } + + ~AcceptorThread( ) + { + if ( isRunning( ) ) + { + asAcceptorSocket.shutdown(); + t_print("# error: Acceptor thread not terminated.\n" ); + } + } +}; + +namespace osl_Socket +{ + + /** testing the methods: + inline Socket( ); + inline Socket( const Socket & socket ); + inline Socket( oslSocket socketHandle ); + inline Socket( oslSocket socketHandle, __sal_NoAcquire noacquire ); + */ + + /** test writer's comment: + + class Socket can not be initialized by its protected constructor, though the protected + constructor is the most convenient way to create a new socket. + it only allow the method of C function osl_createSocket like: + ::osl::Socket sSocket( osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, + osl_Socket_ProtocolIp ) ); + the use of C method lost some of the transparent of tester using C++ wrapper. + */ + + + class ctors : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void ctors_none() + { + /// Socket constructor. + // ::osl::Socket sSocket(); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors_none constructor function: check if the socket was created successfully, if no exception occurred", + 1 == 1 ); + } + + void ctors_acquire() + { + /// Socket constructor. + ::osl::Socket sSocket( sHandle ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors_acquire constructor function: check if the socket was created successfully", + osl_Socket_TypeStream == sSocket.getType( ) ); + } + + void ctors_no_acquire() + { + /// Socket constructor. + ::osl::Socket sSocket( sHandle, SAL_NO_ACQUIRE ); + + CPPUNIT_ASSERT_MESSAGE(" test for ctors_no_acquire constructor function: check if the socket was created successfully", + osl_Socket_TypeStream == sSocket.getType( ) ); + } + + void ctors_copy_ctor() + { + ::osl::Socket sSocket( sHandle ); + /// Socket copy constructor. + ::osl::Socket copySocket( sSocket ); + + CPPUNIT_ASSERT_MESSAGE(" test for ctors_copy_ctor constructor function: create new Socket instance using copy constructor", + osl_Socket_TypeStream == copySocket.getType( ) ); + } + + void ctors_TypeRaw() + { +#ifdef WNT + oslSocket sHandleRaw = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeRaw, osl_Socket_ProtocolIp ); +// LLA: ? ::osl::Socket sSocket( sHandleRaw ); + CPPUNIT_ASSERT_MESSAGE( " type osl_Socket_TypeRaw socket create failed on UNX ", sHandleRaw != NULL); +#else + oslSocket sHandleRaw = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeRaw, osl_Socket_ProtocolIp ); + CPPUNIT_ASSERT_MESSAGE( " can't create socket with type osl_Socket_TypeRaw within UNX is ok.", sHandleRaw == NULL); +#endif + } + + void ctors_family_Ipx() + { + oslSocket sHandleIpx = osl_createSocket( osl_Socket_FamilyIpx, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + CPPUNIT_ASSERT_MESSAGE( " family osl_Socket_FamilyIpx socket create failed! ", sHandleIpx != NULL); + ::osl::Socket sSocket( sHandleIpx ); //, SAL_NO_ACQUIRE ); + t_print("#Type is %d \n", sSocket.getType( ) ); + + CPPUNIT_ASSERT_MESSAGE(" test for create new Socket instance that family is osl_Socket_FamilyIpx", + osl_Socket_TypeStream == sSocket.getType( ) ); + } + + + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_none ); + CPPUNIT_TEST( ctors_acquire ); + CPPUNIT_TEST( ctors_no_acquire ); + CPPUNIT_TEST( ctors_copy_ctor ); + CPPUNIT_TEST( ctors_TypeRaw ); + //TODO: Check if family_Ipx is still in use? + // CPPUNIT_TEST( ctors_family_Ipx ); + CPPUNIT_TEST_SUITE_END(); + + }; // class ctors + + + /** testing the methods: + inline Socket& SAL_CALL operator= ( oslSocket socketHandle); + inline Socket& SAL_CALL operator= (const Socket& sock); + inline sal_Bool SAL_CALL operator==( const Socket& rSocket ) const ; + inline sal_Bool SAL_CALL operator==( const oslSocket socketHandle ) const; + */ + + class operators : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + /** test writer's comment: + + the assignment operator does not support direct assinment like: + ::osl::Socket sSocket = sHandle. + */ + void operators_assignment_handle() + { + ::osl::Socket sSocket(sHandle); + ::osl::Socket assignSocket = sSocket.getHandle(); + + CPPUNIT_ASSERT_MESSAGE( "test for operators_assignment_handle function: test the assignment operator.", + osl_Socket_TypeStream == assignSocket.getType( ) ); + } + + void operators_assignment() + { + ::osl::Socket sSocket( sHandle ); + ::osl::Socket assignSocket = sSocket; + + CPPUNIT_ASSERT_MESSAGE( "test for operators_assignment function: assignment operator", + osl_Socket_TypeStream == assignSocket.getType( ) ); + } + + void operators_equal_handle_001() + { + /// Socket constructor. + ::osl::Socket sSocket( sHandle ); + ::osl::Socket equalSocket = sSocket; + + CPPUNIT_ASSERT_MESSAGE(" test for operators_equal_handle_001 function: check equal.", + equalSocket == sHandle ); + } + + void operators_equal_handle_002() + { + /// Socket constructor. + ::osl::Socket equalSocket( osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ) ); + + CPPUNIT_ASSERT_MESSAGE(" test for operators_equal_handle_001 function: check unequal.", + !( equalSocket == sHandle ) ); + } + + void operators_equal_001() + { + ::osl::Socket sSocket( sHandle ); + /// Socket copy constructor. + ::osl::Socket equalSocket( sSocket ); + + CPPUNIT_ASSERT_MESSAGE(" test for operators_equal function: check equal.", + equalSocket == sSocket ); + } + + void operators_equal_002() + { + ::osl::Socket sSocket( sHandle ); + /// Socket copy constructor. + ::osl::Socket equalSocket( osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ) ); + + CPPUNIT_ASSERT_MESSAGE(" test for operators_equal_002 function: check unequal.", + !( equalSocket == sSocket ) ); + } + + CPPUNIT_TEST_SUITE( operators ); + CPPUNIT_TEST( operators_assignment_handle ); + CPPUNIT_TEST( operators_assignment ); + CPPUNIT_TEST( operators_equal_handle_001 ); + CPPUNIT_TEST( operators_equal_handle_002 ); + CPPUNIT_TEST( operators_equal_001 ); + CPPUNIT_TEST( operators_equal_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class operators + + + /** testing the methods: + inline void SAL_CALL shutdown( oslSocketDirection Direction = osl_Socket_DirReadWrite ); + inline void SAL_CALL close(); + */ + + class close : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void close_001() + { + ::osl::Socket sSocket(sHandle); + sSocket.close(); + + CPPUNIT_ASSERT_MESSAGE( "test for close_001 function: this function is reserved for test.", + sSocket.getHandle() == sHandle ); + } + + void close_002() + { +//#if defined(LINUX) + ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + AcceptorThread myAcceptorThread( asSocket, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")) ); + myAcceptorThread.create(); + + thread_sleep( 1 ); + //when accepting, close the socket, the thread will not block for accepting + //man close:Any locks held on the file it was associated with, and owned by the process, are removed + asSocket.close(); + //thread_sleep( 2 ); + myAcceptorThread.join(); + + CPPUNIT_ASSERT_MESSAGE( "test for close when is accepting: the socket will quit accepting status.", + myAcceptorThread.isOK() == sal_True ); +//#endif + } + + // to cover "if ( pSockAddrIn->sin_addr.s_addr == htonl(INADDR_ANY) )" in osl_closeSocket( ) + void close_003() + { + ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + AcceptorThread myAcceptorThread( asSocket, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("0.0.0.0")) ); + myAcceptorThread.create(); + + thread_sleep( 1 ); + asSocket.close(); + myAcceptorThread.join(); + + CPPUNIT_ASSERT_MESSAGE( "test for close when is accepting: the socket will quit accepting status.", + myAcceptorThread.isOK() == sal_True ); + } + + CPPUNIT_TEST_SUITE( close ); + CPPUNIT_TEST( close_001 ); + CPPUNIT_TEST( close_002 ); + CPPUNIT_TEST( close_003 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class close + + /** testing the method: + inline void SAL_CALL getLocalAddr( SocketAddr &Addr ) const; + */ + + class getLocalAddr : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + // get the Address of the local end of the socket + void getLocalAddr_001() + { + ::osl::Socket sSocket(sHandle); + ::osl::SocketAddr saBindSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT8 ); + ::osl::SocketAddr saLocalSocketAddr; + + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + + sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); + ::rtl::OUString suError1 = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Socket bind fail:")) + sSocket.getErrorAsString(); + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError1), sal_True == bOK1 ); + + sSocket.getLocalAddr( saLocalSocketAddr ); + + sal_Bool bOK = compareUString( saLocalSocketAddr.getHostname( 0 ), sSocket.getLocalHost() ) ; + + CPPUNIT_ASSERT_MESSAGE( "test for getLocalAddr function: first create a new socket, then a socket address, bind them, and check the address.", + sal_True == bOK ); + } + + + CPPUNIT_TEST_SUITE( getLocalAddr ); + CPPUNIT_TEST( getLocalAddr_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getLocalAddr + + + /** testing the method: + inline sal_Int32 SAL_CALL getLocalPort() const; + */ + + class getLocalPort : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void getLocalPort_001() + { + ::osl::Socket sSocket(sHandle); + ::osl::SocketAddr saBindSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT7 ); // aHostIp1 localhost + ::osl::SocketAddr saLocalSocketAddr; + + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + + sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); + ::rtl::OUString suError1 = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Socket bind fail:")) + sSocket.getErrorAsString(); + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError1), sal_True == bOK1 ); + sal_Bool bOK = ( IP_PORT_MYPORT7 == sSocket.getLocalPort( ) ); + + CPPUNIT_ASSERT_MESSAGE( "test for getLocalPort function: first create a new socket, then a socket address, bind them, and check the port.", + sal_True == bOK ); + } + + /** test writer's comment: + + the invalid port number can not be set by giving invalid port number + such as 99999 or -1, it will convert to ( x mod 65535 ), so it will always be + valid, the only instance that the getLocalPort returns OSL_INVALID_PORT + is when saSocketAddr itself is an invalid one, that is , the IP or host name + can not be found, then the created socket address is not valid. + */ + void getLocalPort_002() + { + ::osl::SocketAddr saBindSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("123.45.67.89")), IP_PORT_TELNET); +#ifdef WNT + ::osl::Socket sSocket(sHandle); + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); // sal_True); + sSocket.bind( saBindSocketAddr ); + //Invalid IP, so bind should fail + ::rtl::OUString suError = outputError(::rtl::OUString::valueOf(sSocket.getLocalPort( )), + ::rtl::OUString::valueOf((sal_Int32)OSL_INVALID_PORT), + "test for getLocalPort function: first create a new socket, then an invalid socket address, bind them, and check the port assigned."); + sal_Bool bOK = ( OSL_INVALID_PORT == sSocket.getLocalPort( ) ); + (void)bOK; +#else + //on Unix, if Addr is not an address of type osl_Socket_FamilyInet, it returns OSL_INVALID_PORT + ::rtl::OUString suError (RTL_CONSTASCII_USTRINGPARAM("on Unix, if Addr is not an address of type osl_Socket_FamilyInet, it returns OSL_INVALID_PORT, but can not create Addr of that case")); +#endif + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError), sal_False ); + + } + + void getLocalPort_003() + { + ::osl::Socket sSocket(sHandle); + ::osl::SocketAddr saBindSocketAddr( getLocalIP(), IP_PORT_INVAL); + + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + + sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); + ::rtl::OUString suError1 = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Socket bind fail:")) + sSocket.getErrorAsString(); + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError1), sal_True == bOK1 ); + ::rtl::OUString suError = outputError(::rtl::OUString::valueOf(sSocket.getLocalPort( )), + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("34463")), + "test for getLocalPort function: first create a new socket, then an invalid socket address, bind them, and check the port assigned"); + sal_Bool bOK = ( sSocket.getLocalPort( ) >= 1 && sSocket.getLocalPort( ) <= 65535); + + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError), sal_True == bOK ); + } + + CPPUNIT_TEST_SUITE( getLocalPort ); + CPPUNIT_TEST( getLocalPort_001 ); +// LLA: CPPUNIT_TEST( getLocalPort_002 ); + CPPUNIT_TEST( getLocalPort_003 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getLocalPort + + + /** testing the method: + inline ::rtl::OUString SAL_CALL getLocalHost() const; + + Mindyliu: on Linux, at first it will check the binded in /etc/hosts, if it has the binded IP, it will return the hostname in it; + else if the binded IP is "127.0.0.1", it will return "localhost", if it's the machine's ethernet ip such as "129.158.217.90", it + will return hostname of current processor such as "aegean.PRC.Sun.COM" + */ + + class getLocalHost : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void getLocalHost_001() + { + ::osl::Socket sSocket(sHandle); + //port number from IP_PORT_HTTP1 to IP_PORT_MYPORT6, mindyliu + ::osl::SocketAddr saBindSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT6 ); + + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + + sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); + ::rtl::OUString suError1 = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Socket bind fail:")) + sSocket.getErrorAsString(); + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError1), sal_True == bOK1 ); + sal_Bool bOK; + ::rtl::OUString suError; +#ifdef WNT + bOK = compareUString( sSocket.getLocalHost( ), getThisHostname( ) ) ; + suError = outputError(sSocket.getLocalHost( ), getThisHostname( ), +"test for getLocalHost function: create localhost socket and check name"); +#else + ::rtl::OUString aUString = ::rtl::OUString::createFromAscii( (const sal_Char *) "localhost" ); + sal_Bool bRes1, bRes2; + bRes1 = compareUString( sSocket.getLocalHost( ), aUString ) ; + bRes2 = compareUString( sSocket.getLocalHost( ), saBindSocketAddr.getHostname(0) ) ; + bOK = bRes1 || bRes2; + suError = outputError(sSocket.getLocalHost( ), aUString, "test for getLocalHost function: create localhost socket and check name"); +#endif + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError), sal_True == bOK ); + } + + void getLocalHost_002() + { + ::osl::Socket sSocket(sHandle); + ::osl::SocketAddr saBindSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("123.45.67.89")), IP_PORT_POP3); + ::osl::SocketAddr saLocalSocketAddr; + + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + sSocket.bind( saBindSocketAddr ); + //Invalid IP, so bind should fail + sal_Bool bOK = compareUString( sSocket.getLocalHost( ), rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("")) ) ; + ::rtl::OUString suError = outputError(sSocket.getLocalHost( ), rtl::OUString(), "test for getLocalHost function: getLocalHost with invalid SocketAddr"); + + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError), sal_True == bOK ); + } + + CPPUNIT_TEST_SUITE( getLocalHost ); + CPPUNIT_TEST( getLocalHost_001 ); + CPPUNIT_TEST( getLocalHost_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getLocalHost + + + /** testing the methods: + inline void SAL_CALL getPeerAddr( SocketAddr & Addr) const; + inline sal_Int32 SAL_CALL getPeerPort() const; + inline ::rtl::OUString SAL_CALL getPeerHost() const; + */ + class getPeer : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + TimeValue *pTimeout; + ::osl::AcceptorSocket asAcceptorSocket; + ::osl::ConnectorSocket csConnectorSocket; + + + // initialization + void setUp( ) + { + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 3; + pTimeout->Nanosec = 0; + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + free( pTimeout ); + sHandle = NULL; + asAcceptorSocket.close( ); + csConnectorSocket.close( ); + } + + + void getPeer_001() + { + ::osl::SocketAddr saLocalSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT ); + ::osl::SocketAddr saTargetSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT ); + ::osl::SocketAddr saPeerSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.202")), IP_PORT_FTP ); + ::osl::StreamSocket ssConnection; + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + /// launch server socket + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind '127.0.0.1' address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + + asAcceptorSocket.enableNonBlockingMode( sal_True ); + asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... + + /// launch client socket + csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... + + /// get peer information + csConnectorSocket.getPeerAddr( saPeerSocketAddr );/// connected. + sal_Int32 peerPort = csConnectorSocket.getPeerPort( ); + ::rtl::OUString peerHost = csConnectorSocket.getPeerHost( ); + + CPPUNIT_ASSERT_MESSAGE( "test for getPeer function: setup a connection and then get the peer address, port and host from client side.", + ( sal_True == compareSocketAddr( saPeerSocketAddr, saLocalSocketAddr ) )&& + ( sal_True == compareUString( peerHost, saLocalSocketAddr.getHostname( 0 ) ) ) && + ( peerPort == saLocalSocketAddr.getPort( ) )); + } + + + CPPUNIT_TEST_SUITE( getPeer ); + CPPUNIT_TEST( getPeer_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getPeer + + + /** testing the methods: + inline sal_Bool SAL_CALL bind(const SocketAddr& LocalInterface); + */ + + + class bind : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void bind_001() + { + ::osl::Socket sSocket(sHandle); + //bind must use local IP address ---mindyliu + ::osl::SocketAddr saBindSocketAddr( getLocalIP(), IP_PORT_MYPORT5 ); + + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "Socket bind fail.", sal_True == bOK1 ); + + sal_Bool bOK2 = compareUString( sSocket.getLocalHost( ), saBindSocketAddr.getHostname( ) ) ; + + sSocket.close(); + CPPUNIT_ASSERT_MESSAGE( "test for bind function: bind a valid address.", sal_True == bOK2 ); + } + + void bind_002() + { + ::osl::Socket sSocket(sHandle); + ::osl::SocketAddr saBindSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("123.45.67.89")), IP_PORT_NETBIOS ); + ::osl::SocketAddr saLocalSocketAddr; + + sSocket.setOption( osl_Socket_OptionReuseAddr, 1); // sal_True); + sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); + sal_Bool bOK2 = compareUString( sSocket.getLocalHost( ), getThisHostname( ) ) ; + + CPPUNIT_ASSERT_MESSAGE( "test for bind function: bind a valid address.", + ( sal_False == bOK1 ) && ( sal_False == bOK2 ) ); + } + + CPPUNIT_TEST_SUITE( bind ); + CPPUNIT_TEST( bind_001 ); + CPPUNIT_TEST( bind_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class bind + + + /** testing the methods: + inline sal_Bool SAL_CALL isRecvReady(const TimeValue *pTimeout = 0) const; + + */ + class isRecvReady : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + TimeValue *pTimeout; + ::osl::AcceptorSocket asAcceptorSocket; + ::osl::ConnectorSocket csConnectorSocket; + + + // initialization + void setUp( ) + { + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 3; + pTimeout->Nanosec = 0; + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + free( pTimeout ); + sHandle = NULL; + asAcceptorSocket.close( ); + csConnectorSocket.close( ); + } + + + void isRecvReady_001() + { + ::osl::SocketAddr saLocalSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT1 ); + ::osl::SocketAddr saTargetSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT1 ); + ::osl::SocketAddr saPeerSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.202")), IP_PORT_FTP ); + ::osl::StreamSocket ssConnection; + /// launch server socket + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); // sal_True); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + asAcceptorSocket.enableNonBlockingMode( sal_True ); + asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... + + /// launch client socket + csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... + + /// is receive ready? + sal_Bool bOK3 = asAcceptorSocket.isRecvReady( pTimeout ); + + CPPUNIT_ASSERT_MESSAGE( "test for isRecvReady function: setup a connection and then check if it can transmit data.", + ( sal_True == bOK3 ) ); + } + + + CPPUNIT_TEST_SUITE( isRecvReady ); + CPPUNIT_TEST( isRecvReady_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class isRecvReady + + + /** testing the methods: + inline sal_Bool SAL_CALL isSendReady(const TimeValue *pTimeout = 0) const; + */ + class isSendReady : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + TimeValue *pTimeout; + ::osl::AcceptorSocket asAcceptorSocket; + ::osl::ConnectorSocket csConnectorSocket; + + + // initialization + void setUp( ) + { + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 3; + pTimeout->Nanosec = 0; + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + free( pTimeout ); + sHandle = NULL; + asAcceptorSocket.close( ); + csConnectorSocket.close( ); + } + + + void isSendReady_001() + { + ::osl::SocketAddr saLocalSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT ); + ::osl::SocketAddr saTargetSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT ); + ::osl::SocketAddr saPeerSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.202")), IP_PORT_FTP ); + ::osl::StreamSocket ssConnection; + + /// launch server socket + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + asAcceptorSocket.enableNonBlockingMode( sal_True ); + asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... + + /// launch client socket + csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... + + /// is send ready? + sal_Bool bOK3 = csConnectorSocket.isSendReady( pTimeout ); + + CPPUNIT_ASSERT_MESSAGE( "test for isSendReady function: setup a connection and then check if it can transmit data.", + ( sal_True == bOK3 ) ); + } + + + CPPUNIT_TEST_SUITE( isSendReady ); + CPPUNIT_TEST( isSendReady_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class isSendReady + + + /** testing the methods: + inline oslSocketType SAL_CALL getType() const; + + */ + + class getType : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void getType_001() + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + ::osl::Socket sSocket(sHandle); + + CPPUNIT_ASSERT_MESSAGE( "test for getType function: get type of socket.", + osl_Socket_TypeStream == sSocket.getType( ) ); + } + + void getType_002() + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ); + ::osl::Socket sSocket(sHandle); + + CPPUNIT_ASSERT_MESSAGE( "test for getType function: get type of socket.", + osl_Socket_TypeDgram == sSocket.getType( ) ); + } + +#ifdef UNX + // mindy: since on LINUX and SOLARIS, Raw type socket can not be created, so do not test getType() here + // mindy: and add one test case to test creating Raw type socket--> ctors_TypeRaw() + void getType_003() + { + CPPUNIT_ASSERT_MESSAGE( "test for getType function: get type of socket.this is not passed in (LINUX, SOLARIS), the osl_Socket_TypeRaw, type socket can not be created.", + sal_True); + } +#else + void getType_003() + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeRaw, osl_Socket_ProtocolIp ); + ::osl::Socket sSocket(sHandle); + + CPPUNIT_ASSERT_MESSAGE( "test for getType function: get type of socket.", + osl_Socket_TypeRaw == sSocket.getType( ) ); + } +#endif + + CPPUNIT_TEST_SUITE( getType ); + CPPUNIT_TEST( getType_001 ); + CPPUNIT_TEST( getType_002 ); + CPPUNIT_TEST( getType_003 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getType + + + + /** testing the methods: + inline sal_Int32 SAL_CALL getOption( + oslSocketOption Option, + void* pBuffer, + sal_uInt32 BufferLen, + oslSocketOptionLevel Level= osl_Socket_LevelSocket) const; + + inline sal_Int32 getOption( oslSocketOption option ) const; + + */ + + class getOption : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + + } + + void tearDown( ) + { + sHandle = NULL; + } + + /** test writer's comment: + + in oslSocketOption, the osl_Socket_OptionType denote 1 as osl_Socket_TypeStream. + 2 as osl_Socket_TypeDgram, etc which is not mapping the oslSocketType enum. differ + in 1. + */ + + void getOption_001() + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + ::osl::Socket sSocket(sHandle); + sal_Int32 * pType = ( sal_Int32 * )malloc( sizeof ( sal_Int32 ) ); + *pType = 0; + sSocket.getOption( osl_Socket_OptionType, pType, sizeof ( sal_Int32 ) ); + sal_Bool bOK = ( SOCK_STREAM == *pType ); + // there is a TypeMap(socket.c) which map osl_Socket_TypeStream to SOCK_STREAM on UNX, and SOCK_STREAM != osl_Socket_TypeStream + //sal_Bool bOK = ( TYPE_TO_NATIVE(osl_Socket_TypeStream) == *pType ); + free( pType ); + + CPPUNIT_ASSERT_MESSAGE( "test for getOption function: get type option of socket.", + sal_True == bOK ); + } + + // getsockopt error + void getOption_004() + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ); + ::osl::Socket sSocket(sHandle); + + sal_Bool * pbDontRoute = ( sal_Bool * )malloc( sizeof ( sal_Bool ) ); + sal_Int32 nRes = sSocket.getOption( osl_Socket_OptionInvalid, pbDontRoute, sizeof ( sal_Bool ) ); + free( pbDontRoute ); + + CPPUNIT_ASSERT_MESSAGE( "test for getOption function: get invalid option of socket, should return -1.", + nRes == -1 ); + } + + void getOption_simple_001() + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ); + ::osl::Socket sSocket(sHandle); + + sal_Bool bOK = ( sal_False == sSocket.getOption( osl_Socket_OptionDontRoute ) ); + + CPPUNIT_ASSERT_MESSAGE( "test for getOption function: get debug option of socket.", + sal_True == bOK ); + } + + void getOption_simple_002() + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ); + ::osl::Socket sSocket(sHandle); + + sal_Bool bOK = ( sal_False == sSocket.getOption( osl_Socket_OptionDebug ) ); + + CPPUNIT_ASSERT_MESSAGE( "test for getOption function: get debug option of socket.", + sal_True == bOK ); + } + + CPPUNIT_TEST_SUITE( getOption ); + CPPUNIT_TEST( getOption_001 ); + CPPUNIT_TEST( getOption_004 ); + CPPUNIT_TEST( getOption_simple_001 ); + CPPUNIT_TEST( getOption_simple_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getOption + + + /** testing the methods: + inline sal_Bool SAL_CALL setOption( oslSocketOption Option, + void* pBuffer, + sal_uInt32 BufferLen, + oslSocketOptionLevel Level= osl_Socket_LevelSocket ) const; + */ + + class setOption : public CppUnit::TestFixture + { + public: + TimeValue *pTimeout; +// LLA: maybe there is an error in the source, +// as long as I remember, if a derived class do not overload all ctors there is a problem. + + ::osl::AcceptorSocket asAcceptorSocket; + + void setUp( ) + { + + } + + void tearDown( ) + { + asAcceptorSocket.close( ); + } + + + // LLA: + // getSocketOption returns BufferLen, or -1 if something failed + + // setSocketOption returns sal_True, if option could stored + // else sal_False + + void setOption_001() + { + /// set and get option. + int nBufferLen = sizeof ( sal_Int32); + // LLA: SO_DONTROUTE expect an integer boolean, what ever it is, it's not sal_Bool! + + sal_Int32 * pbDontRouteSet = ( sal_Int32 * )malloc( sizeof ( sal_Int32 ) ); + *pbDontRouteSet = 1; // sal_True; + + sal_Int32 * pGetBuffer = ( sal_Int32 * )malloc( sizeof ( sal_Int32 ) ); + *pGetBuffer = 0; + + // maybe asAcceptorSocket is not right initialized + sal_Bool b1 = asAcceptorSocket.setOption( osl_Socket_OptionDontRoute, pbDontRouteSet, nBufferLen ); + CPPUNIT_ASSERT_MESSAGE( "setOption function failed.", ( sal_True == b1 ) ); + sal_Int32 n2 = asAcceptorSocket.getOption( osl_Socket_OptionDontRoute, pGetBuffer, nBufferLen ); + CPPUNIT_ASSERT_MESSAGE( "getOption function failed.", ( n2 == nBufferLen ) ); + + // on Linux, the value of option is 1, on Solaris, it's 16, but it's not important the exact value, + // just judge it is zero or not! + sal_Bool bOK = ( 0 != *pGetBuffer ); + t_print("#setOption_001: getOption is %"SAL_PRIdINT32" \n", *pGetBuffer); + + // toggle check, set to 0 + *pbDontRouteSet = 0; + + sal_Bool b3 = asAcceptorSocket.setOption( osl_Socket_OptionDontRoute, pbDontRouteSet, sizeof ( sal_Int32 ) ); + CPPUNIT_ASSERT_MESSAGE( "setOption function failed.", ( sal_True == b3 ) ); + sal_Int32 n4 = asAcceptorSocket.getOption( osl_Socket_OptionDontRoute, pGetBuffer, nBufferLen ); + CPPUNIT_ASSERT_MESSAGE( "getOption (DONTROUTE) function failed.", ( n4 == nBufferLen ) ); + + sal_Bool bOK2 = ( 0 == *pGetBuffer ); + + t_print("#setOption_001: getOption is %"SAL_PRIdINT32" \n", *pGetBuffer); + +// LLA: sal_Bool * pbDontTouteSet = ( sal_Bool * )malloc( sizeof ( sal_Bool ) ); +// LLA: *pbDontTouteSet = sal_True; +// LLA: sal_Bool * pbDontTouteGet = ( sal_Bool * )malloc( sizeof ( sal_Bool ) ); +// LLA: *pbDontTouteGet = sal_False; +// LLA: asAcceptorSocket.setOption( osl_Socket_OptionDontRoute, pbDontTouteSet, sizeof ( sal_Bool ) ); +// LLA: asAcceptorSocket.getOption( osl_Socket_OptionDontRoute, pbDontTouteGet, sizeof ( sal_Bool ) ); +// LLA: ::rtl::OUString suError = outputError(::rtl::OUString::valueOf((sal_Int32)*pbDontTouteGet), +// LLA: ::rtl::OUString::valueOf((sal_Int32)*pbDontTouteSet), +// LLA: "test for setOption function: set osl_Socket_OptionDontRoute and then check"); +// LLA: +// LLA: sal_Bool bOK = ( sal_True == *pbDontTouteGet ); +// LLA: free( pbDontTouteSet ); +// LLA: free( pbDontTouteGet ); + + CPPUNIT_ASSERT_MESSAGE( "test for setOption function: set option of a socket and then check.", + ( sal_True == bOK ) && (sal_True == bOK2) ); + + free( pbDontRouteSet ); + free( pGetBuffer ); +// LLA: CPPUNIT_ASSERT_MESSAGE( suError, sal_True == bOK ); + } + + void setOption_002() + { + /// set and get option. + + // sal_Int32 * pbLingerSet = ( sal_Int32 * )malloc( nBufferLen ); + // *pbLingerSet = 7; + // sal_Int32 * pbLingerGet = ( sal_Int32 * )malloc( nBufferLen ); + /* struct */linger aLingerSet; + sal_Int32 nBufferLen = sizeof( struct linger ); + aLingerSet.l_onoff = 1; + aLingerSet.l_linger = 7; + + linger aLingerGet; + + asAcceptorSocket.setOption( osl_Socket_OptionLinger, &aLingerSet, nBufferLen ); + + sal_Int32 n1 = asAcceptorSocket.getOption( osl_Socket_OptionLinger, &aLingerGet, nBufferLen ); + CPPUNIT_ASSERT_MESSAGE( "getOption (SO_LINGER) function failed.", ( n1 == nBufferLen ) ); + + //t_print("#setOption_002: getOption is %d \n", aLingerGet.l_linger); + sal_Bool bOK = ( 7 == aLingerGet.l_linger ); + CPPUNIT_ASSERT_MESSAGE( "test for setOption function: set option of a socket and then check. ", + sal_True == bOK ); + + } + + void setOption_003() + { + linger aLingerSet; + aLingerSet.l_onoff = 1; + aLingerSet.l_linger = 7; + + sal_Bool b1 = asAcceptorSocket.setOption( osl_Socket_OptionLinger, &aLingerSet, 0 ); + printUString( asAcceptorSocket.getErrorAsString( ) ); + CPPUNIT_ASSERT_MESSAGE( "setOption (SO_LINGER) function failed for optlen is 0.", + ( b1 == sal_False ) ); + } + + void setOption_simple_001() + { + /// set and get option. + asAcceptorSocket.setOption( osl_Socket_OptionDontRoute, 1 ); //sal_True ); + sal_Bool bOK = ( 0 != asAcceptorSocket.getOption( osl_Socket_OptionDontRoute ) ); + + t_print("setOption_simple_001(): getoption is %d \n", (int) asAcceptorSocket.getOption( osl_Socket_OptionDontRoute ) ); + CPPUNIT_ASSERT_MESSAGE( "test for setOption function: set option of a socket and then check.", + ( sal_True == bOK ) ); + } + + void setOption_simple_002() + { + /// set and get option. + // LLA: this does not work, due to the fact that SO_LINGER is a structure +// LLA: asAcceptorSocket.setOption( osl_Socket_OptionLinger, 7 ); +// LLA: sal_Bool bOK = ( 7 == asAcceptorSocket.getOption( osl_Socket_OptionLinger ) ); + +// LLA: CPPUNIT_ASSERT_MESSAGE( "test for setOption function: set option of a socket and then check.", +// LLA: ( sal_True == bOK ) ); + } + + CPPUNIT_TEST_SUITE( setOption ); +// CPPUNIT_TEST( setOption_001 ); + CPPUNIT_TEST( setOption_002 ); + CPPUNIT_TEST( setOption_003 ); + //TODO: Check this test +// CPPUNIT_TEST( setOption_simple_001 ); +// LLA: CPPUNIT_TEST( setOption_simple_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class setOption + + + + /** testing the method: + inline sal_Bool SAL_CALL enableNonBlockingMode( sal_Bool bNonBlockingMode); + */ + class enableNonBlockingMode : public CppUnit::TestFixture + { + public: + ::osl::AcceptorSocket asAcceptorSocket; + + void enableNonBlockingMode_001() + { + ::osl::SocketAddr saLocalSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT ); + ::osl::StreamSocket ssConnection; + + /// launch server socket + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + asAcceptorSocket.enableNonBlockingMode( sal_True ); + asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... + + /// if reach this statement, it is non-blocking mode, since acceptConnection will blocked by default. + sal_Bool bOK = sal_True; + asAcceptorSocket.close( ); + + CPPUNIT_ASSERT_MESSAGE( "test for enableNonBlockingMode function: launch a server socket and make it non blocking. if it can pass the acceptConnection statement, it is non-blocking", + ( sal_True == bOK ) ); + } + + + CPPUNIT_TEST_SUITE( enableNonBlockingMode ); + CPPUNIT_TEST( enableNonBlockingMode_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class enableNonBlockingMode + + + /** testing the method: + inline sal_Bool SAL_CALL isNonBlockingMode() const; + */ + class isNonBlockingMode : public CppUnit::TestFixture + { + public: + ::osl::AcceptorSocket asAcceptorSocket; + + void isNonBlockingMode_001() + { + ::osl::SocketAddr saLocalSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT ); + ::osl::StreamSocket ssConnection; + + /// launch server socket + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); // sal_True); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket bind address failed.", sal_True == bOK1 ); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + CPPUNIT_ASSERT_MESSAGE( "AcceptorSocket listen failed.", sal_True == bOK2 ); + + sal_Bool bOK3 = asAcceptorSocket.isNonBlockingMode( ); + asAcceptorSocket.enableNonBlockingMode( sal_True ); + asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... + + /// if reach this statement, it is non-blocking mode, since acceptConnection will blocked by default. + sal_Bool bOK4 = asAcceptorSocket.isNonBlockingMode( ); + asAcceptorSocket.close( ); + + CPPUNIT_ASSERT_MESSAGE( "test for isNonBlockingMode function: launch a server socket and make it non blocking. it is expected to change from blocking mode to non-blocking mode.", + ( sal_False == bOK3 ) && ( sal_True == bOK4 ) ); + } + + + CPPUNIT_TEST_SUITE( isNonBlockingMode ); + CPPUNIT_TEST( isNonBlockingMode_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class isNonBlockingMode + + /** testing the method: + inline void SAL_CALL clearError() const; + */ + class clearError : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void clearError_001() + { + ::osl::Socket sSocket(sHandle); + ::osl::SocketAddr saBindSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("123.45.67.89")), IP_PORT_HTTP2 ); + ::osl::SocketAddr saLocalSocketAddr; + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + sSocket.bind( saBindSocketAddr );//build an error "osl_Socket_E_AddrNotAvail" + oslSocketError seBind = sSocket.getError( ); + sSocket.clearError( ); + + CPPUNIT_ASSERT_MESSAGE( "test for clearError function: trick an error called sSocket.getError( ), and then clear the error states, check the result.", + osl_Socket_E_None == sSocket.getError( ) && seBind != osl_Socket_E_None ); + } + + + CPPUNIT_TEST_SUITE( clearError ); + CPPUNIT_TEST( clearError_001 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class clearError + + + /** testing the methods: + inline oslSocketError getError() const; + inline ::rtl::OUString getErrorAsString( ) const; + */ + class getError : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void getError_001() + { + ::osl::Socket sSocket(sHandle); + ::osl::SocketAddr saBindSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_FTP ); + ::osl::SocketAddr saLocalSocketAddr; + + CPPUNIT_ASSERT_MESSAGE( "test for getError function: should get no error.", + osl_Socket_E_None == sSocket.getError( ) ); + } + + void getError_002() + { + ::osl::Socket sSocket(sHandle); + ::osl::SocketAddr saBindSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("123.45.67.89")), IP_PORT_FTP ); + ::osl::SocketAddr saLocalSocketAddr; + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + sSocket.bind( saBindSocketAddr );//build an error "osl_Socket_E_AddrNotAvail" + //on Solaris, the error no is EACCES, but it has no mapped value, so getError() returned osl_Socket_E_InvalidError. +#if defined(SOLARIS) + CPPUNIT_ASSERT_MESSAGE( "trick an error called sSocket.getError( ), check the getError result.Failed on Solaris, returned osl_Socket_E_InvalidError because no entry to map the errno EACCES. ", + osl_Socket_E_InvalidError == sSocket.getError( ) ); +#else + //while on Linux & Win32, the errno is EADDRNOTAVAIL, getError returned osl_Socket_E_AddrNotAvail. + + CPPUNIT_ASSERT_MESSAGE( "trick an error called sSocket.getError( ), check the getError result.Failed on Solaris, returned osl_Socket_E_InvalidError because no entry to map the errno EACCES. Passed on Linux & Win32", + osl_Socket_E_AddrNotAvail == sSocket.getError( ) ); +#endif + } + + CPPUNIT_TEST_SUITE( getError ); + CPPUNIT_TEST( getError_001 ); + CPPUNIT_TEST( getError_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getError + + + + /** testing the methods: + inline oslSocket getHandle() const; + */ + + class getHandle : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + void getHandle_001() + { + ::osl::Socket sSocket(sHandle); + ::osl::Socket assignSocket = sSocket.getHandle(); + + CPPUNIT_ASSERT_MESSAGE( "test for operators_assignment_handle function: test the assignment operator.", + osl_Socket_TypeStream == assignSocket.getType( ) ); + } + + void getHandle_002() + { + ::osl::Socket sSocket( sHandle ); + ::osl::Socket assignSocket ( sSocket.getHandle( ) ); + + CPPUNIT_ASSERT_MESSAGE( "test for operators_assignment function: assignment operator", + osl_Socket_TypeStream == assignSocket.getType( ) ); + } + + CPPUNIT_TEST_SUITE( getHandle ); + CPPUNIT_TEST( getHandle_001 ); + CPPUNIT_TEST( getHandle_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getHandle + + +// ----------------------------------------------------------------------------- + + +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::ctors); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::operators); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::close); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::getLocalAddr); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::getLocalPort); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::getLocalHost); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::getPeer); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::bind); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::isRecvReady); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::isSendReady); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::getType); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::getOption); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::setOption); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::enableNonBlockingMode); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::isNonBlockingMode); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::clearError); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::getError); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::getHandle); + +} // namespace osl_Socket + +// ----------------------------------------------------------------------------- + +// this macro creates an empty function, which will called by the RegisterAllFunctions() +// to let the user the possibility to also register some functions by hand. +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/socket/osl_Socket2.xsce b/sal/qa/osl/socket/osl_Socket2.xsce new file mode 100644 index 000000000000..66e3bf1379ec --- /dev/null +++ b/sal/qa/osl/socket/osl_Socket2.xsce @@ -0,0 +1,2 @@ +osl_Socket.ctors.ctors_family_Ipx +osl_Socket.getLocalHost.getLocalHost_001 wntmsci diff --git a/sal/qa/osl/socket/osl_SocketAddr.cxx b/sal/qa/osl/socket/osl_SocketAddr.cxx new file mode 100644 index 000000000000..476fadea3d49 --- /dev/null +++ b/sal/qa/osl/socket/osl_SocketAddr.cxx @@ -0,0 +1,890 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +/** test coder preface: + 1. the BSD socket function will meet "unresolved external symbol error" on Windows platform + if you are not including ws2_32.lib in makefile.mk, the including format will be like this: + + .IF "$(GUI)" == "WNT" + SHL1STDLIBS += $(SOLARLIBDIR)$/cppunit.lib + SHL1STDLIBS += ws2_32.lib + .ENDIF + + likewise on Solaris platform. + .IF "$(GUI)" == "UNX" + SHL1STDLIBS+=$(SOLARLIBDIR)$/libcppunit$(DLLPOSTFIX).a + SHL1STDLIBS += -lsocket -ldl -lnsl + .ENDIF + + 2. since the Socket implementation of osl is only IPv4 oriented, our test are mainly focus on IPv4 + category. + + 3. some fragment of Socket source implementation are lack of comment so it is hard for testers + guess what the exact functionality or usage of a member. Hope the Socket section's comment + will be added. + + 4. following functions are declared but not implemented: + inline sal_Bool SAL_CALL operator== (const SocketAddr & Addr) const; + */ + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> + + +#include "sockethelper.hxx" + +using namespace osl; + +using ::rtl::OUString; +using ::rtl::OUStringToOString; +using ::rtl::OString; + +#define IP_PORT_ZERO 0 +#define IP_PORT_FTP 21 +#define IP_PORT_TELNET 23 +#define IP_PORT_HTTP1 80 +#define IP_PORT_HTTP2 8080 + +#define IP_PORT_MYPORT 8881 //8888 +#define IP_PORT_MYPORT2 8883 //8890 +#define IP_PORT_MYPORT3 8884 //8891 +#define IP_PORT_INVAL 99999 +#define IP_PORT_MYPORT4 8885 //8892 +#define IP_PORT_NETBIOS_DGM 138 + + +namespace osl_SocketAddr +{ + + /** testing the methods: + inline SocketAddr(); + inline SocketAddr(const SocketAddr& Addr); + inline SocketAddr(const oslSocketAddr , __osl_socket_NoCopy nocopy ); + inline SocketAddr(oslSocketAddr Addr); + inline SocketAddr( const ::rtl::OUString& strAddrOrHostName, sal_Int32 nPort ); + */ + + class ctors : public CppUnit::TestFixture + { + public: + + void ctors_none() + { + /// SocketAddr constructor. + ::osl::SocketAddr saSocketAddr; + + // oslSocketResult aResult; + // rtl::OUString suHost = saSocketAddr.getLocalHostname( &aResult); + + // rtl::OUString suHost2 = getThisHostname(); + + CPPUNIT_ASSERT_MESSAGE("test for none parameter constructor function: check if the socket address was created successfully", + sal_True == saSocketAddr.is( ) ); + } + + void ctors_none_000() + { + /// SocketAddr constructor. + ::osl::SocketAddr saSocketAddr; + + oslSocketResult aResult; + rtl::OUString suHost = saSocketAddr.getLocalHostname( &aResult); + rtl::OUString suHost2 = getThisHostname(); + + sal_Bool bOk = compareUString(suHost, suHost2); + + rtl::OUString suError (RTL_CONSTASCII_USTRINGPARAM("Host names should be the same. From SocketAddr.getLocalHostname() it is'")); + suError += suHost; + suError += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("', from getThisHostname() it is '")); + suError += suHost2; + suError += rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("'.")); + + CPPUNIT_ASSERT_MESSAGE(STD_STRING(suError), sal_True == bOk); + } + + void ctors_copy() + { + /// SocketAddr copy constructor. + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("localhost")), IP_PORT_HTTP1 ); + ::osl::SocketAddr saCopySocketAddr( saSocketAddr ); + + sal_Int32 nPort = saCopySocketAddr.getPort( ); + + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr copy constructor function: copy constructor, do an action of copy construction then check the port with original set.", + ( sal_True == saCopySocketAddr.is( ) ) && ( nPort == IP_PORT_HTTP1 ) ); + } + + void ctors_copy_no_001() + { + ::osl::SocketAddr* pSocketAddr = new ::osl::SocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("localhost")), IP_PORT_HTTP1 ); + CPPUNIT_ASSERT_MESSAGE("check for new SocketAddr", pSocketAddr != NULL); + + oslSocketAddr psaOSLSocketAddr = pSocketAddr->getHandle( ); + + ::osl::SocketAddr* pSocketAddrCopy = new ::osl::SocketAddr( psaOSLSocketAddr, SAL_NO_COPY ); + + pSocketAddrCopy->setPort( IP_PORT_HTTP2 ); + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr no copy constructor function: do a no copy constructor on a given SocketAddr instance, modify the new instance's port, check the original one.", + pSocketAddr->getPort( ) == IP_PORT_HTTP2 ); + + delete pSocketAddrCopy; + // LLA: don't do this also: delete pSocketAddr; + } + + void ctors_copy_no_002() + { + ::osl::SocketAddr* pSocketAddr = new ::osl::SocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("localhost")), IP_PORT_HTTP1 ); + CPPUNIT_ASSERT_MESSAGE("check for new SocketAddr", pSocketAddr != NULL); + oslSocketAddr psaOSLSocketAddr = pSocketAddr->getHandle( ); + ::osl::SocketAddr* pSocketAddrCopy = new ::osl::SocketAddr( psaOSLSocketAddr, SAL_NO_COPY ); + + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr no copy constructor function: do a no copy constructor on a given SocketAddr instance, modify the new instance's port, check the original one.", + pSocketAddr->getHandle( ) == pSocketAddrCopy->getHandle( ) ); + + delete pSocketAddrCopy; + } + + void ctors_copy_handle_001() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("localhost")), IP_PORT_HTTP1 ); + ::osl::SocketAddr saSocketAddrCopy( saSocketAddr.getHandle( ) ); + + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr copy handle constructor function: copy another Socket's handle, get its port to check copy effect.", + saSocketAddrCopy.getPort( ) == IP_PORT_HTTP1 ); + } + + void ctors_copy_handle_002() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("localhost")), IP_PORT_HTTP1 ); + ::osl::SocketAddr saSocketAddrCopy( saSocketAddr.getHandle( ) ); + saSocketAddrCopy.setPort( IP_PORT_HTTP2 ); + + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr copy handle constructor function: copy another Socket's handle, the original one should not be changed.", + saSocketAddr.getPort( ) != IP_PORT_HTTP2 ); + } + + void ctors_hostname_port_001() + { + /// tcpip-specif constructor. + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_FTP ); + printUString( saSocketAddr.getHostname( ), "ctors_hostname_port_001:getHostname"); + + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr tcpip specif constructor function: do a constructor using tcpip spec, check the result.", + saSocketAddr.is( ) == sal_True && + ( saSocketAddr.getPort( ) == IP_PORT_FTP ) + ); + } + + //same as is_002 + void ctors_hostname_port_002() + { + /// tcpip-specif constructor. + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("123.345.67.89")), IP_PORT_MYPORT2 ); + + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr tcpip specif constructor function: using an invalid IP address, the socketaddr ctors should fail", sal_False == saSocketAddr.is( )); + } + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_none ); + CPPUNIT_TEST( ctors_none_000 ); + CPPUNIT_TEST( ctors_copy ); + CPPUNIT_TEST( ctors_copy_no_001 ); + CPPUNIT_TEST( ctors_copy_no_002 ); + CPPUNIT_TEST( ctors_copy_handle_001 ); + CPPUNIT_TEST( ctors_copy_handle_002 ); + CPPUNIT_TEST( ctors_hostname_port_001 ); + CPPUNIT_TEST( ctors_hostname_port_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class ctors + + + /** testing the method: + inline sal_Bool is() const; + */ + + class is : public CppUnit::TestFixture + { + public: + void is_001() + { + ::osl::SocketAddr saSocketAddr; + + CPPUNIT_ASSERT_MESSAGE("test for is() function: create an unknown type socket, it should be True when call is.", + sal_True == saSocketAddr.is( ) ); + } + // refer to setPort_003() + void is_002() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_INVAL ); + + CPPUNIT_ASSERT_MESSAGE("test for is() function: create a tcp-ip socket using invalid port number", + sal_True == saSocketAddr.is( ) ); + } + + void is_003() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("123.345.67.89")), IP_PORT_MYPORT ); + + CPPUNIT_ASSERT_MESSAGE("test for is() function: create a tcp-ip socket using invalid Ip number", + sal_True != saSocketAddr.is( ) ); + } + + CPPUNIT_TEST_SUITE( is ); + CPPUNIT_TEST( is_001 ); + CPPUNIT_TEST( is_002 ); + CPPUNIT_TEST( is_003 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class is + + + /** testing the method: + inline ::rtl::OUString SAL_CALL getHostname( oslSocketResult *pResult = 0 ) const; + */ + + class getHostname : public CppUnit::TestFixture + { + public: + void setUp() + { + } + + void tearDown() + { + } + + void getHostname_000() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.107")), IP_PORT_FTP ); + rtl::OUString suResult = saSocketAddr.getHostname( 0 ); + + } + + /** it will search the Ip in current machine's /etc/hosts at first, if find, then return the + mapped hostname, otherwise, it will search via DNS server, and often return hostname+ Domain name + like "sceri.PRC.Sun.COM" + The process is same as Socket::getLocalHost(), but getLocalHost can only return hostname of the current machine. + */ + void getHostname_001() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.107")), IP_PORT_FTP ); + rtl::OUString suResult = saSocketAddr.getHostname( 0 ); + rtl::OUString suError = outputError(suResult, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("sceri.PRC.Sun.COM")), "test for getHostname(0)"); + sal_Bool bOK = compareUString( suResult, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("sceri.PRC.Sun.COM")) ); + // search the returned hostname in /etc/hosts, if find, and the IP in the row is same as IP + // in the Addr, it's right also. + if ( bOK == sal_False) + { + rtl::OString aString = ::rtl::OUStringToOString( suResult, RTL_TEXTENCODING_ASCII_US ); + if ( compareUString( getIPbyName( aString ), rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.107")) ) == sal_True ) + bOK = sal_True; + } + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError), sal_True == bOK); + } + +// LLA: now we have to control, if this behaviour is right. +// LLA: this function does not work in company (Linux, Windows) but at home + void getHostname_002() + { + rtl::OUString suHostname (RTL_CONSTASCII_USTRINGPARAM("cn-1.germany.sun.com")); + rtl::OString aString = ::rtl::OUStringToOString( suHostname, RTL_TEXTENCODING_ASCII_US ); + rtl::OUString aHostIP = getIPbyName( aString ); + + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("localhost")), IP_PORT_FTP ); + sal_Bool bOK = saSocketAddr.setHostname( suHostname ); + CPPUNIT_ASSERT_MESSAGE("#SocketAddr.setHostname failed", sal_True == bOK ); + oslSocketResult aResult; + rtl::OUString suResult = saSocketAddr.getHostname( &aResult ); + CPPUNIT_ASSERT_MESSAGE("SocketAddr.getHostname failed.", aResult == osl_Socket_Ok); + + rtl::OUString suError = outputError(suResult, suHostname, "test for getHostname(0)"); + bOK = compareUString( suResult, suHostname ); + if ( bOK == sal_False) + { + rtl::OString aStringResult = ::rtl::OUStringToOString( suResult, RTL_TEXTENCODING_ASCII_US ); + rtl::OString aStringHostname = ::rtl::OUStringToOString( suHostname, RTL_TEXTENCODING_ASCII_US ); + if ( compareUString( getIPbyName( aStringResult ) , getIPbyName( aStringHostname ) ) == sal_True ) + { + bOK = sal_True; + } + } + + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError), sal_True == bOK ); + } + + + CPPUNIT_TEST_SUITE( getHostname ); + CPPUNIT_TEST( getHostname_001 ); + CPPUNIT_TEST( getHostname_002 ); + CPPUNIT_TEST_SUITE_END(); + + }; // class getHostname + + + /** testing the method: + inline sal_Int32 SAL_CALL getPort() const; + */ + + class getPort : public CppUnit::TestFixture + { + public: + void getPort_001() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_FTP ); + + CPPUNIT_ASSERT_MESSAGE( "test for getPort() function: get a normal port number.", + IP_PORT_FTP == saSocketAddr.getPort( ) ); + } + + void getPort_002() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.202")), IP_PORT_INVAL ); + + //t_print("#getPort_002: Port number is %d \n", saSocketAddr.getPort( )); + + CPPUNIT_ASSERT_MESSAGE( "test for getPort( ) function: give an invalid port to a SocketAddr, get the port to see if it can detect. it did not pass in (W32).", + saSocketAddr.getPort( )>=1 && saSocketAddr.getPort( ) <= 65535 ); + } + //two cases will return OSL_INVALID_PORT: 1. not valid SocketAddr + //2. SocketAddr family is not osl_Socket_FamilyInet, but case 2 could not be constructed + void getPort_003() + { + rtl::OUString suInvalidIP (RTL_CONSTASCII_USTRINGPARAM("123.345.67.89")); + ::osl::SocketAddr saSocketAddr( suInvalidIP, IP_PORT_MYPORT ); + + CPPUNIT_ASSERT_MESSAGE( "test for getPort( ) function: give an invalid IP to a SocketAddr, get the port to see returned value. ", + saSocketAddr.getPort( ) == OSL_INVALID_PORT ); + } + + CPPUNIT_TEST_SUITE( getPort ); + CPPUNIT_TEST( getPort_001 ); + CPPUNIT_TEST( getPort_002 ); + CPPUNIT_TEST( getPort_003 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class getPort + + + /** testing the method: + inline sal_Bool SAL_CALL setPort( sal_Int32 nPort ); + rfc1413.txt: TCP port numbers are from 1-65535 + rfc1700.txt: 0/tcp Reserved ; 0/udp Reserved + */ + + class setPort : public CppUnit::TestFixture + { + public: + void setPort_001() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_FTP ); + sal_Bool bOK = saSocketAddr.setPort( IP_PORT_TELNET ); + + CPPUNIT_ASSERT_MESSAGE( "test for setPort() function: modify a port number setting, and check it.", + ( sal_True == bOK ) && + ( IP_PORT_TELNET == saSocketAddr.getPort( ) ) ); + } + + /** 0 to 1024 is known as the reserved port range (traditionally only root can assign programs to ports in + this range) and the ephemeral port range from 1025 to 65535. + As many of you programmers will know, when you specify the source port of 0 when you connect to a host, + the OS automatically reassigns the port number to high numbered ephemeral port. The same happens if you + try to bind a listening socket to port 0. + http://www.securiteam.com/securityreviews/5XP0Q2AAKS.html + another: http://www.muq.org/~cynbe/muq/mufref_564.html + */ + void setPort_002() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_FTP ); + sal_Bool bOK = saSocketAddr.setPort( IP_PORT_ZERO ); + + oslSocket sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + ::osl::Socket sSocket(sHandle); + sSocket.setOption( osl_Socket_OptionReuseAddr, 1 );//sal_True); + sal_Bool bOK1 = sSocket.bind( saSocketAddr ); + CPPUNIT_ASSERT_MESSAGE( "bind SocketAddr failed", bOK1 == sal_True ); + + sal_Int32 newPort = sSocket.getLocalPort(); + //t_print("#new port is %d\n", newPort ); + + CPPUNIT_ASSERT_MESSAGE( "test for setPort() function: port number should be in 1 ~ 65535, set port 0, it should be converted to a port number between 1024~65535.", + ( 1024 <= newPort ) && ( 65535 >= newPort ) && ( bOK == sal_True ) ); + + } + + void setPort_003() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_FTP); + sal_Bool bOK = saSocketAddr.setPort( IP_PORT_INVAL ); + //on Linux, getPort return 34463 + //t_print("#Port number is %d \n", saSocketAddr.getPort( )); + + CPPUNIT_ASSERT_MESSAGE( "test for setPort( ) function: set an address with invalid port. it should return error or convert it to a valid port.", + ( ( 1 <= saSocketAddr.getPort( ) ) && ( 65535 >= saSocketAddr.getPort( ) ) &&( bOK == sal_True ) ) || + bOK == sal_False); + } + + /* this is not a inet-addr => can't set port */ + void setPort_004() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("123.345.67.89")), IP_PORT_FTP); + sal_Bool bOK = saSocketAddr.setPort( IP_PORT_MYPORT ); + + CPPUNIT_ASSERT_MESSAGE( "test for setPort( ) function: set an invalid address with valid port. it should return error.", + bOK == sal_False); + } + + + CPPUNIT_TEST_SUITE( setPort ); + CPPUNIT_TEST( setPort_001 ); + CPPUNIT_TEST( setPort_002 ); + CPPUNIT_TEST( setPort_003 ); + CPPUNIT_TEST( setPort_004 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class setPort + + + /** tester comment: + + In the following two functions, it use ::rtl::ByteSequence as an intermediate storage for address, + the ByteSequence object can hold sal_Int8 arrays, which is raged [-127, 127], in case of IP addr + that is greater than 127, say 129.158.217.202, it will stored as -127, -98, -39, -54, it is unique + in the range of sal_Int8, but lack of readability. + so may be a sal_uInt8 array is better. + */ + + + /** testing the method: + inline sal_Bool SAL_CALL setAddr( const ::rtl::ByteSequence & address ); + */ + + class setAddr : public CppUnit::TestFixture + { + public: + void setAddr_001() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.202")), IP_PORT_FTP ); + saSocketAddr.setAddr( UStringIPToByteSequence( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")) ) ); + ::rtl::ByteSequence bsSocketAddr = saSocketAddr.getAddr( 0 ); + sal_Bool bOK = sal_False; + + // if ( ( bsSocketAddr[0] == 127 ) && ( bsSocketAddr[1] == 0 ) && ( bsSocketAddr[2] == 0 ) && ( bsSocketAddr[3] == 1 ) ) + // bOK = sal_True; + bOK = ifIpv4is( bsSocketAddr, 127, 0, 0, 1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for setAddr() function: construct Addr with \"129.158.217.202\", set it to \"127.0.0.1\", and check the correctness ", + sal_True == bOK ); + } + + + CPPUNIT_TEST_SUITE( setAddr ); + CPPUNIT_TEST( setAddr_001 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class setAddr + + + /** testing the method: + inline ::rtl::ByteSequence SAL_CALL getAddr( oslSocketResult *pResult = 0 ) const; + */ + + class getAddr : public CppUnit::TestFixture + { + public: + void getAddr_001() + { + oslSocketResult SocketResult; + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_FTP ); + ::rtl::ByteSequence bsSocketAddr = saSocketAddr.getAddr( &SocketResult ); + + sal_Bool bOK = sal_False; + + //if ( ( osl_Socket_Ok == SocketResult ) &&( bsSocketAddr[0] == 127 ) && ( bsSocketAddr[1] == 0 ) &&( bsSocketAddr[2] == 0 ) && ( bsSocketAddr[3] == 1 ) ) + // bOK = sal_True; + bOK = ifIpv4is( bsSocketAddr, 127, 0, 0, 1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for getAddr() function: construct a socketaddr with IP assigned, get the address to check correctness.Caught unknown exception on (Win32)", + sal_True == bOK && SocketResult == osl_Socket_Ok); + } + + CPPUNIT_TEST_SUITE( getAddr ); + CPPUNIT_TEST( getAddr_001 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class getAddr + + + /** testing the methods: + inline SocketAddr & SAL_CALL operator= (oslSocketAddr Addr); + inline SocketAddr & SAL_CALL operator= (const SocketAddr& Addr); + inline SocketAddr & SAL_CALL assign( oslSocketAddr Addr, __osl_socket_NoCopy nocopy ); + inline sal_Bool SAL_CALL operator== (oslSocketAddr Addr) const; + inline sal_Bool SAL_CALL operator== (const SocketAddr & Addr) const; /// not implemented. + */ + + class operator_equal : public CppUnit::TestFixture + { + public: + void operator_equal_001() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_TELNET); + ::osl::SocketAddr saSocketAddrEqual( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.202")), IP_PORT_FTP ); + + saSocketAddrEqual = saSocketAddr; + sal_Bool bOK = sal_False; + ::rtl::ByteSequence bsSocketAddr = saSocketAddrEqual.getAddr( 0 ); + + // if ( ( IP_PORT_TELNET == saSocketAddrEqual.getPort( ) ) &&( bsSocketAddr[0] == 127 ) && ( bsSocketAddr[1] == 0 ) &&( bsSocketAddr[2] == 0 ) && ( bsSocketAddr[3] == 1 ) ) + if ( ( IP_PORT_TELNET == saSocketAddrEqual.getPort( ) ) && ( ifIpv4is( bsSocketAddr, 127, 0, 0, 1 ) == sal_True ) ) + bOK = sal_True; + + CPPUNIT_ASSERT_MESSAGE( "test for operator_equal() function: use operator= to assign Ip1 to Ip2, check its modification.", + sal_True == bOK ); + } + + + void operator_equal_002() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.199")), IP_PORT_TELNET); + ::osl::SocketAddr saSocketAddrEqual( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.202")), IP_PORT_FTP ); + + saSocketAddrEqual = saSocketAddr; + CPPUNIT_ASSERT_MESSAGE( "after assign, the assigned SocketAddr is not same as the original Addr", + IP_PORT_TELNET == saSocketAddrEqual.getPort( ) ); + saSocketAddrEqual.setPort( IP_PORT_MYPORT3 ); + saSocketAddr.setPort( IP_PORT_HTTP2 ); + + CPPUNIT_ASSERT_MESSAGE( "test for operator_equal() function: perform an equal action, then try to change the original address's port. it should not be changed ( handle released), it did not pass in (W32), this is under discussion.", + IP_PORT_MYPORT3 == saSocketAddrEqual.getPort( ) ); + } + + void operator_equal_const_001() + { + const ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_TELNET); + ::osl::SocketAddr saSocketAddrEqual( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.202")), IP_PORT_FTP ); + + saSocketAddrEqual = saSocketAddr; + sal_Bool bOK = sal_False; + ::rtl::ByteSequence bsSocketAddr = saSocketAddrEqual.getAddr( 0 ); + + // if ( ( IP_PORT_TELNET == saSocketAddrEqual.getPort( ) ) &&( bsSocketAddr[0] == 127 ) && ( bsSocketAddr[1] == 0 ) &&( bsSocketAddr[2] == 0 ) && ( bsSocketAddr[3] == 1 ) ) + if ( ( IP_PORT_TELNET == saSocketAddrEqual.getPort( ) ) && ifIpv4is( bsSocketAddr, 127, 0, 0, 1 ) == sal_True ) + bOK = sal_True; + + CPPUNIT_ASSERT_MESSAGE( "test for operator_equal_const() function: use operator= const to assign Ip1 to Ip2, verify the change on the second one.", + sal_True == bOK ); + } + + void operator_equal_const_002() + { + const ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_TELNET); + ::osl::SocketAddr saSocketAddrEqual( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.202")), IP_PORT_FTP ); + + saSocketAddrEqual = saSocketAddr; + saSocketAddrEqual.setPort( IP_PORT_HTTP1 ); + + CPPUNIT_ASSERT_MESSAGE( "test for operator_equal_const() function: change the second instance, the first one should not be altered, since it does not released the handle.", + IP_PORT_HTTP1 != saSocketAddr.getPort( ) ); + } + + void operator_equal_assign_001() + { + ::osl::SocketAddr* pSocketAddr = new ::osl::SocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_TELNET ); + CPPUNIT_ASSERT_MESSAGE("check for new SocketAddr", pSocketAddr != NULL); + ::osl::SocketAddr* pSocketAddrAssign = new ::osl::SocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.202")), IP_PORT_FTP ); + oslSocketAddr poslSocketAddr = pSocketAddr->getHandle( ); + //if( m_handle ) osl_destroySocketAddr( m_handle ); so pSocketAddrAssign had been destroyed and then point to pSocketAddr + pSocketAddrAssign->assign(poslSocketAddr, SAL_NO_COPY); + + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr no copy constructor function: do a no copy constructor on a given SocketAddr instance, modify the new instance's port, check the original one.", + pSocketAddrAssign->getPort( ) == IP_PORT_TELNET ); + + delete pSocketAddrAssign; + } + + void operator_is_equal_001() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_TELNET); + ::osl::SocketAddr saSocketAddrequal( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_TELNET ); + + CPPUNIT_ASSERT_MESSAGE( "test for operator_equal_equal() function: check two identical Address.", + sal_True == ( saSocketAddrequal == saSocketAddr.getHandle( ) ) ); + } + + void operator_is_equal_002() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("129.158.217.202")), IP_PORT_FTP); + ::osl::SocketAddr saSocketAddrequal( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_TELNET ); + + CPPUNIT_ASSERT_MESSAGE( "test for operator_equal_equal() function: check two different Address.", + sal_False == ( saSocketAddrequal == saSocketAddr.getHandle( ) ) ); + } + + CPPUNIT_TEST_SUITE( operator_equal ); + CPPUNIT_TEST( operator_equal_001 ); + CPPUNIT_TEST( operator_equal_002 ); + CPPUNIT_TEST( operator_equal_const_001 ); + CPPUNIT_TEST( operator_equal_const_002 ); + CPPUNIT_TEST( operator_equal_assign_001 ); + CPPUNIT_TEST( operator_is_equal_001 ); + CPPUNIT_TEST( operator_is_equal_002 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class operator_equal + + + + /** testing the method: + inline oslSocketAddr SAL_CALL getHandle() const; + */ + + class getSocketAddrHandle : public CppUnit::TestFixture + { + public: + + void getSocketAddrHandle_001() + { + ::osl::SocketAddr* pSocketAddr = new ::osl::SocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("localhost")), IP_PORT_HTTP1 ); + CPPUNIT_ASSERT_MESSAGE("check for new SocketAddr", pSocketAddr != NULL); + oslSocketAddr psaOSLSocketAddr = pSocketAddr->getHandle( ); + ::osl::SocketAddr* pSocketAddrCopy = new ::osl::SocketAddr( psaOSLSocketAddr, SAL_NO_COPY ); + + CPPUNIT_ASSERT_MESSAGE("test for SocketAddr no copy constructor function: do a no copy constructor on a given SocketAddr instance, modify the new instance's port, check the original one.", + pSocketAddr->getHandle( ) == pSocketAddrCopy->getHandle( ) ); + + delete pSocketAddrCopy; + } + + void getSocketAddrHandle_002() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("deuce.PRC.Sun.COM")), IP_PORT_MYPORT4 ); + oslSocketAddr poslSocketAddr = saSocketAddr.getHandle( ); + + sal_Bool bOK = ( saSocketAddr == poslSocketAddr ); + //t_print("getSocketAddrHandle_002\n"); + CPPUNIT_ASSERT_MESSAGE( "test for getHandle() function: use getHandle() function as an intermediate way to create identical address.", + sal_True == bOK ); + } + + CPPUNIT_TEST_SUITE( getSocketAddrHandle ); + CPPUNIT_TEST( getSocketAddrHandle_001 ); + CPPUNIT_TEST( getSocketAddrHandle_002 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class getSocketAddrHandle + + + /** testing the method: + static inline ::rtl::OUString SAL_CALL getLocalHostname( oslSocketResult *pResult = 0); + */ + + class getLocalHostname : public CppUnit::TestFixture + { + public: + /* the process of getLocalHostname: 1.gethostname (same as /bin/hostname) returned name A + 2. search A in /etc/hosts, if there is an alias name is A, return the name in the same row + */ + + void getLocalHostname_000() + { + // _osl_getFullQualifiedDomainName( ); + oslSocketResult aResult = osl_Socket_Error; + rtl::OUString suHostname = osl::SocketAddr::getLocalHostname(&aResult); + CPPUNIT_ASSERT_MESSAGE("getLocalHostname failed", aResult == osl_Socket_Ok); + } + + void getLocalHostname_001() + { + oslSocketResult *pResult = NULL; + //printSocketResult(*pResult); + ::rtl::OUString suResult = ::osl::SocketAddr::getLocalHostname( pResult ); + + // LLA: IMHO localhost, or hostname by itself should be ok. + rtl::OUString suThisHost = getThisHostname( ); + bool bOk = false; + if (suThisHost.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("localhost")))) + { + bOk = true; + } + else + { + if (suThisHost.equals(suResult)) + { + bOk = true; + } + } + + ::rtl::OUString suError; + suError = outputError(suResult, getThisHostname( ), "test for getLocalHostname() function"); + + CPPUNIT_ASSERT_MESSAGE( STD_STRING(suError), bOk == true ); + } + + CPPUNIT_TEST_SUITE( getLocalHostname ); + CPPUNIT_TEST( getLocalHostname_000 ); + CPPUNIT_TEST( getLocalHostname_001 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class getLocalHostname + + + /** testing the method: + static inline void SAL_CALL resolveHostname( const ::rtl::OUString & strHostName , SocketAddr & Addr ); + */ + + class resolveHostname : public CppUnit::TestFixture + { + public: + void resolveHostname_001() + { + ::osl::SocketAddr saSocketAddr; + ::osl::SocketAddr::resolveHostname( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), saSocketAddr ); + ::rtl::ByteSequence bsSocketAddr = saSocketAddr.getAddr( 0 ); + sal_Bool bOK = sal_False; + + if ( ( bsSocketAddr[0] == 127 ) && ( bsSocketAddr[1] == 0 ) &&( bsSocketAddr[2] == 0 ) && ( bsSocketAddr[3] == 1 ) ) + bOK = sal_True; + + CPPUNIT_ASSERT_MESSAGE( "test for resolveHostname() function: try to resolve localhost to 127.0.0.1.", + sal_True == bOK ); + } + + CPPUNIT_TEST_SUITE( resolveHostname ); + CPPUNIT_TEST( resolveHostname_001 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class resolveHostname + + + /** testing the method: + static inline sal_Int32 SAL_CALL getServicePort( + const ::rtl::OUString& strServiceName, + const ::rtl::OUString & strProtocolName= ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("tcp")) ); + */ + + class gettheServicePort : public CppUnit::TestFixture + { + public: + void gettheServicePort_001() + { + rtl::OUString suServiceFTP (RTL_CONSTASCII_USTRINGPARAM("ftp")); + rtl::OUString suProtocolTCP (RTL_CONSTASCII_USTRINGPARAM("tcp")); + + CPPUNIT_ASSERT_MESSAGE( "test for getServicePort() function: try to get ftp service port on TCP protocol.", + IP_PORT_FTP== ::osl::SocketAddr::getServicePort( suServiceFTP, suProtocolTCP ) ); + } + + void gettheServicePort_002() + { + rtl::OUString suServiceTELNET (RTL_CONSTASCII_USTRINGPARAM("telnet")); + rtl::OUString suProtocolTCP (RTL_CONSTASCII_USTRINGPARAM("tcp")); + CPPUNIT_ASSERT_MESSAGE( "test for getServicePort() function: try to get telnet service port on TCP protocol.", + IP_PORT_TELNET== ::osl::SocketAddr::getServicePort( suServiceTELNET, suProtocolTCP ) ); + } + + void gettheServicePort_003() + { + //Solaris has no service called "https", please see /etc/services + rtl::OUString suServiceNETBIOS (RTL_CONSTASCII_USTRINGPARAM("netbios-dgm")); + rtl::OUString suProtocolUDP (RTL_CONSTASCII_USTRINGPARAM("udp")); + CPPUNIT_ASSERT_MESSAGE( "test for getServicePort() function: try to get netbios-ssn service port on UDP protocol.", + IP_PORT_NETBIOS_DGM == ::osl::SocketAddr::getServicePort( suServiceNETBIOS, suProtocolUDP ) ); + } + + void gettheServicePort_004() + { + rtl::OUString suProtocolUDP(RTL_CONSTASCII_USTRINGPARAM( "udp" )); + CPPUNIT_ASSERT_MESSAGE( "test for getServicePort() function: try to get a service port which is not exist.", + OSL_INVALID_PORT == ::osl::SocketAddr::getServicePort( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("notexist")), suProtocolUDP ) ); + } + + CPPUNIT_TEST_SUITE( gettheServicePort ); + CPPUNIT_TEST( gettheServicePort_001 ); + CPPUNIT_TEST( gettheServicePort_002 ); + CPPUNIT_TEST( gettheServicePort_003 ); + CPPUNIT_TEST( gettheServicePort_004 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class gettheServicePort + + /** testing the method: + + */ + + class getFamilyOfSocketAddr : public CppUnit::TestFixture + { + public: + void getFamilyOfSocketAddr_001() + { + ::osl::SocketAddr saSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("localhost")), IP_PORT_HTTP1 ); + oslSocketAddr psaOSLSocketAddr = saSocketAddr.getHandle( ); + CPPUNIT_ASSERT_EQUAL( + osl_Socket_FamilyInet, + osl_getFamilyOfSocketAddr( psaOSLSocketAddr ) ); + + CPPUNIT_ASSERT_MESSAGE( "test for osl_getFamilyOfSocketAddr.", + osl_getFamilyOfSocketAddr( psaOSLSocketAddr ) == osl_Socket_FamilyInet ); + } + + CPPUNIT_TEST_SUITE( getFamilyOfSocketAddr ); + CPPUNIT_TEST( getFamilyOfSocketAddr_001 ); + CPPUNIT_TEST_SUITE_END( ); + + }; // class getFamilyOfSocketAddr + +// ----------------------------------------------------------------------------- + + +CPPUNIT_TEST_SUITE_REGISTRATION(osl_SocketAddr::ctors); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_SocketAddr::is); +//TODO: enable Test with valid host names +//CPPUNIT_TEST_SUITE_REGISTRATION(osl_SocketAddr::getHostname); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_SocketAddr::getPort); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_SocketAddr::setPort); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_SocketAddr::setAddr); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_SocketAddr::getAddr); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_SocketAddr::operator_equal); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_SocketAddr::getSocketAddrHandle); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_SocketAddr::getLocalHostname); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_SocketAddr::resolveHostname); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_SocketAddr::gettheServicePort); +CPPUNIT_TEST_SUITE_REGISTRATION(osl_SocketAddr::getFamilyOfSocketAddr); + +} // namespace osl_SocketAddr + +// ----------------------------------------------------------------------------- + +// this macro creates an empty function, which will called by the RegisterAllFunctions() +// to let the user the possibility to also register some functions by hand. +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/socket/osl_SocketAddr.xsce b/sal/qa/osl/socket/osl_SocketAddr.xsce new file mode 100644 index 000000000000..e69de29bb2d1 --- /dev/null +++ b/sal/qa/osl/socket/osl_SocketAddr.xsce diff --git a/sal/qa/osl/socket/osl_SocketOld.xsce b/sal/qa/osl/socket/osl_SocketOld.xsce new file mode 100644 index 000000000000..3f8120fc6943 --- /dev/null +++ b/sal/qa/osl/socket/osl_SocketOld.xsce @@ -0,0 +1,14 @@ +osl_Socket.ctors.ctors_family_Ipx +osl_SocketAddr.getHostname.getHostname_002 +osl_StreamSocket.send_recv.write_read_001 + +osl_ConnectorSocket.connect.connect_003 wntmsci +osl_Socket.getLocalHost.getLocalHost_001 wntmsci + +# hangs within solaris +osl_StreamSocket.send_recv.write_read_002 unxsols +osl_StreamSocket.send_recv.write_read_003 unxsols +osl_StreamSocket.send_recv.write_read_004 unxsols + +# hangs within solaris +osl_StreamSocket.send_recv.send_recv1 unxsols diff --git a/sal/qa/osl/socket/osl_Socket_Const.h b/sal/qa/osl/socket/osl_Socket_Const.h new file mode 100644 index 000000000000..0aff414a34a0 --- /dev/null +++ b/sal/qa/osl/socket/osl_Socket_Const.h @@ -0,0 +1,181 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _OSL_SOCKET_CONST_H_ +#define _OSL_SOCKET_CONST_H_ + +#include <sal/types.h> +#include <rtl/textenc.h> +#include <rtl/ustring.hxx> +#include <rtl/ustring.h> + +#ifndef _OSL_SOCLET_HXX_ +#include <osl/socket.hxx> +#endif +#include <osl/socket.h> + +#ifndef _OSL_THREAD_HXX +#include <osl/thread.hxx> +#endif + +#ifndef _OSL_FILE_HXX +#include <osl/file.hxx> +#endif + +#ifndef _OSL_MUTEX_HXX +#include <osl/mutex.hxx> +#endif +#include <osl/time.h> + +const char * pTestString1 = "test socket"; +const char * pTestString2 = " Passed#OK"; + +#ifdef __cplusplus +extern "C" +{ +#endif + +# include <stdio.h> +//------------------------------------------------------------------------ +// OS dependent declaration and includes +//------------------------------------------------------------------------ +#if ( defined UNX ) || ( defined OS2 ) //Unix +# include <unistd.h> +# include <limits.h> +# include <string.h> +# include <math.h> +# include <errno.h> +# include <fcntl.h> +# include <sys/stat.h> +# include <sys/statfs.h> +# include <sys/statvfs.h> +# include <sys/types.h> +# include <sys/socket.h> +# include <netdb.h> +# include <netinet/in.h> +# include <arpa/inet.h> +#endif +#if ( defined WNT ) // Windows +# include <winsock.h> +# include <string.h> +#endif + + +//------------------------------------------------------------------------ +// macro definition for the ASCII array/OUString declarations, +// we use p### for the ASCII array, +// a### for the OUString, +// n###Len for its length +//------------------------------------------------------------------------ + +#define OSLTEST_DECLARE( str_name, str_value ) \ + static const sal_Char p##str_name[] = str_value; \ + static const sal_Int32 n##str_name##Len = sizeof( p##str_name ) -1; \ + ::rtl::OUString a##str_name = rtl::OUString::createFromAscii( p##str_name ) + + +//------------------------------------------------------------------------ +// Ip version definition +//------------------------------------------------------------------------ +#define IP_VER 4 /// currently only IPv4 is considered. + +//------------------------------------------------------------------------ +// Ip port definition +//------------------------------------------------------------------------ +// #define IP_PORT_ZERO 0 +// #define IP_PORT_TELNET 23 +// #define IP_PORT_SMTP 25 +// #define IP_PORT_GOPHER 70 +// #define IP_PORT_POP3 110 +// #define IP_PORT_NETBIOS_DGM 138 +// #define IP_PORT_NETBIOS 139 +// #define IP_PORT_IMAP 143 +// #define IP_PORT_HTTPS 443 +// /**reference: http://www.iana.org/assignments/port-numbers */ +// #define IP_PORT_MYPORT 8881 //8888 +// #define IP_PORT_MYPORT1 8882 //8889 +// #define IP_PORT_MYPORT3 8884 //8891 +// #define IP_PORT_MYPORT4 8885 //8892 +// #define IP_PORT_MYPORT5 8886 //8893 +// #define IP_PORT_MYPORT6 8887 //8894 +// #define IP_PORT_MYPORT7 8895 +// #define IP_PORT_MYPORT8 8896 +// #define IP_PORT_MYPORT9 8897 +// #define IP_PORT_MYPORT10 8898 +// +// #define IP_PORT_TMP 9999 +// #define IP_PORT_INVAL 99999 + +//------------------------------------------------------------------------ +// service definitions. +//------------------------------------------------------------------------ +// OSLTEST_DECLARE( ServiceFTP, "ftp" ); +// OSLTEST_DECLARE( ServiceTELNET, "telnet" ); +// OSLTEST_DECLARE( ServiceGOPHER, "gopher" ); +// OSLTEST_DECLARE( ServiceIMAP, "imap" ); +// OSLTEST_DECLARE( ServiceHTTPS, "https" ); +// OSLTEST_DECLARE( ServiceNETBIOS, "netbios-dgm" ); + +//------------------------------------------------------------------------ +// protocol definitions. +//------------------------------------------------------------------------ +// OSLTEST_DECLARE( ProtocolTCP, "tcp" ); +// OSLTEST_DECLARE( ProtocolUDP, "udp" ); + +//------------------------------------------------------------------------ +// Hostnames. +//------------------------------------------------------------------------ +// OSLTEST_DECLARE( HostName1, "localhost" ); +// OSLTEST_DECLARE( HostIp1, "127.0.0.1" ); +OSLTEST_DECLARE( HostName2, "longshot.prc.sun.com" ); +OSLTEST_DECLARE( HostIp2, "129.158.217.202" ); +OSLTEST_DECLARE( HostName3, "deuce.prc.sun.com" ); +OSLTEST_DECLARE( HostIp3, "129.158.217.199" ); +OSLTEST_DECLARE( HostName4, "sceri.PRC.Sun.COM" ); //Beijing server for test +OSLTEST_DECLARE( HostIp4, "129.158.217.107" ); +OSLTEST_DECLARE( HostName5, "koori.SFBay.Sun.COM" ); //"grande.Germany.Sun.COM" ); //Germany server for test +OSLTEST_DECLARE( HostIp5, "10.5.32.20" ); +OSLTEST_DECLARE( HostName6, "crumple.SFBay.Sun.COM" ); //sfbay +OSLTEST_DECLARE( HostIp6, "10.6.103.83" ); +OSLTEST_DECLARE( HostIpInval, "123.45.67.89" ); //this is valid ip number,but can not arrive --mindy +// OSLTEST_DECLARE( HostIpInval1, "123.345.67.89" ); //this is real invalid ip number --mindy +OSLTEST_DECLARE( HostNameInval, "www.the_hostname_that_can_not_resolvable_to_an_IP_Address.com" ); +OSLTEST_DECLARE( HostIpZero, "0.0.0.0" ); + +//------------------------------------------------------------------------ +// OS independent file definition +//------------------------------------------------------------------------ +OSLTEST_DECLARE( NullURL, "" ); + +#ifdef __cplusplus +} +#endif + +#endif /* _OSL_SOCKET_CONST_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/socket/osl_Socket_Const_orig.h b/sal/qa/osl/socket/osl_Socket_Const_orig.h new file mode 100644 index 000000000000..76fb491459ec --- /dev/null +++ b/sal/qa/osl/socket/osl_Socket_Const_orig.h @@ -0,0 +1,185 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _OSL_SOCKET_CONST_H_ +#define _OSL_SOCKET_CONST_H_ + +#include <sal/types.h> +#include <rtl/textenc.h> +#include <rtl/ustring.hxx> +#include <rtl/ustring.h> + +#ifndef _OSL_SOCLET_HXX_ +#include <osl/socket.hxx> +#endif +#include <osl/socket.h> + +#ifndef _OSL_THREAD_HXX +#include <osl/thread.hxx> +#endif + +#ifndef _OSL_FILE_HXX +#include <osl/file.hxx> +#endif + +#ifndef _OSL_MUTEX_HXX +#include <osl/mutex.hxx> +#endif +#include <osl/time.h> + +const char * pTestString1 = "test socket"; +const char * pTestString2 = " Passed#OK"; + +#ifdef __cplusplus +extern "C" +{ +#endif + +# include <stdio.h> +//------------------------------------------------------------------------ +// OS dependent declaration and includes +//------------------------------------------------------------------------ +#if ( defined UNX ) || ( defined OS2 ) //Unix +# include <unistd.h> +# include <limits.h> +# include <string.h> +# include <math.h> +# include <errno.h> +# include <fcntl.h> +# include <sys/stat.h> +# include <sys/statfs.h> +# include <sys/statvfs.h> +# include <sys/types.h> +# include <sys/socket.h> +# include <netdb.h> +# include <netinet/in.h> +# include <arpa/inet.h> +#endif +#if ( defined WNT ) // Windows +# include <winsock.h> +# include <string.h> +#endif + + +//------------------------------------------------------------------------ +// macro definition for the ASCII array/OUString declarations, +// we use p### for the ASCII array, +// a### for the OUString, +// n###Len for its length +//------------------------------------------------------------------------ + +#define OSLTEST_DECLARE( str_name, str_value ) \ + static const sal_Char p##str_name[] = str_value; \ + static const sal_Int32 n##str_name##Len = sizeof( p##str_name ) -1; \ + ::rtl::OUString a##str_name = rtl::OUString::createFromAscii( p##str_name ) + + +//------------------------------------------------------------------------ +// Ip version definition +//------------------------------------------------------------------------ +#define IP_VER 4 /// currently only IPv4 is considered. + +//------------------------------------------------------------------------ +// Ip port definition +//------------------------------------------------------------------------ +#define IP_PORT_ZERO 0 +#define IP_PORT_FTP 21 +#define IP_PORT_TELNET 23 +#define IP_PORT_SMTP 25 +#define IP_PORT_GOPHER 70 +#define IP_PORT_HTTP1 80 +#define IP_PORT_POP3 110 +#define IP_PORT_NETBIOS_DGM 138 +#define IP_PORT_NETBIOS 139 +#define IP_PORT_IMAP 143 +#define IP_PORT_HTTPS 443 +#define IP_PORT_HTTP2 8080 +/**reference: http://www.iana.org/assignments/port-numbers */ +#define IP_PORT_MYPORT 8881 //8888 +#define IP_PORT_MYPORT1 8882 //8889 +#define IP_PORT_MYPORT2 8883 //8890 +#define IP_PORT_MYPORT3 8884 //8891 +#define IP_PORT_MYPORT4 8885 //8892 +#define IP_PORT_MYPORT5 8886 //8893 +#define IP_PORT_MYPORT6 8887 //8894 +#define IP_PORT_MYPORT7 8895 +#define IP_PORT_MYPORT8 8896 +#define IP_PORT_MYPORT9 8897 +#define IP_PORT_MYPORT10 8898 + +#define IP_PORT_TMP 9999 +#define IP_PORT_INVAL 99999 + +//------------------------------------------------------------------------ +// service definitions. +//------------------------------------------------------------------------ +OSLTEST_DECLARE( ServiceFTP, "ftp" ); +OSLTEST_DECLARE( ServiceTELNET, "telnet" ); +OSLTEST_DECLARE( ServiceGOPHER, "gopher" ); +OSLTEST_DECLARE( ServiceIMAP, "imap" ); +OSLTEST_DECLARE( ServiceHTTPS, "https" ); +OSLTEST_DECLARE( ServiceNETBIOS, "netbios-dgm" ); + +//------------------------------------------------------------------------ +// protocol definitions. +//------------------------------------------------------------------------ +OSLTEST_DECLARE( ProtocolTCP, "tcp" ); +OSLTEST_DECLARE( ProtocolUDP, "udp" ); + +//------------------------------------------------------------------------ +// Hostnames. +//------------------------------------------------------------------------ +OSLTEST_DECLARE( HostName1, "localhost" ); +OSLTEST_DECLARE( HostIp1, "127.0.0.1" ); +OSLTEST_DECLARE( HostName2, "longshot.prc.sun.com" ); +OSLTEST_DECLARE( HostIp2, "129.158.217.202" ); +OSLTEST_DECLARE( HostName3, "deuce.prc.sun.com" ); +OSLTEST_DECLARE( HostIp3, "129.158.217.199" ); +OSLTEST_DECLARE( HostName4, "sceri.PRC.Sun.COM" ); //Beijing server for test +OSLTEST_DECLARE( HostIp4, "129.158.217.107" ); +OSLTEST_DECLARE( HostName5, "koori.SFBay.Sun.COM" ); //"grande.Germany.Sun.COM" ); //Germany server for test +OSLTEST_DECLARE( HostIp5, "10.5.32.20" ); +OSLTEST_DECLARE( HostName6, "crumple.SFBay.Sun.COM" ); //sfbay +OSLTEST_DECLARE( HostIp6, "10.6.103.83" ); +OSLTEST_DECLARE( HostIpInval, "123.45.67.89" ); //this is valid ip number,but can not arrive --mindy +OSLTEST_DECLARE( HostIpInval1, "123.345.67.89" ); //this is real invalid ip number --mindy +OSLTEST_DECLARE( HostNameInval, "www.the_hostname_that_can_not_resolvable_to_an_IP_Address.com" ); +OSLTEST_DECLARE( HostIpZero, "0.0.0.0" ); + +//------------------------------------------------------------------------ +// OS independent file definition +//------------------------------------------------------------------------ +OSLTEST_DECLARE( NullURL, "" ); + +#ifdef __cplusplus +} +#endif + +#endif /* _OSL_SOCKET_CONST_H_ */ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/socket/osl_Socket_tests.cxx b/sal/qa/osl/socket/osl_Socket_tests.cxx new file mode 100644 index 000000000000..120d9fa24a91 --- /dev/null +++ b/sal/qa/osl/socket/osl_Socket_tests.cxx @@ -0,0 +1,93 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +//------------------------------------------------------------------------ +// include files +//------------------------------------------------------------------------ +#include <osl_Socket_Const.h> + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> +#include <osl/socket.hxx> +//------------------------------------------------------------------------ +// helper functions +//------------------------------------------------------------------------ + +//------------------------------------------------------------------------ +// tests cases begins here +//------------------------------------------------------------------------ + +namespace osl_Socket +{ + + class tests : public CppUnit::TestFixture + { + public: + + void test_001() + { + // _osl_getFullQualifiedDomainName( ); + oslSocketResult aResult; + rtl::OUString suHostname = osl::SocketAddr::getLocalHostname(&aResult); + CPPUNIT_ASSERT_MESSAGE("getLocalHostname failed", aResult == osl_Socket_Ok); + } + + CPPUNIT_TEST_SUITE( tests ); + CPPUNIT_TEST( test_001 ); + CPPUNIT_TEST_SUITE_END(); + }; + + CPPUNIT_TEST_SUITE_REGISTRATION(osl_Socket::tests); +} + + +// ----------------------------------------------------------------------------- + +// this macro creates an empty function, which will called by the RegisterAllFunctions() +// to let the user the possibility to also register some functions by hand. + +/*#if (defined LINUX) + +void RegisterAdditionalFunctions( FktRegFuncPtr _pFunc ) +{ + // for cover lines in _osl_getFullQualifiedDomainName( ) + // STAR_OVERRIDE_DOMAINNAME is more an internal HACK for 5.2, which should remove from sal + setenv( "STAR_OVERRIDE_DOMAINNAME", "PRC.Sun.COM", 0 ); +} + +#else*/ + +CPPUNIT_PLUGIN_IMPLEMENT(); + +//#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/socket/osl_Socket_tests.xsce b/sal/qa/osl/socket/osl_Socket_tests.xsce new file mode 100644 index 000000000000..d247b2365273 --- /dev/null +++ b/sal/qa/osl/socket/osl_Socket_tests.xsce @@ -0,0 +1 @@ +osl_SocketTest.tests.test_001 diff --git a/sal/qa/osl/socket/osl_StreamSocket.cxx b/sal/qa/osl/socket/osl_StreamSocket.cxx new file mode 100644 index 000000000000..c2683d6ead46 --- /dev/null +++ b/sal/qa/osl/socket/osl_StreamSocket.cxx @@ -0,0 +1,1431 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +/** test coder preface: + 1. the BSD socket function will meet "unresolved external symbol error" on Windows platform + if you are not including ws2_32.lib in makefile.mk, the including format will be like this: + + .IF "$(GUI)" == "WNT" + SHL1STDLIBS += $(SOLARLIBDIR)$/cppunit.lib + SHL1STDLIBS += ws2_32.lib + .ENDIF + + likewise on Solaris platform. + .IF "$(GUI)" == "UNX" + SHL1STDLIBS+=$(SOLARLIBDIR)$/libcppunit$(DLLPOSTFIX).a + SHL1STDLIBS += -lsocket -ldl -lnsl + .ENDIF + + 2. since the Socket implementation of osl is only IPv4 oriented, our test are mainly focus on IPv4 + category. + + 3. some fragment of Socket source implementation are lack of comment so it is hard for testers + guess what the exact functionality or usage of a member. Hope the Socket section's comment + will be added. + + 4. following functions are declared but not implemented: + inline sal_Bool SAL_CALL operator== (const SocketAddr & Addr) const; +*/ + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> + +#include "sockethelper.hxx" +#include <osl/conditn.hxx> + +using namespace osl; + +using ::rtl::OUString; +using ::rtl::OString; + +#define IP_PORT_MYPORT9 8897 +#define IP_PORT_MYPORT10 18900 + +const char * pTestString1 = "test socket"; +const char * pTestString2 = " Passed#OK"; + +//------------------------------------------------------------------------ +// helper functions +//------------------------------------------------------------------------ + +// just used to test socket::close() when accepting +class AcceptorThread : public Thread +{ + ::osl::AcceptorSocket asAcceptorSocket; + ::rtl::OUString aHostIP; + sal_Bool bOK; +protected: + void SAL_CALL run( ) + { + ::osl::SocketAddr saLocalSocketAddr( aHostIP, IP_PORT_MYPORT9 ); + ::osl::StreamSocket ssStreamConnection; + + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //integer not sal_Bool : sal_True); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + if ( sal_True != bOK1 ) + { + t_print("# AcceptorSocket bind address failed.\n" ) ; + return; + } + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + if ( sal_True != bOK2 ) + { + t_print("# AcceptorSocket listen address failed.\n" ) ; + return; + } + + asAcceptorSocket.enableNonBlockingMode( sal_False ); + + oslSocketResult eResult = asAcceptorSocket.acceptConnection( ssStreamConnection ); + if (eResult != osl_Socket_Ok ) + { + bOK = sal_True; + t_print("AcceptorThread: acceptConnection failed! \n"); + } + } +public: + AcceptorThread(::osl::AcceptorSocket & asSocket, ::rtl::OUString const& aBindIP ) + : asAcceptorSocket( asSocket ), aHostIP( aBindIP ) + { + bOK = sal_False; + } + + sal_Bool isOK() { return bOK; } + + ~AcceptorThread( ) + { + if ( isRunning( ) ) + { + asAcceptorSocket.shutdown(); + t_print("# error: Acceptor thread not terminated.\n" ); + } + } +}; + +/** Server Socket Thread, served as a temp little server to communicate with client. + */ +class ServerSocketThread : public Thread +{ + osl::Condition &m_aCondition; +protected: + oslThreadIdentifier m_id; + + void SAL_CALL run( ) + { + ::osl::AcceptorSocket asAcceptorSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + ::osl::SocketAddr saLocalSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT9 ); + ::osl::StreamSocket ssStreamConnection; + + //if has not set this option, socket addr can not be binded in some time(maybe 2 minutes) by another socket + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //integer not sal_Bool : sal_True); + while ( schedule( ) == sal_True ) + { + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + if ( sal_True != bOK1 ) + { + t_print("# ServerSocketThread: AcceptorSocket bind address failed.\n" ) ; + break; + } + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + if ( sal_True != bOK2 ) + { + t_print("# ServerSocketThread: AcceptorSocket listen address failed.\n" ) ; + break; + } + + asAcceptorSocket.enableNonBlockingMode( sal_False ); + m_aCondition.set(); + + oslSocketResult eResult = asAcceptorSocket.acceptConnection( ssStreamConnection ); + if (eResult != osl_Socket_Ok ) + { + t_print("ServerSocketThread: acceptConnection failed! \n"); + break; + } + sal_Int32 nReadNumber1 = ssStreamConnection.recv( pReadBuffer, 11 ); + sal_Int32 nReadNumber2 = ssStreamConnection.recv( pReadBuffer + nReadNumber1, 11 ); + pReadBuffer[nReadNumber1 + nReadNumber2] = '\0'; + //t_print("# read buffer content: %s\n", pReadBuffer ); + break; + } + ssStreamConnection.close(); + asAcceptorSocket.close(); + + } + + void SAL_CALL onTerminated( ) + { + //t_print("# normally terminate this server thread %d!\n", m_id ); + } + +public: + // public to check if data transmition is OK + sal_Char pReadBuffer[30]; + ServerSocketThread( osl::Condition &_aCond ):m_aCondition(_aCond) + { + m_aCondition.reset(); + t_print("#init ServerSocketThread\n"); + m_id = getIdentifier( ); + //t_print("# successfully creat this ServerSocketThread %d!\n", m_id ); + } + + ~ServerSocketThread( ) + { + if ( isRunning( ) ) + t_print("# error: ServerSocketThread has not terminated.\n" ); + } +}; + +/** Client Socket Thread, served as a temp little client to communicate with server. + */ +class ClientSocketThread : public Thread +{ +protected: + osl::Condition &m_aCondition; + oslThreadIdentifier m_id; + ::osl::SocketAddr m_saTargetSocketAddr; + ::osl::ConnectorSocket m_csConnectorSocket; + + void SAL_CALL run( ) + { + TimeValue *pTimeout; + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 5; + pTimeout->Nanosec = 0; + + /// if the thread should terminate, schedule return false + //while ( schedule( ) == sal_True ) + //{ + if ( osl::Condition::result_ok != m_aCondition.wait( pTimeout ) ) + { + free( pTimeout ); + return; + } + + if ( osl_Socket_Ok == m_csConnectorSocket.connect( m_saTargetSocketAddr, pTimeout )) + { + m_csConnectorSocket.send( pTestString1, 11 ); // "test socket" + m_csConnectorSocket.send( pTestString2, 10); + } + else + t_print("# ClientSocketThread: connect failed! \n"); + // terminate(); + //} + m_csConnectorSocket.close(); + free( pTimeout ); + } + + void SAL_CALL onTerminated( ) + { + //t_print("# normally terminate this thread %d!\n", m_id ); + } + +public: + ClientSocketThread( osl::Condition &_aCond ): + m_aCondition(_aCond), + m_saTargetSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT9 ), + m_csConnectorSocket( ) + { + m_id = getIdentifier( ); + //t_print("# successfully creat this client thread %d!\n", m_id ); + } + + ~ClientSocketThread( ) + { + if ( isRunning( ) ) + t_print("# error: client thread not terminated.\n" ); + } + +}; + +// ----------------------------------------------------------------------------- +// Helper functions, to create buffers, check buffers +class ValueCheckProvider +{ + bool m_bFoundFailure; + char *m_pBuffer; + sal_Int32 m_nBufferSize; + +public: + ValueCheckProvider() + :m_bFoundFailure(false), + m_pBuffer(NULL), + m_nBufferSize(0) + { + } + + bool isFailure() {return m_bFoundFailure;} + + const char* getBuffer() {return m_pBuffer;} + char* getWriteBuffer() {return m_pBuffer;} + + sal_Int32 getBufferSize() {return m_nBufferSize;} + + bool checkValues(sal_Int32 _nLength, int _nValue) + { + m_bFoundFailure = false; + for(sal_Int32 i=0;i<_nLength;i++) + { + if (m_pBuffer[i] != _nValue) + { + m_bFoundFailure = true; + } + } + return m_bFoundFailure; + } + + void createBuffer(sal_Int32 _nLength, int _nValue) + { + m_nBufferSize = _nLength; + m_pBuffer = (char*) malloc(m_nBufferSize); + if (m_pBuffer) + { + memset(m_pBuffer, _nValue, m_nBufferSize); + } + } + + void freeBuffer() + { + if (m_pBuffer) free(m_pBuffer); + } + +}; + +// ----------------------------------------------------------------------------- +/** Client Socket Thread, served as a temp little client to communicate with server. + */ + +class ReadSocketThread : public Thread +{ + ValueCheckProvider m_aValues; + int m_nValue; + osl::Condition &m_aCondition; + +protected: + oslThreadIdentifier m_id; + + void SAL_CALL run( ) + { + ::osl::SocketAddr m_aTargetSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT10 ); + ::osl::ConnectorSocket m_aConnectorSocket; + + if (! m_aTargetSocketAddr.is()) + { + t_print("# SocketAddr was NOT created successfully!\n"); + } + else + { + t_print("start ReadSocketThread\n"); + + TimeValue *pTimeout; + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 5; + pTimeout->Nanosec = 0; + + m_aCondition.wait(); + + t_print("connect()\n"); + + oslSocketResult eResult = m_aConnectorSocket.connect( m_aTargetSocketAddr, pTimeout ); + if ( osl_Socket_Ok == eResult ) + { + sal_Int32 nReadCount = m_aConnectorSocket.read( m_aValues.getWriteBuffer(), m_aValues.getBufferSize() ); + m_aValues.checkValues(nReadCount, m_nValue); + } + else + { + t_print("# ReadSocketThread: connect failed! \n"); + printSocketResult(eResult); + } + + //remove this line for deadlock on solaris( margritte.germany ) + m_aConnectorSocket.close(); + free( pTimeout ); + } + } + + void SAL_CALL onTerminated( ) + { + //t_print("# normally terminate this thread %d!\n", m_id ); + } + +public: + sal_Int32 getCount() {return m_aValues.getBufferSize();} + bool isOk() {return m_aValues.isFailure() == true ? false : true;} + + ReadSocketThread(sal_Int32 _nBufferSize, int _nValue, osl::Condition &_aCond ) + : m_nValue( _nValue ), + m_aCondition(_aCond) + { + t_print("#init ReadSocketThread\n"); + m_id = getIdentifier( ); + + //t_print("# successfully creat this client thread %d!\n", m_id ); + m_aValues.createBuffer(_nBufferSize, 0); + } + + ~ReadSocketThread( ) + { + if ( isRunning( ) ) + t_print("# error: client thread not terminated.\n" ); + m_aValues.freeBuffer(); + } + +}; + +/** Server Socket Thread, write a file which is large + */ +class WriteSocketThread : public Thread +{ + ValueCheckProvider m_aValues; + osl::Condition &m_aCondition; + +protected: + oslThreadIdentifier m_id; + + void SAL_CALL run( ) + { + t_print("start WriteSocketThread\n"); + ::osl::AcceptorSocket asAcceptorSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + ::osl::SocketAddr saLocalSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT10 ); + if (! saLocalSocketAddr.is()) + { + t_print("LocalSocketAddr was NOT created successfully!\n"); + } + + ::osl::StreamSocket ssStreamConnection; + + //if has not set this option, socket addr can not be binded in some time(maybe 2 minutes) by another socket + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + + /// if the thread should terminate, schedule return false + // while ( schedule( ) == sal_True ) + // { + t_print("bind()\n"); + sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); + if ( sal_True != bOK1 ) + { + t_print("# WriteSocketThread: AcceptorSocket bind address failed. \n" ) ; + } + else + { + t_print("listen()\n"); + sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); + if ( sal_True != bOK2 ) + { + t_print("# WriteSocketThread: AcceptorSocket listen address failed. \n" ) ; + } + else + { + + // blocking mode, if read/recv failed, block until success + asAcceptorSocket.enableNonBlockingMode( sal_False); + t_print("acceptConnection()\n"); + m_aCondition.set(); + + oslSocketResult eResult = asAcceptorSocket.acceptConnection( ssStreamConnection ); + if (eResult != osl_Socket_Ok ) + { + t_print("WriteSocketThread: acceptConnection failed! \n"); + } + else + { + + t_print("write()\n"); + + ssStreamConnection.write( m_aValues.getBuffer(), m_aValues.getBufferSize() ); + t_print("done written.\n"); + } + } + } + ssStreamConnection.close(); + asAcceptorSocket.close(); + } + + void SAL_CALL onTerminated( ) + { + //t_print("# normally terminate this server thread %d!\n", m_id ); + } + +public: + // public to check if data transmition is OK + WriteSocketThread(sal_Int32 _nBufferSize, int _nValue, osl::Condition &_aCond ) + : m_aCondition(_aCond) + { + m_aCondition.reset(); + + t_print("#init WriteSocketThread\n"); + m_id = getIdentifier( ); + //t_print("# successfully creat this server thread %d!\n", m_id ); + + m_aValues.createBuffer(_nBufferSize, _nValue); + } + + ~WriteSocketThread( ) + { + if ( isRunning( ) ) + t_print("# error: server thread not terminated.\n" ); + m_aValues.freeBuffer(); + } +}; + +// ----------------------------------------------------------------------------- + +namespace osl_StreamSocket +{ + + /** testing the methods: + inline StreamSocket(oslAddrFamily Family = osl_Socket_FamilyInet, + oslProtocol Protocol = osl_Socket_ProtocolIp, + oslSocketType Type = osl_Socket_TypeStream); + + inline StreamSocket( const StreamSocket & ); + + inline StreamSocket( oslSocket Socket , __sal_NoAcquire noacquire ); + + inline StreamSocket( oslSocket Socket ); + */ + + class ctors : public CppUnit::TestFixture + { + public: + oslSocket sHandle; + // initialization + void setUp( ) + { + sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); + } + + void tearDown( ) + { + sHandle = NULL; + } + + + void ctors_none() + { + /// Socket constructor. + ::osl::StreamSocket ssSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors_none constructor function: check if the stream socket was created successfully.", + osl_Socket_TypeStream == ssSocket.getType( ) ); + } + + void ctors_acquire() + { + /// Socket constructor. + ::osl::StreamSocket ssSocket( sHandle ); + + CPPUNIT_ASSERT_MESSAGE( "test for ctors_acquire constructor function: check if the socket was created successfully", + osl_Socket_TypeStream == ssSocket.getType( ) ); + } + + void ctors_no_acquire() + { + /// Socket constructor. + ::osl::StreamSocket ssSocket( sHandle, SAL_NO_ACQUIRE ); + + CPPUNIT_ASSERT_MESSAGE(" test for ctors_no_acquire constructor function: check if the socket was created successfully", + osl_Socket_TypeStream == ssSocket.getType( ) ); + } + + void ctors_copy_ctor() + { + /// Socket constructor. + ::osl::StreamSocket ssSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + /// Socket copy constructor. + ::osl::StreamSocket copySocket( ssSocket ); + + CPPUNIT_ASSERT_MESSAGE(" test for ctors_copy_ctor constructor function: create new Socket instance using copy constructor", + osl_Socket_TypeStream == copySocket.getType( ) ); + } + + CPPUNIT_TEST_SUITE( ctors ); + CPPUNIT_TEST( ctors_none ); + CPPUNIT_TEST( ctors_acquire ); + CPPUNIT_TEST( ctors_no_acquire ); + CPPUNIT_TEST( ctors_copy_ctor ); + CPPUNIT_TEST_SUITE_END(); + + }; // class ctors + + class send_recv: public CppUnit::TestFixture + { + public: + // initialization + void setUp( ) + { + } + + void tearDown( ) + { + + } + + void send_recv1() + { + osl::Condition aCondition; + //client sent two strings, and server received, check the order and value + ServerSocketThread myServerThread( aCondition ); + ClientSocketThread myClientThread( aCondition ); + myServerThread.create( ); + myClientThread.create( ); + + //wait until the thread terminate + myClientThread.join( ); + myServerThread.join( ); + sal_Char myStr[30] = ""; + strcat( myStr, pTestString1 ); + strcat( myStr, pTestString2 ); + sal_Int32 nRes = strcmp( myServerThread.pReadBuffer, myStr ); + CPPUNIT_ASSERT_MESSAGE(" test for send/recv with two threads: launch Server/Client threads, send data from client, check received data in Server thread.", + nRes == 0 ); + } + + // error when recv + void send_recv2() + { + ::osl::AcceptorSocket asAcceptorSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + ::osl::SocketAddr saLocalSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT9 ); + ::osl::StreamSocket ssStreamConnection; + sal_Char pReadBuffer[30] = ""; + + osl::Condition aCondition; + aCondition.reset(); + ClientSocketThread myClientThread( aCondition ); + myClientThread.create( ); + + asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); + + asAcceptorSocket.bind( saLocalSocketAddr ); + asAcceptorSocket.listen( 1 ); + asAcceptorSocket.enableNonBlockingMode( sal_True ); + aCondition.set(); + + asAcceptorSocket.acceptConnection( ssStreamConnection ); + sal_Int32 nReadNumber = ssStreamConnection.recv( pReadBuffer, 11 ); + + myClientThread.join( ) ; + ssStreamConnection.close(); + asAcceptorSocket.close(); + CPPUNIT_ASSERT_MESSAGE(" test for send/recv, recv error!", nReadNumber == -1 ); + } + + // LLA: This is a helper function, which create 2 threads, a server and a client. + // the server writes the buffersize to the client. + + void write_read(sal_Int32 _nBufferSize, int _nValue) + { + //client sent two strings, and server received, check the order and value + osl::Condition aCondition; + WriteSocketThread myServerThread(_nBufferSize, _nValue, aCondition); + ReadSocketThread myClientThread(_nBufferSize, _nValue, aCondition); + myServerThread.create( ); +// thread_sleep( 1 ); + myClientThread.create( ); + + //wait until the thread terminate + myClientThread.join( ); + myServerThread.join( ); + + //Maximum Packet Size is ( ARPANET, MILNET = 1007 Ethernet (10Mb) = 1500 + // Proteon PRONET = 2046), so here test read 4000 bytes + sal_Int32 nLength = myClientThread.getCount(); + bool bIsOk = myClientThread.isOk(); // check if the values are right. + + t_print("Length:=%d\n", (int) nLength); + t_print(" bIsOk:=%d\n", bIsOk); + + CPPUNIT_ASSERT_MESSAGE(" test for write/read values with two threads: send data from server, check readed data in client.", + nLength == _nBufferSize && bIsOk == true); + } + + // Tests with different values and sizes + void write_read_001() + { + write_read(50, 10); + } + void write_read_002() + { + write_read(1024, 20); + } + void write_read_003() + { + write_read(4000, 1); + } + void write_read_004() + { + write_read(8192, 3); + } + void write_read_005() + { + write_read(32768, 3); + } + + CPPUNIT_TEST_SUITE( send_recv ); + CPPUNIT_TEST( write_read_001 ); + CPPUNIT_TEST( write_read_002 ); + CPPUNIT_TEST( write_read_003 ); + CPPUNIT_TEST( write_read_004 ); + CPPUNIT_TEST( write_read_005 ); + CPPUNIT_TEST( send_recv1 ); + CPPUNIT_TEST( send_recv2 ); +// CPPUNIT_TEST( write_read ); + CPPUNIT_TEST_SUITE_END(); + }; // class send_recv + +// ----------------------------------------------------------------------------- + + class SendClientThread : public Thread + { + protected: + ::osl::SocketAddr m_saTargetSocketAddr; + ::osl::ConnectorSocket m_csConnectorSocket; + void SAL_CALL run( ) + { + TimeValue *pTimeout; + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 5; + pTimeout->Nanosec = 0; + + if ( osl_Socket_Ok == m_csConnectorSocket.connect( m_saTargetSocketAddr, pTimeout )) + { +#if !SILENT_TEST + sal_Int32 nWrite1 = +#endif + m_csConnectorSocket.write( pTestString1, 11 ); // "test socket" +#if !SILENT_TEST + sal_Int32 nWrite2 = +#endif + m_csConnectorSocket.write( pTestString2, strlen( pTestString2 ) + 1 ); + thread_sleep( 2 ); + m_csConnectorSocket.write( pTestString2, strlen( pTestString2 ) + 1 ); + t_print("nWrite1 is %d, nWrite2 is %d\n", (int) nWrite1, (int) nWrite2 ); + //thread_sleep( 1 ); + } + else + t_print("# SendClientThread: connect failed! \n"); + + m_csConnectorSocket.close(); + free( pTimeout ); + } + public: + SendClientThread( ): + m_saTargetSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT9 ), + m_csConnectorSocket( ) + { + //t_print("# successfully creat this SendClientThread %d!\n", m_id ); + } + + ~SendClientThread( ) + { + if ( isRunning( ) ) + t_print("# error: SendClientThread has not terminated.\n" ); + } + + }; + + class shutdown: public CppUnit::TestFixture + { + public: + // initialization + void setUp( ) + { + } + + void tearDown( ) + { + + } + + // similar to close_002 + void shutdown_001() + { +#if defined(LINUX) + ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + AcceptorThread myAcceptorThread( asSocket, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")) ); + myAcceptorThread.create(); + + thread_sleep( 1 ); + + //when accepting, shutdown the socket, the thread will not block for accepting + asSocket.shutdown(); + myAcceptorThread.join(); + + CPPUNIT_ASSERT_MESSAGE( "test for close when is accepting: the socket will quit accepting status.", + myAcceptorThread.isOK( ) == sal_True ); +#endif + } + + void shutdown_002() + { + ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + ::osl::SocketAddr saLocalSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT9); + asSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); + CPPUNIT_ASSERT_MESSAGE("shutdown_002: bind fail", asSocket.bind( saLocalSocketAddr ) == sal_True); + CPPUNIT_ASSERT_MESSAGE("shutdown_002: listen fail", asSocket.listen( 1 ) == sal_True ); + sal_Char pReadBuffer[40]; +// osl::Condition aCondition; + SendClientThread mySendThread; + mySendThread.create(); + + asSocket.enableNonBlockingMode( sal_False ); + ::osl::StreamSocket ssConnectionSocket; + oslSocketResult eResult = asSocket.acceptConnection( ssConnectionSocket ); + CPPUNIT_ASSERT_MESSAGE("shutdown_002: acceptConnection fail", eResult == osl_Socket_Ok ); + + /* set socket option SO_LINGER 0, so close immediatly */ + linger aLingerSet; + sal_Int32 nBufferLen = sizeof( struct linger ); + aLingerSet.l_onoff = 0; + aLingerSet.l_linger = 0; + + ssConnectionSocket.setOption( osl_Socket_OptionLinger, &aLingerSet, nBufferLen ); + thread_sleep( 1 ); + //sal_uInt32 nRecv1 = 0; + sal_Int32 nRead1 = ssConnectionSocket.read( pReadBuffer, 11 ); + + //shutdown read after client the first send complete + ssConnectionSocket.shutdown( osl_Socket_DirRead ); + + sal_Int32 nRead2 = ssConnectionSocket.read( pReadBuffer + nRead1, 12 ); + sal_Int32 nRead3 = ssConnectionSocket.read( pReadBuffer + nRead1 + nRead2, 12 ); + t_print("after read 2, nRead1 is %d, nRead2 is %d, nRead3 is %d \n", (int) nRead1, (int) nRead2, (int) nRead3 ); + mySendThread.join(); + + ssConnectionSocket.close(); + asSocket.close(); + + /* on Linux, if send is before shutdown(DirRead), can read, nRecv2 still > 0, + http://dbforums.com/arch/186/2002/12/586417 + While on Solaris, after shutdown(DirRead), all read will return 0 + */ +#ifdef LINUX + CPPUNIT_ASSERT_MESSAGE( "test for shutdown read direction: the socket can not read(recv).", + nRead1 > 0 && nRead3 == 0 ); +#else + CPPUNIT_ASSERT_MESSAGE( "test for shutdown read direction: the socket can not read(recv).", + nRead1 > 0 && nRead2 == 0 && nRead3 == 0 ); +#endif + + } + + void shutdown_003() + { + ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + ::osl::SocketAddr saLocalSocketAddr( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("127.0.0.1")), IP_PORT_MYPORT9); + asSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); + CPPUNIT_ASSERT_MESSAGE("shutdown_002: bind fail", asSocket.bind( saLocalSocketAddr ) == sal_True); + CPPUNIT_ASSERT_MESSAGE("shutdown_002: listen fail", asSocket.listen( 1 ) == sal_True ); + sal_Char pReadBuffer[40]; + osl::Condition aCondition; + SendClientThread mySendThread; + mySendThread.create(); + + asSocket.enableNonBlockingMode( sal_False ); + ::osl::StreamSocket ssConnectionSocket; + oslSocketResult eResult = asSocket.acceptConnection( ssConnectionSocket ); + CPPUNIT_ASSERT_MESSAGE("shutdown_002: acceptConnection fail", eResult == osl_Socket_Ok ); + + thread_sleep( 1 ); + //shutdown write after client the first send complete + ssConnectionSocket.shutdown( osl_Socket_DirWrite ); + + // recv should not shutdown + sal_Int32 nRead1 = ssConnectionSocket.read( pReadBuffer, 11 ); + + sal_Int32 nWrite = ssConnectionSocket.write( pReadBuffer, 11 ); + // still can read + sal_Int32 nRead3 = ssConnectionSocket.read( pReadBuffer + nRead1 , 12 ); + t_print("after read 2, nRead1 is %d, nWrite is %d, nRead3 is %d\n", (int) nRead1, (int) nWrite, (int) nRead3 ); + mySendThread.join(); + ssConnectionSocket.close(); + asSocket.close(); + + CPPUNIT_ASSERT_MESSAGE( "test for shutdown read direction: the socket can not send(write).", + nRead1 > 0 && nWrite == 0 && nRead3 > 0); + + } + + CPPUNIT_TEST_SUITE( shutdown ); + CPPUNIT_TEST( shutdown_001 ); + CPPUNIT_TEST( shutdown_002 ); + CPPUNIT_TEST( shutdown_003 ); + CPPUNIT_TEST_SUITE_END(); + }; // class shutdown + + class isExceptionPending: public CppUnit::TestFixture + { + public: + void isExPending_001() + { + ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + TimeValue *pTimeout; + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 3; + pTimeout->Nanosec = 0; + sal_Bool bOk = asSocket.isExceptionPending( pTimeout ); + free( pTimeout ); + + CPPUNIT_ASSERT_MESSAGE( "test for isExceptionPending.", + bOk == sal_False ); + } + + /**tester's comments: lack of a case that return sal_True, do not know when it will return sal_True*/ + + + CPPUNIT_TEST_SUITE( isExceptionPending ); + CPPUNIT_TEST( isExPending_001 ); + CPPUNIT_TEST_SUITE_END(); + }; // class isExceptionPending + +// ----------------------------------------------------------------------------- +/** Client Socket Thread, served as a temp little client to communicate with server. + */ + +#define IP_PORT_TEST 8900 + + class ReadSocket2Thread : public Thread + { + osl::Condition &m_aCondition; + char* m_pBuffer; + sal_Int32 m_nBufferSize; + sal_Int32 m_nReadCount; + rtl::OString m_sAddr; + + bool m_bOk; + + void setFailed() + { + m_bOk = false; + } + + protected: + oslThreadIdentifier m_id; + + void read() + { + if (m_sAddr.getLength() == 0) + { + setFailed(); + return; + } + + // 10.16.66.252 + ::osl::SocketAddr aSocketAddr( rtl::OUString::createFromAscii(m_sAddr.getStr()), IP_PORT_TEST ); + ::osl::ConnectorSocket aSocket; // ( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + + aSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True; + + m_aCondition.wait(); + t_print("wait done\n"); + + TimeValue *pTimeout; + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 20; + pTimeout->Nanosec = 0; + + + // blocking mode, if read/recv failed, block until success + t_print("enableNonBlockingMode(false)\n"); + aSocket.enableNonBlockingMode( sal_False ); + + + t_print("connect()\n"); + oslSocketResult eResult = aSocket.connect( aSocketAddr, pTimeout ); + if ( osl_Socket_Ok == eResult) + { + if (m_pBuffer) + { + t_print("read()\n"); + m_nReadCount = aSocket.read( m_pBuffer, m_nBufferSize ); + t_print("%d bytes recived.\n", (int) m_nReadCount); + } + } + else + { + t_print("# ReadSocket2Thread: connect failed! \n"); + printSocketResult(eResult); + setFailed(); + } + + //remove this line for deadlock on solaris( margritte.germany ) + aSocket.close(); + free( pTimeout ); + } + + void SAL_CALL run( ) + { + read(); + } + + void SAL_CALL onTerminated( ) + { + //t_print("# normally terminate this thread %d!\n", m_id ); + } + + public: + sal_Int32 getCount() {return m_nReadCount;} + bool isOk() {return m_nReadCount == 0 ? false : true;} + bool getFailed() {return m_bOk == false ? true : false;} + + ReadSocket2Thread(osl::Condition &_aCondition) + :m_aCondition(_aCondition), + m_nReadCount(0), + m_bOk( true ) + { + m_aCondition.reset(); + m_pBuffer = (char*) malloc(1024); + if (m_pBuffer) + { + m_nBufferSize = 1024; + } + + m_id = getIdentifier( ); + //t_print("# successfully creat this client thread %d!\n", m_id ); + } + + void setAddr(rtl::OString const& _sAddr) + { + m_sAddr = _sAddr; + } + + ~ReadSocket2Thread( ) + { + if ( isRunning( ) ) + t_print("# error: client thread not terminated.\n" ); + free(m_pBuffer); + } + + }; + + // ----------------------------------------------------------------------------- + + class justtest : public CppUnit::TestFixture + { + void send_Acceptor(rtl::OString const& _sAddr, osl::Condition &) + { + ::osl::AcceptorSocket aSocket; // ( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + ::osl::SocketAddr aSocketAddr; + + if (! aSocketAddr.setPort(IP_PORT_TEST)) + { + t_print("# cant set port\n" ); + } + + if (! aSocketAddr.setHostname(rtl::OUString::createFromAscii(_sAddr.getStr()))) + { + t_print("# cant set hostname/ip\n" ); + } + + rtl::OUString aHostname = aSocketAddr.getHostname(); + aSocketAddr.getPort(); + + + //if has not set this option, socket addr can not be binded in some time(maybe 2 minutes) by another socket + aSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); + + /// if the thread should terminate, schedule return false + // while ( schedule( ) == sal_True ) + // { + if (! aSocket.bind( aSocketAddr )) + { + t_print("# can't bind.\n" ); + } + if (! aSocket.listen( )) + { + t_print("# can't listen. \n" ); + } + + // blocking mode, if read/recv failed, block until success + aSocket.enableNonBlockingMode( sal_False); + ::osl::StreamSocket ssStreamConnection; + + oslSocketResult eResult = aSocket.acceptConnection( ssStreamConnection ); + if (eResult != osl_Socket_Ok ) + { + t_print("WriteSocketThread: acceptConnection failed! \n"); + // break; + } + char const * pBuffer = "Test String\n"; + sal_Int32 nBufferSize = strlen(pBuffer); + ssStreamConnection.write( pBuffer, nBufferSize ); + // break; + // } + + // ssStreamConnection.close(); + aSocket.close(); + } + + // ----------------------------------------------------------------------------- + + void send_Connector(rtl::OString const& _sAddr, osl::Condition &/*_aCondition*/ ) + { + ::osl::ConnectorSocket aSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + ::osl::SocketAddr aSocketAddr( rtl::OUString::createFromAscii(_sAddr.getStr()), IP_PORT_TEST ); + + if (! aSocketAddr.is()) + { + t_print("is failed.\n"); + return; + } + + //if has not set this option, socket addr can not be binded in some time(maybe 2 minutes) by another socket + aSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True; + + oslSocketResult aResult = aSocket.connect( aSocketAddr ); + if ( aResult != osl_Socket_Ok ) + { + t_print("# send_Connector: connect failed. \n" ); + } + else + { + // blocking mode, if read/recv failed, block until success +// aSocket.enableNonBlockingMode( sal_False ); + +// _aCondition.set(); + + ::osl::StreamSocket ssStreamConnection(aSocket); + + char const * pBuffer = "GET / HTTP/1.0\015\012\015\012"; + sal_Int32 nBufferSize = strlen(pBuffer); + ssStreamConnection.write( pBuffer, nBufferSize ); + + char *pBufferPeek = (char*) malloc(1024); + sal_Int32 nReadNumber = ssStreamConnection.recv( pBufferPeek, 1024, osl_Socket_MsgPeek); + free(pBufferPeek); + + char *pBuffer2 = (char*) malloc(nReadNumber + 1); + sal_Int32 nReadNumberReal = ssStreamConnection.read( pBuffer2, nReadNumber ); + pBuffer2[nReadNumberReal] = '\0'; + + t_print("received: %s\n", pBuffer2); + + rtl::OUString suError = ssStreamConnection.getErrorAsString(); + free(pBuffer2); + // ssStreamConnection.close(); + + // ssStreamConnection.close(); + } + aSocket.shutdown(osl_Socket_DirReadWrite); + aSocket.close(); + } + + + public: +// LLA: orig void send_recv() +// LLA: orig { +// LLA: orig if ( ifAvailable(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("margritte.germany"))) == sal_True ) +// LLA: orig t_print("margritte is alive ! \n"); +// LLA: orig if ( ifAvailable(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("10.16.66.252"))) == sal_False ) +// LLA: orig { +// LLA: orig t_print("ip 10.16.66.252 is not alive! \n"); +// LLA: orig return; +// LLA: orig } +// LLA: orig ReadSocket2Thread myReadThread; +// LLA: orig myReadThread.create(); +// LLA: orig +// LLA: orig thread_sleep( 2 ); +// LLA: orig // send_Acceptor(); +// LLA: orig send_Connector(); +// LLA: orig +// LLA: orig myReadThread.join(); +// LLA: orig +// LLA: orig // statistics +// LLA: orig sal_uInt32 nLength = myReadThread.getCount(); +// LLA: orig bool bIsOk = myReadThread.isOk(); // check if the values are right. +// LLA: orig +// LLA: orig t_print("Length:=%d\n", nLength); +// LLA: orig t_print(" bIsOk:=%d\n", bIsOk); +// LLA: orig } + + // ----------------------------------------------------------------------------- + + // LLA: send_Connector_2_margritte works, it send strings to echo server on margritte + // but can not receive anything + + void send_Connector_2_margritte(rtl::OString const& _sAddr) + { + ::osl::ConnectorSocket aSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + ::osl::SocketAddr aSocketAddr( rtl::OUString::createFromAscii(_sAddr.getStr()), IP_PORT_TEST ); + + //if has not set this option, socket addr can not be binded in some time(maybe 2 minutes) by another socket + aSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True; + + oslSocketResult aResult = aSocket.connect( aSocketAddr ); + if ( aResult != osl_Socket_Ok ) + { + t_print("# connect failed. \n" ); + } + else + { + // blocking mode, if read/recv failed, block until success + aSocket.enableNonBlockingMode( sal_False ); + + ::osl::StreamSocket ssStreamConnection(aSocket); + + char const * pBuffer = "Test String\n"; + sal_Int32 nBufferSize = strlen(pBuffer); + ssStreamConnection.write( pBuffer, nBufferSize ); + + char const * pBuffer3 = "quit\n"; + nBufferSize = strlen(pBuffer3); + ssStreamConnection.write( pBuffer3, nBufferSize ); + + ssStreamConnection.close(); + } + aSocket.close(); + } + + void send_recv_2_margritte() + { + rtl::OString sAddr; + sAddr = "margritte.germany.sun.com"; + if ( ifAvailable(rtl::OUString::createFromAscii(sAddr.getStr())) == sal_True ) + { + t_print("found %s!\n", sAddr.getStr()); + } + send_Connector_2_margritte(sAddr); + } + + // ----------------------------------------------------------------------------- + + void send_recv() + { + rtl::OString sAddr; + // if ( ifAvailable(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("margritte.germany"))) == sal_True ) + // { + // t_print("margritte is alive ! \n"); + // sAddr = "margritte.germany"; + // } + + sAddr = "margritte.germany.sun.com"; + if ( ifAvailable(rtl::OUString::createFromAscii(sAddr.getStr())) == sal_True ) + { + t_print("found %s!\n", sAddr.getStr()); + } +// else +// { +// if ( ifAvailable(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("192.168.7.2"))) == sal_True ) +// { +// sAddr = "192.168.7.2"; +// t_print("moon found ! \n"); +// } +// else +// { +// if ( ifAvailable(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("moon.linux.bogus"))) == sal_True ) +// { +// sAddr = "moon.linux.bogus"; +// t_print("moon found ! \n"); +// } +// else +// { +// if ( ifAvailable(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("moon"))) == sal_True ) +// { +// sAddr = "moon"; +// t_print("moon found ! \n"); +// } +// } +// } +// } + + // if ( ifAvailable(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("10.16.64.196"))) == sal_False ) + // { + // t_print("ip 10.16.64.196 is not alive! \n"); + // return; + // } + + osl::Condition aCondition; + ReadSocket2Thread myReadThread(aCondition); + myReadThread.setAddr(sAddr); +// myReadThread.create(); + + thread_sleep( 2 ); + if (! myReadThread.getFailed()) + { + // send_Acceptor(sAddr, aCondition); + send_Connector(sAddr, aCondition); + + thread_sleep( 2 ); + if (myReadThread.isRunning()) + { + myReadThread.join(); + } + // termAndJoinThread(&myReadThread); + + // statistics +#if !SILENT_TEST + sal_uInt32 nLength = +#endif + myReadThread.getCount(); + +#if !SILENT_TEST + bool bIsOk = +#endif + myReadThread.isOk(); // check if the values are right. + + t_print("Length:=%d\n", (int) nLength); + t_print(" bIsOk:=%d\n", bIsOk); + } + else + { + t_print("ERROR: No echo Server on %s found.\n", sAddr.getStr()); + } + } + + + void getPage(rtl::OString const& _sAddr); + void test_getPage() + { + // rtl::OString sPage("lla-1.germany.sun.com"); + // getPage(sPage); + + rtl::OString sPage("lla-1"); + getPage(sPage); + } + + CPPUNIT_TEST_SUITE( justtest ); + CPPUNIT_TEST( send_recv ); + CPPUNIT_TEST( test_getPage ); + CPPUNIT_TEST_SUITE_END(); + }; // class isExceptionPending + + + void justtest::getPage(rtl::OString const& _sAddr) + { + rtl::OUString suAddr = rtl::OUString::createFromAscii(_sAddr.getStr()); + ::osl::ConnectorSocket aSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + ::osl::SocketAddr aSocketAddr( suAddr, 80 ); + + { + // some checks + aSocketAddr.getPort(); + oslSocketResult aResult; + rtl::ByteSequence aSeq = aSocketAddr.getAddr(&aResult); + if (aResult != osl_Socket_Ok) + { + t_print("problem with getAddr: "); + printSocketResult(aResult); + } + + rtl::OUString sStr = aSocketAddr.getHostname(&aResult); + if (aResult != osl_Socket_Ok) + { + t_print("problem with hostname: "); + printSocketResult(aResult); + } + } + + oslSocketResult aResult; + + // SocketAddr::resolveHostname(suAddr, aSocketAddr); + // if (! aSocketAddr.is()) + // { + // t_print("Can't resolve Hostname.\n"); + // return; + // } + // rtl::OUString sStr = aSocketAddr.getHostname(&aResult); + // if (aResult != osl_Socket_Ok) + // { + // t_print("problem with hostname: "); + // printSocketResult(aResult); + // + // } + + if (! aSocketAddr.is()) + { + t_print("SocketAddr::is() failed.\n"); + return; + } + + //if has not set this option, socket addr can not be binded in some time(maybe 2 minutes) by another socket + aSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True; + + aResult = aSocket.connect( aSocketAddr ); + if ( aResult != osl_Socket_Ok ) + { + t_print("# send_Connector: connect failed. \n" ); + } + else + { + // blocking mode, if read/recv failed, block until success +// aSocket.enableNonBlockingMode( sal_False ); + +// _aCondition.set(); + + ::osl::StreamSocket ssStreamConnection(aSocket); + + char const * pBuffer = "GET / HTTP/1.0\015\012\015\012"; + sal_Int32 nBufferSize = strlen(pBuffer); + ssStreamConnection.write( pBuffer, nBufferSize ); + + + char *pBufferPeek = (char*) malloc(1024); + sal_Int32 nReadNumber = 1; + while ( nReadNumber != 0) + { + nReadNumber = ssStreamConnection.recv( pBufferPeek, 1024, osl_Socket_MsgPeek); + if (nReadNumber > 0) + { + char *pBuffer2 = (char*) malloc(nReadNumber + 1); + sal_Int32 nReadNumberReal = ssStreamConnection.read( pBuffer2, nReadNumber ); + pBuffer2[nReadNumberReal] = '\0'; + t_print("%s", pBuffer2); + free(pBuffer2); + } + } + free(pBufferPeek); + + rtl::OUString suError = ssStreamConnection.getErrorAsString(); + } + aSocket.shutdown(osl_Socket_DirReadWrite); + aSocket.close(); + } + +// ----------------------------------------------------------------------------- + + CPPUNIT_TEST_SUITE_REGISTRATION(osl_StreamSocket::ctors); + CPPUNIT_TEST_SUITE_REGISTRATION(osl_StreamSocket::send_recv); +// CPPUNIT_TEST_SUITE_REGISTRATION(osl_StreamSocket::shutdown); + CPPUNIT_TEST_SUITE_REGISTRATION(osl_StreamSocket::isExceptionPending); + +// CPPUNIT_TEST_SUITE_REGISTRATION(osl_StreamSocket::justtest); + +} // namespace osl_StreamSocket + +// ----------------------------------------------------------------------------- + +// this macro creates an empty function, which will called by the RegisterAllFunctions() +// to let the user the possibility to also register some functions by hand. +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/socket/osl_StreamSocket.xsce b/sal/qa/osl/socket/osl_StreamSocket.xsce new file mode 100644 index 000000000000..9c9513969d4a --- /dev/null +++ b/sal/qa/osl/socket/osl_StreamSocket.xsce @@ -0,0 +1,4 @@ +osl_StreamSocket.send_recv.send_recv2 +osl_StreamSocket.send_recv.write_read_001 wntmsci unxsols +osl_StreamSocket.justtest.test_getPage wntmsci + diff --git a/sal/qa/osl/socket/sockethelper.cxx b/sal/qa/osl/socket/sockethelper.cxx new file mode 100644 index 000000000000..c60ca0006fcc --- /dev/null +++ b/sal/qa/osl/socket/sockethelper.cxx @@ -0,0 +1,340 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" +#include "sockethelper.hxx" +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> + +#if OSL_DEBUG_LEVEL > 0 +# define SILENT_TEST 0 +#else +# define SILENT_TEST 1 +#endif + +#if SILENT_TEST +# define t_print(...) { } +#else +# define t_print printf +#endif + +//------------------------------------------------------------------------ +// Ip version definition +//------------------------------------------------------------------------ +#define IP_VER 4 /// currently only IPv4 is considered. + +//------------------------------------------------------------------------ +// helper functions +//------------------------------------------------------------------------ + +/** compare two OUString. +*/ +sal_Bool compareUString( const ::rtl::OUString & ustr1, const ::rtl::OUString & ustr2 ) +{ + sal_Bool bOk = ustr1.equalsIgnoreAsciiCase( ustr2 ); + + return bOk; +} + +/** compare a OUString and an ASCII string. +*/ +sal_Bool compareUString( const ::rtl::OUString & ustr, const sal_Char *astr ) +{ + ::rtl::OUString ustr2 = rtl::OUString::createFromAscii( astr ); + sal_Bool bOk = ustr.equalsIgnoreAsciiCase( ustr2 ); + + return bOk; +} + +/** compare two socket address. +*/ +sal_Bool compareSocketAddr( const ::osl::SocketAddr & addr1 , const ::osl::SocketAddr & addr2 ) +{ + return ( ( sal_True == compareUString( addr1.getHostname( 0 ), addr2.getHostname( 0 ) ) ) && ( addr2.getPort( ) == addr2.getPort( ) ) ); +} + +/** print a UNI_CODE String. And also print some comments of the string. +*/ +void printUString( const ::rtl::OUString & str, const char* msg) +{ +#if SILENT_TEST + (void)str; + (void)msg; +#else + t_print("#%s #printUString_u# ", msg ); + rtl::OString aString; + aString = ::rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US ); + t_print("%s\n", aString.getStr( ) ); +#endif +} + +/** get the local host name. + mindy: gethostbyname( "localhost" ), on Linux, it returns the hostname in /etc/hosts + domain name, + if no entry in /etc/hosts, it returns "localhost" + domain name +*/ +::rtl::OUString getHost( void ) +{ + struct hostent *hptr; + + hptr = gethostbyname( "localhost" ); + OSL_ENSURE( hptr != NULL, "#In getHostname function, error on gethostbyname()" ); + ::rtl::OUString aUString = ::rtl::OUString::createFromAscii( (const sal_Char *) hptr->h_name ); + + return aUString; +} + +/** get the full host name of the current processor, such as "aegean.prc.sun.com" --mindyliu +*/ +::rtl::OUString getThisHostname( void ) +{ + ::rtl::OUString aUString; +#ifdef WNT + struct hostent *hptr; + hptr = gethostbyname( "localhost" ); + OSL_ENSURE( hptr != NULL, "#In getHostname function, error on gethostbyname()" ); + rtl::OString sHostname(hptr->h_name); + aUString = ::rtl::OStringToOUString(sHostname, RTL_TEXTENCODING_ASCII_US); +#else + char hostname[255]; + if (gethostname(hostname, 255) != 0) { + OSL_FAIL( "#Error: gethostname failed." ); + } + + struct hostent *hptr; + //first search /ets/hosts, then search from dns + hptr = gethostbyname( hostname); + if ( hptr != NULL ) + { + strcpy( hostname, hptr->h_name ); + } + + t_print("hostname is %s \n", hostname ); + rtl::OString sHostname( hostname ); + aUString = ::rtl::OStringToOUString( sHostname, RTL_TEXTENCODING_ASCII_US ); + aUString.getLength(); +#endif + return aUString; +} + +/** get IP by name, search /etc/hosts first, then search from dns, fail return OUString("") +*/ +::rtl::OUString getIPbyName( rtl::OString const& str_name ) +{ + ::rtl::OUString aUString; + struct hostent *hptr; + //first search /ets/hosts, then search from dns + hptr = gethostbyname( str_name.getStr()); + if ( hptr != NULL ) + { + struct in_addr ** addrptr; + addrptr = (struct in_addr **) hptr->h_addr_list ; + //if there are more than one IPs on the same machine, we select one + for (; *addrptr; addrptr++) + { + t_print("#Local IP Address: %s\n", inet_ntoa(**addrptr)); + aUString = ::rtl::OUString::createFromAscii( (sal_Char *) (inet_ntoa(**addrptr)) ); + } + } + return aUString; +} + +/** get local ethernet IP +*/ +::rtl::OUString getLocalIP( ) +{ + char hostname[255]; + gethostname(hostname, 255); + + return getIPbyName( hostname ); +} + +/** construct error message +*/ +::rtl::OUString outputError( const ::rtl::OUString & returnVal, const ::rtl::OUString & rightVal, const sal_Char * msg ) +{ + ::rtl::OUString aUString; + if ( returnVal.equals( rightVal ) ) + return aUString; + aUString += ::rtl::OUString::createFromAscii(msg); + aUString += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(": the returned value is '")); + aUString += returnVal; + aUString += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("', but the value should be '")); + aUString += rightVal; + aUString += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("'.")); + return aUString; +} + +/** wait _nSec seconds. +*/ +void thread_sleep( sal_Int32 _nSec ) +{ + /// print statement in thread process must use fflush() to force display. + // printf("wait %d seconds. ", _nSec ); + // fflush(stdout); + +#ifdef WNT //Windows + Sleep( _nSec * 100 ); +#endif +#if ( defined UNX ) || ( defined OS2 ) //Unix + usleep(_nSec * 100000); +#endif + // t_print("# done\n" ); +} + +/** print Boolean value. +*/ +void printBool( sal_Bool bOk ) +{ +#if SILENT_TEST + (void)bOk; +#else + t_print("#printBool# " ); + t_print ("%s", (sal_True == bOk) ? "YES!\n" : "NO!\n"); +#endif +} + +/** print content of a ByteSequence. +*/ +void printByteSequence_IP( const ::rtl::ByteSequence & bsByteSeq, sal_Int32 nLen ) +{ +#if SILENT_TEST + (void)bsByteSeq; + (void)nLen; +#else + t_print("#ByteSequence is: " ); + for ( int i = 0; i < nLen; i++ ){ + if ( bsByteSeq[i] < 0 ) + t_print("%d ", 256 + bsByteSeq[i] ); + else + t_print("%d ", bsByteSeq[i] ); + } + t_print(" .\n" ); +#endif +} + +/** convert an IP which is stored as a UString format to a ByteSequence array for later use. +*/ +::rtl::ByteSequence UStringIPToByteSequence( ::rtl::OUString aUStr ) +{ + + rtl::OString aString = ::rtl::OUStringToOString( aUStr, RTL_TEXTENCODING_ASCII_US ); + const sal_Char *pChar = aString.getStr( ) ; + sal_Char tmpBuffer[4]; + sal_Int32 nCharCounter = 0; + ::rtl::ByteSequence bsByteSequence( IP_VER ); + sal_Int32 nByteSeqCounter = 0; + + for ( int i = 0; i < aString.getLength( ) + 1 ; i++ ) + { + if ( ( *pChar != '.' ) && ( i !=aString.getLength( ) ) ) + tmpBuffer[nCharCounter++] = *pChar; + else + { + tmpBuffer[nCharCounter] = '\0'; + nCharCounter = 0; + bsByteSequence[nByteSeqCounter++] = static_cast<sal_Int8>(atoi( tmpBuffer )); + } + pChar++; + } + return bsByteSequence; +} + +/** print a socket result name. +*/ +void printSocketResult( oslSocketResult eResult ) +{ + t_print("printSocketResult: " ); + if (!eResult) + switch (eResult) + { + case osl_Socket_Ok: + t_print("client connected\n"); + break; + case osl_Socket_Error: + t_print("got an error ... exiting\r\n\r\n" ); + break; + case osl_Socket_TimedOut: + t_print("timeout\n"); + break; + case osl_Socket_Interrupted: + t_print("interrupted\n"); + break; + case osl_Socket_InProgress: + t_print("in progress\n"); + break; + default: + t_print("unknown result\n"); + break; + } +} + +/** if 4 parts of an IP addr are equal to specified values +*/ +sal_Bool ifIpv4is( const ::rtl::ByteSequence Ipaddr, sal_Int8 seq1, sal_Int8 seq2, sal_Int8 seq3, sal_Int8 seq4 ) +{ + if ( ( Ipaddr[0] == seq1 ) && ( Ipaddr[1] == seq2 ) && ( Ipaddr[2] == seq3 ) && ( Ipaddr[3] == seq4 ) ) + return sal_True; + return sal_False; +} + +sal_Bool ifAvailable( rtl::OUString const& strAddrOrHostName ) +{ + ::osl::ConnectorSocket aSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); + ::osl::SocketAddr aSocketAddr( strAddrOrHostName, 7 ); + + if (! aSocketAddr.is()) + { + aSocket.close(); + return sal_False; + } + + aSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True; + + TimeValue *pTimeout; + pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); + pTimeout->Seconds = 3; + pTimeout->Nanosec = 0; + + oslSocketResult aResult = aSocket.connect( aSocketAddr, pTimeout ); + free( pTimeout ); + aSocket.close(); + if ( aResult != osl_Socket_Ok ) + { + t_print("Error: "); + printSocketResult(aResult); + t_print("\n"); + + return sal_False; + } + return sal_True; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/socket/sockethelper.hxx b/sal/qa/osl/socket/sockethelper.hxx new file mode 100644 index 000000000000..c0f6e85ad3ec --- /dev/null +++ b/sal/qa/osl/socket/sockethelper.hxx @@ -0,0 +1,168 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _SOCKETHELPER_HXX_ +#define _SOCKETHELPER_HXX_ + +#include <sal/types.h> +#include <rtl/textenc.h> +#include <rtl/ustring.hxx> +#include <rtl/ustring.h> + +#include <osl/socket.hxx> +#include <osl/socket.h> + +#include <osl/thread.hxx> + +#include <osl/file.hxx> + +#include <osl/mutex.hxx> +#include <osl/time.h> + +#ifdef __cplusplus +extern "C" +{ +#endif + +//------------------------------------------------------------------------ +// OS dependent declaration and includes +//------------------------------------------------------------------------ +#if ( defined UNX ) || ( defined OS2 ) //Unix + +#include <unistd.h> +#include <limits.h> +#include <string.h> +#include <math.h> +#include <errno.h> +#include <fcntl.h> +#include <sys/stat.h> +#include <sys/statfs.h> +#include <sys/statvfs.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <netdb.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <sys/wait.h> +#endif + +#ifndef _OSL_SOCKET_CONST_H_ + +#if ( defined WNT ) // Windows +#include <winsock.h> +#include <string.h> +#endif + +#endif + +#ifdef __cplusplus +} +#endif + +/** test output if SILENT_TEST is 0 +*/ +#if OSL_DEBUG_LEVEL > 0 +# define SILENT_TEST 0 +#else +# define SILENT_TEST 1 +#endif + +#if SILENT_TEST +# define t_print(...) { } +#else +# define t_print printf +#endif + +/** convert UString and OUString to std::string +*/ +#define STD_STRING(s) (std::string((const char *)s.getStr())) + +/** compare two OUString. +*/ +sal_Bool compareUString( const ::rtl::OUString & ustr1, const ::rtl::OUString & ustr2 ); +/** compare a OUString and an ASCII string. +*/ +sal_Bool compareUString( const ::rtl::OUString & ustr, const sal_Char *astr ); +/** compare two socket address. +*/ +sal_Bool compareSocketAddr( const ::osl::SocketAddr & addr1 , const ::osl::SocketAddr & addr2 ); +//char * oustring2char( const ::rtl::OUString & str ); +/** print a UNI_CODE String. And also print some comments of the string. +*/ +void printUString( const ::rtl::OUString & str, const char * msg = "" ); +/** get the local host name. + mindy: gethostbyname( "localhost" ), on Linux, it returns the hostname in /etc/hosts + domain name, + if no entry in /etc/hosts, it returns "localhost" + domain name +*/ +::rtl::OUString getHost( void ); +/** get the full host name of the current processor, such as "aegean.prc.sun.com" --mindyliu +*/ +::rtl::OUString getThisHostname( void ); +/** get IP by name, search /etc/hosts first, then search from dns, fail return OUString("") +*/ +::rtl::OUString getIPbyName( rtl::OString const& str_name ); +/** get local ethernet IP +*/ +::rtl::OUString getLocalIP( ); +/** construct error message +*/ +::rtl::OUString outputError( const ::rtl::OUString & returnVal, const ::rtl::OUString & rightVal, const sal_Char * msg = ""); +void thread_sleep( sal_Int32 _nSec ); +/** print Boolean value. +*/ +void printBool( sal_Bool bOk ); +/** print content of a ByteSequence. +*/ +void printByteSequence_IP( const ::rtl::ByteSequence & bsByteSeq, sal_Int32 nLen ); +/** convert an IP which is stored as a UString format to a ByteSequence array for later use. +*/ +::rtl::ByteSequence UStringIPToByteSequence( ::rtl::OUString aUStr ); +/** print a socket result name. +*/ +void printSocketResult( oslSocketResult eResult ); +/** if 4 parts of an IP addr are equal to specified values +*/ +sal_Bool ifIpv4is( const ::rtl::ByteSequence Ipaddr, sal_Int8 seq1, sal_Int8 seq2, sal_Int8 seq3, sal_Int8 seq4 ); +/** if the IP or hostname is availble( alive ) +*/ +//sal_Bool ifAvailable( const char * stringAddrOrHostName ); +sal_Bool ifAvailable( rtl::OUString const& strAddrOrHostName ); +/* +class ClientSocketThread : public Thread +class ServerSocketThread : public Thread +class ValueCheckProvider +class ClientReadSocketThread : public Thread +class ServerWriteSocketThread : public Thread +class AcceptorThread : public Thread +class CloseSocketThread : public Thread + +*/ + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/sal/qa/osl/thread/makefile.mk b/sal/qa/osl/thread/makefile.mk new file mode 100644 index 000000000000..949fe0b0e0e7 --- /dev/null +++ b/sal/qa/osl/thread/makefile.mk @@ -0,0 +1,49 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# <http://www.openoffice.org/license.html> +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +PRJ := ..$/..$/.. +PRJNAME := sal +TARGET := qa_osl_thread + +ENABLE_EXCEPTIONS := TRUE + +.INCLUDE: settings.mk + +DLLPRE = # no leading "lib" on .so files + +SHL1TARGET = $(TARGET) +SHL1OBJS = $(SLO)$/test_thread.obj +SHL1STDLIBS= $(SALLIB) $(CPPUNITLIB) +SHL1VERSIONMAP = $(PRJ)$/qa$/export.map +SHL1IMPLIB = i$(SHL1TARGET) +DEF1NAME = $(SHL1TARGET) + +SLOFILES = $(SHL1OBJS) + +.INCLUDE: target.mk + +.INCLUDE: $(PRJ)$/qa$/cppunit_local.mk diff --git a/sal/qa/osl/thread/test_thread.cxx b/sal/qa/osl/thread/test_thread.cxx new file mode 100644 index 000000000000..9dbc307907b1 --- /dev/null +++ b/sal/qa/osl/thread/test_thread.cxx @@ -0,0 +1,94 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_sal.hxx" + +#include "sal/config.h" + +#include <cppunit/TestFixture.h> +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/plugin/TestPlugIn.h> +#include "osl/conditn.hxx" +#include "osl/thread.hxx" +#include "osl/time.h" +#include "sal/types.h" + +namespace { + +osl::Condition global; + +class Thread: public osl::Thread { +public: + explicit Thread(osl::Condition & cond): m_cond(cond) {} + +private: + virtual void SAL_CALL run() {} + + virtual void SAL_CALL onTerminated() { + m_cond.set(); + CPPUNIT_ASSERT_EQUAL(osl::Condition::result_ok, global.wait()); + } + + osl::Condition & m_cond; +}; + +class Test: public CppUnit::TestFixture { +public: + // Nondeterministic, best effort test that an osl::Thread can be destroyed + // (and in particular osl_destroyThread---indirectly---be called) before the + // corresponding thread has terminated: + void test() { + for (int i = 0; i < 50; ++i) { + osl::Condition c; + Thread t(c); + CPPUNIT_ASSERT(t.create()); + // Make sure virtual Thread::run/onTerminated are called before + // Thread::~Thread: + CPPUNIT_ASSERT_EQUAL(osl::Condition::result_ok, c.wait()); + } + // Make sure Thread::~Thread is called before each spawned thread + // terminates: + global.set(); + // Give the spawned threads enough time to terminate: + TimeValue const twentySeconds = { 20, 0 }; + osl::Thread::wait(twentySeconds); + } + + CPPUNIT_TEST_SUITE(Test); + CPPUNIT_TEST(test); + CPPUNIT_TEST_SUITE_END(); +}; + +CPPUNIT_TEST_SUITE_REGISTRATION(Test); + +} + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ |