├── .gitignore ├── ADDITIONAL_GOODIES.md ├── HOWTO_BUILD_TESTS.md ├── HOWTO_WRITE_TESTS.md ├── KNOWN_ISSUES.md ├── LICENSE.md ├── Makefile ├── README.md ├── TESTING_PHILOSOPHY.md ├── appveyor.yml ├── cxxtest ├── COPYING ├── README ├── TODO ├── Versions ├── VoodooConfiguration.h ├── cxxtest.spec ├── cxxtest │ ├── Descriptions.cpp │ ├── Descriptions.h │ ├── DummyDescriptions.cpp │ ├── DummyDescriptions.h │ ├── ErrorFormatter.h │ ├── ErrorPrinter.h │ ├── Flags.h │ ├── GlobalFixture.cpp │ ├── GlobalFixture.h │ ├── Gui.h │ ├── LinkedList.cpp │ ├── LinkedList.h │ ├── Mock.h │ ├── ParenPrinter.h │ ├── PrintStack.h │ ├── QtGui.h │ ├── RealDescriptions.cpp │ ├── RealDescriptions.h │ ├── Root.cpp │ ├── SelfTest.h │ ├── StdHeaders.h │ ├── StdValueTraits.h │ ├── StdioFilePrinter.h │ ├── StdioPrinter.h │ ├── TeeListener.h │ ├── TestListener.h │ ├── TestRunner.h │ ├── TestSuite.cpp │ ├── TestSuite.h │ ├── TestTracker.cpp │ ├── TestTracker.h │ ├── ValueTraits.cpp │ ├── ValueTraits.h │ ├── VerboseListener.h │ ├── Win32Gui.h │ ├── X11Gui.h │ └── YesNoRunner.h ├── cxxtestgen.pl ├── cxxtestgen.py ├── docs │ ├── Thumbs.db │ ├── convert.pl │ ├── guide.html │ └── index.html ├── keeponlyonetestingeneratedcxx.py ├── sample │ ├── Construct │ ├── CreatedTest.h │ ├── DeltaTest.h │ ├── EnumTraits.h │ ├── ExceptionTest.h │ ├── FixtureTest.h │ ├── Makefile.PL │ ├── Makefile.bcc32 │ ├── Makefile.msvc │ ├── Makefile.unix │ ├── MessageTest.h │ ├── SimpleTest.h │ ├── TraitsTest.h │ ├── aborter.tpl │ ├── file_printer.tpl │ ├── gui │ │ └── GreenYellowRed.h │ ├── mock │ │ ├── Dice.cpp │ │ ├── Dice.h │ │ ├── Makefile │ │ ├── MockStdlib.h │ │ ├── T │ │ │ └── stdlib.h │ │ ├── TestDice.h │ │ ├── mock_stdlib.cpp │ │ ├── real_stdlib.cpp │ │ └── roll.cpp │ ├── msvc │ │ ├── CxxTest_1_Run.dsp │ │ ├── CxxTest_2_Build.dsp │ │ ├── CxxTest_3_Generate.dsp │ │ ├── CxxTest_Workspace.dsw │ │ ├── FixFiles.bat │ │ ├── Makefile │ │ └── ReadMe.txt │ ├── only.tpl │ ├── parts │ │ └── Makefile.unix │ ├── winddk │ │ ├── Makefile │ │ ├── Makefile.inc │ │ ├── RunTests.tpl │ │ └── SOURCES │ └── yes_no_runner.cpp └── simplecxxtestgen.py ├── examples ├── 1_simplest_project │ ├── File.h │ ├── Makefile │ ├── Map.h │ ├── main.cpp │ └── tests │ │ └── Test_Map.h ├── 2_feature_full_project_scaffold__copy_me │ ├── Makefile │ ├── README.md │ ├── cpp │ │ ├── Common │ │ │ ├── Debug.h │ │ │ └── MyError.h │ │ └── MapExample │ │ │ ├── File.h │ │ │ ├── Map.h │ │ │ ├── main.cpp │ │ │ └── tests │ │ │ └── Test_Map.h │ ├── env │ └── tools │ │ ├── make │ │ ├── Makefile │ │ └── rules.Makefile │ │ └── vim │ │ └── settings.vim ├── 3_writing_cpp_tests │ ├── custom_stubs │ │ ├── Makefile │ │ └── cpp │ │ │ ├── Common │ │ │ ├── Debug.h │ │ │ └── MyError.h │ │ │ └── Example │ │ │ ├── MockMe.h │ │ │ ├── UnderTest.h │ │ │ └── tests │ │ │ └── Test_UnderTest.h │ ├── deriving_a_mocked_interface │ │ ├── Makefile │ │ └── cpp │ │ │ └── Example │ │ │ ├── SomeInterface.h │ │ │ ├── UnderTest.h │ │ │ └── tests │ │ │ └── Test_UnderTest.h │ ├── expectation_based_mock_objects │ │ ├── Makefile │ │ └── cpp │ │ │ └── Example │ │ │ ├── Data.h │ │ │ ├── Mocked.h │ │ │ ├── UnderTest.h │ │ │ └── tests │ │ │ └── Test_UnderTest.h │ ├── mocking_template_classes │ │ ├── Makefile │ │ └── cpp │ │ │ ├── Common │ │ │ ├── Debug.h │ │ │ └── MyError.h │ │ │ └── Example │ │ │ ├── MockMe.h │ │ │ ├── UnderTest.h │ │ │ └── tests │ │ │ └── Test_UnderTest.h │ └── mocking_template_methods │ │ ├── Makefile │ │ └── cpp │ │ ├── Common │ │ ├── Debug.h │ │ └── MyError.h │ │ └── Example │ │ ├── MockMe.h │ │ ├── UnderTest.h │ │ └── tests │ │ └── Test_UnderTest.h ├── 6_coverage_enforcement │ ├── Makefile │ ├── cpp │ │ ├── FileNotCovered.h │ │ ├── SemiCoveredExemptFile.h │ │ ├── ToCover.h │ │ └── tests │ │ │ ├── Test_CoverageErrors.h │ │ │ └── Test_IncludesButDoesntCover_DoesNotIntefeareWithOtherTestSuitesThatDo.h │ └── undertest.Makefile └── 7_simple_python_unittest │ ├── Makefile │ ├── test_add_two_numbers.py │ └── test_add_two_numbers_newstyleclass.py ├── make ├── 1_generate.Makefile ├── 2_build.Makefile ├── 3_run.Makefile ├── 4_optional_enforce_cpp_coverage.Makefile ├── common.Makefile ├── enforce_cpp_coverage.py ├── integrations │ ├── complete.Makefile │ └── most.Makefile ├── runsingletest.sh └── runsingletestsuite.sh ├── pytest ├── .gitignore ├── __init__.py ├── findtestname.py ├── fixtures.py ├── pystacktrace.py ├── pytestharness.py ├── pytestmock.py ├── pytestrunner.py ├── pytestsimplecui.py ├── pytestsimplegui.py ├── pytestsuite.py ├── pytesttracker.py ├── pytestui.py ├── pytestverbosecui.py ├── pytestworld.py ├── pyvoodoo │ ├── .gitignore │ ├── __init__.py │ ├── expectations.py │ ├── scenario.py │ ├── threadedhook.py │ ├── ultimateclass.py │ ├── ultimateobject.py │ └── voodooexception.py └── untee.py ├── requirements.txt ├── vim ├── columindent │ ├── configuredmain.py │ ├── constructorreferenceargumentscpp.py │ ├── constructorreferenceargumentspy.py │ ├── formatcolums.py │ ├── main.py │ ├── parsecpp.py │ ├── parsecppfunctionsignature.py │ ├── parsecppmemberlist.py │ ├── parsesimplecall.py │ ├── tab.py │ ├── tests │ │ └── test.py │ └── tokenize.py ├── dirtytrace.py ├── doc │ ├── bufexplorer.txt │ └── tags ├── ftplugin │ └── python │ │ ├── pyflakes.vim │ │ └── pyflakes │ │ ├── LICENSE │ │ ├── NEWS.txt │ │ ├── bin │ │ └── pyflakes │ │ ├── pyflakes │ │ ├── __init__.py │ │ ├── checker.py │ │ ├── messages.py │ │ ├── scripts │ │ │ ├── __init__.py │ │ │ └── pyflakes.py │ │ └── test │ │ │ ├── __init__.py │ │ │ ├── harness.py │ │ │ ├── test_imports.py │ │ │ ├── test_other.py │ │ │ ├── test_script.py │ │ │ └── test_undefined_names.py │ │ └── setup.py ├── newfile.py ├── plugin │ ├── bufexplorer.vim │ ├── runtests.vim │ ├── togglecomment.vim │ └── voodootools.vim └── settings.vim ├── vimenv ├── voodoo ├── Readme.txt ├── Tutorial │ ├── 1 - Compiling The Parser │ │ ├── UNIX │ │ │ └── readme.txt │ │ └── readme.txt │ ├── 2 - Command Line Usage │ │ ├── example.sh │ │ ├── original │ │ │ ├── DontParseMe.h │ │ │ ├── FakeWindows.h │ │ │ ├── Header1.h │ │ │ ├── Header2.h │ │ │ └── HeaderWithSyntaxError.h │ │ └── readme.txt │ ├── 3 - Expectation Based Mock Objects │ │ ├── 1 - Your First Test │ │ │ ├── compile.bat │ │ │ ├── include │ │ │ │ ├── Number.h │ │ │ │ └── Sum.h │ │ │ ├── readme.txt │ │ │ └── tests │ │ │ │ └── Test_Sum.cpp │ │ ├── 2 - Expectation Types │ │ │ ├── compile.bat │ │ │ ├── include │ │ │ │ ├── Mocked.h │ │ │ │ └── Tested.h │ │ │ ├── readme.txt │ │ │ └── tests │ │ │ │ └── Test_All.cpp │ │ ├── 3 - Parameter Expectation Types │ │ │ ├── compile.bat │ │ │ ├── include │ │ │ │ ├── Data.h │ │ │ │ ├── Mocked.h │ │ │ │ └── Tested.h │ │ │ ├── readme.txt │ │ │ └── tests │ │ │ │ └── Test_All.cpp │ │ └── 4 - Copy Construction │ │ │ ├── include │ │ │ ├── GetAndSet.h │ │ │ └── PseudoSharedPtr.h │ │ │ ├── readme.txt │ │ │ └── tests │ │ │ └── Test_All.cpp │ ├── clean.sh │ └── readme.txt ├── VoodooCommon │ ├── All.h │ ├── Always.h │ ├── Common.h │ ├── Custom.h │ ├── Expect.h │ ├── ExpectLineMessage.h │ ├── ExpectParameter.h │ ├── Hook.h │ ├── HookMacros.h │ ├── Multiplexer.h │ ├── Scenario.h │ ├── Sprintf.h │ ├── Utils.h │ ├── VoodooConfigurationForCxxTest.hpp │ └── VoodooConfigurationForNoTestSuite.hpp ├── clang │ ├── __init__.py │ ├── cindex.py │ └── enumerations.py ├── compileclang.py ├── emulate_gcc_in_clang_preinclude.h ├── filelock.py ├── functiondecomposition.py ├── gccparity.py ├── growcode.py ├── iterateapi.py ├── libclang.so ├── multi.py ├── perfilesettings.py ├── preprocessor.py ├── protectionignoring.py ├── single.py ├── unittests │ ├── __init__.py │ ├── savingiterator.py │ ├── test_c_parsing.py │ ├── test_cpp_parsing.py │ └── tools.py ├── voodoo.py ├── voodoochain.py ├── voodoodbiterator.py ├── voodoodefs.py ├── voodooexpect.py ├── voodooexpectfunction.py ├── voodooexpectiterator.py ├── voodoohint.py ├── voodooiterator.py ├── voodoomock.py └── voodoomultiplexeriterator.py └── wercker.yml /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | build* 3 | *.swp 4 | -------------------------------------------------------------------------------- /HOWTO_WRITE_TESTS.md: -------------------------------------------------------------------------------- 1 | Please checkout the examples under examples/3_writing_tests for a tutorial on 2 | writing tests. 3 | -------------------------------------------------------------------------------- /KNOWN_ISSUES.md: -------------------------------------------------------------------------------- 1 | Known Issues: 2 | ------------- 3 | - #define of a built in type (e.g., 'int', 'bool'), causes CLang compiler 4 | to behave unexpectedly. Do not define those. A special treatment for 5 | including GCCs stdbool.h is handled inside 6 | voodoo/emulate_gcc_in_clang_preinclude.h . You might need to edit this 7 | file to force skipping of other issues not encoutered yet in voodoo 8 | development. If you do, please send a email or bug report our way. 9 | - code created from macros can be included, but not parsed correctly 10 | to produce a valid header 11 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: build unittest 2 | 3 | build: build_examples 4 | clean: clean_examples 5 | 6 | unittest: unittest_c unittest_cpp 7 | unittest_c: 8 | cd voodoo; PYTHONPATH=. LD_LIBRARY_PATH=. python unittests/test_c_parsing.py 9 | unittest_cpp: 10 | cd voodoo; PYTHONPATH=. LD_LIBRARY_PATH=. python unittests/test_cpp_parsing.py 11 | 12 | clean_examples: 13 | make -C examples/1_simplest_project clean 14 | cd examples/2_feature_full_project_scaffold__copy_me; ./env make clean 15 | make -C examples/3_writing_cpp_tests/mocking_template_methods clean 16 | make -C examples/3_writing_cpp_tests/mocking_template_classes clean 17 | make -C examples/3_writing_cpp_tests/custom_stubs clean 18 | make -C examples/3_writing_cpp_tests/deriving_a_mocked_interface clean 19 | make -C examples/3_writing_cpp_tests/expectation_based_mock_objects clean 20 | make -C examples/6_coverage_enforcement clean 21 | make -C examples/7_simple_python_unittest clean 22 | 23 | build_examples: 24 | make -C examples/1_simplest_project 25 | cd examples/2_feature_full_project_scaffold__copy_me; ./env make 26 | make -C examples/3_writing_cpp_tests/mocking_template_methods 27 | make -C examples/3_writing_cpp_tests/mocking_template_classes 28 | make -C examples/3_writing_cpp_tests/custom_stubs 29 | make -C examples/3_writing_cpp_tests/deriving_a_mocked_interface 30 | make -C examples/3_writing_cpp_tests/expectation_based_mock_objects 31 | make -C examples/7_simple_python_unittest 32 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | shallow_clone: true 2 | clone_folder: c:\projects\Voodoo-Mock 3 | 4 | install: 5 | #let's use the pre-installed mingw 6 | - ps: $env:PATH = 'C:\MinGW\bin;C:\MinGW\mingw32\bin;C:\MinGW\msys\1.0\bin;' + $env:PATH 7 | #we copy mingw32-make to have a "make" executable 8 | - cmd: copy c:\MinGW\bin\mingw32-make.exe c:\MinGW\bin\make.exe 9 | 10 | #needed to download other deps 11 | - cinst wget 12 | 13 | #let's install the LLVM distribution 14 | - cmd: mkdir LLVM_DOWNLOAD 15 | - cmd: cd LLVM_DOWNLOAD 16 | - cmd: wget "http://llvm.org/releases/3.6.0/LLVM-3.6.0-win32.exe" 17 | - cmd: 7z x LLVM-3.6.0-win32.exe 18 | - cmd: ren $_OUTDIR LLVM-3.6.0 19 | - cmd: move LLVM-3.6.0 c:\ 20 | - ps: $env:PATH = 'c:\LLVM-3.6.0\bin;' + $env:PATH 21 | 22 | #python modules 23 | - cmd: C:\Python27\scripts\pip install futures 24 | - cmd: C:\Python27\scripts\pip install clang==3.5 25 | - ps: $env:PATH = 'c:\Python27\Lib\site-packages;' + $env:PATH 26 | 27 | build_script: 28 | #build / test Voodoo-Mock 29 | # - cmd: sh -c "g++ -E -x c++ - -v < /dev/null" 30 | # - cmd: type c:\mingw\include\unistd.h 31 | # - cmd: sh -c "grep -rnC20 _exit c:/mingw/include" 32 | - ps: cd "c:\projects\Voodoo-Mock" 33 | - cmd: sh -c "make V=1" 34 | -------------------------------------------------------------------------------- /cxxtest/README: -------------------------------------------------------------------------------- 1 | Introduction 2 | ------------ 3 | 4 | CxxTest is a JUnit/CppUnit/xUnit-like framework for C++. 5 | 6 | Its advantages over existing alternatives are that it: 7 | - Doesn't require RTTI 8 | - Doesn't require member template functions 9 | - Doesn't require exception handling 10 | - Doesn't require any external libraries (including memory management, 11 | file/console I/O, graphics libraries) 12 | 13 | This makes it extremely portable and usable. 14 | 15 | CxxTest is available under the GNU Lesser General Public Licence (LGPL). 16 | See http://www.gnu.org/copyleft/lesser.html for the license. 17 | 18 | Simple user's guide 19 | ------------------- 20 | 21 | 1. Create a test suite header file: 22 | 23 | MyTest.h: 24 | #include 25 | 26 | class MyTestSuite : public CxxTest::TestSuite 27 | { 28 | public: 29 | void testAddition( void ) 30 | { 31 | TS_ASSERT( 1 + 1 > 1 ); 32 | TS_ASSERT_EQUALS( 1 + 1, 2 ); 33 | } 34 | }; 35 | 36 | 37 | 2. Generate the tests file: 38 | 39 | # cxxtestgen.pl -o tests.cpp MyTestSuite.h 40 | 41 | 42 | 3. Create a main function that runs the tests 43 | 44 | main.cpp: 45 | #include 46 | 47 | int main( void ) 48 | { 49 | CxxText::ErrorPrinter::runAllTests(); 50 | return 0; 51 | } 52 | 53 | 54 | 4. Compile and run! 55 | 56 | # g++ -o main main.cpp tests.cpp 57 | # ./main 58 | Running 1 test(s).OK! 59 | 60 | 61 | Advanced User's Guide 62 | --------------------- 63 | See docs/guide.html. 64 | -------------------------------------------------------------------------------- /cxxtest/TODO: -------------------------------------------------------------------------------- 1 | This is an -*- Outline -*- of ideas for future versions of CxxTest. 2 | It is not meant to be "human readable". 3 | 4 | * CxxTest To Do list 5 | 6 | ** Mock framework 7 | 8 | Write some mocks 9 | 10 | *** Distribution 11 | Seperate packages (w/ binaries)? How would that be used? 12 | For Windows: .lib for "Real" and "Mock" parts. 13 | For Linux: Maybe. Different compilers etc. 14 | So probably only source release with Makefiles and .ds[pw]? Or just Win32 binary. 15 | 16 | **** Installation? 17 | extract cxxtest-x.y.z.tar.gz 18 | (extract cxxtest-mock-x.y.z.tar.gz) ? 19 | make -C cxxtest/Real 20 | make -C cxxtest/Mock 21 | 22 | or maybe make -C cxxtest -f Makefile.mock 23 | but then Makefile.mock.bcc32, Makefile.mock.msvc, Makefile.mock.gcc, and heaven knows what else. 24 | 25 | Could put the Makefile.mock.* in cxxtest/Real and cxxtest/Mock or in cxxtest/T 26 | 27 | Maybe this should be a different package altogether? 28 | Seems logical, since they evolve separately. But then you'd want to download both. 29 | 30 | ** Thoughts 31 | -fomit-frame-pointer 32 | 33 | ** TS_HEX 34 | 35 | -------------------------------------------------------------------------------- /cxxtest/VoodooConfiguration.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #if !defined(_WIN32) && defined( __GNUG__ ) 4 | 5 | #include 6 | 7 | # define VOODOO_FAIL_TEST( s ) do { \ 8 | try { \ 9 | TS_FAIL( s ); \ 10 | } catch( ... ) { \ 11 | void * bt[ 64 ]; \ 12 | int result = backtrace( bt, 64 ); \ 13 | backtrace_symbols_fd( bt, result, 1 ); \ 14 | throw; \ 15 | } \ 16 | } while ( 0 ) 17 | 18 | #else // __GNUC__ 19 | 20 | # define VOODOO_FAIL_TEST( s ) TS_FAIL( s ) 21 | 22 | #endif // __GNUC__ 23 | 24 | #define VOODOO_FAIL_TEST_NO_THROW( s ) do { \ 25 | try { \ 26 | VOODOO_FAIL_TEST( s ); \ 27 | } catch( CxxTest::AbortTest & ) {} \ 28 | } while ( false ) 29 | 30 | #define VOODOO_WARNING( x ) TS_WARN( x ) 31 | 32 | #define VOODOO_TO_STRING( x ) TS_AS_STRING( x ) 33 | -------------------------------------------------------------------------------- /cxxtest/cxxtest.spec: -------------------------------------------------------------------------------- 1 | Name: cxxtest 2 | Summary: CxxTest Testing Framework for C++ 3 | Version: 3.10.1 4 | Release: 1 5 | Copyright: LGPL 6 | Group: Development/C++ 7 | Source: cxxtest-%{version}.tar.gz 8 | BuildRoot: /tmp/cxxtest-build 9 | BuildArch: noarch 10 | Prefix: /usr 11 | 12 | %description 13 | CxxTest is a JUnit/CppUnit/xUnit-like framework for C++. 14 | Its advantages over existing alternatives are that it: 15 | - Doesn't require RTTI 16 | - Doesn't require member template functions 17 | - Doesn't require exception handling 18 | - Doesn't require any external libraries (including memory management, 19 | file/console I/O, graphics libraries) 20 | 21 | %prep 22 | %setup -n cxxtest 23 | 24 | %build 25 | 26 | %install 27 | install -m 755 -d $RPM_BUILD_ROOT/usr/bin $RPM_BUILD_ROOT/usr/include/cxxtest 28 | install -m 755 cxxtestgen.p[ly] $RPM_BUILD_ROOT/usr/bin/ 29 | install -m 644 cxxtest/* $RPM_BUILD_ROOT/usr/include/cxxtest/ 30 | 31 | %clean 32 | rm -rf $RPM_BUILD_ROOT 33 | 34 | %files 35 | %attr(-, root, root) %doc README 36 | %attr(-, root, root) %doc sample 37 | %attr(-, root, root) /usr/include/cxxtest 38 | %attr(-, root, root) /usr/bin/cxxtestgen.pl 39 | %attr(-, root, root) /usr/bin/cxxtestgen.py 40 | 41 | -------------------------------------------------------------------------------- /cxxtest/cxxtest/Descriptions.cpp: -------------------------------------------------------------------------------- 1 | #ifndef __cxxtest__Descriptions_cpp__ 2 | #define __cxxtest__Descriptions_cpp__ 3 | 4 | #include 5 | 6 | namespace CxxTest 7 | { 8 | TestDescription::~TestDescription() {} 9 | SuiteDescription::~SuiteDescription() {} 10 | WorldDescription::~WorldDescription() {} 11 | 12 | // 13 | // Convert total tests to string 14 | // 15 | #ifndef _CXXTEST_FACTOR 16 | char *WorldDescription::strTotalTests( char *s ) const 17 | { 18 | numberToString( numTotalTests(), s ); 19 | return s; 20 | } 21 | #else // _CXXTEST_FACTOR 22 | char *WorldDescription::strTotalTests( char *s ) const 23 | { 24 | char *p = numberToString( numTotalTests(), s ); 25 | 26 | if ( numTotalTests() <= 1 ) 27 | return s; 28 | 29 | unsigned n = numTotalTests(); 30 | unsigned numFactors = 0; 31 | 32 | for ( unsigned factor = 2; (factor * factor) <= n; factor += (factor == 2) ? 1 : 2 ) { 33 | unsigned power; 34 | 35 | for ( power = 0; (n % factor) == 0; n /= factor ) 36 | ++ power; 37 | 38 | if ( !power ) 39 | continue; 40 | 41 | p = numberToString( factor, copyString( p, (numFactors == 0) ? " = " : " * " ) ); 42 | if ( power > 1 ) 43 | p = numberToString( power, copyString( p, "^" ) ); 44 | ++ numFactors; 45 | } 46 | 47 | if ( n > 1 ) { 48 | if ( !numFactors ) 49 | copyString( p, tracker().failedTests() ? " :(" : tracker().warnings() ? " :|" : " :)" ); 50 | else 51 | numberToString( n, copyString( p, " * " ) ); 52 | } 53 | return s; 54 | } 55 | #endif // _CXXTEST_FACTOR 56 | }; 57 | 58 | #endif // __cxxtest__Descriptions_cpp__ 59 | -------------------------------------------------------------------------------- /cxxtest/cxxtest/Descriptions.h: -------------------------------------------------------------------------------- 1 | #ifndef __cxxtest__Descriptions_h__ 2 | #define __cxxtest__Descriptions_h__ 3 | 4 | // 5 | // TestDescription, SuiteDescription and WorldDescription 6 | // hold information about tests so they can be run and reported. 7 | // 8 | 9 | #include 10 | 11 | namespace CxxTest 12 | { 13 | class TestSuite; 14 | 15 | class TestDescription : public Link 16 | { 17 | public: 18 | virtual ~TestDescription(); 19 | 20 | virtual const char *file() const = 0; 21 | virtual unsigned line() const = 0; 22 | virtual const char *testName() const = 0; 23 | virtual const char *suiteName() const = 0; 24 | 25 | virtual void run() = 0; 26 | 27 | virtual const TestDescription *next() const = 0; 28 | virtual TestDescription *next() = 0; 29 | }; 30 | 31 | class SuiteDescription : public Link 32 | { 33 | public: 34 | virtual ~SuiteDescription(); 35 | 36 | virtual const char *file() const = 0; 37 | virtual unsigned line() const = 0; 38 | virtual const char *suiteName() const = 0; 39 | virtual TestSuite *suite() const = 0; 40 | 41 | virtual unsigned numTests() const = 0; 42 | virtual const TestDescription &testDescription( unsigned /*i*/ ) const = 0; 43 | 44 | virtual TestDescription *firstTest() = 0; 45 | virtual const TestDescription *firstTest() const = 0; 46 | virtual SuiteDescription *next() = 0; 47 | virtual const SuiteDescription *next() const = 0; 48 | 49 | virtual void activateAllTests() = 0; 50 | virtual bool leaveOnly( const char * /*testName*/ ) = 0; 51 | }; 52 | 53 | class WorldDescription : public Link 54 | { 55 | public: 56 | virtual ~WorldDescription(); 57 | 58 | virtual unsigned numSuites( void ) const = 0; 59 | virtual unsigned numTotalTests( void ) const = 0; 60 | virtual const SuiteDescription &suiteDescription( unsigned /*i*/ ) const = 0; 61 | 62 | enum { MAX_STRLEN_TOTAL_TESTS = 32 }; 63 | char *strTotalTests( char * /*buffer*/ ) const; 64 | 65 | virtual SuiteDescription *firstSuite() = 0; 66 | virtual const SuiteDescription *firstSuite() const = 0; 67 | 68 | virtual void activateAllTests() = 0; 69 | virtual bool leaveOnly( const char * /*suiteName*/, const char * /*testName*/ = 0 ) = 0; 70 | }; 71 | } 72 | 73 | #endif // __cxxtest__Descriptions_h__ 74 | 75 | -------------------------------------------------------------------------------- /cxxtest/cxxtest/DummyDescriptions.h: -------------------------------------------------------------------------------- 1 | #ifndef __cxxtest__DummyDescriptions_h__ 2 | #define __cxxtest__DummyDescriptions_h__ 3 | 4 | // 5 | // DummyTestDescription, DummySuiteDescription and DummyWorldDescription 6 | // 7 | 8 | #include 9 | 10 | namespace CxxTest 11 | { 12 | class DummyTestDescription : public TestDescription 13 | { 14 | public: 15 | DummyTestDescription(); 16 | 17 | const char *file() const; 18 | unsigned line() const; 19 | const char *testName() const; 20 | const char *suiteName() const; 21 | bool setUp(); 22 | void run(); 23 | bool tearDown(); 24 | 25 | TestDescription *next(); 26 | const TestDescription *next() const; 27 | }; 28 | 29 | class DummySuiteDescription : public SuiteDescription 30 | { 31 | public: 32 | DummySuiteDescription(); 33 | 34 | const char *file() const; 35 | unsigned line() const; 36 | const char *suiteName() const; 37 | TestSuite *suite() const; 38 | unsigned numTests() const; 39 | const TestDescription &testDescription( unsigned ) const; 40 | SuiteDescription *next(); 41 | TestDescription *firstTest(); 42 | const SuiteDescription *next() const; 43 | const TestDescription *firstTest() const; 44 | void activateAllTests(); 45 | bool leaveOnly( const char * /*testName*/ ); 46 | 47 | bool setUp(); 48 | bool tearDown(); 49 | 50 | private: 51 | DummyTestDescription _test; 52 | }; 53 | 54 | class DummyWorldDescription : public WorldDescription 55 | { 56 | public: 57 | DummyWorldDescription(); 58 | 59 | unsigned numSuites( void ) const; 60 | unsigned numTotalTests( void ) const; 61 | const SuiteDescription &suiteDescription( unsigned ) const; 62 | SuiteDescription *firstSuite(); 63 | const SuiteDescription *firstSuite() const; 64 | void activateAllTests(); 65 | bool leaveOnly( const char * /*suiteName*/, const char * /*testName*/ = 0 ); 66 | 67 | bool setUp(); 68 | bool tearDown(); 69 | 70 | private: 71 | DummySuiteDescription _suite; 72 | }; 73 | } 74 | 75 | #endif // __cxxtest__DummyDescriptions_h__ 76 | 77 | -------------------------------------------------------------------------------- /cxxtest/cxxtest/ErrorPrinter.h: -------------------------------------------------------------------------------- 1 | #ifndef __cxxtest__ErrorPrinter_h__ 2 | #define __cxxtest__ErrorPrinter_h__ 3 | 4 | // 5 | // The ErrorPrinter is a simple TestListener that 6 | // just prints "OK" if everything goes well, otherwise 7 | // reports the error in the format of compiler messages. 8 | // The ErrorPrinter uses std::cout 9 | // 10 | 11 | #include 12 | 13 | #ifndef _CXXTEST_HAVE_STD 14 | # define _CXXTEST_HAVE_STD 15 | #endif // _CXXTEST_HAVE_STD 16 | 17 | #include 18 | #include 19 | 20 | #ifdef _CXXTEST_OLD_STD 21 | # include 22 | #else // !_CXXTEST_OLD_STD 23 | # include 24 | #endif // _CXXTEST_OLD_STD 25 | 26 | namespace CxxTest 27 | { 28 | class ErrorPrinter : public ErrorFormatter 29 | { 30 | public: 31 | ErrorPrinter( CXXTEST_STD(ostream) &o = CXXTEST_STD(cout), const char *preLine = ":", const char *postLine = "" ) : 32 | ErrorFormatter( new Adapter(o), preLine, postLine ) {} 33 | virtual ~ErrorPrinter() { delete outputStream(); } 34 | 35 | private: 36 | class Adapter : public OutputStream 37 | { 38 | CXXTEST_STD(ostream) &_o; 39 | public: 40 | Adapter( CXXTEST_STD(ostream) &o ) : _o(o) {} 41 | void flush() { _o.flush(); } 42 | OutputStream &operator<<( const char *s ) { _o << s; return *this; } 43 | OutputStream &operator<<( Manipulator m ) { return OutputStream::operator<<( m ); } 44 | OutputStream &operator<<( unsigned i ) 45 | { 46 | char s[1 + 3 * sizeof(unsigned)]; 47 | numberToString( i, s ); 48 | _o << s; 49 | return *this; 50 | } 51 | }; 52 | }; 53 | } 54 | 55 | #endif // __cxxtest__ErrorPrinter_h__ 56 | -------------------------------------------------------------------------------- /cxxtest/cxxtest/GlobalFixture.cpp: -------------------------------------------------------------------------------- 1 | #ifndef __cxxtest__GlobalFixture_cpp__ 2 | #define __cxxtest__GlobalFixture_cpp__ 3 | 4 | #include 5 | 6 | namespace CxxTest 7 | { 8 | bool GlobalFixture::setUpWorld() { return true; } 9 | bool GlobalFixture::tearDownWorld() { return true; } 10 | bool GlobalFixture::setUp() { return true; } 11 | bool GlobalFixture::tearDown() { return true; } 12 | 13 | GlobalFixture::GlobalFixture() { attach( _list ); } 14 | GlobalFixture::~GlobalFixture() { detach( _list ); } 15 | 16 | GlobalFixture *GlobalFixture::firstGlobalFixture() { return (GlobalFixture *)_list.head(); } 17 | GlobalFixture *GlobalFixture::lastGlobalFixture() { return (GlobalFixture *)_list.tail(); } 18 | GlobalFixture *GlobalFixture::nextGlobalFixture() { return (GlobalFixture *)next(); } 19 | GlobalFixture *GlobalFixture::prevGlobalFixture() { return (GlobalFixture *)prev(); } 20 | } 21 | 22 | #endif // __cxxtest__GlobalFixture_cpp__ 23 | 24 | -------------------------------------------------------------------------------- /cxxtest/cxxtest/GlobalFixture.h: -------------------------------------------------------------------------------- 1 | #ifndef __cxxtest__GlobalFixture_h__ 2 | #define __cxxtest__GlobalFixture_h__ 3 | 4 | #include 5 | 6 | namespace CxxTest 7 | { 8 | class GlobalFixture : public Link 9 | { 10 | public: 11 | virtual bool setUpWorld(); 12 | virtual bool tearDownWorld(); 13 | virtual bool setUp(); 14 | virtual bool tearDown(); 15 | 16 | GlobalFixture(); 17 | ~GlobalFixture(); 18 | 19 | static GlobalFixture *firstGlobalFixture(); 20 | static GlobalFixture *lastGlobalFixture(); 21 | GlobalFixture *nextGlobalFixture(); 22 | GlobalFixture *prevGlobalFixture(); 23 | 24 | private: 25 | static List _list; 26 | }; 27 | } 28 | 29 | #endif // __cxxtest__GlobalFixture_h__ 30 | 31 | -------------------------------------------------------------------------------- /cxxtest/cxxtest/LinkedList.h: -------------------------------------------------------------------------------- 1 | #ifndef __cxxtest__LinkedList_h__ 2 | #define __cxxtest__LinkedList_h__ 3 | 4 | #include 5 | 6 | namespace CxxTest 7 | { 8 | struct List; 9 | class Link; 10 | 11 | struct List 12 | { 13 | Link *_head; 14 | Link *_tail; 15 | 16 | void initialize(); 17 | 18 | Link *head(); 19 | const Link *head() const; 20 | Link *tail(); 21 | const Link *tail() const; 22 | 23 | bool empty() const; 24 | unsigned size() const; 25 | Link *nth( unsigned n ); 26 | 27 | void activateAll(); 28 | void leaveOnly( const Link &link ); 29 | }; 30 | 31 | class Link 32 | { 33 | public: 34 | Link(); 35 | virtual ~Link(); 36 | 37 | bool active() const; 38 | void setActive( bool value = true ); 39 | 40 | Link *justNext(); 41 | Link *justPrev(); 42 | 43 | Link *next(); 44 | Link *prev(); 45 | const Link *next() const; 46 | const Link *prev() const; 47 | 48 | virtual bool setUp() = 0; 49 | virtual bool tearDown() = 0; 50 | 51 | void attach( List &l ); 52 | void detach( List &l ); 53 | 54 | private: 55 | Link *_next; 56 | Link *_prev; 57 | bool _active; 58 | 59 | Link( const Link & ); 60 | Link &operator=( const Link & ); 61 | }; 62 | } 63 | 64 | #endif // __cxxtest__LinkedList_h__ 65 | 66 | -------------------------------------------------------------------------------- /cxxtest/cxxtest/ParenPrinter.h: -------------------------------------------------------------------------------- 1 | #ifndef __cxxtest__ParenPrinter_h__ 2 | #define __cxxtest__ParenPrinter_h__ 3 | 4 | // 5 | // The ParenPrinter is identical to the ErrorPrinter, except it 6 | // prints the line number in a format expected by some compilers 7 | // (notably, MSVC). 8 | // 9 | 10 | #include 11 | 12 | namespace CxxTest 13 | { 14 | class ParenPrinter : public ErrorPrinter 15 | { 16 | public: 17 | ParenPrinter( CXXTEST_STD(ostream) &o = CXXTEST_STD(cout) ) : ErrorPrinter( o, "(", ")" ) {} 18 | }; 19 | } 20 | 21 | #endif // __cxxtest__ParenPrinter_h__ 22 | -------------------------------------------------------------------------------- /cxxtest/cxxtest/Root.cpp: -------------------------------------------------------------------------------- 1 | #ifndef __cxxtest__Root_cpp__ 2 | #define __cxxtest__Root_cpp__ 3 | 4 | // 5 | // This file holds the "root" of CxxTest, i.e. 6 | // the parts that must be in a source file file. 7 | // 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | #endif // __cxxtest__Root_cpp__ 19 | -------------------------------------------------------------------------------- /cxxtest/cxxtest/SelfTest.h: -------------------------------------------------------------------------------- 1 | #ifndef __cxxtest_SelfTest_h__ 2 | #define __cxxtest_SelfTest_h__ 3 | 4 | #define CXXTEST_SUITE(name) 5 | #define CXXTEST_CODE(member) 6 | 7 | #endif // __cxxtest_SelfTest_h__ 8 | -------------------------------------------------------------------------------- /cxxtest/cxxtest/StdHeaders.h: -------------------------------------------------------------------------------- 1 | #ifndef __cxxtest_StdHeaders_h__ 2 | #define __cxxtest_StdHeaders_h__ 3 | 4 | // 5 | // This file basically #includes the STL headers. 6 | // It exists to support warning level 4 in Visual C++ 7 | // 8 | 9 | #ifdef _MSC_VER 10 | # pragma warning( push, 1 ) 11 | #endif // _MSC_VER 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | #ifdef _MSC_VER 22 | # pragma warning( pop ) 23 | #endif // _MSC_VER 24 | 25 | #endif // __cxxtest_StdHeaders_h__ 26 | -------------------------------------------------------------------------------- /cxxtest/cxxtest/StdioFilePrinter.h: -------------------------------------------------------------------------------- 1 | #ifndef __cxxtest__StdioFilePrinter_h__ 2 | #define __cxxtest__StdioFilePrinter_h__ 3 | 4 | // 5 | // The StdioFilePrinter is a simple TestListener that 6 | // just prints "OK" if everything goes well, otherwise 7 | // reports the error in the format of compiler messages. 8 | // This class uses , i.e. FILE * and fprintf(). 9 | // 10 | 11 | #include 12 | #include 13 | 14 | namespace CxxTest 15 | { 16 | class StdioFilePrinter : public ErrorFormatter 17 | { 18 | public: 19 | StdioFilePrinter( FILE *o, const char *preLine = ":", const char *postLine = "" ) : 20 | ErrorFormatter( new Adapter(o), preLine, postLine ) {} 21 | virtual ~StdioFilePrinter() { delete outputStream(); } 22 | 23 | private: 24 | class Adapter : public OutputStream 25 | { 26 | Adapter( const Adapter & ); 27 | Adapter &operator=( const Adapter & ); 28 | 29 | FILE *_o; 30 | 31 | public: 32 | Adapter( FILE *o ) : _o(o) {} 33 | void flush() { fflush( _o ); } 34 | OutputStream &operator<<( unsigned i ) { fprintf( _o, "%u", i ); return *this; } 35 | OutputStream &operator<<( const char *s ) { fputs( s, _o ); return *this; } 36 | OutputStream &operator<<( Manipulator m ) { return OutputStream::operator<<( m ); } 37 | }; 38 | }; 39 | } 40 | 41 | #endif // __cxxtest__StdioFilePrinter_h__ 42 | -------------------------------------------------------------------------------- /cxxtest/cxxtest/StdioPrinter.h: -------------------------------------------------------------------------------- 1 | #ifndef __cxxtest__StdioPrinter_h__ 2 | #define __cxxtest__StdioPrinter_h__ 3 | 4 | // 5 | // The StdioPrinter is an StdioFilePrinter which defaults to stdout. 6 | // This should have been called StdOutPrinter or something, but the name 7 | // has been historically used. 8 | // 9 | 10 | #include 11 | 12 | namespace CxxTest 13 | { 14 | class StdioPrinter : public StdioFilePrinter 15 | { 16 | public: 17 | StdioPrinter( FILE *o = stdout, const char *preLine = ":", const char *postLine = "" ) : 18 | StdioFilePrinter( o, preLine, postLine ) {} 19 | }; 20 | } 21 | 22 | #endif // __cxxtest__StdioPrinter_h__ 23 | -------------------------------------------------------------------------------- /cxxtest/cxxtest/VerboseListener.h: -------------------------------------------------------------------------------- 1 | #ifndef __cxxtest__VerboseListener_h__ 2 | #define __cxxtest__VerboseListener_h__ 3 | 4 | #include 5 | 6 | namespace CxxTest 7 | { 8 | class VerboseListener : public ErrorPrinter 9 | { 10 | private: 11 | void enterWorld( const WorldDescription & desc ) 12 | { 13 | * outputStream() << "\nCOUNT " << desc.numTotalTests() << "\n"; 14 | outputStream()->flush(); 15 | } 16 | void enterSuite( const SuiteDescription & desc ) 17 | { 18 | * outputStream() << "\nSUITE '" << desc.suiteName() << "'\n"; 19 | outputStream()->flush(); 20 | } 21 | void enterTest( const TestDescription & desc ) 22 | { 23 | * outputStream() << "\nTEST '" << desc.testName() << "'\n"; 24 | outputStream()->flush(); 25 | } 26 | void leaveWorld( const WorldDescription &desc ) 27 | { 28 | * outputStream() << "\nPassed tests: " << desc.numTotalTests() - TestTracker::tracker().failedTests() << "\n"; 29 | * outputStream() << "Failed tests: " << TestTracker::tracker().failedTests() << "\n\n"; 30 | outputStream()->flush(); 31 | } 32 | void leaveTest( const TestDescription & ) {} 33 | }; 34 | } 35 | 36 | #endif // __cxxtest__VerboseListener_h__ 37 | -------------------------------------------------------------------------------- /cxxtest/cxxtest/YesNoRunner.h: -------------------------------------------------------------------------------- 1 | #ifndef __cxxtest__YesNoRunner_h__ 2 | #define __cxxtest__YesNoRunner_h__ 3 | 4 | // 5 | // The YesNoRunner is a simple TestListener that 6 | // just returns true iff all tests passed. 7 | // 8 | 9 | #include 10 | #include 11 | 12 | namespace CxxTest 13 | { 14 | class YesNoRunner : public TestListener 15 | { 16 | public: 17 | YesNoRunner() 18 | { 19 | } 20 | 21 | int run() 22 | { 23 | TestRunner::runAllTests( *this ); 24 | return tracker().failedTests(); 25 | } 26 | }; 27 | } 28 | 29 | #endif // __cxxtest__YesNoRunner_h__ 30 | -------------------------------------------------------------------------------- /cxxtest/docs/Thumbs.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shlomimatichin/Voodoo-Mock/02fc8c4f3029673fc1c16bc754577593a5d088c3/cxxtest/docs/Thumbs.db -------------------------------------------------------------------------------- /cxxtest/docs/convert.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | die "Usage: $0 \n" 4 | unless scalar @ARGV == 3; 5 | 6 | my ($text, $html, $texi) = @ARGV; 7 | 8 | open TEXT, "<$text" or die "Cannot open text file \"$text\"\n"; 9 | open HTML, ">$html" or die "Cannot create html file \"$html\"\n"; 10 | open TEXI, ">$texi" or die "Cannot create TexInfo file \"$texi\"\n"; 11 | 12 | print HTML ""; 13 | 14 | sub analyze($) { 15 | my ($line) = @_; 16 | my ($htmlLine, $texiLine) = ($line, $line); 17 | 18 | # command line options 19 | $texiLine =~ s/ (--?[a-z-]*)/ \@option{$1}/g; 20 | $htmlLine =~ s/ (--?[a-z-]*)/ $1<\/tt>/g; 21 | 22 | # [Class::]function() 23 | $texiLine =~ s/([^A-Za-z])(([A-Z][A-Za-z0-9]*::)?[A-Za-z0-9]+\(\))/$1\@code{$2}/g; 24 | $htmlLine =~ s/([^A-Za-z])(([A-Z][A-Za-z0-9]*::)?[A-Za-z0-9]+\(\))/$1$2<\/code>/g; 25 | 26 | # `file' 27 | $texiLine =~ s/`([A-Za-z.\/]*)'/\@file{$1}/g; 28 | $htmlLine =~ s/`([A-Za-z.\/]*)'/`$1'<\/tt>/g; 29 | 30 | # TS... 31 | $texiLine =~ s/(^|[^A-Z])(TS[A-Za-z_*()]*)/$1\@code{$2}/g; 32 | $htmlLine =~ s/(^|[^A-Z])(TS[A-Za-z_*()]*)/$1$2<\/code>/g; 33 | 34 | # CXXTEST_ 35 | $texiLine =~ s/(CXXTEST_[A-Z_]*)/\@code{$1}/g; 36 | $htmlLine =~ s/(CXXTEST_[A-Z_]*)/$1<\/tt>/g; 37 | 38 | return ($htmlLine, $texiLine); 39 | } 40 | 41 | my $line; 42 | my $inRelease = 0; 43 | while ( defined( $line = ) ) { 44 | chomp $line; 45 | if ( $line =~ m/^CxxTest Releases/ ) { 46 | print HTML "CxxTest Releases\n"; 47 | print HTML "

CxxTest Releases

\n\n"; 48 | 49 | print TEXI "\@appendix Version history\n"; 50 | print TEXI "\@itemize \@bullet\n"; 51 | } 52 | elsif ( $line =~ m/^(.*):$/ ) { 53 | if ( $inRelease ) { 54 | print HTML "\n\n"; 55 | print TEXI "\@end itemize\n"; 56 | } 57 | 58 | print HTML "

$1

\n"; 59 | print HTML "
    \n"; 60 | 61 | print TEXI "\@item\n\@strong{$1}\n"; 62 | print TEXI "\@itemize \@minus\n"; 63 | 64 | $inRelease = 1; 65 | } 66 | elsif ( $line =~ m/^ - (.*)$/ ) { 67 | my ($htmlLine, $texiLine) = analyze($1); 68 | print HTML "
  • $htmlLine
  • \n"; 69 | print TEXI "\@item\n$texiLine\n"; 70 | } 71 | } 72 | 73 | if ( $inRelease ) { 74 | print HTML "
\n\n"; 75 | print TEXI "\@end itemize\n\n"; 76 | } 77 | 78 | print HTML "\n"; 79 | print TEXI "\@end itemize\n"; 80 | 81 | close TEXT or die "Error closing text file \"$text\"\n"; 82 | close HTML or die "Error closing html file \"$html\"\n"; 83 | close TEXI or die "Error closing TexInfo file \"$texi\"\n"; 84 | -------------------------------------------------------------------------------- /cxxtest/docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | CxxTest 3 |

Introduction

4 | 5 |

CxxTest is a JUnit/CppUnit/xUnit-like framework for C++. 6 | 7 |

Its advantages over existing alternatives are that it: 8 |

    9 |
  • Doesn't require RTTI 10 |
  • Doesn't require member template functions 11 |
  • Doesn't require exception handling 12 |
  • Doesn't require any external libraries (including memory management, 13 | file/console I/O, graphics libraries) 14 |
  • Is distributed entirely as a set of header files 15 |
16 | 17 |

This makes it extremely portable and usable. 18 | 19 |

CxxTest is available under the GNU 20 | Lesser General Public License. 21 | 22 |

See the user's guide for information. 23 | It is also available as a PDF file. 24 | 25 |

The version history is available here. 26 | 27 |

Getting CxxTest

28 | You can always get the latest release from 29 | here or 30 | here. 31 | 32 |

There are several files you can download: 33 |

    34 |
  • cxxtest-version-1.noarch.rpm 35 |
  • cxxtest-version.tar.gz 36 |
  • cxxtest-version.zip 37 |
  • cxxtest-guide-version.pdf (the user's guide) 38 |
39 | Note that, since CxxTest consists entirely of header files, 40 | there is no distinction between source and binary distribution. 41 | 42 |

There are also files called cxxtest-selftest-*: these 43 | are used (usually by me) to test the portability of CxxTest, so you 44 | can probably do without them. 45 | 46 |

If you just can't wait for the next release, I sometimes upload betas 47 | to here. 48 | 49 |

Getting started

50 | Get the sources and build the samples in the sample subdirectory. 51 | 52 |
53 |

54 | SourceForge Logo 55 | 56 | 57 | -------------------------------------------------------------------------------- /cxxtest/keeponlyonetestingeneratedcxx.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | parser = argparse.ArgumentParser() 4 | parser.add_argument( "--generated", required = True ) 5 | parser.add_argument( "--toStdout", action = "store_true" ) 6 | parser.add_argument( "--testName", required = True ) 7 | args = parser.parse_args() 8 | 9 | contents = open( args.generated ).read() 10 | split = contents.split( "\n\n" ) 11 | keep = [ s for s in split if 'CxxTest::RealTestDescription' not in s or '"' + args.testName + '"' in s ] 12 | result = "\n\n".join( keep ) 13 | 14 | if args.toStdout: 15 | print result 16 | else: 17 | with open( args.generated, "w" ) as f: 18 | f.write( result ) 19 | -------------------------------------------------------------------------------- /cxxtest/sample/Construct: -------------------------------------------------------------------------------- 1 | # -*- Perl -*- 2 | 3 | # 4 | # This file shows how to use CxxTest with Cons 5 | # 6 | 7 | $env = new cons( CXX => ("$^O" eq 'MSWin32') ? 'cl -nologo -GX' : 'c++', 8 | CPPPATH => '..', 9 | CXXTESTGEN => 'perl -w ../cxxtestgen.pl' ); 10 | 11 | @tests = <*.h>; 12 | 13 | # The error printer is the most basic runner 14 | CxxTestErrorPrinter $env 'error_printer', @tests; 15 | 16 | # You can also specify which runner you want to use 17 | CxxTestRunner $env 'stdio_printer', 'StdioPrinter', @tests; 18 | 19 | # For more control, use template files 20 | CxxTestTemplate $env 'file_printer', 'file_printer.tpl', @tests; 21 | 22 | # Or, you can always separate the tests from the runner 23 | CxxTest $env 'tests.cpp', '', @tests; 24 | Program $env 'yes_no_runner', ('yes_no_runner.cpp', 'tests.cpp'); 25 | 26 | 27 | # 28 | # Here is the code used to build these files 29 | # You can use this in your own Construct files 30 | # 31 | 32 | # cons::CxxTest $env $dst, $options, @srcs 33 | # Generates a CxxTest source file, passing the specified options to cxxtestgen 34 | sub cons::CxxTest($$$@) { 35 | my ($env, $dst, $options, @srcs) = @_; 36 | Command $env $dst, @srcs, "%CXXTESTGEN -o %> ${options} %<"; 37 | } 38 | 39 | # cons::CxxTestTemplate $env $dst, $template, @srcs 40 | # Generates and builds a CxxTest runner using a template file 41 | sub cons::CxxTestTemplate($$$@) { 42 | my ($env, $dst, $template, @srcs) = @_; 43 | my $source = "${dst}.cpp"; 44 | CxxTest $env $source, "--template=${template}", ($template, @srcs); 45 | Program $env $dst, $source; 46 | } 47 | 48 | # cons::CxxTestRunner $env $dst, $runner, @srcs 49 | # Generates and builds a CxxTest runner using the --runner option 50 | sub cons::CxxTestRunner($$$@) { 51 | my ($env, $dst, $runner, @srcs) = @_; 52 | my $source = "${dst}.cpp"; 53 | CxxTest $env $source, "--runner=${runner}", @srcs; 54 | Program $env $dst, $source; 55 | } 56 | 57 | # cons::CxxTestErrorPrinter $env $dst, @srcs 58 | # Generates and builds a CxxTest ErrorPrinter 59 | sub cons::CxxTestErrorPrinter($$@) { 60 | my ($env, $dst, @srcs) = @_; 61 | CxxTestRunner $env $dst, 'ErrorPrinter', @srcs; 62 | } 63 | 64 | 65 | -------------------------------------------------------------------------------- /cxxtest/sample/CreatedTest.h: -------------------------------------------------------------------------------- 1 | #ifndef __CREATEDTEST_H 2 | #define __CREATEDTEST_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | // 9 | // This test suite shows what to do when your test case 10 | // class cannot be instantiated statically. 11 | // As an example, this test suite requires a non-default constructor. 12 | // 13 | 14 | class CreatedTest : public CxxTest::TestSuite 15 | { 16 | char *_buffer; 17 | public: 18 | CreatedTest( unsigned size ) : _buffer( new char[size] ) {} 19 | virtual ~CreatedTest() { delete [] _buffer; } 20 | 21 | static CreatedTest *createSuite() { return new CreatedTest( 16 ); } 22 | static void destroySuite( CreatedTest *suite ) { delete suite; } 23 | 24 | void test_nothing() 25 | { 26 | TS_FAIL( "Nothing to test" ); 27 | } 28 | }; 29 | 30 | 31 | #endif // __CREATEDTEST_H 32 | -------------------------------------------------------------------------------- /cxxtest/sample/DeltaTest.h: -------------------------------------------------------------------------------- 1 | #ifndef __DELTATEST_H 2 | #define __DELTATEST_H 3 | 4 | #include 5 | #include 6 | 7 | class DeltaTest : public CxxTest::TestSuite 8 | { 9 | double _pi, _delta; 10 | 11 | public: 12 | void setUp() 13 | { 14 | _pi = 3.1415926535; 15 | _delta = 0.0001; 16 | } 17 | 18 | void testSine() 19 | { 20 | TS_ASSERT_DELTA( sin(0.0), 0.0, _delta ); 21 | TS_ASSERT_DELTA( sin(_pi / 6), 0.5, _delta ); 22 | TS_ASSERT_DELTA( sin(_pi / 2), 1.0, _delta ); 23 | TS_ASSERT_DELTA( sin(_pi), 0.0, _delta ); 24 | } 25 | }; 26 | 27 | #endif // __DELTATEST_H 28 | -------------------------------------------------------------------------------- /cxxtest/sample/EnumTraits.h: -------------------------------------------------------------------------------- 1 | // 2 | // This is a test of CxxTest's ValueTraits for enumerations. 3 | // 4 | #include 5 | 6 | // 7 | // First define your enumeration 8 | // 9 | enum Answer { 10 | Yes, 11 | No, 12 | Maybe, 13 | DontKnow, 14 | DontCare 15 | }; 16 | 17 | // 18 | // Now make CxxTest aware of it 19 | // 20 | CXXTEST_ENUM_TRAITS( Answer, 21 | CXXTEST_ENUM_MEMBER( Yes ) 22 | CXXTEST_ENUM_MEMBER( No ) 23 | CXXTEST_ENUM_MEMBER( Maybe ) 24 | CXXTEST_ENUM_MEMBER( DontKnow ) 25 | CXXTEST_ENUM_MEMBER( DontCare ) ); 26 | 27 | class EnumTraits : public CxxTest::TestSuite 28 | { 29 | public: 30 | void test_Enum_traits() 31 | { 32 | TS_FAIL( Yes ); 33 | TS_FAIL( No ); 34 | TS_FAIL( Maybe ); 35 | TS_FAIL( DontKnow ); 36 | TS_FAIL( DontCare ); 37 | TS_FAIL( (Answer)1000 ); 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /cxxtest/sample/ExceptionTest.h: -------------------------------------------------------------------------------- 1 | #ifndef __EXCEPTIONTEST_H 2 | #define __EXCEPTIONTEST_H 3 | 4 | #include 5 | 6 | // 7 | // This test suite demonstrates the use of TS_ASSERT_THROWS 8 | // 9 | 10 | class ExceptionTest : public CxxTest::TestSuite 11 | { 12 | public: 13 | void testAssertion( void ) 14 | { 15 | // This assert passes, since throwThis() throws (Number) 16 | TS_ASSERT_THROWS( throwThis(3), const Number & ); 17 | // This assert passes, since throwThis() throws something 18 | TS_ASSERT_THROWS_ANYTHING( throwThis(-30) ); 19 | // This assert fails, since throwThis() doesn't throw char * 20 | TS_ASSERT_THROWS( throwThis(5), const char * ); 21 | // This assert fails since goodFunction() throws nothing 22 | TS_ASSERT_THROWS_ANYTHING( goodFunction(1) ); 23 | // The regular TS_ASSERT macros will catch unhandled exceptions 24 | TS_ASSERT_EQUALS( throwThis(3), 333 ); 25 | // You can assert that a function throws nothing 26 | TS_ASSERT_THROWS_NOTHING( throwThis(-1) ); 27 | // If you want to catch the exceptions yourself, use the ETS_ marcos 28 | try { 29 | ETS_ASSERT_EQUALS( throwThis(3), 333 ); 30 | } catch( const Number & ) { 31 | TS_FAIL( "throwThis(3) failed" ); 32 | } 33 | } 34 | 35 | private: 36 | void goodFunction( int ) 37 | { 38 | } 39 | 40 | class Number 41 | { 42 | public: 43 | Number( int ) {} 44 | }; 45 | 46 | int throwThis( int i ) 47 | { 48 | throw Number( i ); 49 | } 50 | }; 51 | 52 | #endif // __EXCEPTIONTEST_H 53 | -------------------------------------------------------------------------------- /cxxtest/sample/FixtureTest.h: -------------------------------------------------------------------------------- 1 | #ifndef __FIXTURETEST_H 2 | #define __FIXTURETEST_H 3 | 4 | #include 5 | #include 6 | 7 | // 8 | // This test suite shows how to use setUp() and tearDown() 9 | // to initialize data common to all tests. 10 | // setUp()/tearDown() will be called before and after each 11 | // test. 12 | // 13 | 14 | class FixtureTest : public CxxTest::TestSuite 15 | { 16 | char *_buffer; 17 | public: 18 | void setUp() 19 | { 20 | _buffer = new char[1024]; 21 | } 22 | 23 | void tearDown() 24 | { 25 | delete [] _buffer; 26 | } 27 | 28 | void test_strcpy() 29 | { 30 | strcpy( _buffer, "Hello, world!" ); 31 | TS_ASSERT_EQUALS( _buffer[0], 'H' ); 32 | TS_ASSERT_EQUALS( _buffer[1], 'E' ); 33 | } 34 | }; 35 | 36 | 37 | #endif // __FIXTURETEST_H 38 | -------------------------------------------------------------------------------- /cxxtest/sample/Makefile.PL: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | # 3 | # This isn't a "real" `Makefile.PL' 4 | # It just copies the correct `Makefile.*' to `Makefile' 5 | # 6 | use strict; 7 | use Getopt::Long; 8 | use File::Copy; 9 | 10 | sub usage() { 11 | die "Usage: $0 [--bcc32]\n"; 12 | } 13 | 14 | my $source; 15 | my $target = 'Makefile'; 16 | my $windows = $ENV{'windir'}; 17 | 18 | GetOptions( 'bcc32' => sub { $source = 'Makefile.bcc32' } ) or usage(); 19 | if ( !defined( $source ) ) { 20 | $source = $windows ? 'Makefile.msvc' : 'Makefile.unix'; 21 | } 22 | 23 | unlink($target); 24 | $windows ? copy($source, $target) : symlink($source, $target); 25 | 26 | print "`Makefile' is now `$source'.\n"; 27 | 28 | # 29 | # Local Variables: 30 | # compile-command: "perl Makefile.PL" 31 | # End: 32 | # 33 | -------------------------------------------------------------------------------- /cxxtest/sample/Makefile.msvc: -------------------------------------------------------------------------------- 1 | # 2 | # Makefile for Microsoft Visual C++ 3 | # Make sure cl.exe is in the PATH (run vcvars.bat) or change CXXC below 4 | # 5 | 6 | # For the Win32 GUI 7 | WIN32_FLAGS = user32.lib 8 | 9 | # For the Qt GUI 10 | # QTDIR = c:\qt 11 | QT_FLAGS = -I$(QTDIR)/include $(QTDIR)/lib/qt.lib 12 | 13 | TARGETS = error_printer.exe stdio_printer.exe yes_no_runner.exe file_printer.exe aborter.exe only.exe 14 | GUI_TARGETS = win32_runner.exe qt_runner.exe 15 | TESTS = *.h 16 | GUI_TESTS = gui/GreenYellowRed.h $(TESTS) 17 | TESTGEN = perl -w ../cxxtestgen.pl 18 | CXXC = cl.exe -GX -W3 -WX -I. -I.. 19 | 20 | all: $(TARGETS) 21 | 22 | clean: 23 | del *~ *.o *.obj 24 | del $(TARGETS) 25 | del $(GUI_TARGETS) 26 | del tests.cpp error_printer.cpp stdio_printer.cpp file_printer.cpp aborter.cpp only.cpp 27 | del win32_runner.cpp qt_runner.cpp 28 | 29 | distclean: clean 30 | del Makefile 31 | 32 | run: error_printer.exe 33 | error_printer.exe 34 | 35 | run_win32: win32_runner.exe 36 | win32_runner.exe 37 | 38 | run_qt: qt_runner.exe 39 | qt_runner.exe 40 | 41 | error_printer.cpp: $(TESTS) 42 | $(TESTGEN) -o error_printer.cpp --error-printer $(TESTS) 43 | 44 | stdio_printer.cpp: $(TESTS) 45 | $(TESTGEN) -o stdio_printer.cpp --runner=StdioPrinter $(TESTS) 46 | 47 | file_printer.cpp: file_printer.tpl $(TESTS) 48 | $(TESTGEN) -o file_printer.cpp --template=file_printer.tpl $(TESTS) 49 | 50 | aborter.cpp: aborter.tpl $(TESTS) 51 | $(TESTGEN) -o aborter.cpp --template=aborter.tpl $(TESTS) 52 | 53 | only.cpp: only.tpl $(TESTS) 54 | $(TESTGEN) -o only.cpp --template=only.tpl $(TESTS) 55 | 56 | tests.cpp: $(TESTS) 57 | $(TESTGEN) -o tests.cpp $(TESTS) 58 | 59 | win32_runner.cpp: $(GUI_TESTS) 60 | $(TESTGEN) -o win32_runner.cpp --gui=Win32Gui $(GUI_TESTS) 61 | 62 | qt_runner.cpp: $(GUI_TESTS) 63 | $(TESTGEN) -o qt_runner.cpp --gui=QtGui $(GUI_TESTS) 64 | 65 | error_printer.exe: error_printer.cpp 66 | $(CXXC) -o error_printer.exe error_printer.cpp 67 | 68 | stdio_printer.exe: stdio_printer.cpp 69 | $(CXXC) -o stdio_printer.exe stdio_printer.cpp 70 | 71 | file_printer.exe: file_printer.cpp 72 | $(CXXC) -o file_printer.exe file_printer.cpp 73 | 74 | only.exe: only.cpp 75 | $(CXXC) -o only.exe only.cpp 76 | 77 | aborter.exe: aborter.cpp 78 | $(CXXC) -o aborter.exe aborter.cpp 79 | 80 | yes_no_runner.exe: yes_no_runner.cpp tests.cpp 81 | $(CXXC) -o yes_no_runner.exe yes_no_runner.cpp tests.cpp 82 | 83 | win32_runner.exe: win32_runner.cpp 84 | $(CXXC) -o win32_runner.exe win32_runner.cpp $(WIN32_FLAGS) 85 | 86 | qt_runner.exe: qt_runner.cpp 87 | $(CXXC) -o qt_runner.exe qt_runner.cpp $(QT_FLAGS) 88 | 89 | # 90 | # Local Variables: 91 | # compile-command: "nmake -fMakefile.msvc" 92 | # End: 93 | # 94 | -------------------------------------------------------------------------------- /cxxtest/sample/Makefile.unix: -------------------------------------------------------------------------------- 1 | # 2 | # Makefile for UN*X-like systems 3 | # 4 | 5 | # Change this line if you want a different compiler 6 | CXXC = c++ -Wall -W -Werror -I. -I.. 7 | 8 | # If you want to use python, specify USE_PYTHON=1 on the command line 9 | ifdef USE_PYTHON 10 | TESTGEN = ../cxxtestgen.py 11 | else 12 | TESTGEN = ../cxxtestgen.pl 13 | endif 14 | 15 | # For the X11 GUI 16 | X11_FLAGS = -I/usr/X11R6/include -L/usr/X11R6/lib -lX11 17 | 18 | # For the Qt GUI 19 | #QTDIR = /usr/lib/qt 20 | QTLIB = -lqt-mt 21 | #QTLIB = -lqt 22 | QT_FLAGS = -I$(QTDIR)/include -L$(QTDIR)/lib $(QTLIB) -O2 23 | 24 | TARGETS = error_printer stdio_printer yes_no_runner file_printer aborter only 25 | GUI_TARGETS = x11_runner qt_runner 26 | TESTS = *.h 27 | GUI_TESTS = gui/GreenYellowRed.h $(TESTS) 28 | 29 | all: $(TARGETS) 30 | 31 | clean: 32 | rm -f *~ *.o *.obj $(TARGETS) $(GUI_TARGETS) 33 | rm -f tests.cpp error_printer.cpp stdio_printer.cpp file_printer.cpp aborter.cpp only.cpp 34 | rm -f x11_runner.cpp qt_runner.cpp 35 | 36 | distclean: clean 37 | rm -f Makefile 38 | 39 | run: error_printer 40 | ./error_printer 41 | 42 | run_x11: x11_runner 43 | ./x11_runner 44 | 45 | run_qt: qt_runner 46 | ./qt_runner 47 | 48 | error_printer.cpp: $(TESTS) 49 | $(TESTGEN) -o $@ --error-printer $(TESTS) 50 | 51 | stdio_printer.cpp: $(TESTS) 52 | $(TESTGEN) -o $@ --runner=StdioPrinter $(TESTS) 53 | 54 | file_printer.cpp: file_printer.tpl $(TESTS) 55 | $(TESTGEN) -o $@ --template=file_printer.tpl $(TESTS) 56 | 57 | aborter.cpp: aborter.tpl $(TESTS) 58 | $(TESTGEN) -o $@ --template=aborter.tpl $(TESTS) 59 | 60 | only.cpp: only.tpl $(TESTS) 61 | $(TESTGEN) -o $@ --template=only.tpl $(TESTS) 62 | 63 | tests.cpp: $(TESTS) 64 | $(TESTGEN) -o $@ $(TESTS) 65 | 66 | x11_runner.cpp: $(GUI_TESTS) 67 | $(TESTGEN) -o $@ --gui=X11Gui $(GUI_TESTS) 68 | 69 | qt_runner.cpp: $(GUI_TESTS) 70 | $(TESTGEN) -o $@ --gui=QtGui $(GUI_TESTS) 71 | 72 | %: %.cpp 73 | $(CXXC) -o $@ $< 74 | 75 | yes_no_runner: yes_no_runner.cpp tests.cpp 76 | $(CXXC) -o $@ $^ 77 | 78 | x11_runner: x11_runner.cpp 79 | $(CXXC) -o $@ $^ $(X11_FLAGS) 80 | 81 | qt_runner: qt_runner.cpp 82 | $(CXXC) -o $@ $^ $(QT_FLAGS) 83 | 84 | # 85 | # Local Variables: 86 | # compile-command: "make -fMakefile.unix" 87 | # End: 88 | # 89 | -------------------------------------------------------------------------------- /cxxtest/sample/MessageTest.h: -------------------------------------------------------------------------------- 1 | #ifndef __MESSAGETEST_H 2 | #define __MESSAGETEST_H 3 | 4 | #include 5 | 6 | // 7 | // The [E]TSM_ macros can be used to print a specified message 8 | // instead of the default one. 9 | // This is useful when you refactor your tests, as shown below 10 | // 11 | 12 | class MessageTest : public CxxTest::TestSuite 13 | { 14 | public: 15 | void testValues() 16 | { 17 | checkValue( 0, "My hovercraft" ); 18 | checkValue( 1, "is full" ); 19 | checkValue( 2, "of eels" ); 20 | } 21 | 22 | void checkValue( unsigned value, const char *message ) 23 | { 24 | TSM_ASSERT( message, value != 0 ); 25 | TSM_ASSERT_EQUALS( message, value, value * value ); 26 | } 27 | }; 28 | 29 | 30 | #endif // __MESSAGETEST_H 31 | -------------------------------------------------------------------------------- /cxxtest/sample/SimpleTest.h: -------------------------------------------------------------------------------- 1 | #ifndef __SIMPLETEST_H 2 | #define __SIMPLETEST_H 3 | 4 | #include 5 | 6 | // 7 | // A simple test suite: Just inherit CxxTest::TestSuite and write tests! 8 | // 9 | 10 | class SimpleTest : public CxxTest::TestSuite 11 | { 12 | public: 13 | void testEquality() 14 | { 15 | TS_ASSERT_EQUALS( 1, 1 ); 16 | TS_ASSERT_EQUALS( 1, 2 ); 17 | TS_ASSERT_EQUALS( 'a', 'A' ); 18 | TS_ASSERT_EQUALS( 1.0, -12345678900000000000000000000000000000000000000000.1234 ); 19 | } 20 | 21 | void testAddition() 22 | { 23 | TS_ASSERT_EQUALS( 1 + 1, 2 ); 24 | TS_ASSERT_EQUALS( 2 + 2, 5 ); 25 | } 26 | 27 | void TestMultiplication() 28 | { 29 | TS_ASSERT_EQUALS( 2 * 2, 4 ); 30 | TS_ASSERT_EQUALS( 4 * 4, 44 ); 31 | TS_ASSERT_DIFFERS( -2 * -2, 4 ); 32 | } 33 | 34 | void testComparison() 35 | { 36 | TS_ASSERT_LESS_THAN( (int)1, (unsigned long)2 ); 37 | TS_ASSERT_LESS_THAN( -1, -2 ); 38 | } 39 | 40 | void testTheWorldIsCrazy() 41 | { 42 | TS_ASSERT_EQUALS( true, false ); 43 | } 44 | 45 | void test_Failure() 46 | { 47 | TS_FAIL( "Not implemented" ); 48 | TS_FAIL( 1569779912 ); 49 | } 50 | 51 | void test_TS_WARN_macro() 52 | { 53 | TS_WARN( "Just a friendly warning" ); 54 | TS_WARN( "Warnings don't abort the test" ); 55 | } 56 | }; 57 | 58 | 59 | #endif // __SIMPLETEST_H 60 | -------------------------------------------------------------------------------- /cxxtest/sample/TraitsTest.h: -------------------------------------------------------------------------------- 1 | #ifndef __TRAITSTEST_H 2 | #define __TRAITSTEST_H 3 | 4 | // 5 | // This example shows how to use TS_ASSERT_EQUALS for your own classes 6 | // 7 | #include 8 | #include 9 | 10 | // 11 | // Define your class with operator== 12 | // 13 | #include 14 | #include 15 | 16 | class Pet 17 | { 18 | char _name[128]; 19 | public: 20 | Pet( const char *petName ) { strcpy( _name, petName ); } 21 | 22 | const char *name() const { return _name; } 23 | 24 | bool operator== ( const Pet &other ) const 25 | { 26 | return !strcmp( name(), other.name() ); 27 | } 28 | }; 29 | 30 | // 31 | // Instantiate CxxTest::ValueTraits<*your class*> 32 | // Note: Most compilers do not require that you define both 33 | // ValueTraits and ValueTraits, but some do. 34 | // 35 | namespace CxxTest 36 | { 37 | CXXTEST_TEMPLATE_INSTANTIATION 38 | class ValueTraits 39 | { 40 | char _asString[256]; 41 | 42 | public: 43 | ValueTraits( const Pet &pet ) { sprintf( _asString, "Pet(\"%s\")", pet.name() ); } 44 | const char *asString() const { return _asString; } 45 | }; 46 | 47 | CXXTEST_COPY_CONST_TRAITS( Pet ); 48 | } 49 | 50 | // 51 | // Here's how it works 52 | // 53 | class TestFunky : public CxxTest::TestSuite 54 | { 55 | public: 56 | void testPets() 57 | { 58 | Pet pet1("dog"), pet2("cat"); 59 | TS_ASSERT_EQUALS( pet1, pet2 ); 60 | Pet cat("cat"), gato("cat"); 61 | TS_ASSERT_DIFFERS( cat, gato ); 62 | #ifdef _CXXTEST_HAVE_STD 63 | typedef CXXTEST_STD(string) String; 64 | TS_ASSERT_EQUALS( String("Hello"), String("World!") ); 65 | #endif // _CXXTEST_HAVE_STD 66 | } 67 | }; 68 | 69 | #endif // __TRAITSTEST_H 70 | -------------------------------------------------------------------------------- /cxxtest/sample/aborter.tpl: -------------------------------------------------------------------------------- 1 | // -*- C++ -*- 2 | // This template file demonstrates the use of CXXTEST_ABORT_TEST_ON_FAIL 3 | // 4 | 5 | #define CXXTEST_HAVE_STD 6 | #define CXXTEST_ABORT_TEST_ON_FAIL 7 | #include 8 | 9 | int main() 10 | { 11 | return CxxTest::ErrorPrinter().run(); 12 | } 13 | 14 | // The CxxTest "world" 15 | 16 | 17 | -------------------------------------------------------------------------------- /cxxtest/sample/file_printer.tpl: -------------------------------------------------------------------------------- 1 | // -*- C++ -*- 2 | // This is a sample of a custom test runner 3 | // using CxxTest template files. 4 | // This prints the output to a file given on the command line. 5 | // 6 | 7 | #include 8 | #include 9 | 10 | int main( int argc, char *argv[] ) 11 | { 12 | if ( argc != 2 ) { 13 | fprintf( stderr, "Usage: %s \n", argv[0] ); 14 | return -1; 15 | } 16 | 17 | return CxxTest::StdioPrinter( fopen( argv[1], "w" ) ).run(); 18 | } 19 | 20 | // The CxxTest "world" 21 | 22 | 23 | -------------------------------------------------------------------------------- /cxxtest/sample/gui/GreenYellowRed.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #ifdef _WIN32 4 | # include 5 | # define CXXTEST_SAMPLE_GUI_WAIT() Sleep( 1000 ) 6 | #else // !_WIN32 7 | extern "C" unsigned sleep( unsigned seconds ); 8 | # define CXXTEST_SAMPLE_GUI_WAIT() sleep( 1 ) 9 | #endif // _WIN32 10 | 11 | class GreenYellowRed : public CxxTest::TestSuite 12 | { 13 | public: 14 | void wait() 15 | { 16 | CXXTEST_SAMPLE_GUI_WAIT(); 17 | } 18 | 19 | void test_Start_green() 20 | { 21 | wait(); 22 | } 23 | 24 | void test_Green_again() 25 | { 26 | TS_TRACE( "Still green" ); 27 | wait(); 28 | } 29 | 30 | void test_Now_yellow() 31 | { 32 | TS_WARN( "Yellow" ); 33 | wait(); 34 | } 35 | 36 | void test_Cannot_go_back() 37 | { 38 | wait(); 39 | } 40 | 41 | void test_Finally_red() 42 | { 43 | TS_FAIL( "Red" ); 44 | wait(); 45 | } 46 | 47 | void test_Cannot_go_back_to_yellow() 48 | { 49 | TS_WARN( "Yellow?" ); 50 | wait(); 51 | } 52 | 53 | void test_Cannot_go_back_to_green() 54 | { 55 | wait(); 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /cxxtest/sample/mock/Dice.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Dice.h" 3 | 4 | Dice::Dice() 5 | { 6 | T::srand( T::time( 0 ) ); 7 | } 8 | 9 | unsigned Dice::roll() 10 | { 11 | return (T::rand() % 6) + 1; 12 | } 13 | 14 | 15 | -------------------------------------------------------------------------------- /cxxtest/sample/mock/Dice.h: -------------------------------------------------------------------------------- 1 | #ifndef __DICE_H 2 | #define __DICE_H 3 | 4 | class Dice 5 | { 6 | public: 7 | Dice(); 8 | 9 | unsigned roll(); 10 | }; 11 | 12 | #endif // __DICE_H 13 | 14 | -------------------------------------------------------------------------------- /cxxtest/sample/mock/Makefile: -------------------------------------------------------------------------------- 1 | all: roll run 2 | 3 | clean: 4 | rm -f *~ *.o roll test test.cpp 5 | 6 | CXXTEST = ../.. 7 | CCFLAGS = -I. -I$(CXXTEST) 8 | 9 | roll: roll.o Dice.o real_stdlib.o 10 | g++ -o $@ $^ 11 | 12 | run: test 13 | ./test 14 | 15 | test: test.o Dice.o mock_stdlib.o 16 | g++ -o $@ $^ 17 | 18 | .cpp.o: 19 | g++ -c -o $@ $(CCFLAGS) $< 20 | 21 | test.cpp: TestDice.h 22 | $(CXXTEST)/cxxtestgen.pl -o $@ --error-printer $< 23 | -------------------------------------------------------------------------------- /cxxtest/sample/mock/MockStdlib.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class MockStdlib : 4 | public T::Base_srand, 5 | public T::Base_rand, 6 | public T::Base_time 7 | { 8 | public: 9 | unsigned lastSeed; 10 | 11 | void srand( unsigned seed ) 12 | { 13 | lastSeed = seed; 14 | } 15 | 16 | int nextRand; 17 | 18 | int rand() 19 | { 20 | return nextRand; 21 | } 22 | 23 | time_t nextTime; 24 | 25 | time_t time( time_t *t ) 26 | { 27 | if ( t ) 28 | *t = nextTime; 29 | return nextTime; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /cxxtest/sample/mock/T/stdlib.h: -------------------------------------------------------------------------------- 1 | #ifndef __T__STDLIB_H 2 | #define __T__STDLIB_H 3 | 4 | #include 5 | #include 6 | 7 | #include 8 | 9 | CXXTEST_MOCK_VOID_GLOBAL( srand, ( unsigned seed ), ( seed ) ); 10 | CXXTEST_MOCK_GLOBAL( int, rand, ( void ), () ); 11 | CXXTEST_MOCK_GLOBAL( time_t, time, ( time_t *t ), ( t ) ); 12 | 13 | #endif // __T__STDLIB_H 14 | -------------------------------------------------------------------------------- /cxxtest/sample/mock/TestDice.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Dice.h" 3 | #include "MockStdlib.h" 4 | 5 | class TestDice : public CxxTest::TestSuite 6 | { 7 | public: 8 | MockStdlib *stdlib; 9 | 10 | void setUp() 11 | { 12 | TS_ASSERT( stdlib = new MockStdlib ); 13 | } 14 | 15 | void tearDown() 16 | { 17 | delete stdlib; 18 | } 19 | 20 | void test_Randomize_uses_time() 21 | { 22 | stdlib->nextTime = 12345; 23 | Dice dice; 24 | TS_ASSERT_EQUALS( stdlib->lastSeed, 12345 ); 25 | } 26 | 27 | void test_Roll() 28 | { 29 | Dice dice; 30 | 31 | stdlib->nextRand = 0; 32 | TS_ASSERT_EQUALS( dice.roll(), 1 ); 33 | 34 | stdlib->nextRand = 2; 35 | TS_ASSERT_EQUALS( dice.roll(), 3 ); 36 | 37 | stdlib->nextRand = 5; 38 | TS_ASSERT_EQUALS( dice.roll(), 6 ); 39 | 40 | stdlib->nextRand = 7; 41 | TS_ASSERT_EQUALS( dice.roll(), 2 ); 42 | } 43 | 44 | void test_Temporary_override_of_one_mock_function() 45 | { 46 | Dice dice; 47 | 48 | stdlib->nextRand = 2; 49 | TS_ASSERT_EQUALS( dice.roll(), 3 ); 50 | 51 | class Five : public T::Base_rand { int rand() { return 5; } }; 52 | 53 | Five *five = new Five; 54 | TS_ASSERT_EQUALS( dice.roll(), 6 ); 55 | TS_ASSERT_EQUALS( dice.roll(), 6 ); 56 | TS_ASSERT_EQUALS( dice.roll(), 6 ); 57 | delete five; 58 | 59 | stdlib->nextRand = 1; 60 | TS_ASSERT_EQUALS( dice.roll(), 2 ); 61 | } 62 | }; 63 | -------------------------------------------------------------------------------- /cxxtest/sample/mock/mock_stdlib.cpp: -------------------------------------------------------------------------------- 1 | #define CXXTEST_MOCK_TEST_SOURCE_FILE 2 | #include 3 | -------------------------------------------------------------------------------- /cxxtest/sample/mock/real_stdlib.cpp: -------------------------------------------------------------------------------- 1 | #define CXXTEST_MOCK_REAL_SOURCE_FILE 2 | #include 3 | -------------------------------------------------------------------------------- /cxxtest/sample/mock/roll.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Dice.h" 3 | 4 | int main() 5 | { 6 | Dice dice; 7 | printf( "First roll: %u\n", dice.roll() ); 8 | printf( "Second roll: %u\n", dice.roll() ); 9 | 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /cxxtest/sample/msvc/CxxTest_Workspace.dsw: -------------------------------------------------------------------------------- 1 | Microsoft Developer Studio Workspace File, Format Version 6.00 2 | # WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! 3 | 4 | ############################################################################### 5 | 6 | Project: "CxxTest_1_Run"=.\CxxTest_1_Run.dsp - Package Owner=<4> 7 | 8 | Package=<5> 9 | {{{ 10 | }}} 11 | 12 | Package=<4> 13 | {{{ 14 | Begin Project Dependency 15 | Project_Dep_Name CxxTest_2_Build 16 | End Project Dependency 17 | }}} 18 | 19 | ############################################################################### 20 | 21 | Project: "CxxTest_2_Build"=.\CxxTest_2_Build.dsp - Package Owner=<4> 22 | 23 | Package=<5> 24 | {{{ 25 | }}} 26 | 27 | Package=<4> 28 | {{{ 29 | Begin Project Dependency 30 | Project_Dep_Name CxxTest_3_Generate 31 | End Project Dependency 32 | }}} 33 | 34 | ############################################################################### 35 | 36 | Project: "CxxTest_3_Generate"=.\CxxTest_3_Generate.dsp - Package Owner=<4> 37 | 38 | Package=<5> 39 | {{{ 40 | }}} 41 | 42 | Package=<4> 43 | {{{ 44 | }}} 45 | 46 | ############################################################################### 47 | 48 | Global: 49 | 50 | Package=<5> 51 | {{{ 52 | }}} 53 | 54 | Package=<3> 55 | {{{ 56 | }}} 57 | 58 | ############################################################################### 59 | 60 | -------------------------------------------------------------------------------- /cxxtest/sample/msvc/Makefile: -------------------------------------------------------------------------------- 1 | # Where to look for the tests 2 | TESTS = ..\gui\*.h ..\*.h 3 | 4 | # Where the CxxTest distribution is unpacked 5 | CXXTESTDIR = ..\.. 6 | 7 | # Check CXXTESTDIR 8 | !if !exist($(CXXTESTDIR)\cxxtestgen.pl) 9 | !error Please fix CXXTESTDIR 10 | !endif 11 | 12 | # cxxtestgen needs Perl or Python 13 | !if defined(PERL) 14 | CXXTESTGEN = $(PERL) $(CXXTESTDIR)/cxxtestgen.pl 15 | !elseif defined(PYTHON) 16 | CXXTESTGEN = $(PYTHON) $(CXXTESTDIR)/cxxtestgen.py 17 | !else 18 | !error You must define PERL or PYTHON 19 | !endif 20 | 21 | # The arguments to pass to cxxtestgen 22 | # - ParenPrinter is the way MSVC likes its compilation errors 23 | # - --have-eh/--abort-on-fail are nice when you have them 24 | CXXTESTGEN_FLAGS = \ 25 | --gui=Win32Gui \ 26 | --runner=ParenPrinter \ 27 | --have-eh \ 28 | --abort-on-fail 29 | 30 | # How to generate the test runner, `runner.cpp' 31 | runner.cpp: $(TESTS) 32 | $(CXXTESTGEN) $(CXXTESTGEN_FLAGS) -o $@ $(TESTS) 33 | 34 | # How to run the tests, which should be in DIR\runner.exe 35 | run: $(DIR)\runner.exe 36 | $(DIR)\runner.exe 37 | -------------------------------------------------------------------------------- /cxxtest/sample/msvc/ReadMe.txt: -------------------------------------------------------------------------------- 1 | Sample files for Visual Studio 2 | ============================== 3 | 4 | There are three projects in this workspace: 5 | 6 | - CxxTest_3_Generate runs cxxtestgen to create runner.cpp 7 | - CxxTest_2_Build compiles the generated file 8 | - CxxTest_1_Run runs the compiled binary 9 | 10 | Whenever you build this workspace, the tests are run, and any failed assertions 11 | are displayed as compilation errors (you can browse them using F4). 12 | 13 | Note that to run this sample, you need first to create an environment 14 | variable PERL or PYTHON, e.g. PERL=c:\perl\bin\perl.exe 15 | 16 | 17 | To use these .dsp and .dsw files in your own project, run FixFiles.bat 18 | to adjust them to where you've placed CxxTest and your own tests. 19 | 20 | If you want to use just the .dsp files in your own workspace, don't 21 | forget to: 22 | 23 | - Set up the dependencies (CxxTest_3_Generate depends on 24 | CxxTest_2_Build which depends on CxxTest_1_Run) 25 | 26 | - Add your own include paths, libraries etc. to the CxxTest_2_Build project 27 | 28 | 29 | NOTE: I haven't used "Post-Build Step" to run the tests because I 30 | wanted the tests to be executed even if nothing has changed. 31 | -------------------------------------------------------------------------------- /cxxtest/sample/only.tpl: -------------------------------------------------------------------------------- 1 | // -*- C++ -*- 2 | #include 3 | #include 4 | 5 | int main( int argc, char *argv[] ) 6 | { 7 | if ( argc < 2 || argc > 3 ) { 8 | fprintf( stderr, "Usage: only []\n\n" ); 9 | fprintf( stderr, "Available tests:\n" ); 10 | CxxTest::RealWorldDescription wd; 11 | for ( CxxTest::SuiteDescription *sd = wd.firstSuite(); sd; sd = sd->next() ) 12 | for ( CxxTest::TestDescription *td = sd->firstTest(); td; td = td->next() ) 13 | fprintf( stderr, " - %s::%s()\n", sd->suiteName(), td->testName() ); 14 | return 1; 15 | } 16 | 17 | const char *suiteName = argv[1]; 18 | const char *testName = (argc > 2) ? argv[2] : 0; 19 | if ( !CxxTest::leaveOnly( suiteName, testName ) ) { 20 | if ( testName ) 21 | fprintf( stderr, "Cannot find %s::%s()\n", argv[1], argv[2] ); 22 | else 23 | fprintf( stderr, "Cannot find class %s\n", argv[1] ); 24 | return 2; 25 | } 26 | 27 | return CxxTest::StdioPrinter().run(); 28 | } 29 | 30 | 31 | // The CxxTest "world" 32 | 33 | 34 | -------------------------------------------------------------------------------- /cxxtest/sample/parts/Makefile.unix: -------------------------------------------------------------------------------- 1 | # 2 | # (GNU) Makefile for UN*X-like systems 3 | # This makefile shows how to make a different runner for each test 4 | # 5 | 6 | .PHONY: all clean 7 | 8 | all: run 9 | 10 | clean: 11 | rm -f *~ *.cpp *.o runner 12 | 13 | CXXTESTDIR = ../.. 14 | CXXTESTGEN = $(CXXTESTDIR)/cxxtestgen.pl 15 | CXXTESTFLAGS = --have-eh --abort-on-fail 16 | 17 | TESTS = $(wildcard ../*Test.h) 18 | OBJS = runner.o $(TESTS:../%.h=%.o) 19 | 20 | run: runner 21 | ./runner 22 | 23 | runner: $(OBJS) 24 | c++ -o $@ $^ 25 | 26 | %.o: %.cpp 27 | c++ -c -o $@ -I $(CXXTESTDIR) -I .. $^ 28 | 29 | %.cpp: ../%.h 30 | $(CXXTESTGEN) $(CXXTESTFLAGS) --part -o $@ $^ 31 | 32 | runner.cpp: 33 | $(CXXTESTGEN) $(CXXTESTFLAGS) --root --error-printer -o $@ 34 | 35 | # 36 | # Local Variables: 37 | # compile-command: "make -fMakefile.unix" 38 | # End: 39 | # 40 | -------------------------------------------------------------------------------- /cxxtest/sample/winddk/Makefile: -------------------------------------------------------------------------------- 1 | # Standard DDK Makefile 2 | !include $(NTMAKEENV)\makefile.def 3 | -------------------------------------------------------------------------------- /cxxtest/sample/winddk/Makefile.inc: -------------------------------------------------------------------------------- 1 | # -*- Makefile -*- 2 | 3 | # 4 | # Tell the DDK how to generate RunTests.cpp from RunTests.tpl and the tests 5 | # 6 | 7 | PERL=perl 8 | PYTHON=python 9 | CXXTESTGEN=$(PERL) $(CXXTESTDIR)/cxxtestgen.pl 10 | #CXXTESTGEN=$(PYTHON) $(CXXTESTDIR)/cxxtestgen.py 11 | 12 | TEST_SUITES=$(SUITESDIR)/*.h 13 | 14 | RunTests.cpp: RunTests.tpl $(TEST_SUITES) 15 | $(CXXTESTGEN) -o $@ --template=RunTests.tpl $(TEST_SUITES) 16 | -------------------------------------------------------------------------------- /cxxtest/sample/winddk/RunTests.tpl: -------------------------------------------------------------------------------- 1 | // -*- C++ -*- 2 | 3 | // 4 | // The DDK doesn't handle too well 5 | // 6 | #include 7 | 8 | int __cdecl main() 9 | { 10 | return CxxTest::StdioPrinter().run(); 11 | } 12 | 13 | 14 | -------------------------------------------------------------------------------- /cxxtest/sample/winddk/SOURCES: -------------------------------------------------------------------------------- 1 | # -*- Makefile -*- 2 | 3 | # 4 | # Build this sample with the Windows DDK (XP or later) 5 | # 6 | SUITESDIR=.. 7 | CXXTESTDIR=../.. 8 | 9 | # 10 | # Build a user-mode application 11 | # 12 | TARGETNAME=RunTests 13 | TARGETPATH=. 14 | TARGETTYPE=PROGRAM 15 | 16 | # 17 | # Make it a console-mode app 18 | # 19 | UMTYPE=console 20 | 21 | # 22 | # Add CxxTest and tests directory to include path 23 | # 24 | INCLUDES=$(SUITESDIR);$(CXXTESTDIR) 25 | 26 | # 27 | # Enable exception handling and standard library 28 | # 29 | USE_NATIVE_EH=1 30 | LINKER_FLAGS=$(LINKER_FLAGS) -IGNORE:4099 31 | 386_WARNING_LEVEL=-W3 -WX -wd4290 32 | 33 | TARGETLIBS=\ 34 | $(CRT_LIB_PATH)\libcp.lib \ 35 | $(CRT_LIB_PATH)\libc.lib 36 | 37 | # 38 | # Only one source file -- the generated test runner 39 | # 40 | SOURCES=RunTests.cpp 41 | 42 | # 43 | # This line tells the build utility to process Makefile.inc 44 | # 45 | NTTARGETFILE0=RunTests.cpp 46 | 47 | -------------------------------------------------------------------------------- /cxxtest/sample/yes_no_runner.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // A sample program that uses class YesNoRunner to run all the tests 3 | // and find out if all pass. 4 | // 5 | 6 | #include 7 | 8 | int main() 9 | { 10 | return CxxTest::YesNoRunner().run(); 11 | } 12 | -------------------------------------------------------------------------------- /examples/1_simplest_project/File.h: -------------------------------------------------------------------------------- 1 | #ifndef __FILE_H__ 2 | #define __FILE_H__ 3 | 4 | #include 5 | 6 | class File 7 | { 8 | public: 9 | File( std::string filename ) : 10 | _filename( filename ) 11 | {} 12 | 13 | std::string read() 14 | { 15 | std::ifstream input( _filename.c_str(), std::ifstream::in ); 16 | std::string out; 17 | input >> out; 18 | return out; 19 | } 20 | 21 | void write( std::string content ) 22 | { 23 | std::ofstream output; 24 | output.open( _filename.c_str() ); 25 | output << content; 26 | } 27 | 28 | private: 29 | std::string _filename; 30 | }; 31 | 32 | #endif // __FILE_H__ 33 | //FILE_EXEMPT_FROM_CODE_COVERAGE 34 | -------------------------------------------------------------------------------- /examples/1_simplest_project/Makefile: -------------------------------------------------------------------------------- 1 | all: test 2 | 3 | export VOODOO_ROOT_DIR = ../.. 4 | 5 | clean: 6 | rm -fr build_unittest build 7 | 8 | test: buildall 9 | $(MAKE) -f $(VOODOO_ROOT_DIR)/make/1_generate.Makefile 10 | $(MAKE) -f $(VOODOO_ROOT_DIR)/make/2_build.Makefile 11 | $(MAKE) -f $(VOODOO_ROOT_DIR)/make/3_run.Makefile 12 | $(MAKE) -f $(VOODOO_ROOT_DIR)/make/4_optional_enforce_cpp_coverage.Makefile 13 | 14 | buildall: build/main 15 | 16 | build/main: main.cpp File.h Map.h 17 | -mkdir $(@D) 18 | g++ -o $@ $< -Wall 19 | -------------------------------------------------------------------------------- /examples/1_simplest_project/Map.h: -------------------------------------------------------------------------------- 1 | #ifndef __MAP_H__ 2 | #define __MAP_H__ 3 | 4 | #include "File.h" 5 | 6 | //A fictitious "map" object from a number to a string 7 | //by using different file in /tmp for each 8 | class Map 9 | { 10 | public: 11 | Map( std::string name ) : 12 | _name( name ) 13 | {} 14 | 15 | void set( const std::string & key, const std::string & value ) 16 | { 17 | File( pathForKey( key ) ).write( value ); 18 | } 19 | 20 | std::string get( const std::string & key ) 21 | { 22 | return File( pathForKey( key ) ).read(); 23 | } 24 | 25 | private: 26 | std::string _name; 27 | 28 | std::string pathForKey( const std::string & key ) const 29 | { 30 | return "/tmp/map_" + _name + "_" + key + ".dat"; 31 | } 32 | }; 33 | 34 | #endif // __MAP_H__ 35 | -------------------------------------------------------------------------------- /examples/1_simplest_project/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Map.h" 3 | 4 | int main() 5 | { 6 | std::cout << "hello world" << std::endl; 7 | Map map( "example" ); 8 | 9 | map.set( "firstKey", "firstValue" ); 10 | std::cout << "firstKey: " << map.get( "firstKey" ) << std::endl; 11 | return 0; 12 | } 13 | //FILE_EXEMPT_FROM_CODE_COVERAGE 14 | -------------------------------------------------------------------------------- /examples/1_simplest_project/tests/Test_Map.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define VOODOO_EXPECT_File_h 4 | 5 | #include "Map.h" 6 | 7 | using namespace VoodooCommon::Expect; 8 | using namespace VoodooCommon::Expect::Parameter; 9 | 10 | class Test_Map: public CxxTest::TestSuite 11 | { 12 | public: 13 | void test_Read() 14 | { 15 | Map tested( "The Map Name" ); 16 | 17 | Scenario scenario; 18 | scenario << 19 | new Construction< File >( "Fake file" ) << 20 | new EqualsValue< std::string >( "/tmp/map_The Map Name_The Key Name.dat" ) << 21 | new CallReturnValue< std::string >( "Fake file::read", "The Expected Value" ) << 22 | new Destruction( "Fake file" ); 23 | std::string result = tested.get( "The Key Name" ); 24 | scenario.assertFinished(); 25 | TS_ASSERT_EQUALS( result, "The Expected Value" ); 26 | } 27 | 28 | void test_Write() 29 | { 30 | Map tested( "The Map Name" ); 31 | 32 | Scenario scenario; 33 | scenario << 34 | new Construction< File >( "Fake file" ) << 35 | new EqualsValue< std::string >( "/tmp/map_The Map Name_The Key Name.dat" ) << 36 | new CallReturnVoid( "Fake file::write" ) << 37 | new EqualsValue< std::string >( "The Written Value" ) << 38 | new Destruction( "Fake file" ); 39 | tested.set( "The Key Name", "The Written Value" ); 40 | scenario.assertFinished(); 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /examples/2_feature_full_project_scaffold__copy_me/Makefile: -------------------------------------------------------------------------------- 1 | all: targets test 2 | 3 | ifeq ($(V),1) 4 | Q = 5 | else 6 | Q = @ 7 | endif 8 | 9 | export CXXTEST_FIND_ROOT = c cpp 10 | export PYTEST_FIND_ROOT = py 11 | export ENFORCE_COVERAGE_FIND_ROOT_CPP = c cpp 12 | export UNITTEST_INCLUDES = -Ibuild_unittest/voodoo/cpp -Ibuild_unittest/voodoo/c -Icpp -Ic -I. 13 | export VOODOO_INCLUDES = --includePath=cpp --includePath=c 14 | 15 | clean: clean_unittest 16 | rm -fr build 17 | find -name "*.pyc" -exec rm {} \; 18 | 19 | test: targets 20 | 21 | targets: 22 | $(MAKE) -f tools/make/Makefile 23 | 24 | include $(VOODOO_ROOT_DIR)/make/integrations/complete.Makefile 25 | -------------------------------------------------------------------------------- /examples/2_feature_full_project_scaffold__copy_me/README.md: -------------------------------------------------------------------------------- 1 | Scaffold Features: 2 | ------------------ 3 | This scaffold contains all the goodies described in ADDITIONAL_GOODIES.md, 4 | plus: 5 | -------------------------------------------------------------------------------- /examples/2_feature_full_project_scaffold__copy_me/cpp/Common/Debug.h: -------------------------------------------------------------------------------- 1 | #ifndef __COMMON_DEBUG_CPP_H__ 2 | #define __COMMON_DEBUG_CPP_H__ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #ifdef UNITTEST 12 | 13 | //Under unittest: assert fails the test 14 | # define _ASSERT( __condition, __serialize ) do { \ 15 | if ( ! ( __condition ) ) { \ 16 | std::ostringstream __message; \ 17 | __message << __serialize; \ 18 | TS_FAIL( __message.str() ); \ 19 | } \ 20 | } while( 0 ) 21 | 22 | #else // UNITTEST 23 | 24 | # ifdef DEBUG 25 | 26 | //Under debug build: assert exists immidiately 27 | # define _ASSERT( __condition, __serialize ) do { \ 28 | if ( ! ( __condition ) ) { \ 29 | _TRACE( "ASSERT", "Assertion '" #__condition "' failed (" << __FILE__ << ':' << \ 30 | __LINE__ << ')' << __serialize << "\nCommiting suicide\n", std::cerr ); \ 31 | _exit( 1 ); \ 32 | } \ 33 | } while( 0 ) 34 | # define TRACE_DEVEL( __serialize ) _TRACE( "DEVEL", __serialize, std::cerr ) 35 | 36 | # else //DEBUG 37 | 38 | //Under release build: assert does not compile 39 | # define _ASSERT( __condition, __serialize ) do {} while( 0 ) 40 | # define TRACE_DEVEL( __serialize ) please_dont_leave_TRACE_DEVEL_messages_lying_around 41 | 42 | # endif // DEBUG 43 | #endif // UNITTEST 44 | 45 | # define _TRACE( __level, __serialize, __stream ) do { \ 46 | struct timeval timeValue; \ 47 | gettimeofday( & timeValue, nullptr ); \ 48 | __stream << timeValue.tv_sec << '.' << std::setfill( '0' ) << std::setw( 6 ) << timeValue.tv_usec << ':' << \ 49 | __level << ':' << ' ' << __serialize << ' ' << '(' << __FILE__ << ':' << __LINE__ << \ 50 | ')' << std::endl; \ 51 | } while( 0 ) 52 | 53 | #define TRACE_INFO( __serialize ) _TRACE( "INFO", __serialize, std::cout ) 54 | #define TRACE_WARNING( __serialize ) _TRACE( "WARNING", __serialize, std::cerr ) 55 | #define TRACE_ERROR( __serialize ) _TRACE( "ERROR", __serialize, std::cerr ) 56 | #define TRACE_EXCEPTION( __e, __serialize ) _TRACE( "EXCEPTION", "Exception: " << __e.what() << ": " << __serialize, std::cerr ) 57 | #define ASSERT( __x ) _ASSERT( __x, "" ) 58 | #define ASSERT_VERBOSE( __x, __serialize ) _ASSERT( __x, ": " << __serialize ) 59 | 60 | #endif // __COMMON_DEBUG_H__ 61 | //FILE_EXEMPT_FROM_CODE_COVERAGE 62 | -------------------------------------------------------------------------------- /examples/2_feature_full_project_scaffold__copy_me/cpp/Common/MyError.h: -------------------------------------------------------------------------------- 1 | #ifndef __COMMON_MY_ERROR_H__ 2 | #define __COMMON_MY_ERROR_H__ 3 | 4 | #include 5 | #include 6 | 7 | class MyError : public std::runtime_error 8 | { 9 | public: 10 | MyError( const std::string & what, const char * filename, unsigned line ) : 11 | std::runtime_error( what ), 12 | filename( filename ), 13 | line( line ) 14 | {} 15 | 16 | const char * const filename; 17 | const unsigned line; 18 | }; 19 | 20 | #define EXCEPTION_SUBCLASS( name, superclass ) \ 21 | class name : public superclass \ 22 | { \ 23 | public: \ 24 | using ::MyError::MyError; \ 25 | } 26 | 27 | #define EXCEPTION_CLASS( name ) EXCEPTION_SUBCLASS( name, ::MyError ) 28 | 29 | #define THROW( name, serialize ) do { \ 30 | std::ostringstream __seralize; \ 31 | __seralize << serialize << \ 32 | " (" << __FILE__ << ':' << __LINE__ << ':' << \ 33 | __FUNCTION__ << ')'; \ 34 | throw name( __seralize.str(), __FILE__, __LINE__ ); \ 35 | } while( 0 ) 36 | 37 | #endif // __COMMON_MY_ERROR_H__ 38 | //FILE_EXEMPT_FROM_CODE_COVERAGE 39 | -------------------------------------------------------------------------------- /examples/2_feature_full_project_scaffold__copy_me/cpp/MapExample/File.h: -------------------------------------------------------------------------------- 1 | #ifndef __MAP_EXAMPLE_FILE_H__ 2 | #define __MAP_EXAMPLE_FILE_H__ 3 | 4 | #include 5 | 6 | namespace MapExample 7 | { 8 | 9 | class File 10 | { 11 | public: 12 | File( std::string filename ) : 13 | _filename( filename ) 14 | {} 15 | 16 | std::string read() 17 | { 18 | std::ifstream input( _filename.c_str(), std::ifstream::in ); 19 | std::string out; 20 | input >> out; 21 | return out; 22 | } 23 | 24 | void write( std::string content ) 25 | { 26 | std::ofstream output; 27 | output.open( _filename.c_str() ); 28 | output << content; 29 | } 30 | 31 | private: 32 | std::string _filename; 33 | }; 34 | 35 | } // namespace MapExample 36 | 37 | #endif // __MAP_EXAMPLE_FILE_H__ 38 | //FILE_EXEMPT_FROM_CODE_COVERAGE 39 | -------------------------------------------------------------------------------- /examples/2_feature_full_project_scaffold__copy_me/cpp/MapExample/Map.h: -------------------------------------------------------------------------------- 1 | #ifndef __MAP_EXAMPLE_MAP_H__ 2 | #define __MAP_EXAMPLE_MAP_H__ 3 | 4 | #include "MapExample/File.h" 5 | #include "Common/Debug.h" 6 | 7 | namespace MapExample 8 | { 9 | 10 | //A fictitious "map" object from a number to a string 11 | //by using different file in /tmp for each 12 | class Map 13 | { 14 | public: 15 | Map( std::string name ) : 16 | _name( name ) 17 | { 18 | ASSERT_VERBOSE( name.size() > 0, "Map name must not be zero" ); 19 | ASSERT_VERBOSE( name.find( ' ' ) != std::string::npos, "Map name must not contain spaces" ); 20 | } 21 | 22 | void set( const std::string & key, const std::string & value ) 23 | { 24 | TRACE_INFO( "Saving key '" << key << "'" ); 25 | File( pathForKey( key ) ).write( value ); 26 | } 27 | 28 | std::string get( const std::string & key ) 29 | { 30 | return File( pathForKey( key ) ).read(); 31 | } 32 | 33 | private: 34 | std::string _name; 35 | 36 | std::string pathForKey( const std::string & key ) const 37 | { 38 | return "/tmp/map_" + _name + "_" + key + ".dat"; 39 | } 40 | }; 41 | 42 | } // namespace MapExample 43 | 44 | #endif // __MAP_EXAMPLE_MAP_H__ 45 | -------------------------------------------------------------------------------- /examples/2_feature_full_project_scaffold__copy_me/cpp/MapExample/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "MapExample/Map.h" 3 | 4 | int main() 5 | { 6 | std::cout << "hello world" << std::endl; 7 | MapExample::Map map( "example" ); 8 | 9 | map.set( "firstKey", "firstValue" ); 10 | std::cout << "firstKey: " << map.get( "firstKey" ) << std::endl; 11 | return 0; 12 | } 13 | //FILE_EXEMPT_FROM_CODE_COVERAGE 14 | -------------------------------------------------------------------------------- /examples/2_feature_full_project_scaffold__copy_me/cpp/MapExample/tests/Test_Map.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define VOODOO_EXPECT_cpp_MapExample_File_h 4 | 5 | #include "MapExample/Map.h" 6 | 7 | using namespace VoodooCommon::Expect; 8 | using namespace VoodooCommon::Expect::Parameter; 9 | using namespace MapExample; 10 | 11 | class Test_Map: public CxxTest::TestSuite 12 | { 13 | public: 14 | void test_Read() 15 | { 16 | Map tested( "The Map Name" ); 17 | 18 | Scenario scenario; 19 | scenario << 20 | new Construction< File >( "Fake file" ) << 21 | new EqualsValue< std::string >( "/tmp/map_The Map Name_The Key Name.dat" ) << 22 | new CallReturnValue< std::string >( "Fake file::read", "The Expected Value" ) << 23 | new Destruction( "Fake file" ); 24 | std::string result = tested.get( "The Key Name" ); 25 | scenario.assertFinished(); 26 | TS_ASSERT_EQUALS( result, "The Expected Value" ); 27 | } 28 | 29 | void test_Write() 30 | { 31 | Map tested( "The Map Name" ); 32 | 33 | Scenario scenario; 34 | scenario << 35 | new Construction< File >( "Fake file" ) << 36 | new EqualsValue< std::string >( "/tmp/map_The Map Name_The Key Name.dat" ) << 37 | new CallReturnVoid( "Fake file::write" ) << 38 | new EqualsValue< std::string >( "The Written Value" ) << 39 | new Destruction( "Fake file" ); 40 | tested.set( "The Key Name", "The Written Value" ); 41 | scenario.assertFinished(); 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /examples/2_feature_full_project_scaffold__copy_me/env: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #run vim and work under this environment 3 | 4 | export mydir=`dirname $BASH_SOURCE` 5 | # the next line is a cross platform version of 6 | # mydir=`realpath $mydir` 7 | mydir=`python -c "import os; print os.path.abspath('$mydir')"` 8 | if [ ! -z "$TOP" -a "$TOP" != "$mydir" ] ; then 9 | echo "Error: Nested env" 10 | exit -1 11 | fi 12 | 13 | export TOP=$mydir 14 | unset mydir 15 | # the next line is a cross platform version of 16 | # export VOODOO_ROOT_DIR=`realpath ../..` 17 | export VOODOO_ROOT_DIR=`python -c "import os; print os.path.abspath(os.path.join(r'$TOP', '..', '..'))"` 18 | export VIMINIT="source $TOP/tools/vim/settings.vim" 19 | export PYTHONPATH=$PYTHONPATH:$TOP/py 20 | 21 | # ./env - start a shell for interactive session 22 | # ./env command - run a command under environment 23 | if [ "$#" = "0" ] ; then 24 | exec $SHELL 25 | else 26 | exec "$@" 27 | fi 28 | -------------------------------------------------------------------------------- /examples/2_feature_full_project_scaffold__copy_me/tools/make/Makefile: -------------------------------------------------------------------------------- 1 | all: all-targets 2 | 3 | ifeq ($(V),1) 4 | Q = 5 | else 6 | Q = @ 7 | endif 8 | 9 | TARGET_mapexample = cpp/MapExample/main.cpp 10 | ifneq ($(OS),Windows_NT) 11 | mapexample_LIBRARIES = -lpthread 12 | endif 13 | 14 | #SHAREDLIBRARY_example = cpp/Namespace/object1.cpp cpp/Namespace/object2.cpp 15 | #example_LIBRARIES = -ldl -lrt 16 | #Namespace_object1_o_CFLAGS = -fPIC -DPIC 17 | #Namespace_object2_o_CFLAGS = -fPIC -DPIC 18 | 19 | CONFIGURATION ?= DEBUG 20 | SHELL := /bin/bash 21 | COMMON_CXXFLAGS = -Ic -Icpp -I/usr/include/python2.7 -std=gnu++0x -Werror -Wall 22 | DEBUG_CXXFLAGS = -ggdb -DDEBUG 23 | RELEASE_CXXFLAGS = -O3 24 | COMMON_CFLAGS = -Ic -Werror -Wall 25 | DEBUG_CFLAGS = $(DEBUG_CXXFLAGS) 26 | RELEASE_CFLAGS = $(RELEASE_CXXFLAGS) 27 | CXXFLAGS = $(COMMON_CXXFLAGS) $($(CONFIGURATION)_CXXFLAGS) 28 | CFLAGS = $(COMMON_CFLAGS) $($(CONFIGURATION)_CFLAGS) 29 | 30 | include tools/make/rules.Makefile 31 | -------------------------------------------------------------------------------- /examples/2_feature_full_project_scaffold__copy_me/tools/vim/settings.vim: -------------------------------------------------------------------------------- 1 | source $VOODOO_ROOT_DIR/vim/settings.vim 2 | set runtimepath+=$TOP/tools/vim 3 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/custom_stubs/Makefile: -------------------------------------------------------------------------------- 1 | all: test 2 | 3 | ifeq ($(V),1) 4 | Q = 5 | else 6 | Q = @ 7 | endif 8 | 9 | export VOODOO_ROOT_DIR=../../.. 10 | export CXXTEST_FIND_ROOT = cpp 11 | export ENFORCE_COVERAGE_FIND_ROOT_CPP = cpp 12 | export UNITTEST_INCLUDES = -Ibuild_unittest/voodoo/cpp -Icpp -I. 13 | export VOODOO_INCLUDES = --includePath=cpp 14 | 15 | clean: clean_unittest 16 | 17 | include $(VOODOO_ROOT_DIR)/make/integrations/complete.Makefile 18 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/custom_stubs/cpp/Common/Debug.h: -------------------------------------------------------------------------------- 1 | #ifndef __COMMON_DEBUG_CPP_H__ 2 | #define __COMMON_DEBUG_CPP_H__ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #ifdef UNITTEST 11 | 12 | //Under unittest: assert fails the test 13 | # define _ASSERT( __condition, __serialize ) do { \ 14 | if ( ! ( __condition ) ) { \ 15 | std::ostringstream __message; \ 16 | __message << __serialize; \ 17 | TS_FAIL( __message.str() ); \ 18 | } \ 19 | } while( 0 ) 20 | 21 | #else // UNITTEST 22 | 23 | # ifdef DEBUG 24 | 25 | //Under debug build: assert exists immidiately 26 | # define _ASSERT( __condition, __serialize ) do { \ 27 | if ( ! ( __condition ) ) { \ 28 | _TRACE( "ASSERT", "Assertion '" #__condition "' failed (" << __FILE__ << ':' << \ 29 | __LINE__ << ')' << __serialize << "\nCommiting suicide\n", std::cerr ); \ 30 | _exit( 1 ); \ 31 | } \ 32 | } while( 0 ) 33 | # define TRACE_DEVEL( __serialize ) _TRACE( "DEVEL", __serialize, std::cerr ) 34 | 35 | # else //DEBUG 36 | 37 | //Under release build: assert does not compile 38 | # define _ASSERT( __condition, __serialize ) do {} while( 0 ) 39 | # define TRACE_DEVEL( __serialize ) please_dont_leave_TRACE_DEVEL_messages_lying_around 40 | 41 | # endif // DEBUG 42 | #endif // UNITTEST 43 | 44 | # define _TRACE( __level, __serialize, __stream ) do { \ 45 | struct timeval timeValue; \ 46 | gettimeofday( & timeValue, nullptr ); \ 47 | __stream << timeValue.tv_sec << '.' << std::setfill( '0' ) << std::setw( 6 ) << timeValue.tv_usec << ':' << \ 48 | __level << ':' << ' ' << __serialize << ' ' << '(' << __FILE__ << ':' << __LINE__ << \ 49 | ')' << std::endl; \ 50 | } while( 0 ) 51 | 52 | #define TRACE_INFO( __serialize ) _TRACE( "INFO", __serialize, std::cout ) 53 | #define TRACE_WARNING( __serialize ) _TRACE( "WARNING", __serialize, std::cerr ) 54 | #define TRACE_ERROR( __serialize ) _TRACE( "ERROR", __serialize, std::cerr ) 55 | #define TRACE_EXCEPTION( __e, __serialize ) _TRACE( "EXCEPTION", "Exception: " << __e.what() << ": " << __serialize, std::cerr ) 56 | #define ASSERT( __x ) _ASSERT( __x, "" ) 57 | #define ASSERT_VERBOSE( __x, __serialize ) _ASSERT( __x, ": " << __serialize ) 58 | 59 | #endif // __COMMON_DEBUG_H__ 60 | //FILE_EXEMPT_FROM_CODE_COVERAGE 61 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/custom_stubs/cpp/Common/MyError.h: -------------------------------------------------------------------------------- 1 | #ifndef __COMMON_MY_ERROR_H__ 2 | #define __COMMON_MY_ERROR_H__ 3 | 4 | #include 5 | #include 6 | 7 | class MyError : public std::runtime_error 8 | { 9 | public: 10 | MyError( const std::string & what, const char * filename, unsigned line ) : 11 | std::runtime_error( what ), 12 | filename( filename ), 13 | line( line ) 14 | {} 15 | 16 | const char * const filename; 17 | const unsigned line; 18 | }; 19 | 20 | #define EXCEPTION_SUBCLASS( name, superclass ) \ 21 | class name : public superclass \ 22 | { \ 23 | public: \ 24 | using ::MyError::MyError; \ 25 | } 26 | 27 | #define EXCEPTION_CLASS( name ) EXCEPTION_SUBCLASS( name, ::MyError ) 28 | 29 | #define THROW( name, serialize ) do { \ 30 | std::ostringstream __seralize; \ 31 | __seralize << serialize << \ 32 | " (" << __FILE__ << ':' << __LINE__ << ':' << \ 33 | __FUNCTION__ << ')'; \ 34 | throw name( __seralize.str(), __FILE__, __LINE__ ); \ 35 | } while( 0 ) 36 | 37 | #endif // __COMMON_MY_ERROR_H__ 38 | //FILE_EXEMPT_FROM_CODE_COVERAGE 39 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/custom_stubs/cpp/Example/MockMe.h: -------------------------------------------------------------------------------- 1 | #ifndef __EXAMPLE_MOCK_ME_H__ 2 | #define __EXAMPLE_MOCK_ME_H__ 3 | 4 | namespace Example 5 | { 6 | 7 | class MockMe 8 | { 9 | public: 10 | MockMe(){} 11 | 12 | this class does not pass through the voodoo parser: 13 | 1. maybe its way too complicated to parse (for example, a boost header file) 14 | 2. maybe you are building the stub before writing the code 15 | 3. maybe you just want something very custom in your test 16 | 17 | private: 18 | 19 | MockMe( const MockMe & rhs ) = delete; 20 | MockMe & operator= ( const MockMe & rhs ) = delete; 21 | }; 22 | 23 | } // namespace Example 24 | 25 | #endif // __EXAMPLE_MOCK_ME_H__ 26 | //FILE_EXEMPT_FROM_CODE_COVERAGE 27 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/custom_stubs/cpp/Example/UnderTest.h: -------------------------------------------------------------------------------- 1 | #ifndef __EXAMPLE_UNDER_TEST_H__ 2 | #define __EXAMPLE_UNDER_TEST_H__ 3 | 4 | #include "Example/MockMe.h" 5 | 6 | namespace Example 7 | { 8 | 9 | class UnderTest 10 | { 11 | public: 12 | UnderTest(){} 13 | 14 | void underTest() 15 | { 16 | int what = 8; 17 | MockMe mockMe( what ); 18 | int first = 1; 19 | const char * second = "yada"; 20 | mockMe.justASimpleVoidMethod( first, second ); 21 | int result = mockMe.returnsAnInt(); 22 | (void) result; 23 | std::unique_ptr< int > result2 = mockMe.returnsAUniquePtr(); 24 | (void) result2; 25 | 26 | globalFunction( second ); 27 | int result3 = globalFunctionReturningInt(); 28 | (void) result3; 29 | std::string result4 = globalFunctionMoveReturn(); 30 | (void) result4; 31 | } 32 | 33 | private: 34 | 35 | UnderTest( const UnderTest & rhs ) = delete; 36 | UnderTest & operator= ( const UnderTest & rhs ) = delete; 37 | }; 38 | 39 | } // namespace Example 40 | 41 | #endif // __EXAMPLE_UNDER_TEST_H__ 42 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/custom_stubs/cpp/Example/tests/Test_UnderTest.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define __EXAMPLE_MOCK_ME_H__ 1 4 | //this macro will cause the real MockMe.h to be "skipped" when included. Instead, we can 5 | //implement our stub here as we see fit (and pehaps even put the code in a separate makefile) 6 | 7 | #include "VoodooCommon/Custom.h" 8 | #include 9 | 10 | using namespace VoodooCommon::Expect; 11 | using namespace VoodooCommon::Expect::Parameter; 12 | 13 | namespace Example { 14 | class MockMe : public Custom::Klass 15 | { 16 | public: 17 | MockMe( int parameter ) : 18 | Custom::Klass( "Example::MockMe" ) 19 | { 20 | voodooConstructor( parameter ); 21 | } 22 | 23 | ~MockMe() 24 | { 25 | voodooDestructor(); 26 | } 27 | 28 | void justASimpleVoidMethod( int first, const char * second ) 29 | { 30 | voodooVoidCall( "justASimpleVoidMethod", first, second ); 31 | } 32 | 33 | int returnsAnInt() 34 | { 35 | return voodooCall< int >( "returnsAnInt" ); 36 | } 37 | 38 | std::unique_ptr< int > returnsAUniquePtr() 39 | { 40 | return std::move( voodooMoveCall< std::unique_ptr< int > >( "returnsAUniquePtr" ) ); 41 | } 42 | }; 43 | void globalFunction( const char * str ) 44 | { 45 | Custom::voodooVoidCall( "Example::globalFunction", str ); 46 | } 47 | int globalFunctionReturningInt() 48 | { 49 | return Custom::voodooCall< int >( "Example::globalFunctionReturningInt" ); 50 | } 51 | std::string globalFunctionMoveReturn() 52 | { 53 | return std::move( Custom::voodooMoveCall< std::string >( "Example::globalFunctionMoveReturn" ) ); 54 | } 55 | 56 | } 57 | 58 | #include "Example/UnderTest.h" 59 | 60 | using namespace Example; 61 | 62 | class Test_Example: public CxxTest::TestSuite 63 | { 64 | public: 65 | void test_TemplateClassCanBeMocked() 66 | { 67 | UnderTest tested; 68 | 69 | Scenario scenario; 70 | scenario << 71 | new Construction< MockMe >( "Fake MockMe" ) << 72 | new EqualsValue< int >( 8 ) << 73 | new CallReturnVoid( "Fake MockMe::justASimpleVoidMethod" ) << 74 | new EqualsValue< int >( 1 ) << 75 | new StringEquals( "yada" ) << 76 | new CallReturnValue< int >( "Fake MockMe::returnsAnInt", 100 ) << 77 | new CallMoveValue< std::unique_ptr< int > >( "Fake MockMe::returnsAUniquePtr", 78 | std::unique_ptr< int >( new int ) ) << 79 | new CallReturnVoid( "Example::globalFunction" ) << 80 | new StringEquals( "yada" ) << 81 | new CallReturnValue< int >( "Example::globalFunctionReturningInt", 19 ) << 82 | new CallMoveValue< std::string >( "Example::globalFunctionMoveReturn", std::string( "yep" ) ) << 83 | new Destruction( "Fake MockMe" ); 84 | tested.underTest(); 85 | scenario.assertFinished(); 86 | } 87 | }; 88 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/deriving_a_mocked_interface/Makefile: -------------------------------------------------------------------------------- 1 | all: test 2 | 3 | ifeq ($(V),1) 4 | Q = 5 | else 6 | Q = @ 7 | endif 8 | 9 | export VOODOO_ROOT_DIR=../../.. 10 | export CXXTEST_FIND_ROOT = cpp 11 | export ENFORCE_COVERAGE_FIND_ROOT_CPP = cpp 12 | export UNITTEST_INCLUDES = -Ibuild_unittest/voodoo/cpp -Icpp -I. 13 | export VOODOO_INCLUDES = --includePath=cpp 14 | 15 | clean: clean_unittest 16 | 17 | include $(VOODOO_ROOT_DIR)/make/integrations/complete.Makefile 18 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/deriving_a_mocked_interface/cpp/Example/SomeInterface.h: -------------------------------------------------------------------------------- 1 | #ifndef __EXAMPLE_SOME_INTERFACE_H_ 2 | #define __EXAMPLE_SOME_INTERFACE_H_ 3 | 4 | namespace Example 5 | { 6 | 7 | class SomeInterface 8 | { 9 | public: 10 | virtual ~SomeInterface(){} 11 | 12 | virtual void doSomething( int i ) = 0; 13 | }; 14 | 15 | } // namespace Example 16 | 17 | #endif // __EXAMPLE_SOME_INTERFACE_H_ 18 | // FILE_EXEMPT_FROM_CODE_COVERAGE 19 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/deriving_a_mocked_interface/cpp/Example/UnderTest.h: -------------------------------------------------------------------------------- 1 | #ifndef __EXAMPLE_UNDER_TEST_H__ 2 | #define __EXAMPLE_UNDER_TEST_H__ 3 | 4 | #include "Example/SomeInterface.h" 5 | 6 | namespace Example 7 | { 8 | 9 | class UnderTest : public SomeInterface 10 | { 11 | public: 12 | UnderTest( SomeInterface * ptr ) : _ptr( ptr ) {} 13 | 14 | void doSomething( int i ) override 15 | { 16 | _ptr->doSomething( i + 1 ); 17 | } 18 | 19 | private: 20 | 21 | UnderTest( const UnderTest & rhs ) = delete; 22 | UnderTest & operator= ( const UnderTest & rhs ) = delete; 23 | 24 | SomeInterface * _ptr; 25 | }; 26 | 27 | } // namespace Example 28 | 29 | #endif // __EXAMPLE_UNDER_TEST_H__ 30 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/deriving_a_mocked_interface/cpp/Example/tests/Test_UnderTest.h: -------------------------------------------------------------------------------- 1 | #include 2 | #define VOODOO_EXPECT_cpp_Example_SomeInterface_h 3 | 4 | #include "Example/SomeInterface.h" 5 | #include "Example/UnderTest.h" 6 | 7 | using namespace VoodooCommon::Expect; 8 | using namespace VoodooCommon::Expect::Parameter; 9 | using namespace Example; 10 | 11 | class Test_Example: public CxxTest::TestSuite 12 | { 13 | public: 14 | SomeInterface * _fakeInterface; 15 | UnderTest * _underTest; 16 | 17 | void setUp() 18 | { 19 | _fakeInterface = new FakeND_SomeInterface( "someInterface" ); 20 | Scenario scenario; 21 | scenario << 22 | new Construction< SomeInterface >( "Parent" ); 23 | _underTest = new UnderTest( _fakeInterface ); 24 | scenario.assertFinished(); 25 | } 26 | 27 | void tearDown() 28 | { 29 | Scenario scenario; 30 | scenario << 31 | new Destruction( "Parent" ); 32 | delete _underTest; 33 | scenario.assertFinished(); 34 | delete _fakeInterface; 35 | } 36 | 37 | void test_TemplateMethodCanBeMocked() 38 | { 39 | int someNum = 9; 40 | Scenario scenario; 41 | scenario << 42 | new CallReturnVoid( "someInterface::doSomething" ) << 43 | new EqualsValue< int > ( someNum + 1 ); 44 | _underTest->doSomething( someNum ); 45 | scenario.assertFinished(); 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/expectation_based_mock_objects/Makefile: -------------------------------------------------------------------------------- 1 | all: test 2 | 3 | ifeq ($(V),1) 4 | Q = 5 | else 6 | Q = @ 7 | endif 8 | 9 | export VOODOO_ROOT_DIR=../../.. 10 | export CXXTEST_FIND_ROOT = cpp 11 | export ENFORCE_COVERAGE_FIND_ROOT_CPP = cpp 12 | export UNITTEST_INCLUDES = -Ibuild_unittest/voodoo/cpp -Icpp -I. 13 | export VOODOO_INCLUDES = --includePath=cpp 14 | 15 | clean: clean_unittest 16 | 17 | include $(VOODOO_ROOT_DIR)/make/integrations/complete.Makefile 18 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/expectation_based_mock_objects/cpp/Example/Data.h: -------------------------------------------------------------------------------- 1 | #ifndef __DATA_H_ 2 | #define __DATA_H_ 3 | 4 | struct Data 5 | { 6 | unsigned a; 7 | unsigned b; 8 | }; 9 | 10 | class DoItInterface 11 | { 12 | public: 13 | virtual ~DoItInterface() {} 14 | virtual void doIt() = 0; 15 | }; 16 | 17 | struct MoveableCtorData 18 | { 19 | MoveableCtorData( unsigned aa ) : a( aa ) {} 20 | MoveableCtorData( MoveableCtorData && o ) : a( std::move( o.a ) ) {} 21 | 22 | unsigned a; 23 | }; 24 | 25 | struct MoveableData 26 | { 27 | MoveableData( unsigned aa ) : a( aa ) {} 28 | MoveableData( MoveableData && o ) : a( std::move( o.a ) ) {} 29 | 30 | MoveableData & operator=( MoveableData && o ) { a = std::move( o.a ); return *this; } 31 | 32 | unsigned a; 33 | }; 34 | 35 | #endif // __DATA_H_ 36 | // FILE_EXEMPT_FROM_CODE_COVERAGE 37 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/expectation_based_mock_objects/cpp/Example/Mocked.h: -------------------------------------------------------------------------------- 1 | #ifndef __MOCKED_H__ 2 | #define __MOCKED_H__ 3 | 4 | #include "Data.h" 5 | #include 6 | 7 | struct AMockedStruct {}; 8 | 9 | struct StructWithTemplateConstructor 10 | { 11 | template< typename T > 12 | StructWithTemplateConstructor( T i ); 13 | }; 14 | 15 | void operateOnStruct( AMockedStruct & s ); 16 | void operateOnStructPtr( AMockedStruct * s ); 17 | void operateOnStructUniquePtr( std::unique_ptr< AMockedStruct > s ); 18 | void clear( Data & data ); 19 | void setInterval( unsigned interval ); 20 | void logMessage( const char * message ); 21 | void giveData( struct Data & data ); 22 | void doMoveData( MoveableData data ); 23 | void doMoveData( MoveableCtorData data ); 24 | void setCallback( DoItInterface & interface ); 25 | void setCallback( DoItInterface * interface ); 26 | void returnValueByReferenceOutParamter( unsigned & out ); 27 | void returnValueByPointerOutParamter( unsigned * out ); 28 | 29 | class ClassWithIgnoredParameterPack 30 | { 31 | public: 32 | template< typename... ARGS > 33 | ClassWithIgnoredParameterPack( float f, ARGS... args ); 34 | 35 | template< typename... ARGS > 36 | void someOperation( int n, ARGS... args ); 37 | }; 38 | 39 | class ClassWithParameterPack 40 | { 41 | public: 42 | template< typename... ARGS > 43 | ClassWithParameterPack( float f, ARGS... args ); 44 | 45 | template< typename... ARGS > 46 | void someOperation( int n, ARGS... args ); 47 | }; 48 | 49 | #endif // __MOCKED_H__ 50 | // FILE_EXEMPT_FROM_CODE_COVERAGE 51 | /*VOODOO_PERFILESETTINGS IGNORE_PARAMETER_PACK.append( 'ClassWithIgnoredParameterPack::someOperation' ) */ 52 | /*VOODOO_PERFILESETTINGS IGNORE_PARAMETER_PACK.append( 'ClassWithIgnoredParameterPack::ClassWithIgnoredParameterPack' ) */ 53 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/expectation_based_mock_objects/cpp/Example/UnderTest.h: -------------------------------------------------------------------------------- 1 | #ifndef __UNDERTEST_H_ 2 | #define __UNDERTEST_H_ 3 | 4 | #include "Mocked.h" 5 | #include 6 | 7 | void setDefaultInterval() 8 | { 9 | setInterval( 4 ); 10 | } 11 | 12 | void setHighInterval() 13 | { 14 | setInterval( 10 ); 15 | } 16 | 17 | void doSomething( AMockedStruct & s) 18 | { 19 | operateOnStruct( s ); 20 | } 21 | 22 | void doSomethingOnUniquePtr( std::unique_ptr< AMockedStruct > s) 23 | { 24 | operateOnStructUniquePtr( std::move( s ) ); 25 | } 26 | 27 | void doSomethingOnPtr( AMockedStruct * s) 28 | { 29 | operateOnStructPtr( s ); 30 | } 31 | 32 | void doSomethingOnIgnoredParameterPack( int n, float f, const char * str ) 33 | { 34 | ClassWithIgnoredParameterPack c { f, n, str }; 35 | c.someOperation( n, f, str ); 36 | } 37 | 38 | void doSomethingOnParameterPack( int n, float f, const char * str ) 39 | { 40 | ClassWithParameterPack c { f, n, str }; 41 | c.someOperation( n, f, str ); 42 | } 43 | 44 | void doubleClear( Data & data ) 45 | { 46 | clear( data ); 47 | clear( data ); 48 | } 49 | 50 | void copyAndClear( Data & data ) 51 | { 52 | Data copy( data ); 53 | clear( copy ); 54 | } 55 | 56 | void giveDataSwitched( struct Data data ) 57 | { 58 | unsigned temp = data.a; 59 | data.a = data.b; 60 | data.b = temp; 61 | giveData( data ); 62 | } 63 | 64 | template < typename T > 65 | void moveData( T data ) 66 | { 67 | doMoveData( std::move( data ) ); 68 | } 69 | 70 | void setCallbackByReference() 71 | { 72 | class DoIt : public DoItInterface 73 | { 74 | public: 75 | void doIt() { setInterval( 0 ); } 76 | }; 77 | 78 | static DoIt it; 79 | setCallback( it ); 80 | } 81 | 82 | void setCallbackByPointer() 83 | { 84 | class DoIt : public DoItInterface 85 | { 86 | public: 87 | void doIt() { setInterval( 1 ); } 88 | }; 89 | 90 | static DoIt it; 91 | setCallback( & it ); 92 | } 93 | 94 | unsigned outParameterToReturnValue() 95 | { 96 | unsigned result; 97 | returnValueByReferenceOutParamter( result ); 98 | return result; 99 | } 100 | 101 | unsigned outPointerParameterToReturnValue() 102 | { 103 | unsigned result; 104 | returnValueByPointerOutParamter( & result ); 105 | return result; 106 | } 107 | 108 | void markLog() 109 | { 110 | logMessage( "MARK" ); 111 | } 112 | 113 | void createWithTemplateConstructor( int n ) 114 | { 115 | StructWithTemplateConstructor c { n }; 116 | } 117 | 118 | #endif // __UNDERTEST_H_ 119 | // FILE_EXEMPT_FROM_CODE_COVERAGE 120 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/mocking_template_classes/Makefile: -------------------------------------------------------------------------------- 1 | all: test 2 | 3 | ifeq ($(V),1) 4 | Q = 5 | else 6 | Q = @ 7 | endif 8 | 9 | export VOODOO_ROOT_DIR=../../.. 10 | export CXXTEST_FIND_ROOT = cpp 11 | export ENFORCE_COVERAGE_FIND_ROOT_CPP = cpp 12 | export UNITTEST_INCLUDES = -Ibuild_unittest/voodoo/cpp -Icpp -I. 13 | export VOODOO_INCLUDES = --includePath=cpp 14 | 15 | clean: clean_unittest 16 | 17 | include $(VOODOO_ROOT_DIR)/make/integrations/complete.Makefile 18 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/mocking_template_classes/cpp/Common/Debug.h: -------------------------------------------------------------------------------- 1 | #ifndef __COMMON_DEBUG_CPP_H__ 2 | #define __COMMON_DEBUG_CPP_H__ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #ifdef UNITTEST 11 | 12 | //Under unittest: assert fails the test 13 | # define _ASSERT( __condition, __serialize ) do { \ 14 | if ( ! ( __condition ) ) { \ 15 | std::ostringstream __message; \ 16 | __message << __serialize; \ 17 | TS_FAIL( __message.str() ); \ 18 | } \ 19 | } while( 0 ) 20 | 21 | #else // UNITTEST 22 | 23 | # ifdef DEBUG 24 | 25 | //Under debug build: assert exists immidiately 26 | # define _ASSERT( __condition, __serialize ) do { \ 27 | if ( ! ( __condition ) ) { \ 28 | _TRACE( "ASSERT", "Assertion '" #__condition "' failed (" << __FILE__ << ':' << \ 29 | __LINE__ << ')' << __serialize << "\nCommiting suicide\n", std::cerr ); \ 30 | _exit( 1 ); \ 31 | } \ 32 | } while( 0 ) 33 | # define TRACE_DEVEL( __serialize ) _TRACE( "DEVEL", __serialize, std::cerr ) 34 | 35 | # else //DEBUG 36 | 37 | //Under release build: assert does not compile 38 | # define _ASSERT( __condition, __serialize ) do {} while( 0 ) 39 | # define TRACE_DEVEL( __serialize ) please_dont_leave_TRACE_DEVEL_messages_lying_around 40 | 41 | # endif // DEBUG 42 | #endif // UNITTEST 43 | 44 | # define _TRACE( __level, __serialize, __stream ) do { \ 45 | struct timeval timeValue; \ 46 | gettimeofday( & timeValue, nullptr ); \ 47 | __stream << timeValue.tv_sec << '.' << std::setfill( '0' ) << std::setw( 6 ) << timeValue.tv_usec << ':' << \ 48 | __level << ':' << ' ' << __serialize << ' ' << '(' << __FILE__ << ':' << __LINE__ << \ 49 | ')' << std::endl; \ 50 | } while( 0 ) 51 | 52 | #define TRACE_INFO( __serialize ) _TRACE( "INFO", __serialize, std::cout ) 53 | #define TRACE_WARNING( __serialize ) _TRACE( "WARNING", __serialize, std::cerr ) 54 | #define TRACE_ERROR( __serialize ) _TRACE( "ERROR", __serialize, std::cerr ) 55 | #define TRACE_EXCEPTION( __e, __serialize ) _TRACE( "EXCEPTION", "Exception: " << __e.what() << ": " << __serialize, std::cerr ) 56 | #define ASSERT( __x ) _ASSERT( __x, "" ) 57 | #define ASSERT_VERBOSE( __x, __serialize ) _ASSERT( __x, ": " << __serialize ) 58 | 59 | #endif // __COMMON_DEBUG_H__ 60 | //FILE_EXEMPT_FROM_CODE_COVERAGE 61 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/mocking_template_classes/cpp/Common/MyError.h: -------------------------------------------------------------------------------- 1 | #ifndef __COMMON_MY_ERROR_H__ 2 | #define __COMMON_MY_ERROR_H__ 3 | 4 | #include 5 | #include 6 | 7 | class MyError : public std::runtime_error 8 | { 9 | public: 10 | MyError( const std::string & what, const char * filename, unsigned line ) : 11 | std::runtime_error( what ), 12 | filename( filename ), 13 | line( line ) 14 | {} 15 | 16 | const char * const filename; 17 | const unsigned line; 18 | }; 19 | 20 | #define EXCEPTION_SUBCLASS( name, superclass ) \ 21 | class name : public superclass \ 22 | { \ 23 | public: \ 24 | using ::MyError::MyError; \ 25 | } 26 | 27 | #define EXCEPTION_CLASS( name ) EXCEPTION_SUBCLASS( name, ::MyError ) 28 | 29 | #define THROW( name, serialize ) do { \ 30 | std::ostringstream __seralize; \ 31 | __seralize << serialize << \ 32 | " (" << __FILE__ << ':' << __LINE__ << ':' << \ 33 | __FUNCTION__ << ')'; \ 34 | throw name( __seralize.str(), __FILE__, __LINE__ ); \ 35 | } while( 0 ) 36 | 37 | #endif // __COMMON_MY_ERROR_H__ 38 | //FILE_EXEMPT_FROM_CODE_COVERAGE 39 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/mocking_template_classes/cpp/Example/MockMe.h: -------------------------------------------------------------------------------- 1 | #ifndef __EXAMPLE_MOCK_ME_H__ 2 | #define __EXAMPLE_MOCK_ME_H__ 3 | 4 | namespace Example 5 | { 6 | 7 | template < typename T > 8 | class Mockme; 9 | 10 | template < typename T > 11 | class MockMe 12 | { 13 | public: 14 | MockMe(){} 15 | 16 | T mockMe( T argument ) 17 | { 18 | return argument + argument; 19 | } 20 | 21 | private: 22 | 23 | MockMe( const MockMe & rhs ) = delete; 24 | MockMe & operator= ( const MockMe & rhs ) = delete; 25 | }; 26 | 27 | } // namespace Example 28 | 29 | #endif // __EXAMPLE_MOCK_ME_H__ 30 | //FILE_EXEMPT_FROM_CODE_COVERAGE 31 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/mocking_template_classes/cpp/Example/UnderTest.h: -------------------------------------------------------------------------------- 1 | #ifndef __EXAMPLE_UNDER_TEST_H__ 2 | #define __EXAMPLE_UNDER_TEST_H__ 3 | 4 | #include "Example/MockMe.h" 5 | 6 | namespace Example 7 | { 8 | 9 | class UnderTest 10 | { 11 | public: 12 | UnderTest(){} 13 | 14 | void underTest() 15 | { 16 | MockMe< int > mockMe; 17 | int result = mockMe.mockMe( 3 ); 18 | (void) result; 19 | } 20 | 21 | private: 22 | 23 | UnderTest( const UnderTest & rhs ) = delete; 24 | UnderTest & operator= ( const UnderTest & rhs ) = delete; 25 | }; 26 | 27 | } // namespace Example 28 | 29 | #endif // __EXAMPLE_UNDER_TEST_H__ 30 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/mocking_template_classes/cpp/Example/tests/Test_UnderTest.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define VOODOO_EXPECT_cpp_Example_MockMe_h 4 | 5 | #include "Example/UnderTest.h" 6 | 7 | using namespace VoodooCommon::Expect; 8 | using namespace VoodooCommon::Expect::Parameter; 9 | using namespace Example; 10 | 11 | class Test_Example: public CxxTest::TestSuite 12 | { 13 | public: 14 | void test_TemplateClassCanBeMocked() 15 | { 16 | UnderTest tested; 17 | 18 | Scenario scenario; 19 | scenario << 20 | new Construction< MockMe< int > >( "Fake MockMe" ) << 21 | new CallReturnValue< int >( "Fake MockMe::mockMe", 0 ) << 22 | new EqualsValue< int >( 3 ) << 23 | new Destruction( "Fake MockMe" ); 24 | tested.underTest(); 25 | scenario.assertFinished(); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/mocking_template_methods/Makefile: -------------------------------------------------------------------------------- 1 | all: test 2 | 3 | ifeq ($(V),1) 4 | Q = 5 | else 6 | Q = @ 7 | endif 8 | 9 | export VOODOO_ROOT_DIR=../../.. 10 | export CXXTEST_FIND_ROOT = cpp 11 | export ENFORCE_COVERAGE_FIND_ROOT_CPP = cpp 12 | export UNITTEST_INCLUDES = -Ibuild_unittest/voodoo/cpp -Icpp -I. 13 | export VOODOO_INCLUDES = --includePath=cpp 14 | 15 | clean: clean_unittest 16 | 17 | include $(VOODOO_ROOT_DIR)/make/integrations/complete.Makefile 18 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/mocking_template_methods/cpp/Common/Debug.h: -------------------------------------------------------------------------------- 1 | #ifndef __COMMON_DEBUG_CPP_H__ 2 | #define __COMMON_DEBUG_CPP_H__ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #ifdef UNITTEST 11 | 12 | //Under unittest: assert fails the test 13 | # define _ASSERT( __condition, __serialize ) do { \ 14 | if ( ! ( __condition ) ) { \ 15 | std::ostringstream __message; \ 16 | __message << __serialize; \ 17 | TS_FAIL( __message.str() ); \ 18 | } \ 19 | } while( 0 ) 20 | 21 | #else // UNITTEST 22 | 23 | # ifdef DEBUG 24 | 25 | //Under debug build: assert exists immidiately 26 | # define _ASSERT( __condition, __serialize ) do { \ 27 | if ( ! ( __condition ) ) { \ 28 | _TRACE( "ASSERT", "Assertion '" #__condition "' failed (" << __FILE__ << ':' << \ 29 | __LINE__ << ')' << __serialize << "\nCommiting suicide\n", std::cerr ); \ 30 | _exit( 1 ); \ 31 | } \ 32 | } while( 0 ) 33 | # define TRACE_DEVEL( __serialize ) _TRACE( "DEVEL", __serialize, std::cerr ) 34 | 35 | # else //DEBUG 36 | 37 | //Under release build: assert does not compile 38 | # define _ASSERT( __condition, __serialize ) do {} while( 0 ) 39 | # define TRACE_DEVEL( __serialize ) please_dont_leave_TRACE_DEVEL_messages_lying_around 40 | 41 | # endif // DEBUG 42 | #endif // UNITTEST 43 | 44 | # define _TRACE( __level, __serialize, __stream ) do { \ 45 | struct timeval timeValue; \ 46 | gettimeofday( & timeValue, nullptr ); \ 47 | __stream << timeValue.tv_sec << '.' << std::setfill( '0' ) << std::setw( 6 ) << timeValue.tv_usec << ':' << \ 48 | __level << ':' << ' ' << __serialize << ' ' << '(' << __FILE__ << ':' << __LINE__ << \ 49 | ')' << std::endl; \ 50 | } while( 0 ) 51 | 52 | #define TRACE_INFO( __serialize ) _TRACE( "INFO", __serialize, std::cout ) 53 | #define TRACE_WARNING( __serialize ) _TRACE( "WARNING", __serialize, std::cerr ) 54 | #define TRACE_ERROR( __serialize ) _TRACE( "ERROR", __serialize, std::cerr ) 55 | #define TRACE_EXCEPTION( __e, __serialize ) _TRACE( "EXCEPTION", "Exception: " << __e.what() << ": " << __serialize, std::cerr ) 56 | #define ASSERT( __x ) _ASSERT( __x, "" ) 57 | #define ASSERT_VERBOSE( __x, __serialize ) _ASSERT( __x, ": " << __serialize ) 58 | 59 | #endif // __COMMON_DEBUG_H__ 60 | //FILE_EXEMPT_FROM_CODE_COVERAGE 61 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/mocking_template_methods/cpp/Common/MyError.h: -------------------------------------------------------------------------------- 1 | #ifndef __COMMON_MY_ERROR_H__ 2 | #define __COMMON_MY_ERROR_H__ 3 | 4 | #include 5 | #include 6 | 7 | class MyError : public std::runtime_error 8 | { 9 | public: 10 | MyError( const std::string & what, const char * filename, unsigned line ) : 11 | std::runtime_error( what ), 12 | filename( filename ), 13 | line( line ) 14 | {} 15 | 16 | const char * const filename; 17 | const unsigned line; 18 | }; 19 | 20 | #define EXCEPTION_SUBCLASS( name, superclass ) \ 21 | class name : public superclass \ 22 | { \ 23 | public: \ 24 | using ::MyError::MyError; \ 25 | } 26 | 27 | #define EXCEPTION_CLASS( name ) EXCEPTION_SUBCLASS( name, ::MyError ) 28 | 29 | #define THROW( name, serialize ) do { \ 30 | std::ostringstream __seralize; \ 31 | __seralize << serialize << \ 32 | " (" << __FILE__ << ':' << __LINE__ << ':' << \ 33 | __FUNCTION__ << ')'; \ 34 | throw name( __seralize.str(), __FILE__, __LINE__ ); \ 35 | } while( 0 ) 36 | 37 | #endif // __COMMON_MY_ERROR_H__ 38 | //FILE_EXEMPT_FROM_CODE_COVERAGE 39 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/mocking_template_methods/cpp/Example/MockMe.h: -------------------------------------------------------------------------------- 1 | #ifndef __EXAMPLE_MOCK_ME_H__ 2 | #define __EXAMPLE_MOCK_ME_H__ 3 | 4 | #include 5 | 6 | namespace Example 7 | { 8 | 9 | class MockMe 10 | { 11 | public: 12 | MockMe(){} 13 | 14 | template < typename T > 15 | void mockMe( std::unique_ptr< T > & argument ) 16 | { 17 | } 18 | 19 | private: 20 | 21 | MockMe( const MockMe & rhs ) = delete; 22 | MockMe & operator= ( const MockMe & rhs ) = delete; 23 | }; 24 | 25 | } // namespace Example 26 | 27 | #endif // __EXAMPLE_MOCK_ME_H__ 28 | //FILE_EXEMPT_FROM_CODE_COVERAGE 29 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/mocking_template_methods/cpp/Example/UnderTest.h: -------------------------------------------------------------------------------- 1 | #ifndef __EXAMPLE_UNDER_TEST_H__ 2 | #define __EXAMPLE_UNDER_TEST_H__ 3 | 4 | #include "Example/MockMe.h" 5 | 6 | namespace Example 7 | { 8 | 9 | class UnderTest 10 | { 11 | public: 12 | UnderTest(){} 13 | 14 | void underTest() 15 | { 16 | std::unique_ptr< int > input( new int ); 17 | MockMe mockMe; 18 | mockMe.mockMe( input ); 19 | } 20 | 21 | private: 22 | 23 | UnderTest( const UnderTest & rhs ) = delete; 24 | UnderTest & operator= ( const UnderTest & rhs ) = delete; 25 | }; 26 | 27 | } // namespace Example 28 | 29 | #endif // __EXAMPLE_UNDER_TEST_H__ 30 | -------------------------------------------------------------------------------- /examples/3_writing_cpp_tests/mocking_template_methods/cpp/Example/tests/Test_UnderTest.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define VOODOO_EXPECT_cpp_Example_MockMe_h 4 | 5 | #include "Example/UnderTest.h" 6 | 7 | using namespace VoodooCommon::Expect; 8 | using namespace VoodooCommon::Expect::Parameter; 9 | using namespace Example; 10 | 11 | class Test_Example: public CxxTest::TestSuite 12 | { 13 | public: 14 | void test_TemplateMethodCanBeMocked() 15 | { 16 | UnderTest tested; 17 | 18 | Scenario scenario; 19 | scenario << 20 | new Construction< MockMe >( "Fake MockMe" ) << 21 | new CallReturnVoid( "Fake MockMe::mockMe" ) << 22 | new Ignore< std::unique_ptr< int > >() << 23 | new Destruction( "Fake MockMe" ); 24 | tested.underTest(); 25 | scenario.assertFinished(); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /examples/6_coverage_enforcement/Makefile: -------------------------------------------------------------------------------- 1 | all: 2 | mkdir -p build_unittest 3 | make -f undertest.Makefile 2>&1 > build_unittest/undertest.log || true 4 | cat build_unittest/undertest.log | grep 'cpp[/\\]FileNotCovered.h:1: COVERAGE ERROR: file is not covered by unit test' 5 | cat build_unittest/undertest.log | grep 'cpp[/\\]ToCover.h:22: COVERAGE ERROR: line is not covered by unit test' 6 | cat build_unittest/undertest.log | grep 'cpp[/\\]ToCover.h:33: COVERAGE ERROR: line is not covered by unit test' 7 | cat build_unittest/undertest.log | grep 'cpp[/\\]ToCover.h:34: COVERAGE ERROR: line is not covered by unit test' 8 | cat build_unittest/undertest.log | grep 'cpp[/\\]ToCover.h:20: COVERAGE_WARNING: non code line marked as exempt' 9 | test `cat build_unittest/undertest.log | grep COVERAGE.ERROR | wc -l` -eq 4 10 | test `cat build_unittest/undertest.log | grep COVERAGE.WARNING | wc -l` -eq 1 11 | 12 | clean: 13 | rm -fr build_unittest 14 | -------------------------------------------------------------------------------- /examples/6_coverage_enforcement/cpp/FileNotCovered.h: -------------------------------------------------------------------------------- 1 | #ifndef __FILE_NOT_COVERED_H__ 2 | #define __FILE_NOT_COVERED_H__ 3 | 4 | // This file does not have a single line of code, and is not exempt, should raise 5 | // file not covered coverage error 6 | 7 | #endif // __FILE_NOT_COVERED_H__ 8 | -------------------------------------------------------------------------------- /examples/6_coverage_enforcement/cpp/SemiCoveredExemptFile.h: -------------------------------------------------------------------------------- 1 | #ifndef __SEMI_COVERED_EXEMPT_FILE_H__ 2 | #define __SEMI_COVERED_EXEMPT_FILE_H__ 3 | 4 | int semiCoveredFunction( int i ) 5 | { 6 | if ( i == 123456 ) 7 | i -= 1; // not covered, but it's ok since the file is exempt 8 | return i; 9 | } 10 | 11 | #endif // __SEMI_COVERED_EXEMPT_FILE_H__ 12 | //FILE_EXEMPT_FROM_CODE_COVERAGE 13 | -------------------------------------------------------------------------------- /examples/6_coverage_enforcement/cpp/ToCover.h: -------------------------------------------------------------------------------- 1 | #ifndef __TO_COVER_H__ 2 | #define __TO_COVER_H__ 3 | 4 | #include "SemiCoveredExemptFile.h" 5 | #include 6 | #include 7 | 8 | void throwExceptionFunction() 9 | { 10 | throw std::runtime_error( "Some error" ); 11 | } 12 | 13 | template < typename T > 14 | void aFunction( T input ) 15 | { 16 | input += 1; // covered line 17 | if ( input == 1000000 ) 18 | input -= 1; // LINE_EXEMPT_FROM_CODE_COVERAGE 19 | // the next line is not a code line, but the EXCEPT comment will report misuse of the whitelisting 20 | // LINE_EXEMPT_FROM_CODE_COVERAGE 21 | if ( input == 10 ) 22 | input -= 2; // this line is not covered therefore its a coverage error 23 | semiCoveredFunction( 10 ); 24 | try { 25 | throwExceptionFunction(); 26 | } 27 | catch ( std::runtime_error ) { 28 | input += 4; 29 | } 30 | catch ( std::exception ) { // LINE_EXEMPT_FROM_CODE_COVERAGE 31 | printf("hello\n"); // LINE_EXEMPT_FROM_CODE_COVERAGE 32 | } 33 | catch ( ... ) { // this line is not covered therefore its a coverage error 34 | printf("hello again\n"); // this line is not covered therefore its a coverage error 35 | } 36 | } 37 | 38 | void anotherFunction() 39 | { 40 | } 41 | 42 | #endif // __TO_COVER_H__ 43 | -------------------------------------------------------------------------------- /examples/6_coverage_enforcement/cpp/tests/Test_CoverageErrors.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "ToCover.h" 4 | 5 | class Test_CoverageErrors: public CxxTest::TestSuite 6 | { 7 | public: 8 | void test_Coverage() 9 | { 10 | aFunction( 0 ); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /examples/6_coverage_enforcement/cpp/tests/Test_IncludesButDoesntCover_DoesNotIntefeareWithOtherTestSuitesThatDo.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "ToCover.h" 4 | 5 | class Test_CoverageErrors: public CxxTest::TestSuite 6 | { 7 | public: 8 | void test_DoesNothingButIncludeTheFile_EnforcementCodeDoesNotGetConfused() 9 | { 10 | TS_ASSERT_EQUALS( 1 + 1, 2 ); 11 | anotherFunction(); 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /examples/6_coverage_enforcement/undertest.Makefile: -------------------------------------------------------------------------------- 1 | all: test 2 | 3 | export CXXTEST_FIND_ROOT = cpp 4 | export ENFORCE_COVERAGE_FIND_ROOT_CPP = cpp 5 | export UNITTEST_INCLUDES = -Ibuild_unittest/voodoo/cpp -Ibuild_unittest/voodoo/c -Icpp -I. 6 | export VOODOO_INCLUDES = --includePath=cpp 7 | export VOODOO_ROOT_DIR = ../.. 8 | 9 | clean: clean_unittest 10 | rm -fr build 11 | 12 | include $(VOODOO_ROOT_DIR)/make/integrations/complete.Makefile 13 | -------------------------------------------------------------------------------- /examples/7_simple_python_unittest/Makefile: -------------------------------------------------------------------------------- 1 | all: test 2 | 3 | export VOODOO_ROOT_DIR = ../.. 4 | 5 | clean: 6 | rm -fr build_unittest build *.pyc 7 | 8 | test: 9 | $(MAKE) -f $(VOODOO_ROOT_DIR)/make/3_run.Makefile 10 | -------------------------------------------------------------------------------- /examples/7_simple_python_unittest/test_add_two_numbers.py: -------------------------------------------------------------------------------- 1 | from pytestsuite import * 2 | 3 | class TestCase(PyTestSuite): 4 | def test_add_two_numbers(self): 5 | TS_ASSERT_EQUALS(1+1, 2) 6 | -------------------------------------------------------------------------------- /examples/7_simple_python_unittest/test_add_two_numbers_newstyleclass.py: -------------------------------------------------------------------------------- 1 | from pytestsuite import * 2 | 3 | class OtherTestingSuite(object): 4 | pass 5 | 6 | class TestCase(PyTestSuite, OtherTestingSuite): 7 | def test_add_two_numbers(self): 8 | TS_ASSERT_EQUALS(1+1, 2) 9 | -------------------------------------------------------------------------------- /make/1_generate.Makefile: -------------------------------------------------------------------------------- 1 | generateTests: generateCxxtest generateVoodoo 2 | 3 | include $(VOODOO_ROOT_DIR)/make/common.Makefile 4 | 5 | VOODOO_SCAN_HEADERS_ROOTS ?= . 6 | VOODOO_MULTI_EXCLUDES ?= "\btests\b" 7 | VOODOO_FLAGS ?= --define=DEBUG --define=BOOST_ASIO_HAS_MOVE 8 | VOODOO_EXTERNALS_FLAGS ?= 9 | VOODOO_INCLUDES ?= --includePath=. 10 | 11 | __VOODOO_ENVIRONMENT = PYTHONPATH=$(VOODOO_ROOT_DIR)/voodoo LD_LIBRARY_PATH=$(VOODOO_ROOT_DIR)/voodoo:$(LD_LIBRARY_PATH) 12 | __VOODOO_MULTI_EXECUTABLE = $(__VOODOO_ENVIRONMENT) python '$(VOODOO_ROOT_DIR)/voodoo/multi.py' 13 | __VOODOO_MULTI_INPUT = $(addprefix --input=,$(VOODOO_SCAN_HEADERS_ROOTS)) 14 | __VOODOO_MULTI_EXCLUDES = $(addprefix --exclude=,$(VOODOO_MULTI_EXCLUDES) '\b$(UNITTEST_BUILD_DIRECTORY)\b') 15 | __VOODOO_SINGLE_EXECUTABLE = $(__VOODOO_ENVIRONMENT) python '$(VOODOO_ROOT_DIR)/voodoo/single.py' 16 | __VOODOO_FLAGS = $(VOODOO_FLAGS) --voodooDB=$(UNITTEST_BUILD_DIRECTORY)/voodooDB.tmp $(VOODOO_INCLUDES) 17 | 18 | $(if $(filter-out %.cxx,$(CXXTEST_GENERATED)),\ 19 | $(error "Unfamiliar extension for test suite files. Supported:" $(__POSSIBLE_UNITTEST_SUFFIXES))) 20 | 21 | define template_per_TEST_FILE 22 | template_per_TEST_FILE_cxx = $$(filter %.cxx,$$(foreach suffix,$(__POSSIBLE_UNITTEST_SUFFIXES),$$(patsubst %$$(suffix),$(UNITTEST_BUILD_DIRECTORY)/%.cxx,$$(subst /,_,$(1))))) 23 | generateCxxtest: $$(template_per_TEST_FILE_cxx) 24 | $$(template_per_TEST_FILE_cxx): $(1) 25 | endef 26 | $(foreach testFile,$(CXXTEST_TEST_FILES), $(eval $(call template_per_TEST_FILE,$(testFile))) ) 27 | 28 | generateCxxtest: $(CXXTEST_GENERATED) 29 | 30 | generateVoodoo: 31 | @echo "Generating voodoo mirror tree" 32 | -@mkdir --parents $(VOODOO_MIRROR_TREE) 33 | $(Q)$(__VOODOO_MULTI_EXECUTABLE) $(__VOODOO_MULTI_INPUT) --output=$(VOODOO_MIRROR_TREE) --concurrent $(__VOODOO_FLAGS) $(__VOODOO_MULTI_EXCLUDES) --onlyIfNew 34 | 35 | #TODO: missing force external headers 36 | generateVoodooForce: 37 | @echo "Force Generating voodoo mirror tree" 38 | -@mkdir --parents $(VOODOO_MIRROR_TREE) 39 | $(Q)$(__VOODOO_MUTLI_EXECUTABLE) $(__VOODOO_MULTI_INPUT) --output=$(VOODOO_MIRROR_TREE) --concurrent $(__VOODOO_FLAGS) $(__VOODOO_MULTI_EXCLUDES) 40 | 41 | generateSingleVoodoo: 42 | $(Q)$(__VOODOO_SINGLE_EXECUTABLE) --input=$(SINGLE_HEADER) --output=/tmp/t.h $(__VOODOO_FLAGS) 43 | 44 | $(VOODOO_MIRROR_TREE)/%.h: 45 | @mkdir -p $(@D) 46 | @echo 'VOODOOEX' $@ 47 | $(Q)$(__VOODOO_SINGLE_EXECUTABLE) --input=$< --output=$@ $(__VOODOO_FLAGS) $(VOODOO_EXTERNALS_FLAGS) 48 | 49 | $(UNITTEST_BUILD_DIRECTORY)/%.cxx: 50 | -$(Q)mkdir --parents $(@D) 51 | @echo 'CXXTSTGN' $@ 52 | $(Q)python $(VOODOO_ROOT_DIR)/cxxtest/simplecxxtestgen.py --output=$@ --input=$< 53 | -------------------------------------------------------------------------------- /make/2_build.Makefile: -------------------------------------------------------------------------------- 1 | buildTests: 2 | 3 | include $(VOODOO_ROOT_DIR)/make/common.Makefile 4 | 5 | UNITTEST_CXXFLAGS ?= -DDEBUG -DUNITTEST 6 | UNITTEST_INCLUDES ?= -I. 7 | UNITTEST_LDFLAGS ?= 8 | ifneq ($(OS),Windows_NT) 9 | UNITTEST_LIBS ?= -ldl 10 | endif 11 | 12 | UNITTEST_CXXFLAGS += -std=gnu++0x -Werror -Wall -ggdb -DDEBUG -DUNITTEST --coverage 13 | UNITTEST_LDFLAGS += --coverage 14 | __UNITTEST_INCLUDES = -I$(VOODOO_MIRROR_TREE) $(UNITTEST_INCLUDES) 15 | #NOTE: VOODOO_MIRROR_TREE must come first in include order, or interception magia will not work 16 | __UNITTEST_INCLUDES += -I$(VOODOO_ROOT_DIR)/voodoo -I$(VOODOO_ROOT_DIR)/cxxtest 17 | 18 | define template_per_TEST_FILE 19 | template_per_TEST_FILE_cxx = $$(addprefix $$(UNITTEST_BUILD_DIRECTORY)/,$$(addsuffix .cxx,$$(basename $$(subst /,_,$(1))))) 20 | template_per_TEST_FILE_bin = $$(patsubst %.cxx,%.bin,$$(template_per_TEST_FILE_cxx)) 21 | template_per_TEST_FILE_o_deps = $$(patsubst %.cxx,%.o.deps,$$(template_per_TEST_FILE_cxx)) 22 | buildTests: $$(template_per_TEST_FILE_bin) 23 | -include $$(template_per_TEST_FILE_o_deps) 24 | endef 25 | $(foreach testFile,$(CXXTEST_TEST_FILES), $(eval $(call template_per_TEST_FILE,$(testFile))) ) 26 | 27 | $(UNITTEST_BUILD_DIRECTORY)/%.o: $(UNITTEST_BUILD_DIRECTORY)/%.cxx 28 | $(Q)echo 'UnitC++ ' $@ 29 | $(Q)g++ $(__UNITTEST_INCLUDES) $(UNITTEST_CXXFLAGS) -MMD -MF $@.deps $< -c -o $@ 30 | 31 | $(UNITTEST_BUILD_DIRECTORY)/%.bin: $(UNITTEST_BUILD_DIRECTORY)/%.o 32 | $(Q)echo 'UnitLink' $@ 33 | $(Q)g++ $< -o $@ $(UNITTEST_LDFLAGS) $(UNITTEST_LIBS) 34 | #Crappy GCC bug: without two stage build, .gcno file created in current directory 35 | -------------------------------------------------------------------------------- /make/3_run.Makefile: -------------------------------------------------------------------------------- 1 | runUnittests: runAllTests 2 | 3 | include $(VOODOO_ROOT_DIR)/make/common.Makefile 4 | 5 | PYTESTHARNESS_FLAGS ?= --cacheFile=$(UNITTEST_BUILD_DIRECTORY)/testharnesscache.tmp --reportFile=$(UNITTEST_BUILD_DIRECTORY)/testharnessreport.json 6 | PYTEST_TEST_FILES = $(shell find $(PYTEST_FIND_PATTERN) $(__HIDE_FIND_ERRORS) $(__REMOVE_DOT_SLASH_PREFIX)) 7 | 8 | runAllTests: 9 | $(Q)echo "Running all tests" 10 | $(Q)rm -fr .coverage* 11 | $(Q)python $(VOODOO_ROOT_DIR)/pytest/pytestharness.py $(PYTESTHARNESS_FLAGS) $(CXXTEST_BINARIES) $(PYTEST_TEST_FILES) 12 | -------------------------------------------------------------------------------- /make/4_optional_enforce_cpp_coverage.Makefile: -------------------------------------------------------------------------------- 1 | enforceCPPCoverage: runEnforcement 2 | 3 | include $(VOODOO_ROOT_DIR)/make/common.Makefile 4 | 5 | ENFORCE_COVERAGE_CPP_SOURCE_FILES = $(shell find $(ENFORCE_COVERAGE_FIND_PATTERN_CPP) $(__HIDE_FIND_ERRORS) $(__REMOVE_DOT_SLASH_PREFIX)) 6 | 7 | runEnforcement: 8 | $(Q)python $(VOODOO_ROOT_DIR)/make/enforce_cpp_coverage.py $(CXXTEST_BINARIES) --enforceOn $(ENFORCE_COVERAGE_CPP_SOURCE_FILES) 9 | -------------------------------------------------------------------------------- /make/common.Makefile: -------------------------------------------------------------------------------- 1 | UNITTEST_BUILD_DIRECTORY ?= build_unittest 2 | CXXTEST_FIND_ROOT ?= 3 | CXXTEST_FIND_PATTERN ?= $(CXXTEST_FIND_ROOT) -name 'test_*.h' -or -name 'Test_*.h' 4 | PYTEST_FIND_ROOT ?= 5 | PYTEST_FIND_PATTERN ?= $(PYTEST_FIND_ROOT) -name 'test_*.py' 6 | ENFORCE_COVERAGE_FIND_ROOT_CPP ?= 7 | ifeq ($(OS),Windows_NT) 8 | ENFORCE_COVERAGE_FIND_EXCLUDE_REGEXES ?= '.*\\<$(UNITTEST_BUILD_DIRECTORY)\\>/.*' '.*\\.*' '.*\\.*' 9 | else 10 | ENFORCE_COVERAGE_FIND_EXCLUDE_REGEXES ?= '.*\<$(UNITTEST_BUILD_DIRECTORY)\>/.*' '.*\.*' '.*\.*' 11 | endif 12 | ENFORCE_COVERAGE_FIND_PATTERN_CPP ?= $(ENFORCE_COVERAGE_FIND_ROOT_CPP) '(' -name '*.cpp' -or -name '*.h' ')' $(patsubst %,-and -not -regex %,$(ENFORCE_COVERAGE_FIND_EXCLUDE_REGEXES)) 13 | 14 | VOODOO_MIRROR_TREE ?= $(UNITTEST_BUILD_DIRECTORY)/voodoo 15 | 16 | __REMOVE_DOT_SLASH_PREFIX = | sed 's@^\./@@' 17 | __HIDE_FIND_ERRORS = 2>/dev/null 18 | __POSSIBLE_UNITTEST_SUFFIXES = .h .H .hh .HH .hxx .HXX .hpp .HPP 19 | CXXTEST_TEST_FILES = $(shell find $(CXXTEST_FIND_PATTERN) $(__HIDE_FIND_ERRORS) $(__REMOVE_DOT_SLASH_PREFIX)) 20 | CXXTEST_GENERATED = $(filter %.cxx,$(foreach suffix,$(__POSSIBLE_UNITTEST_SUFFIXES),$(patsubst %$(suffix),$(UNITTEST_BUILD_DIRECTORY)/%.cxx,$(subst /,_,$(CXXTEST_TEST_FILES))))) 21 | CXXTEST_BINARIES = $(patsubst %.cxx,%.bin,$(CXXTEST_GENERATED)) 22 | 23 | ifeq ($(V),1) 24 | Q = 25 | else 26 | Q = @ 27 | endif 28 | -------------------------------------------------------------------------------- /make/integrations/complete.Makefile: -------------------------------------------------------------------------------- 1 | include $(VOODOO_ROOT_DIR)/make/integrations/most.Makefile 2 | 3 | test: test_all 4 | -------------------------------------------------------------------------------- /make/integrations/most.Makefile: -------------------------------------------------------------------------------- 1 | ifeq ($(V),1) 2 | Q = 3 | else 4 | Q = @ 5 | endif 6 | 7 | clean_unittest: 8 | rm -fr build_unittest coverage 9 | 10 | test_all: 11 | $(MAKE) -f $(VOODOO_ROOT_DIR)/make/1_generate.Makefile 12 | $(MAKE) -f $(VOODOO_ROOT_DIR)/make/2_build.Makefile 13 | $(MAKE) -f $(VOODOO_ROOT_DIR)/make/3_run.Makefile 14 | $(MAKE) -f $(VOODOO_ROOT_DIR)/make/4_optional_enforce_cpp_coverage.Makefile 15 | 16 | test_allPython: 17 | $(MAKE) -f $(VOODOO_ROOT_DIR)/make/3_run.Makefile 18 | 19 | __SINGLE_TEST_SUITE_PYTHON = $(filter-out %.py,$(SINGLE_TEST_SUITE)) 20 | 21 | test_singletest: 22 | $(Q)echo "Running single test $(SINGLE_TEST_SUITE) Line/Name $(REGEX_OR_LINE_NUMBER)" 23 | $(Q)[ "$(SINGLE_TEST_SUITE)" ] || echo 'You must specify "SINGLE_TEST_SUITE="' 24 | $(Q)[ "$(SINGLE_TEST_SUITE)" ] 25 | $(MAKE) -f $(VOODOO_ROOT_DIR)/make/1_generate.Makefile 26 | test -z '$(__SINGLE_TEST_SUITE_PYTHON)' || $(MAKE) -f $(VOODOO_ROOT_DIR)/make/2_build.Makefile CXXTEST_FIND_PATTERN=$(SINGLE_TEST_SUITE) 27 | $(Q)$(VOODOO_ROOT_DIR)/make/runsingletest.sh $(SINGLE_TEST_SUITE) $(REGEX_OR_LINE_NUMBER) 28 | 29 | test_singletestsuite: 30 | $(Q)echo "Running single test suite $(SINGLE_TEST_SUITE)" 31 | $(Q)[ "$(SINGLE_TEST_SUITE)" ] || echo 'You must specify "SINGLE_TEST_SUITE="' 32 | $(Q)[ "$(SINGLE_TEST_SUITE)" ] 33 | $(MAKE) -f $(VOODOO_ROOT_DIR)/make/1_generate.Makefile 34 | test -z '$(__SINGLE_TEST_SUITE_PYTHON)' || $(MAKE) -f $(VOODOO_ROOT_DIR)/make/2_build.Makefile CXXTEST_FIND_PATTERN=$(SINGLE_TEST_SUITE) 35 | $(Q)$(VOODOO_ROOT_DIR)/make/runsingletestsuite.sh $(SINGLE_TEST_SUITE) 36 | 37 | voodoo_compileSingleHeader: 38 | $(MAKE) -f $(VOODOO_ROOT_DIR)/make/1_generate.Makefile generateSingleVoodoo 39 | 40 | voodoo_forceGenerateAll: 41 | $(MAKE) -f $(VOODOO_ROOT_DIR)/make/1_generate.Makefile generateVoodooForce 42 | -------------------------------------------------------------------------------- /make/runsingletest.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | SUITE=$1 3 | REGEX_OR_LINE_NUMBER=$2 4 | 5 | function isPython { 6 | echo $SUITE | grep '\.py$' > /dev/null 7 | } 8 | function isCxxTest { 9 | echo $SUITE | grep 'Test_.*\.[hH].\?.\?$' > /dev/null 10 | } 11 | 12 | if isPython $SUITE; then 13 | TEST_NAME=`python $VOODOO_ROOT_DIR/pytest/findtestname.py $SUITE $REGEX_OR_LINE_NUMBER` 14 | python $VOODOO_ROOT_DIR/pytest/pytestrunner.py --verbose --singleTest=$TEST_NAME $SUITE 15 | else 16 | if [ ! isCxxTest ]; then 17 | echo "$SUITE was not recognized as niether python test suite or CxxTest suite files" 18 | exit 1 19 | fi 20 | TEST_NAME=`python $VOODOO_ROOT_DIR/pytest/findtestname.py $SUITE $REGEX_OR_LINE_NUMBER` 21 | NO_EXT=`echo $SUITE | sed 's@\.[hH].\?.\?$@@'` 22 | NO_EXT_UNDERSCORE=`echo $NO_EXT | sed 's@/@_@g'` 23 | BIN=build_unittest/${NO_EXT_UNDERSCORE}.bin 24 | $BIN $TEST_NAME 25 | fi 26 | -------------------------------------------------------------------------------- /make/runsingletestsuite.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | SUITE=$1 3 | 4 | function isPython { 5 | echo $SUITE | grep '\.py$' > /dev/null 6 | } 7 | function isCxxTest { 8 | echo $SUITE | grep 'Test_.*\.[hH].\?.\?$' > /dev/null 9 | } 10 | 11 | if isPython $SUITE; then 12 | python $VOODOO_ROOT_DIR/pytest/pytestrunner.py --verbose $SUITE 13 | else 14 | if [ ! isCxxTest ]; then 15 | echo "$SUITE was not recognized as niether python test suite or CxxTest suite files" 16 | exit 1 17 | fi 18 | NO_EXT=`echo $SUITE | sed 's@\.[hH].\?.\?$@@'` 19 | NO_EXT_UNDERSCORE=`echo $NO_EXT | sed 's@/@_@g'` 20 | BIN=build_unittest/${NO_EXT_UNDERSCORE}.bin 21 | $BIN 22 | fi 23 | -------------------------------------------------------------------------------- /pytest/.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.swp 3 | *.tmp 4 | -------------------------------------------------------------------------------- /pytest/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shlomimatichin/Voodoo-Mock/02fc8c4f3029673fc1c16bc754577593a5d088c3/pytest/__init__.py -------------------------------------------------------------------------------- /pytest/findtestname.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import re 3 | 4 | PYTHON_TEST_METHOD_DEFINITION = re.compile( "\s+def\s+(test_\w+)\(" ) 5 | CPP_TEST_METHOD_DEFINITION = re.compile( "\s+void\s+(test_\w+)\(" ) 6 | 7 | filename = sys.argv[ 1 ] 8 | lineNumberOrRegex = sys.argv[ 2 ] 9 | 10 | try: 11 | lineNumber = int( sys.argv[ 2 ] ) - 1 12 | secondArgumentIsALineNumber = True 13 | except: 14 | secondArgumentIsALineNumber = False 15 | 16 | if secondArgumentIsALineNumber: 17 | lines = open( filename ).readlines() 18 | assert lineNumber < len(lines), "Line number must be inside file length" 19 | 20 | for line in reversed( lines[ : lineNumber + 1 ] ): 21 | match = PYTHON_TEST_METHOD_DEFINITION.match( line ) 22 | if match: 23 | print match.group( 1 ) 24 | sys.exit( 0 ) 25 | match = CPP_TEST_METHOD_DEFINITION.match( line ) 26 | if match: 27 | print match.group( 1 ) 28 | sys.exit( 0 ) 29 | print "POSITION IN FILE IS NOT INSIDE A TEST METHOD" 30 | else: 31 | content = open( filename ).read() 32 | for testName in PYTHON_TEST_METHOD_DEFINITION.findall(content) + \ 33 | CPP_TEST_METHOD_DEFINITION.findall(content): 34 | if re.search(lineNumberOrRegex, testName) is not None: 35 | print testName 36 | sys.exit( 0 ) 37 | print "REGEX DOES NOT MATCH TEST METHOD" 38 | sys.exit( 1 ) 39 | -------------------------------------------------------------------------------- /pytest/fixtures.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | logging.disable( logging.CRITICAL ) 4 | -------------------------------------------------------------------------------- /pytest/pystacktrace.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | 3 | def stackTrace( ** kwargs ): 4 | if 'removeFrames' not in kwargs: 5 | kwargs[ 'removeFrames' ] = 0 6 | if 'stack' not in kwargs: 7 | kwargs[ 'stack' ] = inspect.stack() 8 | stack = kwargs[ 'stack' ][ 1 + kwargs[ 'removeFrames' ] : ] 9 | result = "STACK TRACE:\n" 10 | for frame in stack: 11 | result += "%s:%d: from Here\n" % ( frame[ 1 ] , frame[ 2 ] ) 12 | result += "STACK TRACE END\n" 13 | return result 14 | -------------------------------------------------------------------------------- /pytest/pytestrunner.py: -------------------------------------------------------------------------------- 1 | from imp import new_module; 2 | from sys import modules; 3 | PyTest = modules["PyTest"] = new_module( "PyTest" ); 4 | 5 | from pytestsuite import *; 6 | from pytestworld import *; 7 | from pytesttracker import *; 8 | from pytestverbosecui import *; 9 | from pytestsimplecui import *; 10 | from pytestmock import *; 11 | 12 | class PyTestRunner: 13 | def __init__( self, places, singleTest ): 14 | self._singleTest = singleTest 15 | self._world = PyTestWorld( places ); 16 | self._buildSuites(); 17 | 18 | def run( self ): 19 | if self._world.loadFailed(): 20 | return ; 21 | self._runSuites(); 22 | 23 | def _buildSuites( self ): 24 | PyTest.suites = []; 25 | for ( suiteName, suiteClass ) in PyTest.suiteClasses.items(): 26 | PyTest.suites.append( suiteClass() ); 27 | 28 | def _runSuites( self ): 29 | self._setUpWrapper(); 30 | self._runSuiteWrapper(); 31 | self._tearDownWrapper(); 32 | 33 | def _setUpWrapper( self ): 34 | PyTest.tracker.enterWorld( self._world.description() ); 35 | self._world.setUp(); 36 | 37 | def _runSuiteWrapper( self ): 38 | for suite in PyTest.suites: 39 | if self._singleTest: 40 | suite._runSingleTest( self._singleTest ) 41 | else: 42 | suite._run(); 43 | 44 | def _tearDownWrapper( self ): 45 | self._world.tearDown(); 46 | PyTest.tracker.leaveWorld( self._world.description() ); 47 | 48 | def run( argv ): 49 | if len( argv ) > 2 and argv[1] == "--verbose": 50 | PyTest.ui = PyTestVerboseCui(); 51 | del argv[1]; 52 | elif len( argv ) > 2 and argv[1] == "--cui": 53 | PyTest.ui = PyTestSimpleCui(); 54 | del argv[1]; 55 | else: 56 | PyTest.ui = PyTestSimpleGui(); 57 | SINGLE_TEST = "--singleTest=" 58 | if len( argv ) > 2 and argv[ 1 ].startswith( SINGLE_TEST ): 59 | singleTest = argv[ 1 ][ len( SINGLE_TEST ) : ] 60 | else: 61 | singleTest = None 62 | places = argv[1:]; 63 | PyTest.tracker = PyTestTracker(); 64 | PyTest.mockTable = PyTestMockTable(); 65 | PyTest.runner = PyTestRunner( places, singleTest ); 66 | PyTest.runner.run(); 67 | if PyTest.tracker._testsFailed > 0: 68 | exit( 1 ) 69 | 70 | __all__ = [ "PyTestRunner", "run" ]; 71 | 72 | if __name__ == "__main__": 73 | from sys import argv; 74 | run( argv ) 75 | -------------------------------------------------------------------------------- /pytest/pytestsimplecui.py: -------------------------------------------------------------------------------- 1 | import PyTest; 2 | 3 | from pytestui import *; 4 | from sys import stderr; 5 | from traceback import format_tb; 6 | 7 | class PyTestSimpleCui(PyTestUi): 8 | def __init__( self ): 9 | self.currentTest = ""; 10 | 11 | def loadSuiteFailed( self, suitePath, lineNum, message ): 12 | stderr.write( "%s:%d: Failed to load suite: %s\n" % 13 | ( suitePath, lineNum, message ) ); 14 | 15 | def caughtException( self, traceback ): 16 | lines = format_tb( traceback ); 17 | stderr.write( "\n%s\n" % "\n".join( lines ) ); 18 | 19 | def writeMessage( self, fullPath, lineNum, message ): 20 | stderr.write( "\n%s:%d: %s\n" % 21 | ( fullPath, lineNum, message ) ); 22 | 23 | def enterWorld( self, description ): 24 | stderr.write( "Running %d tests:\n" % self._countTests() ); 25 | 26 | def failTest( self, fullPath, lineNum, message ): 27 | stderr.write( "\n%s:%d: %s: %s\n" % 28 | ( fullPath, lineNum, self.currentTest, message ) ); 29 | 30 | def enterTest( self, description ): 31 | self.currentTest = description; 32 | stderr.write( "." ); 33 | 34 | def leaveWorld( self, description ): 35 | if ( PyTest.tracker.testsFailed() == 0 ): 36 | stderr.write( "\nOK!\n" ); 37 | else: 38 | stderr.write( "\nFailed %d tests\n" % PyTest.tracker.testsFailed() ); 39 | 40 | def _countTests( self ): 41 | numTests = 0; 42 | for suite in PyTest.suites: 43 | numTests += suite._numTests(); 44 | return numTests; 45 | 46 | __all__ = [ "PyTestSimpleCui" ]; 47 | -------------------------------------------------------------------------------- /pytest/pytesttracker.py: -------------------------------------------------------------------------------- 1 | import PyTest; 2 | from pystacktrace import *; 3 | 4 | class PyTestTracker: 5 | def __init__( self ): 6 | self._testsRun = 0; 7 | self._testsFailed = 0; 8 | if PyTest.ui is None: 9 | from pytestui import PyTestUi; 10 | PyTest.ui = PyTestUi(); 11 | 12 | def loadSuiteFailed( self, suitePath, lineNum, message ): 13 | self._testsFailed += 1; 14 | PyTest.ui.loadSuiteFailed( suitePath, lineNum, message ); 15 | 16 | def caughtException( self, traceback ): 17 | PyTest.ui.caughtException( traceback ); 18 | 19 | def writeMessage( self, message, stackFrame ): 20 | ( fullPath, lineNum ) = self.parseStackFrame( stackFrame ); 21 | PyTest.ui.writeMessage( fullPath, lineNum, message ); 22 | 23 | def enterWorld( self, description ): 24 | PyTest.ui.enterWorld( description ); 25 | 26 | def enterSuite( self, description ): 27 | PyTest.ui.enterSuite( description ); 28 | 29 | def enterTest( self, description ): 30 | self._testsRun = self._testsRun + 1; 31 | PyTest.ui.enterTest( description ); 32 | 33 | def failTest( self, message, stack ): 34 | self._testsFailed += 1; 35 | ( fullPath, lineNum ) = self.findNonPytestFrame( stack ); 36 | message += "\n" + stackTrace( stack = stack ); 37 | PyTest.ui.failTest( fullPath, lineNum, message ); 38 | 39 | def leaveTest( self, description ): 40 | PyTest.ui.leaveTest( description ); 41 | 42 | def leaveSuite( self, description ): 43 | PyTest.ui.leaveSuite( description ); 44 | 45 | def leaveWorld( self, description ): 46 | PyTest.ui.leaveWorld( description ); 47 | 48 | def testsRun( self ): 49 | return self.testsRun; 50 | 51 | def testsFailed( self ): 52 | return self._testsFailed; 53 | 54 | def parseStackFrame( self, stackFrame ): 55 | ( frame, filePath, lineNumber, functionName, lines, lineIndex ) = stackFrame; 56 | return ( filePath, lineNumber ); 57 | 58 | def findNonPytestFrame( self, stack ): 59 | for frame in stack: 60 | if 'pytest' not in frame[ 1 ]: 61 | return ( frame[ 1 ], frame[ 2 ] ) 62 | return ( stack[ -1 ][ 1 ], stack[ -1 ][ 2 ] ) 63 | 64 | __all__ = [ "PyTestTracker" ]; 65 | -------------------------------------------------------------------------------- /pytest/pytestui.py: -------------------------------------------------------------------------------- 1 | import PyTest; 2 | 3 | class PyTestUi: 4 | def loadSuiteFailed( self, where, message ): 5 | pass ; 6 | 7 | def caughtException( self, traceback ): 8 | pass ; 9 | 10 | def writeMessage( self, fullPath, lineNum, message ): 11 | pass ; 12 | 13 | def enterWorld( self, description ): 14 | pass ; 15 | 16 | def enterSuite( self, description ): 17 | pass ; 18 | 19 | def enterTest( self, description ): 20 | pass ; 21 | 22 | def failTest( self, description, where, traceback ): 23 | pass ; 24 | 25 | def leaveTest( self, description ): 26 | pass ; 27 | 28 | def leaveSuite( self, description ): 29 | pass ; 30 | 31 | def leaveWorld( self, description ): 32 | pass ; 33 | 34 | __all__ = [ "PyTestUi" ]; 35 | -------------------------------------------------------------------------------- /pytest/pytestverbosecui.py: -------------------------------------------------------------------------------- 1 | import PyTest 2 | 3 | from pytestui import * 4 | from sys import stderr 5 | from traceback import format_tb 6 | 7 | class PyTestVerboseCui(PyTestUi): 8 | def __init__( self ): 9 | self.currentTest = "" 10 | 11 | def loadSuiteFailed( self, suitePath, lineNum, message ): 12 | stderr.write( "%s:%s: Failed to load suite: %s\n" % 13 | ( suitePath, lineNum, message ) ) 14 | 15 | def caughtException( self, traceback ): 16 | lines = format_tb( traceback ) 17 | stderr.write( "\n%s\n" % "\n".join( lines ) ) 18 | 19 | def writeMessage( self, fullPath, lineNum, message ): 20 | stderr.write( "\n%s:%d: %s\n" % 21 | ( fullPath, lineNum, message ) ) 22 | 23 | def enterWorld( self, description ): 24 | stderr.write( "COUNT %d\n" % self._countTests() ) 25 | 26 | def failTest( self, fullPath, lineNum, message ): 27 | stderr.write( "\n%s:%d: %s: %s\n" % 28 | ( fullPath, lineNum, self.currentTest, message ) ) 29 | 30 | def enterSuite( self, description ): 31 | stderr.write( "SUITE '%s'\n" % description ) 32 | 33 | def enterTest( self, description ): 34 | stderr.write( "TEST '%s'\n" % description ) 35 | self.currentTest = description 36 | 37 | def leaveWorld( self, description ): 38 | if ( PyTest.tracker.testsFailed() == 0 ): 39 | stderr.write( "OK!\n" ) 40 | else: 41 | stderr.write( "Failed %d tests\n" % PyTest.tracker.testsFailed() ) 42 | 43 | def _countTests( self ): 44 | numTests = 0 45 | for suite in PyTest.suites: 46 | numTests += suite._numTests() 47 | return numTests 48 | 49 | __all__ = [ "PyTestVerboseCui" ] 50 | -------------------------------------------------------------------------------- /pytest/pytestworld.py: -------------------------------------------------------------------------------- 1 | import PyTest; 2 | 3 | from glob import glob; 4 | from imp import load_source; 5 | from os import path; 6 | from types import ClassType; 7 | from exceptions import SyntaxError; 8 | from sys import stderr, exc_info; 9 | 10 | import fixtures 11 | 12 | class PyTestWorld: 13 | def __init__( self, places ): 14 | PyTest.suiteClasses = {}; 15 | self._loadFailed = False; 16 | self._places = places; 17 | self._collectSuites(); 18 | 19 | def loadFailed( self ): 20 | return self._loadFailed; 21 | 22 | def setUp( self ): 23 | pass ; 24 | 25 | def tearDown( self ): 26 | pass ; 27 | 28 | def _collectSuites( self ): 29 | for place in self._places: 30 | files = glob( place ); 31 | for fullPath in files: 32 | self._collectSuitesFromFile( fullPath ); 33 | 34 | def _collectSuitesFromFile( self, fullPath ): 35 | mod = self._loadModule( fullPath ); 36 | if mod is None: return ; 37 | for ( key, value ) in mod.__dict__.items(): 38 | if self._isTestClass( value ): 39 | PyTest.suiteClasses[ key ] = value; 40 | 41 | def _isTestClass( self, value ): 42 | if not type(value) in [ClassType, type]: 43 | return False; 44 | if value.__name__ == "PyTestSuite": 45 | return False; 46 | basenames = [ base.__name__ for base in value.__bases__ ]; 47 | return ("PyTestSuite" in basenames); 48 | 49 | def _loadModule( self, fullPath ): 50 | ( head, tail ) = path.split( fullPath ); 51 | ( basename, ext ) = path.splitext( tail ); 52 | try: 53 | return load_source( basename, fullPath ); 54 | except SyntaxError, e: 55 | PyTest.tracker.loadSuiteFailed( e.filename, e.lineno, 56 | "Syntax error at offset %s" % str( e.offset ) ); 57 | PyTest.tracker.caughtException( exc_info()[2] ); 58 | except Exception, e: 59 | PyTest.tracker.loadSuiteFailed( fullPath, -1, "Exception: <%s> while loading <%s>" % ( str(e) , basename ) ); 60 | PyTest.tracker.caughtException( exc_info()[2] ); 61 | except: 62 | stderr.write( fullPath + ":-1: Unknown exception" ); 63 | 64 | self._loadFailed = True; 65 | return None; 66 | 67 | def description( self ): 68 | return "PyTest"; 69 | 70 | __all__ = [ "PyTestWorld" ]; 71 | -------------------------------------------------------------------------------- /pytest/pyvoodoo/.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.swp 3 | *.tmp 4 | -------------------------------------------------------------------------------- /pytest/pyvoodoo/__init__.py: -------------------------------------------------------------------------------- 1 | from pyvoodoo.scenario import Scenario, ScenarioIterator 2 | from pyvoodoo.ultimateobject import UltimateObject 3 | from pyvoodoo.ultimateobject import UltimateObjectNC 4 | from pyvoodoo.ultimateclass import UltimateClass 5 | from pyvoodoo.expectations import * 6 | from pyvoodoo.threadedhook import * 7 | import sys 8 | 9 | def _pleaseDontMock( message ): 10 | raise Exception( message ) 11 | _exceptions = { 12 | 'threading': lambda: sys.modules[ 'threading' ].voodooAddAttribute( '_shutdown', lambda: 0 ), 13 | 'os': lambda: _pleaseDontMock( "Os is dangerous to mock: logging and other modules use it. Please override specific functions" ) 14 | } 15 | 16 | def castVoodooUponModule( module ): 17 | assert isinstance( module , str ) 18 | obj = UltimateObject( module ) 19 | sys.modules[ module ] = obj 20 | if module in _exceptions: 21 | _exceptions[ module ]() 22 | ancestorModuleNameParts = module.split( "." ) [ : -1 ] 23 | moduleName = module.split( "." ) [ -1 ] 24 | if len( ancestorModuleNameParts ) > 0: 25 | ancestorModuleName = ".".join( ancestorModuleNameParts ) 26 | ancestorModule = __import__( ancestorModuleName, globals(), locals(), [ '__name__' ], -1 ) 27 | ancestorModule.__dict__[ moduleName ] = obj 28 | 29 | def castVoodooUponClass( classPath ): 30 | parts = classPath.split( "." ) 31 | module = parts[ : -1 ] 32 | ultimateObjects = [] 33 | className = parts[ -1 ] 34 | while True: 35 | if len( module ) == 0: 36 | raise Exception( "no exsiting module for '%s'" % classPath ) 37 | moduleName = ".".join( module ) 38 | if moduleName in sys.modules: 39 | break 40 | ultimateObjects.push( module.pop() ) 41 | if not isinstance( sys.modules[ moduleName ] , UltimateObject ): 42 | raise Exception( "'%s' is in a non voodoo module '%s'" % ( classPath , path ) ) 43 | current = sys.modules[ moduleName ] 44 | while len( ultimateObjects ) > 0: 45 | current.voodooAddAttribute( ultimateObjects[ 0 ] , UltimateObject( current._voodooPath + "." + ultimateObjects[ 0 ] ) ) 46 | current = current.__dict__[ ultimateObjects[ 0 ] ] 47 | ultimateObjects.pop( 0 ) 48 | current.voodooAddAttribute( className , UltimateClass( current._voodooPath + "." + className ) ) 49 | -------------------------------------------------------------------------------- /pytest/pyvoodoo/threadedhook.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | _allExceptions = {} 4 | _threads = [] 5 | 6 | def voodooAssertAllThreadsCompletedSuccessfully(): 7 | assert _threads == [] 8 | assert _allExceptions == {} 9 | 10 | def voodooAssertThreadCompletedWithException( thread ): 11 | assert thread in _allExceptions 12 | 13 | VoodooEvent = threading.Event 14 | 15 | class VoodooThreadedHook( threading.Thread ): 16 | def __init__( self, callback ): 17 | self._callback = callback 18 | threading.Thread.__init__( self, name = "VoodooThreadedHook" ) 19 | self.setDaemon( True ) 20 | 21 | def __call__( self ): 22 | _threads.append( self ) 23 | self.start() 24 | 25 | def run( self ): 26 | try: 27 | self._callback() 28 | except Exception, e: 29 | _allExceptions[ self ] = e 30 | finally: 31 | _threads.remove( self ) 32 | -------------------------------------------------------------------------------- /pytest/pyvoodoo/ultimateclass.py: -------------------------------------------------------------------------------- 1 | from pyvoodoo.ultimateobject import UltimateObject 2 | from pyvoodoo.scenario import lookupExpectationsInScenario, completeExpectation 3 | 4 | class _UltimateClass( UltimateObject ): 5 | def __init__( self , * args , ** kwargs ): 6 | expectation = lookupExpectationsInScenario( self._VOODOO_PATH )[ 0 ] 7 | expectation.compare( args, kwargs ) 8 | completeExpectation( expectation ) 9 | self.__dict__[ '_voodooPath' ] = expectation.voodooPath() 10 | self.voodooObjects.append( self ) 11 | expectation.returnValue() 12 | 13 | def __setattr__( self , name , value ): 14 | self.__dict__[ name ] = value 15 | 16 | def UltimateClass( voodooPath ): 17 | class NewCopy( _UltimateClass ): 18 | pass 19 | NewCopy._VOODOO_PATH = voodooPath 20 | NewCopy.voodooObjects = [] 21 | return NewCopy 22 | -------------------------------------------------------------------------------- /pytest/pyvoodoo/ultimateobject.py: -------------------------------------------------------------------------------- 1 | from pytestsuite import * 2 | from pyvoodoo.scenario import lookupExpectationsInScenario, completeExpectation 3 | from pyvoodoo.voodooexception import VoodooException 4 | 5 | class UltimateObject: 6 | def __init__( self, path, ** attributes ): 7 | self.__dict__[ "_voodooPath" ] = path 8 | for k, v in attributes.iteritems(): 9 | self.__dict__[ k ] = v 10 | 11 | def voodooPath( self ): 12 | return self.__dict__[ '_voodooPath' ] 13 | 14 | def voodooAddAttribute( self , name , value ): 15 | self.__dict__[ name ] = value 16 | 17 | def __hash__( self ): 18 | return id( self ).__hash__() 19 | 20 | def __str__( self ): 21 | return "" % self.voodooPath() 22 | 23 | def __repr__( self ): 24 | return "" % self.voodooPath() 25 | 26 | def __getattr__( self , name ): 27 | if name == "__path__": 28 | return "UltimateObject module" 29 | voodooPath = self.__dict__[ "_voodooPath" ] 30 | return UltimateObject( voodooPath + "." + name ) 31 | 32 | def __setattr__( self , name , value ): 33 | voodooPath = self.__dict__[ "_voodooPath" ] 34 | expectation = lookupExpectationsInScenario( voodooPath + "." + name )[ 0 ] 35 | TS_ASSERT( expectation._voodooExpectationType.startsWith( 36 | "SetAttr" ) ); 37 | expectation.compare( value ) 38 | completeExpectation( expectation ) 39 | 40 | def __call__( self , * args , ** kwargs ): 41 | voodooPath = self.__dict__[ "_voodooPath" ] 42 | expectations = lookupExpectationsInScenario( voodooPath ) 43 | TS_ASSERT_LESS_THAN( 0 , expectations ) 44 | exceptions = [] 45 | for expectation in expectations: 46 | try: 47 | expectation.compare( args , kwargs ) 48 | completeExpectation( expectation ) 49 | return expectation.returnValue() 50 | except VoodooException, e: 51 | exceptions.append( e ) 52 | try: 53 | paramsRepr = str( ( args , kwargs ) ) 54 | except: 55 | paramsRepr = "" 56 | TS_FAIL( "No expectation matched '%s( %s )'; Errors; %s" % ( 57 | self._voodooPath , 58 | paramsRepr , 59 | "\n".join( [ str( e ) for e in exceptions ] ) ) ) 60 | 61 | class UltimateObjectNC( UltimateObject, object ): 62 | def __eq__( self, other ): 63 | return other is self 64 | -------------------------------------------------------------------------------- /pytest/pyvoodoo/voodooexception.py: -------------------------------------------------------------------------------- 1 | class VoodooException( Exception ): 2 | pass 3 | -------------------------------------------------------------------------------- /pytest/untee.py: -------------------------------------------------------------------------------- 1 | import __builtin__; 2 | import imp; 3 | import sys; 4 | 5 | __all__ = [ "installUntee" ]; 6 | 7 | oldImport = __builtin__.__import__; 8 | 9 | def importOverride( name, globals=None, locals=None, fromlist=None ): 10 | if name == "T": 11 | return importFromTee( name, fromlist ); 12 | 13 | if name.startswith( "T." ): 14 | return importFromSubtee( name , globals , locals , fromlist ); 15 | 16 | return oldImport( name, globals, locals, fromlist ); 17 | 18 | def importFromTee( name, fromlist ): 19 | if name not in sys.modules.keys(): 20 | sys.modules[ name ] = imp.new_module( name ); 21 | module = sys.modules[ name ]; 22 | for each in fromlist: 23 | setattr( module, each, oldImport( each ) ); 24 | return module; 25 | 26 | def importFromSubtee( name , globals , locals , fromlist ): 27 | return oldImport( name[2:] , globals , locals , fromlist ); 28 | 29 | def installUntee(): 30 | __builtin__.__import__ = importOverride; 31 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | futures 2 | -------------------------------------------------------------------------------- /vim/columindent/configuredmain.py: -------------------------------------------------------------------------------- 1 | import os 2 | import argparse 3 | import main 4 | 5 | def underDirectory( filename, directory ): 6 | return directory in filename.split( os.path.sep ) 7 | 8 | parser = argparse.ArgumentParser() 9 | parser.add_argument( "filename" ) 10 | parser.add_argument( "cmd", choices = [ 'indent', 'indentCPPDeclaration', 'constructorReferenceArguments' ] ) 11 | parser.add_argument( "--optimizeForMaximumLineLength", default = 116, type = int ) 12 | parser.add_argument( "--minimumSpaceBetweenColumns", default = 2, type = int ) 13 | 14 | args = parser.parse_args() 15 | if args.filename.endswith( ".py" ): 16 | args.asterixInFirstColum = False 17 | args.indentWithTabs = False 18 | args.alwaysNewLineForFirstParameter = False 19 | args.noSpaceBeforeClosingParenthesis = False 20 | args.tabSize = 4 21 | elif underDirectory( args.filename, 'c' ) and not underDirectory( args.filename, 'tests' ): 22 | args.asterixInFirstColum = True 23 | args.indentWithTabs = True 24 | args.alwaysNewLineForFirstParameter = True 25 | args.noSpaceBeforeClosingParenthesis = True 26 | args.tabSize = 8 27 | else: 28 | args.asterixInFirstColum = False 29 | args.indentWithTabs = True 30 | args.alwaysNewLineForFirstParameter = False 31 | args.noSpaceBeforeClosingParenthesis = False 32 | args.tabSize = 8 33 | main.main( args ) 34 | -------------------------------------------------------------------------------- /vim/columindent/constructorreferenceargumentscpp.py: -------------------------------------------------------------------------------- 1 | import parsecppfunctionsignature 2 | import re 3 | import tab 4 | import formatcolums 5 | import parsecppmemberlist 6 | 7 | class ConstructorReferenceArgumentsCPP: 8 | def __init__( self, input, args ): 9 | self._input = input 10 | self._args = args 11 | self._tab = tab.Tab( args ) 12 | self._parse = parsecppfunctionsignature.ParseCPPFunctionSignature( input ) 13 | 14 | def format( self ): 15 | return self._input + \ 16 | self._formatInitializationList() + \ 17 | self._indentation() + '{}\n\n' + \ 18 | "private:\n" + \ 19 | self._formatMembers() 20 | 21 | def _formatMembers( self ): 22 | membersRaw = self._tab.produce( self._args.tabSize ) + ";\n".join( r[ 0 ] + ' _' + r[ 1 ] for r in self._parse.argumentsTwoColumTable() ) + ";\n" 23 | parse = parsecppmemberlist.ParseCPPMemberList( membersRaw ); 24 | return formatcolums.FormatColums( parse, self._args ).format() 25 | 26 | def _indentation( self, add = "" ): 27 | spacePrefix = re.match( r"\s*", self._input ).group( 0 ) 28 | size = self._tab.roundUp( self._tab.countChars( spacePrefix + add ) ) 29 | return self._tab.produce( size ) 30 | 31 | def _formatInitializationList( self ): 32 | return ",\n".join( self._indentation( '\t' ) + "_%s( %s )" % ( p, p ) for p in self._parameters() ) + '\n' 33 | 34 | def _parameters( self ): 35 | return [ re.search( r"\w+", r[ 1 ] ).group( 0 ) for r in self._parse.rows() ] 36 | -------------------------------------------------------------------------------- /vim/columindent/constructorreferenceargumentspy.py: -------------------------------------------------------------------------------- 1 | import parsesimplecall 2 | import re 3 | import tab 4 | 5 | class ConstructorReferenceArgumentsPy: 6 | def __init__( self, input, args ): 7 | self._input = input 8 | self._args = args 9 | self._tab = tab.Tab( args ) 10 | self._parse = parsesimplecall.ParseSimpleCall( input ) 11 | 12 | def format( self ): 13 | return self._input + "\n" + \ 14 | self._formatInitialization() 15 | 16 | def _indentation( self, add = "" ): 17 | spacePrefix = re.match( r"\s*", self._input ).group( 0 ) 18 | size = self._tab.roundUp( self._tab.countChars( spacePrefix + add ) ) 19 | return self._tab.produce( size ) 20 | 21 | def _formatInitialization( self ): 22 | return "".join( self._indentation( '\t' ) + "self._%s = %s\n" % ( p, p ) for p in self._parameters() ) 23 | 24 | def _parameters( self ): 25 | parameters = [ re.search( r"\w+", r[ 0 ] ).group( 0 ) for r in self._parse.rows() ] 26 | if parameters[ 0 ] == "self": 27 | del parameters[ 0 ] 28 | return parameters 29 | -------------------------------------------------------------------------------- /vim/columindent/formatcolums.py: -------------------------------------------------------------------------------- 1 | import re 2 | import tab 3 | 4 | class FormatColums: 5 | def __init__( self, parse, args ): 6 | self._parse = parse 7 | self._args = args 8 | self._tab = tab.Tab( args ) 9 | self._lines = self._toLines( parse.rows() ) 10 | self._lead = parse.lead() 11 | if self._lead.isspace(): 12 | self._indentationCharacters = self._tab.countChars( self._lead ) 13 | else: 14 | self._indentationCharacters = self._tab.countChars( self._lead + '\t' ) 15 | mustAddNewLine = self._args.alwaysNewLineForFirstParameter 16 | if self._indentationCharacters + self._longestLine() > args.optimizeForMaximumLineLength: 17 | mustAddNewLine = True 18 | self._indentationCharacters = args.optimizeForMaximumLineLength - self._tab.roundUp( self._longestLine ) 19 | if self._indentationCharacters < self._minimumIndentation(): 20 | self._indentationCharacters = self._minimumIndentation() 21 | if mustAddNewLine: 22 | self._lead + '\n' + self._indentation() 23 | else: 24 | assert self._indentationCharacters > self._tab.countChars( self._lead ) 25 | self._lead += ' ' * ( self._indentationCharacters - self._tab.countChars( self._lead ) ) 26 | 27 | def format( self ): 28 | return self._lead + ( '\n' + self._indentation() ).join( self._lines ) + self._tail() 29 | 30 | def _minimumIndentation( self ): 31 | assert not self._lead.isspace() 32 | spacePrefix = re.match( r'(\s*)', self._lead ).group( 0 ) 33 | return self._tab.countChars( spacePrefix + '\t' ) 34 | 35 | def _tail( self ): 36 | tail = self._parse.tail() 37 | if len( tail ) > 0 and not tail.isspace(): 38 | if self._args.noSpaceBeforeClosingParenthesis: 39 | return tail 40 | return ' ' + tail 41 | else: 42 | return tail 43 | 44 | def _indentation( self ): 45 | return self._tab.produce( self._indentationCharacters ) 46 | 47 | def _longestLine( self ): 48 | return max( len( l ) for l in self._lines ) 49 | 50 | def _toLines( self, rows ): 51 | if len( rows[ 0 ] ) == 1: 52 | return [ r[ 0 ] for r in rows ] 53 | else: 54 | return self._twoColumnsToLines( rows ) 55 | 56 | def _twoColumnsToLines( self, rows ): 57 | assert len( rows[ 0 ] ) == 2 58 | maxLengthFirstColumn = max( len( r[ 0 ] ) for r in rows ) 59 | firstColumSize = maxLengthFirstColumn + self._args.minimumSpaceBetweenColumns 60 | return [ r[ 0 ] + ' ' * ( firstColumSize - len( r[ 0 ] ) ) + r[ 1 ] for r in rows ] 61 | -------------------------------------------------------------------------------- /vim/columindent/parsecpp.py: -------------------------------------------------------------------------------- 1 | import tokenize 2 | 3 | class VariableDeclaration: 4 | #input: 'int a' 5 | #output: ( 'int', 'a' ) 6 | def __init__( self, declaration, asterixInFirstColum = True ): 7 | tokens = tokenize.Tokenize( declaration.strip() ).tokens() 8 | splitPoint = len( tokens ) 9 | if '[' in tokens and tokens.index( '[' ) < splitPoint: 10 | splitPoint = tokens.index( '[' ) 11 | if '=' in tokens and tokens.index( '=' ) < splitPoint: 12 | splitPoint = tokens.index( '=' ) 13 | self._firstColum = tokens[ : splitPoint ] 14 | self._secondColum = tokens[ splitPoint : ] 15 | self._moveSpacesFromFirstColumToSecondColum() 16 | if len( self._firstColum ) == 0: 17 | self._firstColum = self._secondColum 18 | self._secondColum = [] 19 | return 20 | self._moveTokenFromFirstColumToSecondColum() #eat variable name 21 | 22 | if not asterixInFirstColum: 23 | self._moveAsterixesFromFirstColumToSecondColum() 24 | 25 | def colums( self ): 26 | return "".join( self._firstColum ).strip(), "".join( self._secondColum ).strip() 27 | 28 | def _moveTokenFromFirstColumToSecondColum( self ): 29 | assert len( self._firstColum ) > 0 30 | self._secondColum.insert( 0, self._firstColum[ -1 ] ) 31 | self._firstColum.pop() 32 | 33 | def _moveTokensFromFirstColumsToSecondColum( self, matching ): 34 | while len( self._firstColum ) > 0 and matching( self._firstColum[ -1 ] ): 35 | self._moveTokenFromFirstColumToSecondColum() 36 | 37 | def _moveSpacesFromFirstColumToSecondColum( self ): 38 | self._moveTokensFromFirstColumsToSecondColum( lambda x: x.isspace() ) 39 | 40 | def _moveAsterixesFromFirstColumToSecondColum( self ): 41 | self._moveTokensFromFirstColumsToSecondColum( lambda x: x.isspace() or x == '*' ) 42 | 43 | class Classification: 44 | def __init__( self, string ): 45 | self._string = string 46 | self._lines = string.strip().split( "\n" ) 47 | 48 | def memberList( self ): 49 | return not self._looksLikeACallOrFunctionDeclaration() 50 | 51 | def _looksLikeACallOrFunctionDeclaration( self ): 52 | return '(' in self._lines[ 0 ] and ')' in self._lines[ -1 ] 53 | -------------------------------------------------------------------------------- /vim/columindent/parsecppfunctionsignature.py: -------------------------------------------------------------------------------- 1 | import parsecpp 2 | import tokenize 3 | 4 | class ParseCPPFunctionSignature: 5 | def __init__( self, input ): 6 | self._input = input 7 | self._lead, self._parameters, self._tail = tokenize.Tokenize( input ).splitByParenthesis() 8 | 9 | def lead( self ): return self._lead 10 | 11 | def rows( self ): 12 | colums = self.argumentsTwoColumTable() 13 | addComma = [ m[ : -1 ] + ( m[ -1 ] + ',', ) for m in colums[ : -1 ] ] + [ colums[ -1 ] ] 14 | return addComma 15 | 16 | def tail( self ): return self._tail 17 | 18 | def argumentsTwoColumTable( self ): 19 | arguments = self._argumentsExpressions() 20 | colums = [ parsecpp.VariableDeclaration( a ).colums() for a in arguments ] 21 | return colums 22 | 23 | def _argumentsExpressions( self ): 24 | return tokenize.Tokenize( self._parameters ).splitByZeroParenLevel() 25 | -------------------------------------------------------------------------------- /vim/columindent/parsecppmemberlist.py: -------------------------------------------------------------------------------- 1 | import parsecpp 2 | import re 3 | 4 | class ParseCPPMemberList: 5 | def __init__( self, input ): 6 | self._input = input 7 | 8 | def lead( self ): 9 | return self._spaceBeforeFirstMember() 10 | 11 | def rows( self ): 12 | colums = self.memberTwoColumTable() 13 | addSemicolon = [ m[ : -1 ] + ( m[ -1 ] + ';', ) for m in colums ] 14 | return addSemicolon 15 | 16 | def tail( self ): 17 | return "" 18 | 19 | def memberTwoColumTable( self ): 20 | members = self._memberExpressions() 21 | colums = [ parsecpp.VariableDeclaration( m ).colums() for m in members ] 22 | return colums 23 | 24 | def _memberExpressions( self ): 25 | members = [ m.strip() for m in self._input.split( ';' ) ] 26 | assert len( members ) > 0 27 | if members[ -1 ] == "": 28 | members.pop() 29 | return members 30 | 31 | def _spaceBeforeFirstMember( self ): 32 | return re.search( r"^(\s*)" , self._input ).groups()[ 0 ] 33 | -------------------------------------------------------------------------------- /vim/columindent/parsesimplecall.py: -------------------------------------------------------------------------------- 1 | import tokenize 2 | 3 | class ParseSimpleCall: 4 | def __init__( self, input ): 5 | self._input = input 6 | self._lead, self._parameters, self._tail = tokenize.Tokenize( input ).splitByParenthesis() 7 | 8 | def lead( self ): return self._lead 9 | def rows( self ): 10 | params = tokenize.Tokenize( self._parameters ).splitByZeroParenLevel() 11 | withCommas = [ p + "," for p in params[ : -1 ] ] + [ params[ -1 ] ] 12 | return [ ( p, ) for p in withCommas ] 13 | def tail( self ): return self._tail 14 | -------------------------------------------------------------------------------- /vim/columindent/tab.py: -------------------------------------------------------------------------------- 1 | class Tab: 2 | def __init__( self, args ): 3 | self._args = args 4 | 5 | def roundUp( self, value ): 6 | reminder = value % self._args.tabSize 7 | if reminder == 0: 8 | return value 9 | return value + self._args.tabSize - reminder 10 | 11 | def countChars( self, string ): 12 | result = 0 13 | string = [ c for c in string ] 14 | while len( string ) > 0: 15 | char = string.pop( 0 ) 16 | if char == '\t': 17 | result = self.roundUp( result + 1 ) 18 | else: 19 | result += 1 20 | return result 21 | 22 | def produce( self, size ): 23 | assert size % self._args.tabSize == 0 24 | if self._args.indentWithTabs: 25 | return '\t' * ( size / self._args.tabSize ) 26 | else: 27 | return ' ' * size 28 | -------------------------------------------------------------------------------- /vim/dirtytrace.py: -------------------------------------------------------------------------------- 1 | import re 2 | import argparse 3 | import sys 4 | 5 | parser = argparse.ArgumentParser() 6 | subparsers = parser.add_subparsers( dest = "cmd" ) 7 | trace = subparsers.add_parser( "trace", help = "Put a trace line with sorrounding comments, for easy spotting with diff" ) 8 | breakpoint = subparsers.add_parser( "breakpoint", help = "Put a breakpoint" ) 9 | parser.add_argument( "filename" ) 10 | args = parser.parse_args() 11 | 12 | inputLines = sys.stdin.readlines() 13 | indent = re.match( r"(\s*)\S", inputLines[ 0 ] ).group( 1 ) 14 | input = "".join( inputLines ) 15 | 16 | if args.cmd == "trace": 17 | if args.filename.endswith( ".py" ): 18 | sys.stdout.write( "### DIRTY TRACE\n" + 19 | indent + "print 'X'*100\n" + 20 | "### DIRTY TRACE END\n" + 21 | input ) 22 | elif args.filename.endswith( ".cpp" ) or args.filename.endswith( ".h" ): 23 | sys.stdout.write( "/// DIRTY TRACE\n" + 24 | '''std::cerr << __FILE__ << ':' << __LINE__ << ": XXXX " << std::endl;\n''' + 25 | "/// DIRTY TRACE END\n" + 26 | input ) 27 | else: 28 | assert False, "Not implemented for this file type" 29 | elif args.cmd == "breakpoint": 30 | if args.filename.endswith( ".py" ): 31 | sys.stdout.write( "### DIRTY BREAKPOINT\n" + 32 | indent + "import pdb\n" + 33 | indent + "pdb.set_trace()\n" + 34 | "### DIRTY BREAKPOINT END\n" + 35 | input ) 36 | else: 37 | assert False, "Not implemented for this file type" 38 | -------------------------------------------------------------------------------- /vim/doc/bufexplorer.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shlomimatichin/Voodoo-Mock/02fc8c4f3029673fc1c16bc754577593a5d088c3/vim/doc/bufexplorer.txt -------------------------------------------------------------------------------- /vim/ftplugin/python/pyflakes/LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Copyright (c) 2005 Divmod, Inc., http://www.divmod.com/ 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining 5 | a copy of this software and associated documentation files (the 6 | "Software"), to deal in the Software without restriction, including 7 | without limitation the rights to use, copy, modify, merge, publish, 8 | distribute, sublicense, and/or sell copies of the Software, and to 9 | permit persons to whom the Software is furnished to do so, subject to 10 | the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 19 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 20 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 21 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /vim/ftplugin/python/pyflakes/NEWS.txt: -------------------------------------------------------------------------------- 1 | 0.4.0 (2009-11-25): 2 | - Fix reporting for certain SyntaxErrors which lack line number 3 | information. 4 | - Check for syntax errors more rigorously. 5 | - Support checking names used with the class decorator syntax in versions 6 | of Python which have it. 7 | - Detect local variables which are bound but never used. 8 | - Handle permission errors when trying to read source files. 9 | - Handle problems with the encoding of source files. 10 | - Support importing dotted names so as not to incorrectly report them as 11 | redefined unused names. 12 | - Support all forms of the with statement. 13 | - Consider static `__all__` definitions and avoid reporting unused names 14 | if the names are listed there. 15 | - Fix incorrect checking of class names with respect to the names of their 16 | bases in the class statement. 17 | - Support the `__path__` global in `__init__.py`. 18 | 19 | 0.3.0 (2009-01-30): 20 | - Display more informative SyntaxError messages. 21 | - Don't hang flymake with unmatched triple quotes (only report a single 22 | line of source for a multiline syntax error). 23 | - Recognize __builtins__ as a defined name. 24 | - Improve pyflakes support for python versions 2.3-2.5 25 | - Support for if-else expressions and with statements. 26 | - Warn instead of error on non-existant file paths. 27 | - Check for __future__ imports after other statements. 28 | - Add reporting for some types of import shadowing. 29 | - Improve reporting of unbound locals 30 | -------------------------------------------------------------------------------- /vim/ftplugin/python/pyflakes/bin/pyflakes: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from pyflakes.scripts.pyflakes import main 4 | main() 5 | -------------------------------------------------------------------------------- /vim/ftplugin/python/pyflakes/pyflakes/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | __version__ = '0.4.0' 3 | -------------------------------------------------------------------------------- /vim/ftplugin/python/pyflakes/pyflakes/scripts/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shlomimatichin/Voodoo-Mock/02fc8c4f3029673fc1c16bc754577593a5d088c3/vim/ftplugin/python/pyflakes/pyflakes/scripts/__init__.py -------------------------------------------------------------------------------- /vim/ftplugin/python/pyflakes/pyflakes/test/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shlomimatichin/Voodoo-Mock/02fc8c4f3029673fc1c16bc754577593a5d088c3/vim/ftplugin/python/pyflakes/pyflakes/test/__init__.py -------------------------------------------------------------------------------- /vim/ftplugin/python/pyflakes/pyflakes/test/harness.py: -------------------------------------------------------------------------------- 1 | 2 | import textwrap 3 | import _ast 4 | 5 | from twisted.trial import unittest 6 | 7 | from pyflakes import checker 8 | 9 | 10 | class Test(unittest.TestCase): 11 | 12 | def flakes(self, input, *expectedOutputs, **kw): 13 | ast = compile(textwrap.dedent(input), "", "exec", 14 | _ast.PyCF_ONLY_AST) 15 | w = checker.Checker(ast, **kw) 16 | outputs = [type(o) for o in w.messages] 17 | expectedOutputs = list(expectedOutputs) 18 | outputs.sort() 19 | expectedOutputs.sort() 20 | self.assert_(outputs == expectedOutputs, '''\ 21 | for input: 22 | %s 23 | expected outputs: 24 | %s 25 | but got: 26 | %s''' % (input, repr(expectedOutputs), '\n'.join([str(o) for o in w.messages]))) 27 | return w 28 | -------------------------------------------------------------------------------- /vim/ftplugin/python/pyflakes/setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # (c) 2005-2009 Divmod, Inc. See LICENSE file for details 3 | 4 | from distutils.core import setup 5 | 6 | setup( 7 | name="pyflakes", 8 | license="MIT", 9 | version="0.4.0", 10 | description="passive checker of Python programs", 11 | author="Phil Frost", 12 | maintainer="Moe Aboulkheir", 13 | maintainer_email="moe@divmod.com", 14 | url="http://www.divmod.org/trac/wiki/DivmodPyflakes", 15 | packages=["pyflakes", "pyflakes.scripts", "pyflakes.test"], 16 | scripts=["bin/pyflakes"], 17 | long_description="""Pyflakes is program to analyze Python programs and detect various errors. It 18 | works by parsing the source file, not importing it, so it is safe to use on 19 | modules with side effects. It's also much faster.""", 20 | classifiers=[ 21 | "Development Status :: 6 - Mature", 22 | "Environment :: Console", 23 | "Intended Audience :: Developers", 24 | "License :: OSI Approved :: MIT License", 25 | "Programming Language :: Python", 26 | "Topic :: Software Development", 27 | "Topic :: Utilities", 28 | ]) 29 | -------------------------------------------------------------------------------- /vim/plugin/runtests.vim: -------------------------------------------------------------------------------- 1 | function RunSingleTest() 2 | let bufferName = bufname( "%" ) 3 | let line = line( "." ) 4 | execute "make test_singletest SINGLE_TEST_SUITE=\"`python -c 'import os; import sys; print os.path.relpath( sys.argv[ 1 ], os.getcwd() )' " . bufferName . "`\" REGEX_OR_LINE_NUMBER=" . line 5 | endfunction 6 | 7 | function RunSingleTestSuite() 8 | let bufferName = bufname( "%" ) 9 | execute "make test_singletestsuite SINGLE_TEST_SUITE=\"`python -c 'import os; import sys; print os.path.relpath( sys.argv[ 1 ], os.getcwd() )' " . bufferName . "`\"" 10 | endfunction 11 | 12 | map :w`T:w:call RunSingleTest() 13 | map :w`T:w:call RunSingleTestSuite() 14 | map :w:make -j 15 | -------------------------------------------------------------------------------- /vim/plugin/togglecomment.vim: -------------------------------------------------------------------------------- 1 | function ToggleComment() 2 | let bufferName = bufname( "%" ) 3 | if bufferName =~ "[.]h$" || bufferName =~ "[.]cpp$" || bufferName =~ "[.]c$" || bufferName =~ "[.]js$" || bufferName =~ "[.]html$" 4 | let commentSign = "//" 5 | let uncommentAction = "0xx" 6 | else 7 | let commentSign = "#" 8 | let uncommentAction = "0x" 9 | endif 10 | let line = getline( "." ) 11 | if line[ 0 ] == commentSign || line[ 0 : 1 ] == commentSign 12 | execute "normal " . uncommentAction 13 | else 14 | execute "normal " . "0i" . commentSign 15 | endif 16 | endfunction 17 | 18 | map co :call ToggleComment() 19 | -------------------------------------------------------------------------------- /vim/plugin/voodootools.vim: -------------------------------------------------------------------------------- 1 | function VoodooParseSingleFile() 2 | let bufferName = bufname( "%" ) 3 | execute "make voodoo_compileSingleHeader V=1 SINGLE_HEADER=\"`python -c 'import os; import sys; print os.path.relpath( sys.argv[ 1 ], os.getcwd() )' " . bufferName . "`\"" 4 | endfunction 5 | 6 | function VoodooHint() 7 | let line = line( "." ) 8 | execute "%!python $VOODOO_ROOT_DIR/voodoo/voodoohint.py --db=build_unittest/voodooDB.tmp --hintLine=" . line 9 | execute ":".line 10 | endfunction 11 | 12 | map :call VoodooParseSingleFile() 13 | map :make voodoo_forceGenerateAll 14 | map :call VoodooHint() 15 | -------------------------------------------------------------------------------- /vim/settings.vim: -------------------------------------------------------------------------------- 1 | set tabstop=4 2 | set shiftwidth=4 3 | set autoindent 4 | set incsearch 5 | set expandtab 6 | filetype on 7 | filetype plugin on 8 | filetype indent on 9 | au FileType cpp setl tabstop=8 10 | au FileType cpp setl shiftwidth=8 11 | au FileType cpp setl noexpandtab 12 | au FileType c setl tabstop=8 13 | au FileType c setl shiftwidth=8 14 | au FileType c setl noexpandtab 15 | 16 | set runtimepath+=$VOODOO_ROOT_DIR/vim 17 | set hlsearch 18 | set encoding=utf-8 19 | 20 | command Ctags !ctags --exclude=build --exclude=build_unittest --exclude=tools -R . 21 | command NewFile %!python $VOODOO_ROOT_DIR/vim/newfile.py % 22 | command Coverage !python $VOODOO_ROOT_DIR/vim/coverage.py % 23 | command -range Colin :,!python $VOODOO_ROOT_DIR/vim/columindent/configuredmain.py % indent 24 | command -range ColinDeclaration :,!python $VOODOO_ROOT_DIR/vim/columindent/configuredmain.py % indentCPPDeclaration 25 | command -range ConstructorReferenceArguments :,!python $VOODOO_ROOT_DIR/vim/columindent/configuredmain.py % constructorReferenceArguments 26 | command -range DirtyTrace :,!python $VOODOO_ROOT_DIR/vim/dirtytrace.py trace % 27 | command -range DirtyBreakPoint :,!python $VOODOO_ROOT_DIR/vim/dirtytrace.py breakpoint % 28 | 29 | map :Colin 30 | "Fast movement in the location list: 31 | map :cn 32 | map :cp 33 | 34 | "Fast movement in the buffer list: 35 | map :bp 36 | map :bn 37 | map :bn 38 | map :bp 39 | 40 | "Fast movement for next/previous tags 41 | map #8 :tp 42 | map #9 :tn 43 | 44 | "Fast movement between splits 45 | map  46 | map W 47 | 48 | if has("gui_running") 49 | colorscheme darkblue 50 | set guifont=Monospace\ 18 51 | endif 52 | command TinyFont :set guifont=Monospace\ 12 53 | command SmallFont :set guifont=Monospace\ 14 54 | command LargeFont :set guifont=Monospace\ 18 55 | 56 | "source $VIM/_vimrc 57 | 58 | function! s:PathComplete(ArgLead, CmdLine, CursorPos) 59 | return genutils#UserFileComplete(a:ArgLead, a:CmdLine, a:CursorPos, 1, &path) 60 | endfunction 61 | command! -nargs=1 -bang -complete=custom,PathComplete FindInPath 62 | \ :find 63 | 64 | "Remove trailing spaces and replace tabs with spaces on save 65 | autocmd BufWritePre *.py :%s/\s\+$//e 66 | autocmd BufWritePre *.py :retab 67 | 68 | set listchars=eol:$,tab:>-,trail:~,extends:>,precedes:< 69 | map wi :set list 70 | map wo :set nolist 71 | -------------------------------------------------------------------------------- /vimenv: -------------------------------------------------------------------------------- 1 | export VOODOO_ROOT_DIR=`realpath .` 2 | export VIMINIT="source $VOODOO_ROOT_DIR/vim/settings.vim" 3 | -------------------------------------------------------------------------------- /voodoo/Tutorial/1 - Compiling The Parser/UNIX/readme.txt: -------------------------------------------------------------------------------- 1 | libclang.so compatible with Ubuntu 13.04 is included in the package. 2 | All other versions and distros will need to compile a compatible version. 3 | 4 | To compile libclang.so: 5 | --------------------------- 6 | run compileclang.py 7 | -------------------------------------------------------------------------------- /voodoo/Tutorial/1 - Compiling The Parser/readme.txt: -------------------------------------------------------------------------------- 1 | The parser used by voodoo-mock is the LLVM C++ complier, CLang. The 2 | parser is accessed using the Python API to libclang.so. 3 | 4 | Compiled versions: 5 | ------------------ 6 | Ubuntu - the libclang.so in the main directory is compiled with the 7 | default tools of the latest ubuntu at this time - 13.04 8 | 9 | Procceed to subfolders if you still must compile the parser. It should take 10 | up to 30 minutes. 11 | -------------------------------------------------------------------------------- /voodoo/Tutorial/2 - Command Line Usage/example.sh: -------------------------------------------------------------------------------- 1 | #you'll probably only ever use multi 2 | export LD_LIBRARY_PATH=../.. 3 | mkdir multi-result 4 | python ../../multi.py --input=original --output=multi-result --exclude=Dont --define=IN= --define=OUT= --define=INOUT= 5 | #you might also want to read about multi --concurrent flag, and --only-if-new flag. run multi.py with --help 6 | 7 | #you might sometime want a more complicated build process, and create the h files single handedly 8 | mkdir single-result 9 | #the next line will create single-result/original/Header1.h 10 | python ../../single.py --input=original/Header1.h --output=single-result --define=IN= --define=OUT= --define=INOUT= 11 | python ../../single.py --input=original/Header2.h --output=single-result/Header2.h 12 | 13 | #but mostly single.py is used to produce external voodoos. more on external in it's tutorial chapter 14 | -------------------------------------------------------------------------------- /voodoo/Tutorial/2 - Command Line Usage/original/DontParseMe.h: -------------------------------------------------------------------------------- 1 | sometimes the parser fails on certains files, with complicated 2 | macro use and so on. so what you can do is force it to ignore these files. 3 | -------------------------------------------------------------------------------- /voodoo/Tutorial/2 - Command Line Usage/original/FakeWindows.h: -------------------------------------------------------------------------------- 1 | BOOL CreateProcessA( 2 | IN LPCSTR lpApplicationName , 3 | IN LPSECURITY_ATTRIBUTES lpProcessAttributes , 4 | IN LPSECURITY_ATTRIBUTES lpThreadAttributes , 5 | IN BOOL bInheritHandles , 6 | IN DWORD dwCreationFlags , 7 | IN LPVOID lpEnvironment , 8 | IN LPCSTR lpCurrentDirectory , 9 | IN LPSTARTUPINFOA lpStartupInfo , 10 | OUT LPPROCESS_INFORMATION lpProcessInformation ); 11 | -------------------------------------------------------------------------------- /voodoo/Tutorial/2 - Command Line Usage/original/Header1.h: -------------------------------------------------------------------------------- 1 | #ifndef _HEADER1 2 | #define _HEADER1 3 | 4 | extern int a; 5 | 6 | class Nothing {}; 7 | 8 | // these macros are not C++ and should be ignored 9 | IN OUT INOUT 10 | 11 | #endif 12 | -------------------------------------------------------------------------------- /voodoo/Tutorial/2 - Command Line Usage/original/Header2.h: -------------------------------------------------------------------------------- 1 | #ifndef _HEADER2 2 | #define _HEADER2 3 | 4 | class IAmInHeader2 {}; 5 | 6 | #endif 7 | -------------------------------------------------------------------------------- /voodoo/Tutorial/2 - Command Line Usage/original/HeaderWithSyntaxError.h: -------------------------------------------------------------------------------- 1 | If you are happy and you know it, syntax error! 2 | -------------------------------------------------------------------------------- /voodoo/Tutorial/2 - Command Line Usage/readme.txt: -------------------------------------------------------------------------------- 1 | Voodoo can be invoked to run on a single file at a time, or to scan a 2 | complete trees of source code. 3 | 4 | The goal is to provide each header file an alternative implementation. The 5 | test suite compiler must make sure that the header file generated is included 6 | before the real header, in the include order. I.e., if the output of multi 7 | mode goes into the directory 'voodoo', then the compile switch -Ivoodoo must 8 | come before any other -I switches. 9 | 10 | Also note, that an #include directive with "" (instead of <>), adds the 11 | current directory as the first directory in the include order, and therefore 12 | can mess things up. This is solved by generating code for every file in the 13 | source tree, so the #include "" will first look for files under the voodoo 14 | output tree. 15 | 16 | Single mode: 17 | ------------ 18 | please run python single.py --help for command line usage. 19 | 20 | Multi mode: 21 | ----------- 22 | please run python multi.py --help for command line usage. 23 | 24 | 25 | just view the examples, and run them. 26 | -------------------------------------------------------------------------------- /voodoo/Tutorial/3 - Expectation Based Mock Objects/1 - Your First Test/compile.bat: -------------------------------------------------------------------------------- 1 | python ..\..\..\multi.py --input=include --output=voodoo --exclude=VoodooConfiguration --only-if-new 2 | copy /Y ..\..\..\VoodooCommon\VoodooConfigurationForNoTestSuite.hpp voodoo\VoodooConfiguration.h 3 | cl /EHs tests\Test_Sum.cpp -Ivoodoo -Iinclude -I../../.. 4 | Test_Sum.exe 5 | -------------------------------------------------------------------------------- /voodoo/Tutorial/3 - Expectation Based Mock Objects/1 - Your First Test/include/Number.h: -------------------------------------------------------------------------------- 1 | #ifndef __NUMBER_H__ 2 | #define __NUMBER_H__ 3 | 4 | class Number 5 | { 6 | public: 7 | Number( unsigned value ) : _value( value ) {} 8 | unsigned value() const { return _value; } 9 | private: 10 | unsigned _value; 11 | }; 12 | 13 | #endif 14 | -------------------------------------------------------------------------------- /voodoo/Tutorial/3 - Expectation Based Mock Objects/1 - Your First Test/include/Sum.h: -------------------------------------------------------------------------------- 1 | #ifndef __SUM_H__ 2 | #define __SUM_H__ 3 | 4 | #include 5 | 6 | class Sum 7 | { 8 | public: 9 | Sum( const Number & first , const Number & second ) : 10 | _result( first.value() + second.value() ) 11 | { 12 | } 13 | 14 | unsigned result() const { return _result; } 15 | private: 16 | unsigned _result; 17 | }; 18 | 19 | #endif 20 | -------------------------------------------------------------------------------- /voodoo/Tutorial/3 - Expectation Based Mock Objects/1 - Your First Test/readme.txt: -------------------------------------------------------------------------------- 1 | First of all, to use Voodoo-Mock, you must configure it. Don't worry, it 2 | takes two seconds: You need to define few macros, in a file included as 3 | #include "VoodooConfiguration.h" 4 | 5 | There ready configurations in the VoodooCommon dir: one for CxxTest unit 6 | testing frame work (very recommended), one for CppUnit (less recommended), 7 | and one for working with plain exceptions, no unit testing frame work. 8 | If you do happen to implement more configuration files for other unit-testing 9 | frameworks, please contribute them back to the community. 10 | 11 | For the purpose of the tutorial, the tests are written without a framework. 12 | 13 | Now, just read the test file and two header files. 14 | -------------------------------------------------------------------------------- /voodoo/Tutorial/3 - Expectation Based Mock Objects/1 - Your First Test/tests/Test_Sum.cpp: -------------------------------------------------------------------------------- 1 | // the following line replaces the implementation of Number.h with an 2 | // expectation based mock objects implementation, which causes all the 3 | // definitions in it, i.e., the definition of the class Number, to be 4 | // mocked. This line must preceed any include directives to other code 5 | // that might eventually include Number.h 6 | #define VOODOO_EXPECT_Number_h 7 | 8 | #include "Sum.h" 9 | 10 | #include 11 | 12 | // this using directive is not mandatory, it just shortens the lines below. 13 | using namespace VoodooCommon::Expect; 14 | 15 | class TestFailed {}; 16 | 17 | int main() 18 | { 19 | // a VoodooCommon::Expect::Scenario object is a pre-made recording. the 20 | // tester fills it with what ever is supposed to happen, in the order 21 | // it supposed to happen in. 22 | Scenario scenario; 23 | // 1. the method 'value' of the object called 'Fake Number 1' is called. 24 | // it will return an 'unsigned': 100. 25 | // 2. the method 'value' of the object called 'Fake Number 2' is called. 26 | // it will return an 'unsigned': 200. 27 | scenario << 28 | new CallReturnValue< unsigned >( "Fake Number 1::value" , 100 ) << 29 | new CallReturnValue< unsigned >( "Fake Number 2::value" , 200 ); 30 | 31 | // The class FakeND_Number derives from Number. It allows the tester to 32 | // name the object. Also, this specific object destruction will not 33 | // be relayed to the scenario. 34 | FakeND_Number number1( "Fake Number 1" ); 35 | FakeND_Number number2( "Fake Number 2" ); 36 | 37 | // compare the result of the sum of the two fake objects: 100 + 200 == 300 38 | if ( Sum( number1 , number2 ).result() != 300 ) 39 | throw TestFailed(); 40 | 41 | // the scenario should be complete: both events accoured. 42 | scenario.assertFinished(); 43 | 44 | printf( "OK!\n" ); 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /voodoo/Tutorial/3 - Expectation Based Mock Objects/2 - Expectation Types/compile.bat: -------------------------------------------------------------------------------- 1 | python ..\..\..\multi.py --input=include --output=voodoo --exclude=VoodooConfiguration --only-if-new 2 | copy /Y ..\..\..\VoodooCommon\VoodooConfigurationForNoTestSuite.hpp voodoo\VoodooConfiguration.h 3 | cl /EHs tests\Test_All.cpp -Ivoodoo -Iinclude -I../../.. /Zi 4 | Test_All.exe 5 | -------------------------------------------------------------------------------- /voodoo/Tutorial/3 - Expectation Based Mock Objects/2 - Expectation Types/include/Mocked.h: -------------------------------------------------------------------------------- 1 | #ifndef __MOCKED_H__ 2 | #define __MOCKED_H__ 3 | 4 | #include 5 | 6 | class MockedClass 7 | { 8 | public: 9 | static unsigned & staticMethod(); 10 | char method(); 11 | }; 12 | 13 | void globalFunction(); 14 | namespace MockedNamespace { double globalNamespacedFunction(); } 15 | 16 | void makeRunTimeError(); 17 | 18 | class File 19 | { 20 | public: 21 | File( const char * ); 22 | void writeString( const char * ); 23 | }; 24 | 25 | #endif // __MOCKED_H__ 26 | -------------------------------------------------------------------------------- /voodoo/Tutorial/3 - Expectation Based Mock Objects/2 - Expectation Types/include/Tested.h: -------------------------------------------------------------------------------- 1 | #ifndef __TESTED_H__ 2 | #define __TESTED_H__ 3 | 4 | #include "Mocked.h" 5 | 6 | static inline void callGlobalFunction() 7 | { 8 | globalFunction(); 9 | } 10 | 11 | static inline double callGlobalNamespacedFunction() 12 | { 13 | using namespace MockedNamespace; 14 | return globalNamespacedFunction(); 15 | } 16 | 17 | static inline unsigned & callStaticMethod() 18 | { 19 | return MockedClass::staticMethod(); 20 | } 21 | 22 | static inline char constructClassToCallMethod() 23 | { 24 | return MockedClass().method(); 25 | } 26 | 27 | static inline void catchRunTimeError() 28 | { 29 | try { 30 | makeRunTimeError(); 31 | } catch ( ... ) {} 32 | } 33 | 34 | static inline void logMessage( const char * message ) 35 | { 36 | try { 37 | File( "C:\\log.txt" ).writeString( message ); 38 | } catch ( ... ) {} 39 | } 40 | 41 | #endif // __TESTED_H__ 42 | -------------------------------------------------------------------------------- /voodoo/Tutorial/3 - Expectation Based Mock Objects/3 - Parameter Expectation Types/compile.bat: -------------------------------------------------------------------------------- 1 | python ..\..\..\multi.py --input=include --output=voodoo --exclude=VoodooConfiguration --only-if-new 2 | copy /Y ..\..\..\VoodooCommon\VoodooConfigurationForNoTestSuite.hpp voodoo\VoodooConfiguration.h 3 | cl /EHs tests\Test_All.cpp -Ivoodoo -Iinclude -I../../.. /Zi 4 | Test_All.exe 5 | -------------------------------------------------------------------------------- /voodoo/Tutorial/3 - Expectation Based Mock Objects/3 - Parameter Expectation Types/include/Data.h: -------------------------------------------------------------------------------- 1 | #ifndef __DATA_H__ 2 | #define __DATA_H__ 3 | 4 | struct Data 5 | { 6 | unsigned a; 7 | unsigned b; 8 | }; 9 | 10 | class DoItInterface 11 | { 12 | public: 13 | virtual ~DoItInterface() {} 14 | virtual void doIt() = 0; 15 | }; 16 | 17 | #endif // __DATA_H__ 18 | -------------------------------------------------------------------------------- /voodoo/Tutorial/3 - Expectation Based Mock Objects/3 - Parameter Expectation Types/include/Mocked.h: -------------------------------------------------------------------------------- 1 | #ifndef __MOCKED_H__ 2 | #define __MOCKED_H__ 3 | 4 | #include "Data.h" 5 | 6 | class Spreadsheet {}; 7 | void clear( Spreadsheet & ); 8 | void setInterval( unsigned ); 9 | void logMessage( const char * ); 10 | void giveData( struct Data & data ); 11 | void setCallback( DoItInterface & interface ); 12 | void setCallback( DoItInterface * interface ); 13 | void returnValueByReferenceOutParamter( unsigned & out ); 14 | void returnValueByPointerOutParamter( unsigned * out ); 15 | 16 | #endif // __MOCKED_H__ 17 | -------------------------------------------------------------------------------- /voodoo/Tutorial/3 - Expectation Based Mock Objects/3 - Parameter Expectation Types/include/Tested.h: -------------------------------------------------------------------------------- 1 | #ifndef __TESTED_H__ 2 | #define __TESTED_H__ 3 | 4 | #include "Mocked.h" 5 | 6 | void setDefaultInterval() 7 | { 8 | setInterval( 4 ); 9 | } 10 | 11 | void setHighInterval() 12 | { 13 | setInterval( 10 ); 14 | } 15 | 16 | void doubleClear( Spreadsheet & spreadsheet ) 17 | { 18 | clear( spreadsheet ); 19 | clear( spreadsheet ); 20 | } 21 | 22 | void copyAndClear( Spreadsheet & spreadsheet ) 23 | { 24 | Spreadsheet copy( spreadsheet ); 25 | clear( copy ); 26 | } 27 | 28 | void giveDataSwitched( struct Data data ) 29 | { 30 | unsigned temp = data.a; 31 | data.a = data.b; 32 | data.b = temp; 33 | giveData( data ); 34 | } 35 | 36 | void setCallbackByReference() 37 | { 38 | class DoIt : public DoItInterface 39 | { 40 | public: 41 | void doIt() { setInterval( 0 ); } 42 | }; 43 | 44 | static DoIt it; 45 | setCallback( it ); 46 | } 47 | 48 | void setCallbackByPointer() 49 | { 50 | class DoIt : public DoItInterface 51 | { 52 | public: 53 | void doIt() { setInterval( 1 ); } 54 | }; 55 | 56 | static DoIt it; 57 | setCallback( & it ); 58 | } 59 | 60 | unsigned outParameterToReturnValue() 61 | { 62 | unsigned result; 63 | returnValueByReferenceOutParamter( result ); 64 | return result; 65 | } 66 | 67 | unsigned outPointerParameterToReturnValue() 68 | { 69 | unsigned result; 70 | returnValueByPointerOutParamter( & result ); 71 | return result; 72 | } 73 | 74 | void markLog() 75 | { 76 | logMessage( "MARK" ); 77 | } 78 | 79 | #endif // __TESTED_H__ 80 | -------------------------------------------------------------------------------- /voodoo/Tutorial/3 - Expectation Based Mock Objects/4 - Copy Construction/include/GetAndSet.h: -------------------------------------------------------------------------------- 1 | #ifndef __GET_AND_SET_H__ 2 | #define __GET_AND_SET_H__ 3 | 4 | #include "PseudoSharedPtr.h" 5 | 6 | void getAndSet() 7 | { 8 | PseudoSharedPtr shared = get(); 9 | setFirst( shared ); 10 | setSecond( shared ); 11 | } 12 | 13 | #endif // __GET_AND_SET_H__ 14 | -------------------------------------------------------------------------------- /voodoo/Tutorial/3 - Expectation Based Mock Objects/4 - Copy Construction/include/PseudoSharedPtr.h: -------------------------------------------------------------------------------- 1 | #ifndef __PSEDUO_SHARED_PTR_H__ 2 | #define __PSEDUO_SHARED_PTR_H__ 3 | 4 | class PseudoSharedPtr {}; 5 | 6 | PseudoSharedPtr get(); 7 | void setFirst( PseudoSharedPtr ); 8 | void setSecond( PseudoSharedPtr ); 9 | 10 | #endif // __PSEDUO_SHARED_PTR_H__ 11 | -------------------------------------------------------------------------------- /voodoo/Tutorial/3 - Expectation Based Mock Objects/4 - Copy Construction/readme.txt: -------------------------------------------------------------------------------- 1 | Copy Construction In Expectation Based Mock Objects: 2 | ---------------------------------------------------- 3 | 4 | When a fake object called "ABC", of a mocked class or struct, is 5 | copied, the new instance will automatically be called "Copy of ABC". 6 | If that object gets copied, the new instance will be called 7 | "Copy of Copy of ABC", and so on. 8 | 9 | For every expectation primitive, except destruction, there is another 10 | primitives, which ignores the "Copy of" prefix, or prefixes. 11 | 12 | This allows maximum flexability: in some tests the exact copy makes 13 | the difference, and in some, the exact copy does not matter. 14 | 15 | Destruction does not have an "ignoring" sibling, as a way to force 16 | the tester to be aware to the number of copies the code produces, 17 | since each copy must have a destruction expectation for itself. 18 | 19 | The voodoo expectations, and their "Copy of" ignoring alternatives are: 20 | CallReturnVoid - CallOrCopyOfReturnVoid 21 | CallReturnValue - CallOrCopyOfReturnValue 22 | CallReturnReference - CallOrCopyOfReturnReference 23 | CallReturnAuto - CallOrCopyOfReturnAuto 24 | CallThrowValue - CallOrCopyOfThrowValue 25 | 26 | The voodoo parameter expectation, which has an "Copy of" ignoring 27 | version is: 28 | Named - NamedOrCopyOf 29 | 30 | When to ignore: if the tested code has a ownership of resources 31 | symantics (i.e., you are testing auto_ptr, or shared_ptr), then 32 | you don't want to ignore copies - the test should describe the life 33 | of each copy, to be sure the resources are handled correctly. 34 | 35 | however, if you are testing code, and mocking some other class, 36 | which ownership symantics, and the mocked class is tested as a 37 | different unit, and tested to be defensive againt abuse, then you 38 | can safely ignore copying, since that aspect of the code you are not 39 | testing. 40 | 41 | The example tests a code that is suitable for ignoring copies. 42 | Still, an example for how to test the same code considering copies 43 | is also provided. 44 | -------------------------------------------------------------------------------- /voodoo/Tutorial/3 - Expectation Based Mock Objects/4 - Copy Construction/tests/Test_All.cpp: -------------------------------------------------------------------------------- 1 | #define VOODOO_EXPECT_PseudoSharedPtr_h 2 | 3 | #include "GetAndSet.h" 4 | 5 | #include 6 | 7 | using namespace VoodooCommon::Expect; 8 | using namespace VoodooCommon::Expect::Parameter; 9 | class TestFailed {}; 10 | 11 | void testConsiderCopyConstruction() 12 | { 13 | Scenario scenario; 14 | scenario << 15 | new CallReturnAuto< PseudoSharedPtr >( "get", new FakeND_PseudoSharedPtr( "IT" ) ) << 16 | new CallReturnVoid( "setFirst" ) << 17 | new Named< PseudoSharedPtr >( "Copy of Copy of IT" ) << 18 | new Destruction( "Copy of Copy of IT" ) << 19 | new CallReturnVoid( "setSecond" ) << 20 | new Named< PseudoSharedPtr >( "Copy of Copy of IT" ) << 21 | new Destruction( "Copy of Copy of IT" ) << 22 | new Destruction( "Copy of IT" ); 23 | getAndSet(); 24 | scenario.assertFinished(); 25 | } 26 | 27 | void testIgnoreCopyConstruction() 28 | { 29 | Always always; 30 | always << 31 | new Destruction( "Copy of Copy of IT" ) << 32 | new Destruction( "Copy of IT" ); 33 | Scenario scenario; 34 | scenario << 35 | new CallReturnAuto< PseudoSharedPtr >( "get", new FakeND_PseudoSharedPtr( "IT" ) ) << 36 | new CallReturnVoid( "setFirst" ) << 37 | new NamedOrCopyOf< PseudoSharedPtr >( "IT" ) << 38 | new CallReturnVoid( "setSecond" ) << 39 | new NamedOrCopyOf< PseudoSharedPtr >( "IT" ); 40 | getAndSet(); 41 | scenario.assertFinished(); 42 | } 43 | 44 | int main() 45 | { 46 | testConsiderCopyConstruction(); 47 | testIgnoreCopyConstruction(); 48 | 49 | printf( "OK!\n" ); 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /voodoo/Tutorial/clean.sh: -------------------------------------------------------------------------------- 1 | rm -fr "2 - Command Line Usage/single-result" 2 | rm -fr "2 - Command Line Usage/multi-result" 3 | -------------------------------------------------------------------------------- /voodoo/Tutorial/readme.txt: -------------------------------------------------------------------------------- 1 | All the examples in this tutorial were tested to compile with: 2 | 1. On Ubuntu 13.04. 3 | -------------------------------------------------------------------------------- /voodoo/VoodooCommon/All.h: -------------------------------------------------------------------------------- 1 | #ifndef __VOODOO_EXPECT_ALL_H__ 2 | #define __VOODOO_EXPECT_ALL_H__ 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #endif // __VOODOO_EXPECT_ALL_H__ 9 | -------------------------------------------------------------------------------- /voodoo/VoodooCommon/Common.h: -------------------------------------------------------------------------------- 1 | #ifndef __VOODOO_COMMON 2 | #define __VOODOO_COMMON 3 | 4 | #include "VoodooConfiguration.h" 5 | #include 6 | 7 | class __VoodooMockConstruction {}; 8 | 9 | #define __VoodooRedirectorConstruction __Voodoo_Error_You_Must_Enable_Voodoo_For_This_Derived_Class_Too 10 | class __VoodooRedirectorConstruction {}; 11 | 12 | #ifndef VOODOO_MAX_MESSAGE 13 | #define VOODOO_MAX_MESSAGE 4096 14 | #endif // VOODOO_MAX_MESSAGE 15 | 16 | #define __VOODOO_QUOTE( x ) #x 17 | 18 | class __VoodooGrowingString 19 | { 20 | public: 21 | __VoodooGrowingString() 22 | { 23 | _result[ 0 ] = '\0'; 24 | _result[ VOODOO_MAX_MESSAGE - 1 ] = '\0' ; 25 | _result[ VOODOO_MAX_MESSAGE ] = '\0' ; 26 | } 27 | 28 | void append( const char * source ) 29 | { 30 | unsigned length = strlen( _result ); 31 | strncat( _result , source , VOODOO_MAX_MESSAGE - length ); 32 | } 33 | 34 | const char * result() 35 | { 36 | if ( _result[ VOODOO_MAX_MESSAGE - 1 ] != '\0' ) { 37 | VOODOO_FAIL_TEST( "Please #define VOODOO_MAX_MESSAGE to a value " 38 | "larger than " __VOODOO_QUOTE( VOODOO_MAX_MESSAGE ) ); 39 | } 40 | return _result; 41 | } 42 | 43 | private: 44 | char _result[ VOODOO_MAX_MESSAGE + 1 ]; 45 | }; 46 | 47 | #endif // __VOODOO_COMMON 48 | -------------------------------------------------------------------------------- /voodoo/VoodooCommon/Sprintf.h: -------------------------------------------------------------------------------- 1 | #if ! defined(__VOODOO_COMMON_SPRINTF_H__) 2 | #define __VOODOO_COMMON_SPRINTF_H__ 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | namespace VoodooCommon 9 | { 10 | 11 | class Sprintf 12 | { 13 | public: 14 | Sprintf( const char * format, ... ) 15 | { 16 | va_list args; 17 | va_start( args, format ); 18 | vsnprintf( buffer, sizeof( buffer ), format, args ); 19 | buffer[ sizeof( buffer ) - 1 ] = '\0'; 20 | va_end( args ); 21 | } 22 | 23 | operator const char * () const { return buffer; } 24 | operator std::string () const { return buffer; } 25 | 26 | private: 27 | char buffer[ 512 ]; 28 | }; 29 | 30 | } 31 | 32 | #endif // __VOODOO_COMMON_SPRINTF_H__ 33 | -------------------------------------------------------------------------------- /voodoo/VoodooCommon/VoodooConfigurationForCxxTest.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define VOODOO_FAIL_TEST( s ) TS_FAIL( s ) 4 | 5 | #define VOODOO_FAIL_TEST_NO_THROW( s ) do { \ 6 | try { \ 7 | VOODOO_FAIL_TEST( s ); \ 8 | } catch( CxxTest::AbortTest & ) {} \ 9 | } while ( false ) 10 | 11 | #define VOODOO_WARNING( x ) TS_WARN( stderr , "%s\n" , x ); 12 | 13 | #define VOODOO_TO_STRING( x ) TS_AS_STRING( x ) 14 | -------------------------------------------------------------------------------- /voodoo/VoodooCommon/VoodooConfigurationForNoTestSuite.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __VOODOO_CONFIGURATION_H__ 2 | #define __VOODOO_CONFIGURATION_H__ 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | class VoodooTestFailed {}; 9 | 10 | #define VOODOO_FAIL_TEST( s ) { \ 11 | fprintf( stderr , "%s\n" , s );\ 12 | throw VoodooTestFailed(); \ 13 | } 14 | #define VOODOO_FAIL_TEST_NO_THROW( s ) { \ 15 | fprintf( stderr , "%s\n" , s );\ 16 | _exit(1); \ 17 | } 18 | #define VOODOO_WARNING( x ) fprintf( stderr , "%s\n" , x ); 19 | 20 | #define VOODOO_TO_STRING( x ) \ 21 | ( ( (std::strstream &) (std::strstream() << (x) << '\0') ).str() ) 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /voodoo/clang/__init__.py: -------------------------------------------------------------------------------- 1 | #===- __init__.py - Clang Python Bindings --------------------*- python -*--===# 2 | # 3 | # The LLVM Compiler Infrastructure 4 | # 5 | # This file is distributed under the University of Illinois Open Source 6 | # License. See LICENSE.TXT for details. 7 | # 8 | #===------------------------------------------------------------------------===# 9 | 10 | r""" 11 | Clang Library Bindings 12 | ====================== 13 | 14 | This package provides access to the Clang compiler and libraries. 15 | 16 | The available modules are: 17 | 18 | cindex 19 | 20 | Bindings for the Clang indexing library. 21 | """ 22 | 23 | __all__ = ['cindex'] 24 | 25 | -------------------------------------------------------------------------------- /voodoo/clang/enumerations.py: -------------------------------------------------------------------------------- 1 | #===- enumerations.py - Python Enumerations ------------------*- python -*--===# 2 | # 3 | # The LLVM Compiler Infrastructure 4 | # 5 | # This file is distributed under the University of Illinois Open Source 6 | # License. See LICENSE.TXT for details. 7 | # 8 | #===------------------------------------------------------------------------===# 9 | 10 | """ 11 | Clang Enumerations 12 | ================== 13 | 14 | This module provides static definitions of enumerations that exist in libclang. 15 | 16 | Enumerations are typically defined as a list of tuples. The exported values are 17 | typically munged into other types or classes at module load time. 18 | 19 | All enumerations are centrally defined in this file so they are all grouped 20 | together and easier to audit. And, maybe even one day this file will be 21 | automatically generated by scanning the libclang headers! 22 | """ 23 | 24 | # Maps to CXTokenKind. Note that libclang maintains a separate set of token 25 | # enumerations from the C++ API. 26 | TokenKinds = [ 27 | ('PUNCTUATION', 0), 28 | ('KEYWORD', 1), 29 | ('IDENTIFIER', 2), 30 | ('LITERAL', 3), 31 | ('COMMENT', 4), 32 | ] 33 | 34 | __all__ = ['TokenKinds'] 35 | -------------------------------------------------------------------------------- /voodoo/compileclang.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import os 3 | import shutil 4 | 5 | shutil.rmtree( "/tmp/clang", ignore_errors = True ) 6 | os.mkdir( "/tmp/clang" ) 7 | os.chdir( "/tmp/clang" ) 8 | subprocess.check_call( "svn co http://llvm.org/svn/llvm-project/llvm/trunk@206407 llvm", shell = True ) 9 | checkoutClang = subprocess.Popen( "svn co http://llvm.org/svn/llvm-project/cfe/trunk@206406 clang", shell = True, cwd = "llvm/tools" ) 10 | subprocess.check_call( "svn co http://llvm.org/svn/llvm-project/compiler-rt/trunk@206387 compiler-rt", shell = True, cwd = "llvm/projects" ) 11 | result = checkoutClang.wait() 12 | if result != 0: 13 | raise Exception( "checkout of clang failed" ) 14 | os.mkdir( "build" ) 15 | subprocess.check_call( "../llvm/configure --enable-optimized --disable-assertions --disable-keep-symbols", shell = True, cwd = "build" ) 16 | subprocess.check_call( "make -j 5", shell = True, cwd = "build" ) 17 | shutil.copy2( "build/Release/lib/libclang.so", "libclang.so" ) 18 | shutil.copytree( "llvm/tools/clang/bindings/python/clang", "clang" ) 19 | -------------------------------------------------------------------------------- /voodoo/functiondecomposition.py: -------------------------------------------------------------------------------- 1 | class FunctionDecomposition: 2 | def __init__( self, name, parameters, text, returnType, returnRValue, static, const, templatePrefix = "", 3 | virtual = False ): 4 | self.name = name 5 | self.parameters = parameters 6 | self.text = text 7 | self.returnType = returnType 8 | self.returnRValue = returnRValue 9 | self.static = static 10 | self.templatePrefix = templatePrefix 11 | self.const = const 12 | self.virtual = virtual 13 | 14 | def parametersFullSpec( self ): 15 | return ", ".join( [ p[ 'text' ] for p in self.parameters ] ) 16 | 17 | def parametersForwardingList( self ): 18 | return ", ".join( [ p[ 'name' ] for p in self.parameters ] ) 19 | 20 | def returnTypeIsVoid( self ): 21 | return self.returnType == "void" 22 | 23 | def stringReturnIfNotVoid( self ): 24 | return "" if self.returnTypeIsVoid() else "return " 25 | 26 | def stringStaticIfStatic( self ): 27 | return "static " if self.static else "" 28 | 29 | def stringStaticInlineIfStatic( self ): 30 | return "static inline " if self.static else "" 31 | def stringVirtualIfVirtual( self ): 32 | return "virtual" if self.virtual else "" 33 | -------------------------------------------------------------------------------- /voodoo/gccparity.py: -------------------------------------------------------------------------------- 1 | #tools to make clang compile gcc code 2 | import os 3 | import subprocess 4 | import re 5 | 6 | emulateGCCInClangPreinclude = os.path.join( os.path.dirname( __file__ ), "emulate_gcc_in_clang_preinclude.h" ) 7 | 8 | _cachedGCCIncludePath = None 9 | def gccIncludePath(): 10 | global _cachedGCCIncludePath 11 | if _cachedGCCIncludePath is None: 12 | with open( os.devnull, "r" ) as noInput: 13 | output = subprocess.check_output( [ "g++", "-E", "-x", "c++", "-", "-v" ], stderr = subprocess.STDOUT, stdin = noInput ) 14 | _cachedGCCIncludePath = list() 15 | for filename in re.findall( r"\r?\n (\S+)", output ): 16 | if os.path.isdir(filename): 17 | _cachedGCCIncludePath.append(os.path.normpath(filename).replace("\\","/")) 18 | return _cachedGCCIncludePath 19 | -------------------------------------------------------------------------------- /voodoo/growcode.py: -------------------------------------------------------------------------------- 1 | _DEFAULT_SNIPPET = 1000000 2 | 3 | class GrowCode: 4 | def __init__( self ): 5 | self._snippets = [ "" ] 6 | self._indents = [ 0 ] 7 | self._defaultSnippet = 0 8 | 9 | def _snippetOrDefault( self , snippet ): 10 | if snippet == _DEFAULT_SNIPPET: 11 | return self._defaultSnippet 12 | else: 13 | return snippet 14 | 15 | def lineOut( self , text , snippet = _DEFAULT_SNIPPET ): 16 | indent = "\t" * self._indents[ self._snippetOrDefault( snippet ) ] 17 | indented = indent + ( "\n" + indent ).join( text.split( "\n" ) ) + "\n" 18 | self._snippets[ self._snippetOrDefault( snippet ) ] += indented 19 | 20 | def increaseIndent( self , snippet = _DEFAULT_SNIPPET ): 21 | self._indents[ self._snippetOrDefault( snippet ) ] += 1 22 | 23 | def decreaseIndent( self , snippet = _DEFAULT_SNIPPET ): 24 | assert self._indents[ self._snippetOrDefault( snippet ) ] > 0 25 | self._indents[ self._snippetOrDefault( snippet ) ] -= 1 26 | 27 | def newSnippet( self , snippet = _DEFAULT_SNIPPET ): 28 | snippet = self._snippetOrDefault( snippet ) 29 | self._snippets.insert( snippet + 1 , "" ) 30 | self._indents.insert( snippet + 1 , self._indents[ snippet ] ) 31 | if self._defaultSnippet >= snippet: 32 | self._defaultSnippet += 1 33 | return snippet 34 | 35 | def result( self ): 36 | return "".join( self._snippets ) 37 | -------------------------------------------------------------------------------- /voodoo/libclang.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shlomimatichin/Voodoo-Mock/02fc8c4f3029673fc1c16bc754577593a5d088c3/voodoo/libclang.so -------------------------------------------------------------------------------- /voodoo/perfilesettings.py: -------------------------------------------------------------------------------- 1 | import traceback 2 | import re 3 | 4 | class PerFileSettings: 5 | _EXPRESSION1 = re.compile( r"//\s*VOODOO_PERFILESETTINGS\s*(.*)" ) 6 | _EXPRESSION2 = re.compile( r"/\*\s*VOODOO_PERFILESETTINGS\s*(.*)\*/" ) 7 | _EXPRESSIONS = [ _EXPRESSION1, _EXPRESSION2 ] 8 | 9 | def __init__( self, inputLines ): 10 | self._defaults() 11 | 12 | relevant = self._relevantLines( inputLines ) 13 | if relevant == "": 14 | return 15 | try: 16 | exec relevant in dict(), self.__dict__ 17 | except: 18 | traceback.print_exc() 19 | print "Python syntax error in: '%s'" % relevant 20 | 21 | def filterInherits( self, inherits ): 22 | return [ inherit for inherit in inherits if inherit not in self.NO_INHERITS ] 23 | 24 | def _relevantLines( self, inputLines ): 25 | relevantLines = [] 26 | for line in inputLines: 27 | for exp in self._EXPRESSIONS: 28 | match = exp.search( line ) 29 | if match is not None: 30 | relevantLines.append( match.group( 1 ) ) 31 | continue 32 | return "\n".join( relevantLines ) 33 | 34 | def _defaults( self ): 35 | self.NO_MOCK_DERIVE_AND_USE_DEFAULT_CONSTRUCTOR = [] 36 | self.SKIP = [] 37 | self.NO_MOCK = [] 38 | self.NO_INHERITS = [] 39 | self.IGNORE_PARAMETER_PACK = [] 40 | -------------------------------------------------------------------------------- /voodoo/protectionignoring.py: -------------------------------------------------------------------------------- 1 | class ProtectionIgnoring: 2 | def __init__( self ): 3 | self._protection = [ "public" ] 4 | 5 | def ignore( self ): 6 | return 'private' in self._protection or 'skip' in self._protection 7 | 8 | def enter( self, protection ): 9 | assert protection in [ 'private', 'protected', 'public' ] 10 | self._protection.append( protection ) 11 | 12 | def enterSkipped( self ): 13 | self._protection.append( 'skip' ) 14 | 15 | def leave( self ): 16 | self._protection.pop() 17 | 18 | def change( self, protection ): 19 | assert protection in [ 'private', 'protected', 'public' ] 20 | self._protection[ -1 ] = protection 21 | 22 | def ignoreButLast( self ): 23 | return 'private' in self._protection[ : -1 ] or 'skip' in self._protection 24 | #note: no [:-1] for 'skip', this is not a bug 25 | -------------------------------------------------------------------------------- /voodoo/unittests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shlomimatichin/Voodoo-Mock/02fc8c4f3029673fc1c16bc754577593a5d088c3/voodoo/unittests/__init__.py -------------------------------------------------------------------------------- /voodoo/unittests/savingiterator.py: -------------------------------------------------------------------------------- 1 | import iterateapi 2 | 3 | class SavingIterator( iterateapi.IterateAPI ): 4 | def __init__( self ): 5 | iterateapi.IterateAPI.__init__( self ) 6 | self.printErrors = True 7 | self.saved = [] 8 | self._addSaver( 'structForwardDeclaration' ) 9 | self._addSaver( 'classForwardDeclaration' ) 10 | self._addSaver( 'enterStruct' ) 11 | self._addSaver( 'leaveStruct' ) 12 | self._addSaver( 'enterClass' ) 13 | self._addSaver( 'leaveClass' ) 14 | self._addSaver( 'variableDeclaration' ) 15 | self._addSaver( 'fieldDeclaration' ) 16 | self._addSaver( 'typedef' ) 17 | self._addSaver( 'union' ) 18 | self._addSaver( 'enum' ) 19 | self._addDecompositionSaver( 'functionForwardDeclaration' ) 20 | self._addDecompositionSaver( 'functionDefinition' ) 21 | self._addDecompositionSaver( 'constructorDefinition' ) 22 | self._addDecompositionSaver( 'method' ) 23 | self._addSaver( 'conversionFunction' ) 24 | self._addSaver( 'enterNamespace' ) 25 | self._addSaver( 'leaveNamespace' ) 26 | self._addSaver( 'accessSpec' ) 27 | self._addSaver( 'using' ) 28 | 29 | def _addSaver( self, callName ): 30 | setattr( self, callName, lambda ** kwargs: self._save( callName, ** kwargs ) ) 31 | 32 | def _addDecompositionSaver( self, callName ): 33 | setattr( self, callName, lambda decomposition: self._save( callName, ** decomposition.__dict__ ) ) 34 | 35 | def _save( self, callbackName, fullText = None, ** kwargs ): 36 | if fullText is not None: 37 | kwargs[ 'fullTextNaked' ] = fullText.strip( ';' ).replace( " ", "" ).replace( "\t", "" ).replace( '\n', '' ) 38 | self.saved.append( dict( callbackName = callbackName, ** kwargs ) ) 39 | 40 | def handleError( self, severity, location, spelling, ranges, fixits ): 41 | if self.printErrors: 42 | print "X"*80 43 | print severity 44 | print location 45 | print spelling 46 | print ranges 47 | print fixits 48 | raise Exception( "error parsing" ) 49 | -------------------------------------------------------------------------------- /voodoo/unittests/tools.py: -------------------------------------------------------------------------------- 1 | import contextlib 2 | import os 3 | import tempfile 4 | 5 | @contextlib.contextmanager 6 | def temporaryFile( contents ): 7 | # 8 | # From the python documentation: 9 | # Whether the name can be used to open the file a second time, while the 10 | # named temporary file is still open, varies across platforms (it can be 11 | # so used on Unix; it cannot on Windows NT or later). 12 | # 13 | t = tempfile.NamedTemporaryFile( suffix = ".h", delete = False ) 14 | t.write( contents ) 15 | t.flush() 16 | t.close() 17 | yield t.name 18 | os.unlink(t.name) 19 | -------------------------------------------------------------------------------- /voodoo/voodoo.py: -------------------------------------------------------------------------------- 1 | from preprocessor import Preprocessor 2 | from voodoomultiplexeriterator import VoodooMultiplexerIterator 3 | from perfilesettings import PerFileSettings 4 | import re 5 | 6 | def _readLinesOfFile( fileName ): 7 | f = file( fileName ) 8 | try: 9 | return f.readlines() 10 | finally: 11 | f.close() 12 | 13 | def voodoo( input, output, pathToRemoveFromIdentifier, voodooDBFile, includes, defines, preIncludes, trace = False ): 14 | inputLines = _readLinesOfFile( input ) 15 | perFileSettings = PerFileSettings( inputLines ) 16 | preprocessor = Preprocessor( input, output, inputLines, pathToRemoveFromIdentifier ) 17 | 18 | out = preprocessor.header() 19 | out += '#include \n\n' 20 | iterator = VoodooMultiplexerIterator( perFileSettings, voodooDBFile ) 21 | iterator.process( input, includes = includes, defines = defines, preIncludes = preIncludes ) 22 | out += iterator.iter() 23 | out += preprocessor.switchToExpectation() 24 | out += '#include "VoodooCommon/All.h"\n\n' 25 | out += iterator.expect() 26 | out += preprocessor.footer() 27 | return out 28 | 29 | def externalVoodoo( input, output, linkTo, pathToRemoveFromIdentifier = "", trace = False ): 30 | inputLines = _readLinesOfFile( input ) 31 | perFileSettings = PerFileSettings( inputLines ) 32 | preprocessor = Preprocessor( linkTo, output, inputLines, pathToRemoveFromIdentifier ) 33 | 34 | out = preprocessor.externalHeader() 35 | out += '#include "VoodooConfiguration.h"\n' 36 | out += '#include \n\n' 37 | out += "namespace External\n{\n\n" 38 | iterator = VoodooMultiplexerIterator( perFileSettings ) 39 | iterator.process( input ) 40 | out += iterator.iter() 41 | out += "\n}\n\n" 42 | out += preprocessor.externalSwitchToExpectation() 43 | out += '#include "VoodooCommon/All.h"\n\n' 44 | out += "namespace External\n{\n\n" 45 | out += iterator.expect() 46 | out += "\n}\n\n" 47 | out += preprocessor.externalFooter() 48 | return out 49 | -------------------------------------------------------------------------------- /voodoo/voodoodbiterator.py: -------------------------------------------------------------------------------- 1 | import shelve 2 | import iterateapi 3 | import atexit 4 | import filelock 5 | 6 | class VoodooDBIterator( iterateapi.IterateAPI ): 7 | def __init__( self, perFileSettingsNotUsed, dbFilename ): 8 | self._dbFilename = dbFilename 9 | iterateapi.IterateAPI.__init__( self ) 10 | self._db = {} 11 | atexit.register( self._atExit ) 12 | 13 | def _atExit( self ): 14 | if not self._dbFilename: 15 | return 16 | with filelock.FileLock( self._dbFilename, timeout = 2 ) as lock: 17 | db = shelve.open( self._dbFilename, "c" ) 18 | db.update( self._db ) 19 | db.close() 20 | 21 | def structForwardDeclaration( self, ** kwargs ): pass 22 | def classForwardDeclaration( self, ** kwargs ): pass 23 | def enterStruct( self, ** kwargs ): pass 24 | def leaveStruct( self, ** kwargs ): pass 25 | def enterClass( self, ** kwargs ): pass 26 | def leaveClass( self, ** kwargs ): pass 27 | def variableDeclaration( self, ** kwargs ): pass 28 | def typedef( self, ** kwargs ): pass 29 | def enum( self, ** kwargs ): pass 30 | def fieldDeclaration( self, ** kwargs ): pass 31 | def enterNamespace( self, ** kwargs ): pass 32 | def leaveNamespace( self, ** kwargs ): pass 33 | def accessSpec( self, ** kwargs ): pass 34 | def using( self, ** kwargs ): pass 35 | 36 | def functionForwardDeclaration( self, decomposition ): 37 | self._db[ self._fullIdentifier( decomposition.name ) ] = decomposition 38 | def functionDefinition( self, decomposition ): 39 | self._db[ self._fullIdentifier( decomposition.name ) ] = decomposition 40 | def constructorDefinition( self, decomposition ): 41 | self._db[ self._fullIdentifier( decomposition.name ) ] = decomposition 42 | def method( self, decomposition ): 43 | self._db[ self._fullIdentifier( decomposition.name ) ] = decomposition 44 | 45 | def _fullIdentifier( self, identifier ): 46 | return "::".join( [ identifier ] ) 47 | -------------------------------------------------------------------------------- /voodoo/voodoodefs.py: -------------------------------------------------------------------------------- 1 | MOCK_PREFIX = "Mock_" 2 | FAKE_PREFIX = "Fake_" 3 | FAKE_ND_PREFIX = "FakeND_" 4 | VOODOO_CALL = "__voodooCall" 5 | 6 | def mockClass( identifier ): 7 | return MOCK_PREFIX + identifier 8 | 9 | def fakeClass( identifier ): 10 | return FAKE_PREFIX + identifier 11 | 12 | def fakeNDClass( identifier ): 13 | return FAKE_ND_PREFIX + identifier 14 | 15 | def templateLine( template ): 16 | if template == "": 17 | return template 18 | return template + "\n" 19 | 20 | def returnIfNotVoid( functionDecomposition ): 21 | if functionDecomposition.returnType == 'void': 22 | return "" 23 | else: 24 | return "return " 25 | -------------------------------------------------------------------------------- /wercker.yml: -------------------------------------------------------------------------------- 1 | box: invalidname/cpp11@0.0.3 2 | build: 3 | steps: 4 | - pip-install 5 | 6 | - script: 7 | name: Setup gcov 8 | code: | 9 | sudo update-alternatives --install /usr/bin/gcov gcov /usr/bin/gcov-4.8 99 10 | 11 | - script: 12 | name: Output versions 13 | code: | 14 | echo "python version $(python --version)" 15 | echo "g++ version $(g++ -v)" 16 | echo "gcov version $(gcov -v)" 17 | 18 | - script: 19 | name: Voodoo unittest 20 | code: | 21 | make unittest 22 | 23 | - script: 24 | name: Voodoo examples 25 | code: | 26 | make build 27 | --------------------------------------------------------------------------------