1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-04-29 19:45:01 +02:00

Patch for Brent Nicolle.

Unit tests of code in the Core plugin should now be placed in the core.tests plugin. 
(I did not delete test from the ui.tests plugin, but that's an idea whose time is coming soon.) 

Resources and property files for unit tests are now in a separate directory from the root. 

The testlauncher may experience some turbulence, but out of the box tests work as before.
This commit is contained in:
John Camelon 2003-06-18 21:29:47 +00:00
parent 61f80b02fe
commit 2bbab21405
116 changed files with 15764 additions and 0 deletions

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="model"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="src" path="/org.junit"/>
<classpathentry kind="src" path="/org.eclipse.cdt.core"/>
<classpathentry kind="src" path="/org.eclipse.core.resources"/>
<classpathentry kind="src" path="/org.eclipse.core.runtime"/>
<classpathentry kind="src" path="suite"/>
<classpathentry kind="src" path="/org.eclipse.core.boot"/>
<classpathentry kind="src" path="build"/>
<classpathentry kind="src" path="parser"/>
<classpathentry kind="src" path="/org.apache.xerces"/>
<classpathentry kind="src" path="failures"/>
<classpathentry kind="src" path="/org.eclipse.swt"/>
<classpathentry kind="src" path="/org.eclipse.ui"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View file

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>org.eclipse.cdt.core.tests</name>
<comment></comment>
<projects>
<project>org.apache.xerces</project>
<project>org.eclipse.cdt.core</project>
<project>org.eclipse.cdt.core.linux</project>
<project>org.eclipse.cdt.core.qnx</project>
<project>org.eclipse.cdt.core.solaris</project>
<project>org.eclipse.cdt.core.win32</project>
<project>org.eclipse.core.boot</project>
<project>org.eclipse.core.resources</project>
<project>org.eclipse.core.runtime</project>
<project>org.eclipse.swt</project>
<project>org.eclipse.ui</project>
<project>org.junit</project>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.pde.PluginNature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,570 @@
2003-06-17 Brent Nicolle
Added Interface tests of IStructure.java.
2003-06-16 Vladimir Hirsl
Added /build, /parser, /failures and /suite directories to the library.
Copied resources from /model/org.eclipse.cdt.core.model.tests.resources
to /model/org/clipse/cdt/core/model/tests/resources/cmodel.
Added class AISResultPrinter to format test results.
Class AutomatedIntegrationSuite now implements IPlatformRunnable.
2003-06-17 Victor Mozgin
Added DeclaratorsTests.java (invocation in AllCoreTests).
Added DeclaratorsTests.cpp to org.eclipse.cdt.core.model.tests.resources.
2003-06-14 Victor Mozgin
Moved testBugSingleton192() from LokiFailures to DOMTests.
Added testPointersToMembers() and testPointersToMemberFunctions() to DOMTests.
Added testBug36290() and testBug36931() to DOMTests.
2003-06-13 John Camelon
Added Class/Base infrastructure to public interfaces & requestor callback.
Moved many internal interfaces to external packages.
Organized imports.
2003-06-13 Victor Mozgin
Renamed NullParserCallback into NullSourceElementRequester in AutomatedFramework.
2003-06-13 John Camelon
Merged ParserSymbolTable branch back into HEAD.
2003-06-12 John Camelon
Get rest of JUnit tests working, will merge back to HEAD branch.
2003-06-12 John Camelon
Introduction of ASTFactory strategy, some restructuring of packages and interfaces.
2003-06-11 Victor Mozgin
Old Java TestCase.txt and TestCase2.txt for partioning testing have been replaced with C/C++ files.
Modified AutomatedIntegrationSuite.java so it doesn't produce JUnit warning anymore.
All tests in org.eclipse.cdt.ui.tests should pass now.
3003-06-11 Peter Graves
Update the test.xml to get the location of org.eclipse.test from a property
if set. If the property is not set, it will default to the old value.
2003-06-11 Victor Mozgin
Added TortureTest to test CDT C++ parser with GCC testsuites.
GCC testsuites are not included.
2003-06-10 John Camelon
Futher pursuit of the golden hammer, symbol table integration.
2003-06-10 Brent Nicolle
Added some Interface tests of (IInclude, IMacro, IStructure).
Made sure all the Test Suites have names in the JUnit hierarchy.
2003-06-09 John Camelon
First step in replacing IParserCallback with ISourceElementRequestor.
2003-06-09 Victor Mozgin
Moved testBug36769() from ACEFailedTest.java to DOMTests.java.
Removed ACEFailedTest.java as it is empty now.
Added DOMTests.testBug36769B().
2003-06-09 Victor Mozgin
Moved testBug36932() from DOMFailedTest.java to DOMTests.java.
Added DOMTests.testBug36932B() and DOMTests.testBug36932C().
2003-06-09 Victor Mozgin
Moved testBug36701() from ScannerFailedTests.java to ScannerTestCase.java.
Renamed it to testBug36701A() and fixed it.
Added ScannerTestCase.testBug36701B().
2003-06-07 Victor Mozgin
Moved testBug36766A(), testBug36766B() & testBug36766C() from STLFailedTests.java to DOMTests.java.
Renamed them to testBug36766and36769x(), as they cover both PRs.
Added testBug36766and36769D() - test for templated destructor.
2003-06-05 John Camelon
Moved testBug23478A() & testBug23478B() from failed tests to TranslationUnitTests.java.
Removed TranslationUnitFailedTests.java as it was empty.
2003-05-29 Andrew Niefer
Modified tests to support eType & PtrOp changes in core
Added ParserSymbolTableTest::testTemplateParameterAsParent
Added ParserSymbolTableTest::testTemplateInstanceAsParent
Added ParserSymbolTableTest::testTemplateParameterDefaults
Added ParserSymbolTableTest::testTemplateParameterAsFunctionArgument
started ParserSymbolTableTest::incompletetestTemplateSpecialization
2003-05-26 John Camelon
Rollback PST/Parser integration.
2003-05-13 Andrew Niefer
Modified ParserSymbolTableTest to use new interface
2003-05-08 Andrew Niefer
Added ParserSymbolTableTest::testMarkRollback
2003-05-06 John Camelon
Further integration of SymbolTable into Parser, some refactoring.
2003-05-05 John Camelon/Andrew Niefer
Added CrossReferenceTests to ParserTestSuite to test symbol-table/DOM interworking.
2003-05-05 Andrew Niefer
Rewrote ParserSymbolTableTest to reflect structural changes to the symbol table.
2003-05-01 Andrew Niefer
Updated FractionalAutomatedTest to use threads
Modified ScannerTestCase::testBug36287
Added ScannerTestCase::testBug37011
Added ScannerTestCase::testOtherPreprocessorDefines
2003-04-28 John Camelon
Moved testBug36730() & testBug37019() from DOMFailedTests to DOMTests.
2003-04-28 Andrew Niefer
Added DOMFailedTest::testBug37019
Added DOMFailedTest::testBug36932
Added ScannerFailedTest::testBug37011
2003-04-28 John Camelon
Added DOMTests::testOrder().
2003-04-28 Peter Graves
* model/org/eclipse/cdt/core/model/tests/BinaryTests:
Updated to remove a few small errors, and deal with some changes
to the core CDT
2003-04-27 John Camelon
Added testBug36932() to DOMTests.
Moved testBugFunctor758() from LokiFailures to DOMTests.
Moved testBug36704() from DOMFailedTest to DOMTests.
Moved testBug36699() from DOMFailedTest to DOMTests.
Moved testBug36691() from DOMFailedTest to DOMTests.
2003-04-25 Andrew Niefer
Moved ACEFailedTest::testBug36771 to DOMTests
Moved DOMFailedTest::testBug36714 to DOMTests
Updated ScannerTestCase::testBug36816
2003-04-25 John Camelon
Added DOMTests::testBug36852().
Added DOMTests::testBug36764().
Moved DOMFailedTests::testBug36702() to DOMTests().
2003-04-24 John Camelon
Moved fixed tests from FailedTests to DOMTests.
Added DOMTests::testBug36799().
Cleaned up tests to reduce amount of code necessary to maintain these things.
2003-04-24 John Camelon
Moved fixed tests from FailedTests to DOMTests.
Added LokiFailures.java to failed tests directory.
2003-04-24 Andrew Niefer
Added AutomatedFramework.java
Added FractionalAutomatedTest (which derives from AutomatedFramework)
Refactored AutomatedTest to derive from AutomatdFramework
Added ScannerTestCase.testBug36816
Added ScannerTestCase.testBug36255
2003-04-24 John Camelon
Fixed Java 1.3 compliance issue w/AutomatedTest.java
Fixed False failure in HelloWorld.java.
2003-04-21 John Camelon
Updated DOMTests::testBug36247().
Moved testBug36692(), testBug36703(), testBug36708(), testBug36707(), testBug36689()
and testBug36690() from DOMFailedTests to DOMTests and updated them.
2003-04-20 John Camelon
Added DOMTests::testBug36551().
Adjusted AutomatedTest to turn on line numbering.
Added DOMFailedTests and 11 failed test cases.
2003-04-17 Andrew Niefer
Added ScannerTestCase::testBug36695()
Moved ScannerFailedTest::testBug36521 to ScannerTestCase::testBug36521()
Moved ScannerFailedTest::testBug36509 to ScannerTestCase::testBug36509()
Moved ScannerFailedTest::testBug36475 to ScannerTestCase::testBug36475()
Updated ScannerTestCase::testBug36047
Updated ScannerTestCase::testBug36045
2003-04-17 John Camelon
Updated DOMTests::testBug36600().
Updated LineNumberTest::testDOMLineNos().
Added DOMTests::testBug36559().
2003-04-17 Andrew Niefer
Added AutomatedTest
Added resources.cFiles
Added resources.cppFiles
2003-04-16 John Camelon
Added DOMTests::testBug36532().
Added DOMTests::testBug36432().
Added DOMTests::testBug36594().
Added DOMTests::testBug36600().
Added DOMTests::testArrayOfPointerToFunctions().
2003-04-15 John Camelon
Added ScannerTestCase::testBug36434().
Added ScannerTestCase::testMultipleLines().
Added ParserTestSuite.
Added LineNumberTest.
Updated CModelElementsTests to set the Nature of the C++ project appropriately.
2003-04-15 Andrew Niefer
Moved ScannerFailedTest::testBug36047 to ScannerTestCase::testBug36047
Added ScannerFailedTest::testBug36475
2003-04-13 John Camelon
Added DOMTests::testPointersToFunctions.
2003-04-11 John Camelon
Added DOMTests::testBug36247().
2003-04-11 Andrew Niefer
Moved ScannerFailedTest::testBug36316 to ScannerTestCase::testBug36316
Added ScannerFailedTest::testBug36047
Added ScannerTestCase::testNestedRecursiveDefines
2003-04-10 John Camelon
Added DOMTests::testBug36237().
2003-04-09 John Camelon
Removed all the old Code Model Builder source that was no longer being used (NewModelBuilder.java, etc.).
Moved all the files in parser.util directory to the dom.
Organized imports.
Added DOMTests::testTemplateDeclarationOfMethod().
Added DOMTests::testBug36250().
Added DOMTests::testBug36240().
Added DOMTests::testBug36254().
2003-04-09 John Camelon
Updated ScannerTest::testBug36045().
Added ScannerTest::testBug36287().
Added DOMTests::testBug36288().
2003-04-06 Andrew Niefer
Added ParserSymbolTableTest::testOverloadRanking()
2003-04-04 Alain Magloire
* src/org/eclipse/cdt/testplugin/util/VerifyDialog.java:
Remove some warnings.
2003-04-03 John Camelon
Updated ScannerTest::testSimpleIfdef() for bug36019.
Updated ScannerTest::testNumerics() for bug36020.
Added ScannerTest::testBug36045().
Updated DOMTests::testTemplateDeclaration() for template grammar updates.
2003-04-01 Andrew Niefer
ParserSymbolTableTest. modifications to using declaration tests to reflect changes in the
symbol table. Also added testUserDefinedConversionSequences()
2003-04-01 John Camelon
Added testBug35906() to DOMTests.
2003-03-31 John Camelon
Added testStruct() to DOMTests.
Added test35892()to ScannerTest.
2003-03-31 Andrew Niefer
In ParserSymbolTableTest, renamed testFunctionResolution_2() to testFunctionResolution_PointersAndBaseClasses(),
and modified to reflect changes in function resolution.
Added testFunctionResolution_TypedefsAndPointers().
2003-03-31 John Camelon
Added testWeirdStrings() and testNumerics() to ScannerTestCase.
Added testTemplateSpecialization(), testTemplateDeclaration(), testBug26467(),
testTypedef() and testTemplateInstantiation() to DOMTests.
2003-03-28 John Camelon
Added testConstructorChain() and testASMDefinition() to DOMTests.
2003-03-27 Alain Magloire
Changes were done in the Core Model API, the hierarchy is now
ICModel
ICProject
ICContainer
ITranslationUnit
IArchive
IBinary
We adjust the tests.
* model/org/eclipse/cdt/core/model/tests/ArchiveTests.java
* model/org/eclipse/cdt/core/model/tests/BinaryTests.java
* model/org/eclipse/cdt/core/model/tests/TranslationUniTests.java
* model/org/eclipse/cdt/core/model/tests/WorkingCopyTests.java
2003-03-26 Andrew Niefer
In ParserSymbolTableTest :
updated all tests to reflect TypeInfo changes
Added testFunctionResolution() & testFunctionResolution_2() in
2003-03-25 John Camelon
Added testDeclSpecifier(), testNamespaceDefinition(), testLinkageSpecification(),
testUsingClauses() and testEnumSpecifier() to DOMTests.
2003-03-23 John Camelon
Added ptrOperator() test to DOMTests.
Added testFunctionModifiers() test to DOMTests.
Added testArrays() test to DOMTests.
2003-03-20 Alain Magloire
Patch from Amer Hoda, tests for the CElement deltas for Translation Units.
* model/org/eclipse/cdt/core/model/tests/ElementDeltaTest.java
* model/org/eclipse/cdt/core/model/tests/resource/WorkingCopyTestStart.h
2003-03-19 Alain Magloire
Patch from Amer Hoda, introducing a simple test for the core model.
* model/org/eclipse/cdt/core/model/tests/WorkingCopyTests.java
* model/org/eclipse/cdt/core/model/tests/resource/WorkingCopyTestStart.h
2003-03-18 John Camelon
Updated DOMTests to validate simple case of a function declaration with multiple parameters.
* parser/org/eclipse/cdt/core/parser/tests/DOMTests.java
2003-03-11 John Camelon
Updated DOMTests for core.internal.parser change of merging DeclarationSpecifier and DeclSpecifier
Organized imports
* parser/org/eclipse/cdt/core/parser/tests/DOMTests.java
* parser/org/eclipse/cdt/core/parser/tests/ParserSymbolTableTest.java
2003-03-10 John Camelon
Added macro pasting tests
2003-03-06 Andrew Niefer
Added tests for exercising Namespaces & using directives in new parser's symbol table
2003-03-04 Doug Schaefer
This is a pretty big patch, but it is the merge of the NewParser1 branch into the HEAD branch. lder "parser")
JUnit tests for testing various pieces (source folder "parser" in cdt.ui.tests.
2003-01-29 Peter Graves
Fixed the warnings when accessing static methods
* src/org/eclipse/cdt/testplugin/util/DialogCheck.java:
* src/org/eclipse/cdt/testplugin/CTestPlugin.java
* src/org/eclipse/cdt/testplugin/TestWorkbench.java
* ChangeLog: make all entries have the same formatting
2002-12-17 Peter Graves
* plugin.xml,test.xml: Some simple cleanups to remove refrences to the jdt and
to move closer to automated running
2002-11-27 Alain Magloire
* model/org/eclipse/cdt/core/model/tests/CModelTests.java:
Use CoreModel.getDefault().
2002-10-30 Alain Magloire
* model/org/eclipse/cdt/core/model/tests/CModelTests.java (testGetNatureID):
The fields and the methods use in this test was removed from the CoreModel class.
(testHasNature): The method use in this case was refactor in the classes
CProjectNature and CCProjectNature, fix the test.
2002-10-18 Peter Graves
src/org/eclipse/cdt/testplugin/CProjectHelper.jada
Cleanup of the CProjectHelper file to remove unused imports, commeted out code etc.
=======
2003-04-21 Andrew Niefer
Added DOMFailedTests::testBug36713()
Added DOMFailedTests::testBug36714()
Added DOMFailedTests::testBug36717()
Added DOMFailedTests::testBug36730()
2003-04-21 Andrew Niefer
Added ScannerTestCase::testBug36695()
Moved ScannerFailedTest::testBug36521 to ScannerTestCase::testBug36521()
Moved ScannerFailedTest::testBug36509 to ScannerTestCase::testBug36509()
Moved ScannerFailedTest::testBug36475 to ScannerTestCase::testBug36475()
Updated ScannerTestCase::testBug36047
Updated ScannerTestCase::testBug36045
2003-04-20 John Camelon
Added DOMTests::testBug36551().
Adjusted AutomatedTest to turn on line numbering.
Added DOMFailedTests and 11 failed test cases.
2003-04-17 John Camelon
Updated DOMTests::testBug36600().
Updated LineNumberTest::testDOMLineNos().
Added DOMTests::testBug36559().
2003-04-17 Andrew Niefer
Added AutomatedTest
Added resources.cFiles
Added resources.cppFiles
2003-04-16 John Camelon
Added DOMTests::testBug36532().
Added DOMTests::testBug36432().
Added DOMTests::testBug36594().
Added DOMTests::testBug36600().
Added DOMTests::testArrayOfPointerToFunctions().
2003-04-15 John Camelon
Added ScannerTestCase::testBug36434().
Added ScannerTestCase::testMultipleLines().
Added ParserTestSuite.
Added LineNumberTest.
Updated CModelElementsTests to set the Nature of the C++ project appropriately.
2003-04-15 Andrew Niefer
Moved ScannerFailedTest::testBug36047 to ScannerTestCase::testBug36047
Added ScannerFailedTest::testBug36475
2003-04-13 John Camelon
Added DOMTests::testPointersToFunctions.
2003-04-11 John Camelon
Added DOMTests::testBug36247().
2003-04-11 Andrew Niefer
Moved ScannerFailedTest::testBug36316 to ScannerTestCase::testBug36316
Added ScannerFailedTest::testBug36047
Added ScannerTestCase::testNestedRecursiveDefines
2003-04-10 John Camelon
Added DOMTests::testBug36237().
2003-04-09 John Camelon
Removed all the old Code Model Builder source that was no longer being used (NewModelBuilder.java, etc.).
Moved all the files in parser.util directory to the dom.
Organized imports.
Added DOMTests::testTemplateDeclarationOfMethod().
Added DOMTests::testBug36250().
Added DOMTests::testBug36240().
Added DOMTests::testBug36254().
2003-04-09 John Camelon
Updated ScannerTest::testBug36045().
Added ScannerTest::testBug36287().
Added DOMTests::testBug36288().
2003-04-06 Andrew Niefer
Added ParserSymbolTableTest::testOverloadRanking()
2003-04-04 Alain Magloire
* src/org/eclipse/cdt/testplugin/util/VerifyDialog.java:
Remove some warnings.
2003-04-03 John Camelon
Updated ScannerTest::testSimpleIfdef() for bug36019.
Updated ScannerTest::testNumerics() for bug36020.
Added ScannerTest::testBug36045().
Updated DOMTests::testTemplateDeclaration() for template grammar updates.
2003-04-01 Andrew Niefer
ParserSymbolTableTest. modifications to using declaration tests to reflect changes in the
symbol table. Also added testUserDefinedConversionSequences()
2003-04-01 John Camelon
Added testBug35906() to DOMTests.
2003-03-31 John Camelon
Added testStruct() to DOMTests.
Added test35892()to ScannerTest.
2003-03-31 Andrew Niefer
In ParserSymbolTableTest, renamed testFunctionResolution_2() to testFunctionResolution_PointersAndBaseClasses(),
and modified to reflect changes in function resolution.
Added testFunctionResolution_TypedefsAndPointers().
2003-03-31 John Camelon
Added testWeirdStrings() and testNumerics() to ScannerTestCase.
Added testTemplateSpecialization(), testTemplateDeclaration(), testBug26467(),
testTypedef() and testTemplateInstantiation() to DOMTests.
2003-03-28 John Camelon
Added testConstructorChain() and testASMDefinition() to DOMTests.
2003-03-27 Alain Magloire
Changes were done in the Core Model API, the hierarchy is now
ICModel
ICProject
ICContainer
ITranslationUnit
IArchive
IBinary
We adjust the tests.
* model/org/eclipse/cdt/core/model/tests/ArchiveTests.java
* model/org/eclipse/cdt/core/model/tests/BinaryTests.java
* model/org/eclipse/cdt/core/model/tests/TranslationUniTests.java
* model/org/eclipse/cdt/core/model/tests/WorkingCopyTests.java
2003-03-26 Andrew Niefer
In ParserSymbolTableTest :
updated all tests to reflect TypeInfo changes
Added testFunctionResolution() & testFunctionResolution_2() in
2003-03-25 John Camelon
Added testDeclSpecifier(), testNamespaceDefinition(), testLinkageSpecification(),
testUsingClauses() and testEnumSpecifier() to DOMTests.
2003-03-23 John Camelon
Added ptrOperator() test to DOMTests.
Added testFunctionModifiers() test to DOMTests.
Added testArrays() test to DOMTests.
2003-03-20 Alain Magloire
Patch from Amer Hoda, tests for the CElement deltas for Translation Units.
* model/org/eclipse/cdt/core/model/tests/ElementDeltaTest.java
* model/org/eclipse/cdt/core/model/tests/resource/WorkingCopyTestStart.h
2003-03-19 Alain Magloire
Patch from Amer Hoda, introducing a simple test for the core model.
* model/org/eclipse/cdt/core/model/tests/WorkingCopyTests.java
* model/org/eclipse/cdt/core/model/tests/resource/WorkingCopyTestStart.h
2003-03-18 John Camelon
Updated DOMTests to validate simple case of a function declaration with multiple parameters.
* parser/org/eclipse/cdt/core/parser/tests/DOMTests.java
2003-03-11 John Camelon
Updated DOMTests for core.internal.parser change of merging DeclarationSpecifier and DeclSpecifier
Organized imports
* parser/org/eclipse/cdt/core/parser/tests/DOMTests.java
* parser/org/eclipse/cdt/core/parser/tests/ParserSymbolTableTest.java
2003-03-10 John Camelon
Added macro pasting tests
2003-03-06 Andrew Niefer
Added tests for exercising Namespaces & using directives in new parser's symbol table
2003-03-04 Doug Schaefer
This is a pretty big patch, but it is the merge of the NewParser1 branch into the HEAD branch. lder "parser")
JUnit tests for testing various pieces (source folder "parser" in cdt.ui.tests.
2003-01-29 Peter Graves
Fixed the warnings when accessing static methods
* src/org/eclipse/cdt/testplugin/util/DialogCheck.java:
* src/org/eclipse/cdt/testplugin/CTestPlugin.java
* src/org/eclipse/cdt/testplugin/TestWorkbench.java
* ChangeLog: make all entries have the same formatting
2002-12-17 Peter Graves
* plugin.xml,test.xml: Some simple cleanups to remove refrences to the jdt and
to move closer to automated running
2002-11-27 Alain Magloire
* model/org/eclipse/cdt/core/model/tests/CModelTests.java:
Use CoreModel.getDefault().
2002-10-30 Alain Magloire
* model/org/eclipse/cdt/core/model/tests/CModelTests.java (testGetNatureID):
The fields and the methods use in this test was removed from the CoreModel class.
(testHasNature): The method use in this case was refactor in the classes
CProjectNature and CCProjectNature, fix the test.
2002-10-18 Peter Graves
src/org/eclipse/cdt/testplugin/CProjectHelper.jada
Cleanup of the CProjectHelper file to remove unused imports, commeted out code etc.
>>>>>>> 1.36

View file

@ -0,0 +1,44 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html>
<head>
<title>About</title>
<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1">
</head>
<body lang="EN-US">
<h2>About This Content</h2>
<p>20th June, 2002</p>
<h3>License</h3>
<p>Eclipse.org makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the
Common Public License Version 1.0 (&quot;CPL&quot;). A copy of the CPL is available at <a href="http://www.eclipse.org/legal/cpl-v10.html">http://www.eclipse.org/legal/cpl-v10.html</a>.
For purposes of the CPL, &quot;Program&quot; will mean the Content.</p>
<h3>Third Party Content</h3>
<p>The Content includes items that may be have been sourced from third parties as follows:</p>
<p><b>JUnit 3.7</b></p>
<p>The plug-in is based on software developed by JUnit.org. Your use of JUnit 3.7 in both source and binary code
form contained in the plug-in is subject to the terms and conditions of the IBM Public License 1.0 which is available at
<a href="http://oss.software.ibm.com/developerworks/opensource/license10.html">http://oss.software.ibm.com/developerworks/opensource/license10.html</a>.
The source code is located in testresources/junit37-noUI-src.zip.</p>
<p>i) IBM effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;</p>
<p>ii) IBM effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;</p>
<p>iii) IBM states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party.</p>
<h3>Contributions</h3>
<p>If this Content is licensed to you under the terms and conditions of the CPL, any Contributions, as defined in the CPL, uploaded, submitted, or otherwise
made available to Eclipse.org, members of Eclipse.org and/or the host of Eclipse.org web site, by you that relate to such
Content are provided under the terms and conditions of the CPL and can be made available to others under the terms of the CPL.</p>
<p>If this Content is licensed to you under license terms and conditions other than the CPL (&quot;Other License&quot;), any modifications, enhancements and/or
other code and/or documentation (&quot;Modifications&quot;) uploaded, submitted, or otherwise made available to Eclipse.org, members of Eclipse.org and/or the
host of Eclipse.org, by you that relate to such Content are provided under terms and conditions of the Other License and can be made available
to others under the terms of the Other License. In addition, with regard to Modifications for which you are the copyright holder, you are also
providing the Modifications under the terms and conditions of the CPL and such Modifications can be made available to others under the terms of
the CPL.</p>
</body>
</html>

View file

@ -0,0 +1,19 @@
source.cdtuitests.jar = src/,\
ui/,\
core/,\
model/,\
build/,\
parser/,\
failures/,\
suite/
bin.includes = plugin.xml,\
about.html,\
plugin.properties,\
test.xml,\
resources/
src.includes = plugin.xml,\
about.html,\
plugin.properties,\
test.xml,\
resources/
about.html =

View file

@ -0,0 +1,553 @@
/**********************************************************************
* Copyright (c) 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
**********************************************************************/
package org.eclipse.cdt.core.build.managed.tests;
import java.util.Arrays;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.build.managed.BuildException;
import org.eclipse.cdt.core.build.managed.IConfiguration;
import org.eclipse.cdt.core.build.managed.IOption;
import org.eclipse.cdt.core.build.managed.IOptionCategory;
import org.eclipse.cdt.core.build.managed.IResourceBuildInfo;
import org.eclipse.cdt.core.build.managed.ITarget;
import org.eclipse.cdt.core.build.managed.ITool;
import org.eclipse.cdt.core.build.managed.ManagedBuildManager;
import org.eclipse.cdt.internal.core.build.managed.ToolReference;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
/**
*
*/
public class AllBuildTests extends TestCase {
private static final boolean boolVal = true;
private static final String testConfigName = "test.config.override";
private static final String enumVal = "Another Enum";
private static final String[] listVal = {"_DEBUG", "/usr/include", "libglade.a"};
private static final String projectName = "BuildTest";
private static final String rootExt = "toor";
private static final String stringVal = "-c -Wall";
private static final String subExt = "bus";
public AllBuildTests(String name) {
super(name);
}
public static Test suite() {
TestSuite suite = new TestSuite(AllBuildTests.class.getName());
suite.addTest(new AllBuildTests("testExtensions"));
suite.addTest(new AllBuildTests("testProject"));
suite.addTest(new AllBuildTests("testConfigurations"));
suite.addTest(new AllBuildTests("testTargetArtifacts"));
suite.addTest(new AllBuildTests("cleanup"));
return suite;
}
/**
* Navigates through the build info as defined in the extensions
* defined in this plugin
*/
public void testExtensions() throws Exception {
ITarget testRoot = null;
ITarget testSub = null;
// Note secret null parameter which means just extensions
ITarget[] targets = ManagedBuildManager.getDefinedTargets(null);
for (int i = 0; i < targets.length; ++i) {
ITarget target = targets[i];
if (target.getName().equals("Test Root")) {
testRoot = target;
checkRootTarget(testRoot, "x");
} else if (target.getName().equals("Test Sub")) {
testSub = target;
checkSubTarget(testSub);
}
}
assertNotNull(testRoot);
assertNotNull(testSub);
}
/**
* Create a new configuration based on one defined in the plugin file.
* Overrides all of the configuration settings. Saves, closes, and reopens
* the project. Then calls a method to check the overridden options.
*
* Tests creating a new configuration.
* Tests setting options.
* Tests persisting overridden options between project sessions.
*
*/
public void testConfigurations() throws CoreException, BuildException {
// Open the test project
IProject project = createProject(projectName);
// Make sure there is one and only one target with 2 configs
ITarget[] definedTargets = ManagedBuildManager.getTargets(project);
assertEquals(1, definedTargets.length);
ITarget rootTarget = definedTargets[0];
IConfiguration[] definedConfigs = rootTarget.getConfigurations();
assertEquals(2, definedConfigs.length);
IConfiguration baseConfig = definedConfigs[0];
// Create a new configuration
IConfiguration newConfig = rootTarget.createConfiguration(baseConfig, testConfigName);
assertEquals(3, rootTarget.getConfigurations().length);
// There is only one tool
ITool[] definedTools = newConfig.getTools();
assertEquals(1, definedTools.length);
ITool rootTool = definedTools[0];
// Override options in the new configuration
IOptionCategory topCategory = rootTool.getTopOptionCategory();
assertEquals("Root Tool", topCategory.getName());
IOption[] options = topCategory.getOptions(null);
assertEquals(2, options.length);
ManagedBuildManager.setOption(newConfig, options[0], listVal);
ManagedBuildManager.setOption(newConfig, options[1], boolVal);
IOptionCategory[] categories = topCategory.getChildCategories();
assertEquals(1, categories.length);
options = categories[0].getOptions(null);
assertEquals(2, options.length);
ManagedBuildManager.setOption(newConfig, options[0], stringVal);
ManagedBuildManager.setOption(newConfig, options[1], enumVal);
// Save, close, reopen and test again
ManagedBuildManager.saveBuildInfo(project);
project.close(null);
ManagedBuildManager.removeBuildInfo(project);
project.open(null);
// Test the values in the new configuration
checkOptionReferences(project);
}
public void testProject() throws CoreException, BuildException {
// Create new project
IProject project = createProject(projectName);
// There should not be any targets defined for this project yet
assertEquals(0, ManagedBuildManager.getTargets(project).length);
// Find the base target definition
ITarget targetDef = ManagedBuildManager.getTarget(project, "test.root");
assertNotNull(targetDef);
// Create the target for our project that builds a dummy executable
ITarget newTarget = ManagedBuildManager.createTarget(project, targetDef);
assertEquals(newTarget.getName(), targetDef.getName());
assertFalse(newTarget.equals(targetDef));
String buildArtifactName = projectName + "." + newTarget.getDefaultExtension();
newTarget.setBuildArtifact(buildArtifactName);
ITarget[] targets = ManagedBuildManager.getTargets(project);
assertEquals(1, targets.length);
ITarget target = targets[0];
assertEquals(target, newTarget);
assertFalse(target.equals(targetDef));
// Copy over the configs
IConfiguration defaultConfig = null;
IConfiguration[] configs = targetDef.getConfigurations();
for (int i = 0; i < configs.length; ++i) {
// Make the first configuration the default
if (i == 0) {
defaultConfig = target.createConfiguration(configs[i], target.getId() + "." + i);
} else {
target.createConfiguration(configs[i], target.getId() + "." + i);
}
}
ManagedBuildManager.setDefaultConfiguration(project, defaultConfig);
checkRootTarget(target, "x");
// Override the "String Option in Category" option value
configs = target.getConfigurations();
ITool[] tools = configs[0].getTools();
IOptionCategory topCategory = tools[0].getTopOptionCategory();
IOptionCategory[] categories = topCategory.getChildCategories();
IOption[] options = categories[0].getOptions(configs[0]);
configs[0].setOption(options[0], "z");
options = categories[0].getOptions(null);
assertEquals("x", options[0].getStringValue());
options = categories[0].getOptions(configs[0]);
assertEquals("z", options[0].getStringValue());
// Save, close, reopen and test again
ManagedBuildManager.saveBuildInfo(project);
project.close(null);
ManagedBuildManager.removeBuildInfo(project);
project.open(null);
// Test that the default config was remembered
IResourceBuildInfo info = ManagedBuildManager.getBuildInfo(project);
assertEquals(defaultConfig.getId(), info.getDefaultConfiguration(target).getId());
// Get the targets
targets = ManagedBuildManager.getTargets(project);
assertEquals(1, targets.length);
// See if the artifact name is remembered
assertEquals(targets[0].getArtifactName(), buildArtifactName);
// Check the rest of the default information
checkRootTarget(targets[0], "z");
// Now test the information the makefile builder needs
checkBuildSettings(project);
}
/**
* Tests the tool settings through the interface the makefile generator
* uses.
*
* @param project
*/
private void checkBuildSettings(IProject project) {
String ext1 = "foo";
String ext2 = "bar";
String badExt = "cpp";
String expectedOutput = "toor";
String expectedCmd = "doIt";
// Get that interface, Rover. Go get it. That's a good doggie! Good boy.
IResourceBuildInfo info = ManagedBuildManager.getBuildInfo(project);
assertNotNull(info);
assertEquals(info.getBuildArtifactName(), "BuildTest.toor");
// There should be a default configuration defined for the project
ITarget buildTarget = info.getDefaultTarget();
assertNotNull(buildTarget);
assertEquals(buildTarget.getId(), "test.root.1");
IConfiguration buildConfig = info.getDefaultConfiguration(buildTarget);
assertNotNull(buildConfig);
assertEquals(buildConfig.getId(), "test.root.1.0");
// The default target should be the same as the one-and-only target in the project
List targets = info.getTargets();
assertEquals(targets.size(), 1);
ITarget target = (ITarget) targets.get(0);
assertEquals(target, buildTarget);
// Check that tool handles resources with extensions foo and bar by building a baz
assertEquals(info.getOutputExtension(ext1), expectedOutput);
assertEquals(info.getOutputExtension(ext2), expectedOutput);
// Check that it ignores others based on filename extensions
assertNull(info.getOutputExtension(badExt));
// Now see what the tool command line invocation is for foo and bar
assertEquals(info.getToolForSource(ext1), expectedCmd);
assertEquals(info.getToolForSource(ext2), expectedCmd);
// Make sure that there is no tool to build files of type foo and bar
assertNull(info.getToolForTarget(ext1));
assertNull(info.getToolForTarget(ext2));
// There is no target that builds toor
assertNull(info.getToolForSource(expectedOutput));
// but there is one that produces it
assertEquals(info.getToolForTarget(expectedOutput), expectedCmd);
// Now check the build flags
assertEquals(info.getFlagsForSource(ext1), "-La -Lb z -e1");
assertEquals(info.getFlagsForSource(ext1), info.getFlagsForSource(ext2));
}
/**
* Tests that overridden options are properly read into build model.
* Test that option values that are not overridden remain the same.
*
* @param project The project to get build model information for.
* @throws BuildException
*/
private void checkOptionReferences(IProject project) throws BuildException {
// Get the targets out of the project
ITarget[] definedTargets = ManagedBuildManager.getTargets(project);
assertEquals(1, definedTargets.length);
ITarget rootTarget = definedTargets[0];
// Now get the configs
IConfiguration[] definedConfigs = rootTarget.getConfigurations();
assertEquals(3, definedConfigs.length);
IConfiguration newConfig = rootTarget.getConfiguration(testConfigName);
assertNotNull(newConfig);
// Now get the tool options and make sure the values are correct
ITool[] definedTools = newConfig.getTools();
assertEquals(1, definedTools.length);
ITool rootTool = definedTools[0];
// Check that the options in the new config contain overridden values
IOption[] rootOptions = rootTool.getOptions();
assertEquals(4, rootOptions.length);
// First is the new list
assertEquals("List Option in Top", rootOptions[0].getName());
assertEquals(IOption.STRING_LIST, rootOptions[0].getValueType());
String[] list = rootOptions[0].getStringListValue();
assertEquals(3, list.length);
assertTrue(Arrays.equals(listVal, list));
assertEquals(rootOptions[0].getCommand(), "-L");
// Next option is a boolean in top
assertEquals("Boolean Option in Top", rootOptions[1].getName());
assertEquals(IOption.BOOLEAN, rootOptions[1].getValueType());
assertEquals(boolVal, rootOptions[1].getBooleanValue());
assertEquals("-b", rootOptions[1].getCommand());
// Next option is a string category
assertEquals("String Option in Category", rootOptions[2].getName());
assertEquals(IOption.STRING, rootOptions[2].getValueType());
assertEquals(stringVal, rootOptions[2].getStringValue());
// Final option is an enumerated
assertEquals("Enumerated Option in Category", rootOptions[3].getName());
assertEquals(IOption.ENUMERATED, rootOptions[3].getValueType());
String selEnum = rootOptions[3].getSelectedEnum();
assertEquals(enumVal, selEnum);
String[] enums = rootOptions[3].getApplicableValues();
assertEquals(2, enums.length);
assertEquals("Default Enum", enums[0]);
assertEquals("Another Enum", enums[1]);
assertEquals("-e1", rootOptions[3].getEnumCommand(enums[0]));
assertEquals("-e2", rootOptions[3].getEnumCommand(enums[1]));
assertEquals("-e2", rootOptions[3].getEnumCommand(selEnum));
}
private void checkRootTarget(ITarget target, String oicValue) throws BuildException {
// Target stuff
assertTrue(target.isTestTarget());
assertEquals(target.getDefaultExtension(), rootExt);
// Tools
ITool[] tools = target.getTools();
// Root Tool
ITool rootTool = tools[0];
assertEquals("Root Tool", rootTool.getName());
// 4 Options are defined in the root tool
IOption[] options = rootTool.getOptions();
assertEquals(4, options.length);
// First option is a 2-element list
assertEquals("List Option in Top", options[0].getName());
assertEquals(IOption.STRING_LIST, options[0].getValueType());
String[] valueList = options[0].getStringListValue();
assertEquals(2, valueList.length);
assertEquals("a", valueList[0]);
assertEquals("b", valueList[1]);
assertEquals(options[0].getCommand(), "-L");
// Next option is a boolean in top
assertEquals("Boolean Option in Top", options[1].getName());
assertEquals(IOption.BOOLEAN, options[1].getValueType());
assertEquals(false, options[1].getBooleanValue());
assertEquals("-b", options[1].getCommand());
// Next option is a string category
assertEquals("String Option in Category", options[2].getName());
assertEquals(IOption.STRING, options[2].getValueType());
assertEquals("x", options[2].getStringValue());
// Final option is an enumerated
assertEquals("Enumerated Option in Category", options[3].getName());
assertEquals(IOption.ENUMERATED, options[3].getValueType());
assertEquals("Default Enum", options[3].getSelectedEnum());
valueList = options[3].getApplicableValues();
assertEquals(2, valueList.length);
assertEquals("Default Enum", valueList[0]);
assertEquals("Another Enum", valueList[1]);
assertEquals("-e1", options[3].getEnumCommand(valueList[0]));
assertEquals("-e2", options[3].getEnumCommand(valueList[1]));
// Option Categories
IOptionCategory topCategory = rootTool.getTopOptionCategory();
assertEquals("Root Tool", topCategory.getName());
options = topCategory.getOptions(null);
assertEquals(2, options.length);
assertEquals("List Option in Top", options[0].getName());
assertEquals("Boolean Option in Top", options[1].getName());
IOptionCategory[] categories = topCategory.getChildCategories();
assertEquals(1, categories.length);
assertEquals("Category", categories[0].getName());
options = categories[0].getOptions(null);
assertEquals(2, options.length);
assertEquals("String Option in Category", options[0].getName());
assertEquals("Enumerated Option in Category", options[1].getName());
// Configs
IConfiguration[] configs = target.getConfigurations();
// Root Config
IConfiguration rootConfig = configs[0];
assertEquals("Root Config", rootConfig.getName());
// Tools
tools = rootConfig.getTools();
assertEquals(1, tools.length);
assertEquals("Root Tool", tools[0].getName());
topCategory = tools[0].getTopOptionCategory();
options = topCategory.getOptions(configs[0]);
assertEquals(2, options.length);
assertEquals("List Option in Top", options[0].getName());
valueList = options[0].getStringListValue();
assertEquals("a", valueList[0]);
assertEquals("b", valueList[1]);
assertEquals("Boolean Option in Top", options[1].getName());
categories = topCategory.getChildCategories();
options = categories[0].getOptions(configs[0]);
assertEquals(2, options.length);
assertEquals("String Option in Category", options[0].getName());
assertEquals(oicValue, options[0].getStringValue());
assertEquals("Enumerated Option in Category", options[1].getName());
// Root Override Config
assertEquals("Root Override Config", configs[1].getName());
tools = configs[1].getTools();
assertEquals(1, tools.length);
assertTrue(tools[0] instanceof ToolReference);
assertEquals("Root Tool", tools[0].getName());
topCategory = tools[0].getTopOptionCategory();
options = topCategory.getOptions(configs[1]);
assertEquals(2, options.length);
assertEquals("List Option in Top", options[0].getName());
valueList = options[0].getStringListValue();
assertEquals("a", valueList[0]);
assertEquals("b", valueList[1]);
assertEquals("Boolean Option in Top", options[1].getName());
categories = topCategory.getChildCategories();
options = categories[0].getOptions(configs[1]);
assertEquals(2, options.length);
assertEquals("String Option in Category", options[0].getName());
assertEquals("y", options[0].getStringValue());
assertEquals("Enumerated Option in Category", options[1].getName());
valueList = options[1].getApplicableValues();
assertEquals(2, valueList.length);
assertEquals("Default Enum", valueList[0]);
assertEquals("Another Enum", valueList[1]);
assertEquals("-e1", options[1].getEnumCommand(valueList[0]));
assertEquals("-e2", options[1].getEnumCommand(valueList[1]));
}
private void checkSubTarget(ITarget target) {
// Make sure this is a test target
assertTrue(target.isTestTarget());
// Make sure the build artifact extension is there
assertEquals(target.getDefaultExtension(), subExt);
// Tools
ITool[] tools = target.getTools();
// Root Tool
ITool rootTool = tools[0];
assertEquals("Root Tool", rootTool.getName());
// Sub Tool
ITool subTool = tools[1];
assertEquals("Sub Tool", subTool.getName());
// Configs
IConfiguration[] configs = target.getConfigurations();
// Root Config
IConfiguration rootConfig = configs[0];
assertEquals("Root Config", rootConfig.getName());
assertEquals("Root Override Config", configs[1].getName());
// Sub Config
IConfiguration subConfig = configs[2];
assertEquals("Sub Config", subConfig.getName());
}
/**
* Remove all the project information associated with the project used during test.
*/
public void cleanup() {
removeProject(projectName);
}
/**
* Create a new project named <code>name</code> or return the project in
* the workspace of the same name if it exists.
*
* @param name The name of the project to create or retrieve.
* @return
* @throws CoreException
*/
private IProject createProject(String name) throws CoreException {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject(name);
if (!project.exists()) {
project.create(null);
} else {
project.refreshLocal(IResource.DEPTH_INFINITE, null);
}
if (!project.isOpen()) {
project.open(null);
}
//CCorePlugin.getDefault().convertProjectToC(project, null, CCorePlugin.PLUGIN_ID + ".make", true);
return project;
}
/**
* Remove the <code>IProject</code> with the name specified in the argument from the
* receiver's workspace.
*
* @param name
*/
private void removeProject(String name) {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject(name);
if (project.exists()) {
try {
project.delete(true, false, null);
} catch (CoreException e) {
assertTrue(false);
}
}
}
/**
* Test that the build artifact of a <code>ITarget</code> can be modified
* programmatically.
*/
public void testTargetArtifacts () throws CoreException {
// Open the test project
IProject project = createProject(projectName);
// Make sure there is one and only one target
ITarget[] definedTargets = ManagedBuildManager.getTargets(project);
assertEquals(1, definedTargets.length);
ITarget rootTarget = definedTargets[0];
// Set the build artifact of the target
String ext = rootTarget.getDefaultExtension();
String name = project.getName() + "." + ext;
rootTarget.setBuildArtifact(name);
// Save, close, reopen and test again
ManagedBuildManager.saveBuildInfo(project);
project.close(null);
ManagedBuildManager.removeBuildInfo(project);
project.open(null);
// Make sure there is one and only one target
definedTargets = ManagedBuildManager.getTargets(project);
assertEquals(1, definedTargets.length);
rootTarget = definedTargets[0];
assertEquals(name, rootTarget.getArtifactName());
}
public void testThatAlwaysFails() {
assertTrue(false);
}
}

View file

@ -0,0 +1,116 @@
package org.eclipse.cdt.core.model.failedTests;
/**********************************************************************
* Copyright (c) 2002,2003 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - Initial API and implementation
***********************************************************************/
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Map;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.CCProjectNature;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.INamespace;
import org.eclipse.cdt.core.model.IStructure;
import org.eclipse.cdt.internal.core.model.CElement;
import org.eclipse.cdt.internal.core.model.TranslationUnit;
import org.eclipse.cdt.testplugin.CProjectHelper;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
/**
* @author vhirsl
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class CModelElementsFailedTests extends TestCase {
private ICProject fCProject;
private IFile headerFile;
private NullProgressMonitor monitor;
public static Test suite() {
TestSuite suite= new TestSuite(CModelElementsFailedTests.class.getName());
suite.addTest(new CModelElementsFailedTests("testBug36379"));
return suite;
}
public CModelElementsFailedTests(String name) {
super(name);
}
protected void setUp() throws Exception {
monitor = new NullProgressMonitor();
String pluginRoot=org.eclipse.core.runtime.Platform.getPlugin("org.eclipse.cdt.core.tests").find(new Path("/")).getFile();
fCProject= CProjectHelper.createCProject("TestProject1", "bin");
headerFile = fCProject.getProject().getFile("CModelElementsTest.h");
if (!headerFile.exists()) {
try{
FileInputStream fileIn = new FileInputStream(pluginRoot+ "resources/cfiles/CModelElementsTestStart.h");
headerFile.create(fileIn,false, monitor);
} catch (CoreException e) {
e.printStackTrace();
}
}
if (!fCProject.getProject().hasNature(CCProjectNature.CC_NATURE_ID)) {
addNatureToProject(fCProject.getProject(), CCProjectNature.CC_NATURE_ID, null);
}
CCorePlugin.getDefault().setUseNewParser(true);
}
private static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException {
IProjectDescription description = proj.getDescription();
String[] prevNatures= description.getNatureIds();
String[] newNatures= new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length]= natureId;
description.setNatureIds(newNatures);
proj.setDescription(description, monitor);
}
protected void tearDown() throws Exception {
CProjectHelper.delete(fCProject);
}
public void testBug36379() {
TranslationUnit tu = new TranslationUnit(fCProject, headerFile);
// parse the translation unit to get the elements tree
Map newElement = tu.parse(true); // require line numbers
// tu ---> namespace: MyPackage
ArrayList tuPackages = tu.getChildrenOfType(ICElement.C_NAMESPACE);
INamespace namespace = (INamespace) tuPackages.get(0);
assertEquals(namespace.getElementName(), new String("MyPackage"));
// MyPackage ---> class: Hello
ArrayList nsClasses = namespace.getChildrenOfType(ICElement.C_CLASS);
IStructure classHello = (IStructure) nsClasses.get(0);
assertEquals(classHello.getElementName(), new String("Hello"));
// Bug 36379: parser does not provide line number information for nested definitions
assertEquals(0, ((CElement)classHello).getStartLine());
assertEquals(0, ((CElement)classHello).getEndLine());
}
}

View file

@ -0,0 +1,27 @@
/**********************************************************************
* Copyright (c) 2002,2003 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Rational Software - Initial API and implementation
***********************************************************************/
package org.eclipse.cdt.core.parser.failedTests;
import org.eclipse.cdt.core.parser.tests.BaseDOMTest;
/**
* @author jcamelon
*/
public class DOMFailedTest extends BaseDOMTest {
public DOMFailedTest(String name) {
super(name);
}
public void testBug36730()throws Exception {
failTest("FUNCTION_MACRO( 1, a )\n int i;");
}
}

View file

@ -0,0 +1,40 @@
/**********************************************************************
* Copyright (c) 2002,2003 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Rational Software - Initial API and implementation
***********************************************************************/
package org.eclipse.cdt.core.parser.failedTests;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import org.eclipse.cdt.core.parser.tests.BaseDOMTest;
/**
* @author jcamelon
*/
public class LokiFailures extends BaseDOMTest {
public LokiFailures(String name) {
super(name);
}
public void testBugTypeManip151()
{
Writer code = new StringWriter();
try
{
code.write( "template <class T, class U> struct SuperSubclass {\n" );
code.write( "enum { value = (::Loki::Conversion<const volatile U*, const volatile T*>::exists && \n" );
code.write( "!::Loki::Conversion<const volatile T*, const volatile void*>::sameType) }; };" );
} catch( IOException ioe ){}
failTest( code.toString() );
}
}

View file

@ -0,0 +1,35 @@
/**********************************************************************
* Copyright (c) 2002,2003 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Rational Software - Initial API and implementation
***********************************************************************/
package org.eclipse.cdt.core.parser.failedTests;
import java.io.StringWriter;
import java.io.Writer;
import org.eclipse.cdt.core.parser.tests.BaseDOMTest;
/**
* @author hamer
*/
public class STLFailedTests extends BaseDOMTest {
public STLFailedTests(String name) {
super(name);
}
public void testBug36805() throws Exception{
Writer code = new StringWriter();
code.write("__STL_BEGIN_NAMESPACE\n");
code.write("template <class _CharT> class char_traits\n");
code.write(": public __char_traits_base<_CharT, _CharT>\n");
code.write("{};\n");
failTest(code.toString());
}
}

View file

@ -0,0 +1,43 @@
package org.eclipse.cdt.core.model.tests;
/*
* (c) Copyright QNX Software Systems Ltd. 2002.
* All Rights Reserved.
*/
import junit.framework.Test;
import junit.framework.TestSuite;
/**
*
* AllTests.java
* This is the main entry point for running this suite of JUnit tests
* for all tests within the package "org.eclipse.cdt.core.model"
*
* @author Judy N. Green
* @since Jul 19, 2002
*/
public class AllCoreTests {
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static Test suite() {
TestSuite suite = new TestSuite(AllCoreTests.class.getName());
// Just add more test cases here as you create them for
// each class being tested
suite.addTest(AllLanguageInterfaceTests.suite());
suite.addTest(CModelTests.suite());
suite.addTest(CModelExceptionTest.suite());
suite.addTest(FlagTests.suite());
suite.addTest(ArchiveTests.suite());
suite.addTest(TranslationUnitTests.suite());
return suite;
}
} // End of AllCoreTests.java

View file

@ -0,0 +1,35 @@
/*
* Created on Jun 9, 2003
* by bnicolle
*/
package org.eclipse.cdt.core.model.tests;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* LanguageInterfaceTests
* lists all parts of the C/C++ language interface objects
* to be tested.
* @author bnicolle
*
*/
public class AllLanguageInterfaceTests {
/**
*
*/
public static Test suite() {
TestSuite suite = new TestSuite(AllLanguageInterfaceTests.class.getName());
// Just add more test cases here as you create them for
// each class being tested
suite.addTest(IIncludeTests.suite());
suite.addTest(IMacroTests.suite());
suite.addTest(IStructureTests.suite());
return suite;
}
}

View file

@ -0,0 +1,208 @@
package org.eclipse.cdt.core.model.tests;
/*
* (c) Copyright QNX Software Systems Ltd. 2002.
* All Rights Reserved.
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.model.IArchive;
import org.eclipse.cdt.core.model.IBinary;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.testplugin.CProjectHelper;
import org.eclipse.cdt.testplugin.util.ExpectedStrings;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
/**
* @author Peter Graves
*
* This file contains a set of generic tests for the core C model's Archive
* class. There is nothing exotic here, mostly just sanity type tests
*
*/
public class ArchiveTests extends TestCase {
IWorkspace workspace;
IWorkspaceRoot root;
ICProject testProject;
IFile cfile, exefile, libfile, archfile, objfile;
Path cpath, exepath, libpath, archpath, objpath;
NullProgressMonitor monitor;
/**
* Constructor for ArchiveTests
* @param name
*/
public ArchiveTests(String name) {
super(name);
/***
* The assume that they have a working workspace
* and workspace root object to use to create projects/files in,
* so we need to get them setup first.
*/
workspace= ResourcesPlugin.getWorkspace();
root= workspace.getRoot();
monitor = new NullProgressMonitor();
if (workspace==null)
fail("Workspace was not setup");
if (root==null)
fail("Workspace root was not setup");
}
/**
* Sets up the test fixture.
*
* Called before every test case method.
*
* Example code test the packages in the project
* "com.qnx.tools.ide.cdt.core"
*/
protected void setUp() throws CoreException,FileNotFoundException {
/***
* Setup the various files, paths and projects that are needed by the
* tests
*/
String pluginRoot=org.eclipse.core.runtime.Platform.getPlugin("org.eclipse.cdt.core.tests").find(new Path("/")).getFile();
testProject=CProjectHelper.createCProject("filetest", "none");
if (testProject==null)
fail("Unable to create project");
cfile = testProject.getProject().getFile("exetest.c");
if (!cfile.exists()) {
cfile.create(new FileInputStream(pluginRoot+"resources/exe/main.c"),false, monitor);
}
cpath=new Path(workspace.getRoot().getLocation()+"/filetest/main.c");
objfile = testProject.getProject().getFile("exetest.o");
if (!objfile.exists()) {
objfile.create(new FileInputStream(pluginRoot+"resources/exe/x86/o.g/main.o"),false, monitor);
}
objpath=new Path(workspace.getRoot().getLocation()+"/filetest/main.o");
exefile = testProject.getProject().getFile("test_g");
if (!exefile.exists()) {
exefile.create(new FileInputStream(pluginRoot+"resources/exe/x86/o.g/exe_g"),false, monitor);
}
exepath=new Path(workspace.getRoot().getLocation()+"/filetest/exe_g");
archfile = testProject.getProject().getFile("libtestlib_g.a");
if (!archfile.exists()) {
archfile.create(new FileInputStream(pluginRoot+"resources/testlib/x86/a.g/libtestlib_g.a"),false, monitor);
}
libpath=new Path(workspace.getRoot().getLocation()+"/filetest/libtestlib_g.so");
libfile = testProject.getProject().getFile("libtestlib_g.so");
if (!libfile.exists()) {
libfile.create(new FileInputStream(pluginRoot+"resources/testlib/x86/so.g/libtestlib_g.so"),false, monitor);
}
archpath=new Path(workspace.getRoot().getLocation()+"/filetest/libtestlib_g.a");
}
/**
* Tears down the test fixture.
*
* Called after every test case method.
*/
protected void tearDown() throws CoreException {
CProjectHelper.delete(testProject);
}
public static TestSuite suite() {
return new TestSuite(ArchiveTests.class);
}
public static void main (String[] args){
junit.textui.TestRunner.run(suite());
}
public void testGetBinaries() throws CoreException,FileNotFoundException {
IArchive myArchive;
IBinary[] bins;
ICElement[] elements;
ExpectedStrings expBin, expObj[];
String[] myStrings;
int x;
/****
* Setup the expected strings for the binaries, and the elements within
* the binaries
*/
myStrings=new String[2];
myStrings[0]="test.o";
myStrings[1]="test2.o";
expBin=new ExpectedStrings(myStrings);
expObj=new ExpectedStrings[2];
myStrings[0]="func1";
myStrings[1]="func2";
expObj[0]=new ExpectedStrings(myStrings);
myStrings[0]="test2func1";
myStrings[1]="test2func2";
expObj[1]=new ExpectedStrings(myStrings);
/***
* Grab the archive we want to test, and find all the binaries and
* all the elements in all the binaries and make sure we get
* everything we expect.
*/
myArchive=CProjectHelper.findArchive(testProject, "libtestlib_g.a");
if (myArchive==null)
fail("Could not find archive");
bins=myArchive.getBinaries();
for (x=0;x<bins.length;x++) {
expBin.foundString(bins[x].getElementName());
elements=bins[x].getChildren();
for (int i=0;i<elements.length;i++) {
expObj[x].foundString(elements[i].getElementName());
}
}
assertTrue(expBin.getMissingString(), expBin.gotAll());
assertTrue(expBin.getExtraString(), !expBin.gotExtra());
for (x=0;x<expObj.length;x++) {
assertTrue("Binary " + expBin.expStrings[x] + " " +expObj[x].getMissingString(), expObj[x].gotAll());
assertTrue("Binary " + expBin.expStrings[x] + " " + expObj[x].getExtraString(), !expObj[x].gotExtra());
}
}
/***
* Simple sanity test to make sure Archive.isArchive returns true
*
*/
public void testIsArchive() throws CoreException,FileNotFoundException {
IArchive myArchive;
myArchive=CProjectHelper.findArchive(testProject, "libtestlib_g.a");
assertTrue("A archive", myArchive != null);
myArchive=null;
}
}

View file

@ -0,0 +1,420 @@
package org.eclipse.cdt.core.model.tests;
/*
* (c) Copyright QNX Software Systems Ltd. 2002.
* All Rights Reserved.
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.model.IBinary;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.testplugin.CProjectHelper;
import org.eclipse.cdt.testplugin.util.ExpectedStrings;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
/**
* @author Peter Graves
*
* This file contains a set of generic tests for the core C model's Binary
* class. There is nothing exotic here, mostly just sanity type tests
*
*/
public class BinaryTests extends TestCase {
IWorkspace workspace;
IWorkspaceRoot root;
ICProject testProject;
IFile cfile, exefile, libfile, archfile, objfile, bigexe, ppcexefile, ndexe;
Path cpath, exepath, libpath, archpath, objpath;
NullProgressMonitor monitor;
/**
* Constructor for BinaryTests
* @param name
*/
public BinaryTests(String name) {
super(name);
}
/**
* @see java.lang.Object#finalize()
*/
protected void finalize() throws Throwable {
super.finalize();
/**
* Make sure we leave the workspace clean for the next set of tests
*/
CProjectHelper.delete(testProject);
}
/**
* Sets up the test fixture.
*
* Called before every test case method.
*
* Example code test the packages in the project
* "com.qnx.tools.ide.cdt.core"
*/
protected void setUp() throws CoreException,FileNotFoundException {
String pluginRoot;
/***
* The tests assume that they have a working workspace
* and workspace root object to use to create projects/files in,
* so we need to get them setup first.
*/
workspace= ResourcesPlugin.getWorkspace();
root= workspace.getRoot();
monitor = new NullProgressMonitor();
if (workspace==null)
fail("Workspace was not setup");
if (root==null)
fail("Workspace root was not setup");
/***
* Setup the various files, paths and projects that are needed by the
* tests
*/
testProject=CProjectHelper.createCProject("filetest", "none");
if (testProject==null)
fail("Unable to create project");
pluginRoot=org.eclipse.core.runtime.Platform.getPlugin("org.eclipse.cdt.core.tests").find(new Path("/")).getFile();
cfile = testProject.getProject().getFile("exetest.c");
if (!cfile.exists()) {
cfile.create(new FileInputStream(pluginRoot+"resources/exe/main.c"),false, monitor);
}
cpath=new Path(workspace.getRoot().getLocation()+"/filetest/main.c");
objfile = testProject.getProject().getFile("exetest.o");
if (!objfile.exists()) {
objfile.create(new FileInputStream(pluginRoot+"resources/exe/x86/o.g/main.o"),false, monitor);
}
objpath=new Path(workspace.getRoot().getLocation()+"/filetest/exetest.o");
exefile = testProject.getProject().getFile("test_g");
if (!exefile.exists()) {
exefile.create(new FileInputStream(pluginRoot+"resources/exe/x86/o.g/exe_g"),false, monitor);
}
exepath=new Path(workspace.getRoot().getLocation()+"/filetest/exe_g");
ppcexefile = testProject.getProject().getFile("ppctest_g");
if (!ppcexefile.exists()) {
ppcexefile.create(new FileInputStream(pluginRoot+"resources/exe/ppc/be.g/exe_g"),false, monitor);
}
ndexe = testProject.getProject().getFile("exetest");
if (!ndexe.exists()) {
ndexe.create(new FileInputStream(pluginRoot+"resources/exe/x86/o/exe"),false, monitor);
}
bigexe = testProject.getProject().getFile("exebig_g");
if (!bigexe.exists()) {
bigexe.create(new FileInputStream(pluginRoot+"resources/exebig/x86/o.g/exebig_g"),false, monitor);
}
archfile = testProject.getProject().getFile("libtestlib_g.a");
if (!archfile.exists()) {
archfile.create(new FileInputStream(pluginRoot+"resources/testlib/x86/a.g/libtestlib_g.a"),false, monitor);
}
libpath=new Path(workspace.getRoot().getLocation()+"/filetest/libtestlib_g.so");
libfile = testProject.getProject().getFile("libtestlib_g.so");
if (!libfile.exists()) {
libfile.create(new FileInputStream(pluginRoot+"resources/testlib/x86/so.g/libtestlib_g.so"),false, monitor);
}
archpath=new Path(workspace.getRoot().getLocation()+"/filetest/libtestlib_g.a");
}
/**
* Tears down the test fixture.
*
* Called after every test case method.
*/
protected void tearDown() throws CoreException, InterruptedException {
/* Let everything settle down before we try to delete the project.
*/
Thread.sleep(500);
CProjectHelper.delete(testProject);
}
public static TestSuite suite() {
return new TestSuite(BinaryTests.class);
}
public static void main (String[] args){
junit.textui.TestRunner.run(suite());
}
/****
* Simple tests to make sure we can get all of a binarys children
*/
public void testGetChildren() throws CoreException,FileNotFoundException {
IBinary myBinary;
ICElement[] elements;
ExpectedStrings expSyms;
String[] myStrings = {"atexit", "exit", "_init_libc", "printf",
"test.c", "_init","main.c", "_start", "test2.c", "_btext"};
expSyms=new ExpectedStrings(myStrings);
/***
* Grab the IBinary we want to test, and find all the elements in all
* the binarie and make sure we get everything we expect.
*/
myBinary=CProjectHelper.findBinary(testProject, "test_g");
elements=myBinary.getChildren();
for (int i=0;i<elements.length;i++) {
expSyms.foundString(elements[i].getElementName());
}
assertTrue(expSyms.getMissingString(), expSyms.gotAll());
assertTrue(expSyms.getExtraString(), !expSyms.gotExtra());
}
/***
* A quick check to make sure the getBSS function works as expected.
*/
public void testGetBss(){
IBinary bigBinary,littleBinary;
bigBinary=CProjectHelper.findBinary(testProject, "exebig_g");
littleBinary=CProjectHelper.findBinary(testProject, "test_g");
assertTrue("Expected 432, Got: " + bigBinary.getBSS(), bigBinary.getBSS()==432);
assertTrue("Expected 4, Got: " + littleBinary.getBSS(), littleBinary.getBSS()==4);
}
/***
* A quick check to make sure the getBSS function works as expected.
*/
public void testGetData(){
IBinary bigBinary,littleBinary;
bigBinary=CProjectHelper.findBinary(testProject, "exebig_g");
littleBinary=CProjectHelper.findBinary(testProject, "test_g");
/* These two test used to fail due to pr 23602 */
assertTrue("Expected 256 Got: " + bigBinary.getData(), bigBinary.getData()==256);
assertTrue("Expected 196, Got: " + littleBinary.getData(), littleBinary.getData()==196);
}
/***
* A very small set of tests to make usre Binary.getCPU() seems to return
* something sane for the most common exe type (x86) and one other (ppc)
* This is not a in depth test at all.
*/
public void testGetCpu() {
IBinary myBinary;
myBinary=CProjectHelper.findBinary(testProject, "exebig_g");
assertTrue("Expected: x86 Got: " + myBinary.getCPU(),myBinary.getCPU().equals("x86"));
myBinary=CProjectHelper.findBinary(testProject, ppcexefile.getLocation().lastSegment());
assertTrue("Expected: ppc Got: " + myBinary.getCPU(),myBinary.getCPU().equals("ppc"));
}
/****
* A set of simple tests to make sute getNeededSharedLibs seems to be sane
*/
public void testGetNeededSharedLibs() {
IBinary myBinary;
String[] exelibs={"libsocket.so.2", "libc.so.2"};
String[] bigexelibs={"libc.so.2"};
String[] gotlibs;
ExpectedStrings exp;
int x;
exp=new ExpectedStrings(exelibs);
myBinary=CProjectHelper.findBinary(testProject, "test_g");
gotlibs=myBinary.getNeededSharedLibs();
for (x=0;x<gotlibs.length;x++) {
exp.foundString(gotlibs[x]);
}
assertTrue(exp.getMissingString(), exp.gotAll());
assertTrue(exp.getExtraString(), !exp.gotExtra());
exp=new ExpectedStrings(bigexelibs);
myBinary=CProjectHelper.findBinary(testProject,"exebig_g");
gotlibs=myBinary.getNeededSharedLibs();
for (x=0;x<gotlibs.length;x++) {
exp.foundString(gotlibs[x]);
}
assertTrue(exp.getMissingString(), exp.gotAll());
assertTrue(exp.getExtraString(), !exp.gotExtra());
exp=new ExpectedStrings(bigexelibs);
myBinary=CProjectHelper.findBinary(testProject, "libtestlib_g.so");
gotlibs=myBinary.getNeededSharedLibs();
for (x=0;x<gotlibs.length;x++) {
exp.foundString(gotlibs[x]);
}
assertTrue(exp.getMissingString(), exp.gotAll());
assertTrue(exp.getExtraString(), !exp.gotExtra());
}
/****
* Simple tests for the getSoname method;
*/
public void testGetSoname() {
IBinary myBinary;
String name;
myBinary=CProjectHelper.findBinary(testProject, "test_g");
assertTrue(myBinary.getSoname().equals(""));
myBinary=CProjectHelper.findBinary(testProject, "libtestlib_g.so");
name=myBinary.getSoname();
assertNotNull(name);
assertTrue("Expected: libtestlib_g.so.1 Got: " + name,
name.equals("libtestlib_g.so.1"));
}
/***
* Simple tests for getText
*/
public void testGetText() {
IBinary bigBinary,littleBinary;
bigBinary=CProjectHelper.findBinary(testProject, bigexe.getLocation().lastSegment());
littleBinary=CProjectHelper.findBinary(testProject, exefile.getLocation().lastSegment());
/* These two asserts used to fail due to pr 23602 */
assertTrue("Expected 886, Got: " + bigBinary.getText(), bigBinary.getText()==886);
assertTrue("Expected 1223, Got: " + littleBinary.getText(), littleBinary.getText()==1223);
}
/***
* Simple tests for the hadDebug call
*/
public void testHasDebug() {
IBinary myBinary;
myBinary = CProjectHelper.findBinary(testProject, "test_g");
assertTrue(myBinary.hasDebug());
myBinary = CProjectHelper.findBinary(testProject, "libtestlib_g.so");
assertTrue(myBinary.hasDebug());
myBinary = CProjectHelper.findBinary(testProject, "exetest");
assertTrue(!myBinary.hasDebug());
}
/***
* Sanity - isBinary and isReadonly should always return true;
*/
public void testisBinRead() {
IBinary myBinary;
myBinary =CProjectHelper.findBinary(testProject, "test_g");
assertTrue(myBinary != null);
assertTrue(myBinary.isReadOnly());
}
/***
* Quick tests to make sure isObject works as expected.
*/
public void testIsObject() {
IBinary myBinary;
myBinary=CProjectHelper.findObject(testProject, "exetest.o");
assertTrue(myBinary.isObject());
myBinary= CProjectHelper.findBinary(testProject, "test_g");
assertTrue(!myBinary.isObject());
myBinary= CProjectHelper.findBinary(testProject, "libtestlib_g.so");
assertTrue(!myBinary.isObject());
myBinary= CProjectHelper.findBinary(testProject, "exetest");
assertTrue(!myBinary.isObject());
}
/***
* Quick tests to make sure isSharedLib works as expected.
*/
public void testIsSharedLib() {
IBinary myBinary;
myBinary=CProjectHelper.findObject(testProject, "exetest.o");
assertTrue(!myBinary.isSharedLib());
myBinary= CProjectHelper.findBinary(testProject, "libtestlib_g.so");
assertTrue(myBinary.isSharedLib());
myBinary= CProjectHelper.findBinary(testProject, "test_g");
assertTrue(!myBinary.isSharedLib());
myBinary= CProjectHelper.findBinary(testProject, "exetest");
assertTrue(!myBinary.isSharedLib());
}
/***
* Quick tests to make sure isExecutable works as expected.
*/
public void testIsExecutable() throws InterruptedException {
IBinary myBinary;
myBinary=CProjectHelper.findObject(testProject, "exetest.o");
assertTrue(!myBinary.isExecutable());
myBinary=CProjectHelper.findBinary(testProject, "test_g");
assertTrue(myBinary.isExecutable());
myBinary= CProjectHelper.findBinary(testProject, "libtestlib_g.so");
assertTrue(!myBinary.isExecutable());
myBinary= CProjectHelper.findBinary(testProject, "exetest");
assertTrue(myBinary.isExecutable());
}
/***
* Simple sanity test to make sure Binary.isBinary returns true
*
*/
public void testIsBinary() throws CoreException,FileNotFoundException,Exception {
IBinary myBinary;
myBinary=CProjectHelper.findBinary(testProject, "exebig_g");
assertTrue("A Binary", myBinary != null);
}
}

View file

@ -0,0 +1,473 @@
package org.eclipse.cdt.core.model.tests;
/**********************************************************************
* Copyright (c) 2002,2003 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - Initial API and implementation
***********************************************************************/
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Map;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.CCProjectNature;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.IEnumeration;
import org.eclipse.cdt.core.model.IEnumerator;
import org.eclipse.cdt.core.model.IField;
import org.eclipse.cdt.core.model.IFunction;
import org.eclipse.cdt.core.model.IFunctionDeclaration;
import org.eclipse.cdt.core.model.IInclude;
import org.eclipse.cdt.core.model.IMacro;
import org.eclipse.cdt.core.model.IMember;
import org.eclipse.cdt.core.model.IMethod;
import org.eclipse.cdt.core.model.IMethodDeclaration;
import org.eclipse.cdt.core.model.INamespace;
import org.eclipse.cdt.core.model.IParent;
import org.eclipse.cdt.core.model.IStructure;
import org.eclipse.cdt.core.model.ITypeDef;
import org.eclipse.cdt.core.model.IVariable;
import org.eclipse.cdt.core.model.IVariableDeclaration;
import org.eclipse.cdt.internal.core.model.CElement;
import org.eclipse.cdt.internal.core.model.StructureTemplate;
import org.eclipse.cdt.internal.core.model.FunctionTemplate;
import org.eclipse.cdt.internal.core.model.MethodTemplate;
import org.eclipse.cdt.internal.core.model.TranslationUnit;
import org.eclipse.cdt.internal.core.model.VariableTemplate;
import org.eclipse.cdt.testplugin.CProjectHelper;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
public class CModelElementsTests extends TestCase {
private ICProject fCProject;
private IFile headerFile;
private NullProgressMonitor monitor;
public static Test suite() {
TestSuite suite= new TestSuite(CModelElementsTests.class.getName());
suite.addTest(new CModelElementsTests("testCModelElements"));
return suite;
}
public CModelElementsTests(String name) {
super(name);
}
protected void setUp() throws Exception {
monitor = new NullProgressMonitor();
String pluginRoot=org.eclipse.core.runtime.Platform.getPlugin("org.eclipse.cdt.core.tests").find(new Path("/")).getFile();
fCProject= CProjectHelper.createCProject("TestProject1", "bin");
headerFile = fCProject.getProject().getFile("CModelElementsTest.h");
if (!headerFile.exists()) {
try{
FileInputStream fileIn = new FileInputStream(pluginRoot+ "resources/cfiles/CModelElementsTestStart.h");
headerFile.create(fileIn,false, monitor);
} catch (CoreException e) {
e.printStackTrace();
}
}
if (!fCProject.getProject().hasNature(CCProjectNature.CC_NATURE_ID)) {
addNatureToProject(fCProject.getProject(), CCProjectNature.CC_NATURE_ID, null);
}
CCorePlugin.getDefault().setUseNewParser(true);
}
private static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException {
IProjectDescription description = proj.getDescription();
String[] prevNatures= description.getNatureIds();
String[] newNatures= new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length]= natureId;
description.setNatureIds(newNatures);
proj.setDescription(description, monitor);
}
protected void tearDown() throws Exception {
CProjectHelper.delete(fCProject);
}
public void testCModelElements(){
TranslationUnit tu = new TranslationUnit(fCProject, headerFile);
// parse the translation unit to get the elements tree
Map newElement = tu.parse(true); // require line numbers
// tu ---> include
checkInclude(tu);
// tu ---> macro
checkMacro(tu);
// tu ---> namespace: MyPackage
ArrayList tuPackages = tu.getChildrenOfType(ICElement.C_NAMESPACE);
INamespace namespace = (INamespace) tuPackages.get(0);
assertEquals(namespace.getElementName(), new String("MyPackage"));
checkLineNumbers((CElement)namespace, 8, 130);
checkClass(namespace);
checkEnums(namespace);
checkVariables(namespace);
checkVariableDeclarations(namespace);
checkFunctions(namespace);
checkStructs(namespace);
checkTemplates(namespace);
checkArrays(tu);
}
private void checkInclude(IParent tu){
ArrayList tuIncludes = tu.getChildrenOfType(ICElement.C_INCLUDE);
IInclude inc1 = (IInclude) tuIncludes.get(0);
assertEquals(inc1.getElementName(), new String("stdio.h"));
checkLineNumbers((CElement)inc1, 2, 2);
}
private void checkMacro(IParent tu){
ArrayList tuMacros = tu.getChildrenOfType(ICElement.C_MACRO);
IMacro mac1 = (IMacro) tuMacros.get(0);
assertEquals(mac1.getElementName(), new String("PRINT"));
checkLineNumbers((CElement)mac1, 5, 5);
}
private void checkClass(IParent namespace){
// MyPackage ---> class: Hello
ArrayList nsClasses = namespace.getChildrenOfType(ICElement.C_CLASS);
IStructure classHello = (IStructure) nsClasses.get(0);
assertEquals(classHello.getElementName(), new String("Hello"));
checkLineNumbers((CElement)classHello, 12, 53);
// Hello --> field: int x
ArrayList helloFields = classHello.getChildrenOfType(ICElement.C_FIELD);
IField intX = (IField) helloFields.get(0);
assertEquals(intX.getElementName(), new String("x"));
assertEquals(intX.getTypeName(), new String("int"));
checkLineNumbers((CElement)intX, 17, 17);
int xVisibility = intX.getVisibility();
if (xVisibility != IMember.V_PROTECTED)
fail("visibility should be protected!");
// Hello ---> method: void setX(int X)
ArrayList helloMethods = classHello.getChildrenOfType(ICElement.C_METHOD);
IMethod setX = (IMethod) helloMethods.get(0);
assertEquals(setX.getElementName(), new String("setX"));
assertEquals(setX.getReturnType(), new String("void"));
checkLineNumbers((CElement)setX, 19, 22);
int setXNumOfParam = setX.getNumberOfParameters();
if(setXNumOfParam != 1)
fail("setX should have one parameter!");
String[] setXParamTypes = setX.getParameterTypes();
String firstParamType = setXParamTypes[0];
assertEquals(firstParamType, new String("int"));
// TODO : check for the inline here
checkNestedNamespace(classHello);
}
private void checkNestedNamespace(IParent classHello){
// Hello ---> namespace: MyNestedPackage
ArrayList helloNamespaces = classHello.getChildrenOfType(ICElement.C_NAMESPACE);
INamespace myNestedPackage = (INamespace) helloNamespaces.get(0);
assertEquals(myNestedPackage.getElementName(), new String("MyNestedPackage"));
checkLineNumbers((CElement)myNestedPackage, 25, 52);
checkParentNestedClass(myNestedPackage);
checkDerivedNestedClass(myNestedPackage);
}
private void checkParentNestedClass(IParent myNestedPackage){
// MyNestedPackage ---> class: Y
ArrayList nestedClasses = myNestedPackage.getChildrenOfType(ICElement.C_CLASS);
IStructure classY = (IStructure) nestedClasses.get(0);
assertEquals(classY.getElementName(), new String("Y"));
checkLineNumbers((CElement)classY, 28, 35);
// Y ---> constructor: Y
ArrayList yMethods = classY.getChildrenOfType(ICElement.C_METHOD_DECLARATION);
IMethodDeclaration constructor = (IMethodDeclaration) yMethods.get(0);
assertEquals(constructor.getElementName(), new String("Y"));
assertTrue (constructor.isConstructor());
checkLineNumbers((CElement)constructor, 32, 32);
// Y ---> destructor: ~Y
IMethodDeclaration destructor = (IMethodDeclaration) yMethods.get(1);
assertEquals(destructor.getElementName(), new String("~Y"));
assertTrue (destructor.isDestructor());
checkLineNumbers((CElement)destructor, 34, 34);
// TODO: check for virtual on destructors
}
private void checkDerivedNestedClass(IParent myNestedPackage){
// MyNestedPackage ---> class: X public Y
ArrayList nestedClasses = myNestedPackage.getChildrenOfType(ICElement.C_CLASS);
IStructure classX = (IStructure) nestedClasses.get(1);
assertEquals(classX.getElementName(), new String("X"));
checkLineNumbers((CElement)classX, 38, 51);
// TODO : Check for base classes here
// X --> field: B b
ArrayList xFieldChildren = classX.getChildrenOfType(ICElement.C_FIELD);
IField bB = (IField) xFieldChildren.get(0);
assertEquals(bB.getElementName(), new String("b"));
assertEquals(bB.getTypeName(), new String("B"));
checkLineNumbers((CElement)bB, 42, 42);
int bVisibility = bB.getVisibility();
if (bVisibility != IMember.V_PRIVATE)
fail("visibility should be private!");
// X ---> constructor chain: X
ArrayList xMethodChildren = classX.getChildrenOfType(ICElement.C_METHOD);
IMethod xconstructor = (IMethod) xMethodChildren.get(0);
assertEquals(xconstructor.getElementName(), new String("X"));
assertTrue (xconstructor.isConstructor());
checkLineNumbers((CElement)xconstructor, 46, 48);
// X ---> method declaration: doNothing
ArrayList xMethodDeclarations = classX.getChildrenOfType(ICElement.C_METHOD_DECLARATION);
IMethodDeclaration xDoNothing = (IMethodDeclaration) xMethodDeclarations.get(0);
assertEquals(xDoNothing.getElementName(), new String("doNothing"));
assertEquals(xDoNothing.getReturnType(), new String("int"));
checkLineNumbers((CElement)xDoNothing, 50, 50);
}
private void checkEnums(IParent namespace){
// MyPackage ---> enum: Noname
ArrayList nsEnums = namespace.getChildrenOfType(ICElement.C_ENUMERATION);
IEnumeration enum = (IEnumeration) nsEnums.get(0);
assertEquals(enum.getElementName(), new String(""));
checkLineNumbers((CElement)enum, 57, 61);
// enum ---> enumerator: first
ArrayList enumEnumerators = enum.getChildrenOfType(ICElement.C_ENUMERATOR);
IEnumerator first = (IEnumerator) enumEnumerators.get(0);
assertEquals(first.getElementName(), new String("first"));
// enum ---> enumerator: second
IEnumerator second = (IEnumerator) enumEnumerators.get(1);
assertEquals(second.getElementName(), new String("second"));
// enum ---> enumerator: third
IEnumerator third = (IEnumerator) enumEnumerators.get(2);
assertEquals(third.getElementName(), new String("third"));
// MyPackage ---> enum: MyEnum
IEnumeration myEnum = (IEnumeration) nsEnums.get(1);
assertEquals(myEnum.getElementName(), new String("MyEnum"));
checkLineNumbers((CElement)myEnum, 64, 67);
// enum ---> enumerator: first
ArrayList myEnumEnumerators = myEnum.getChildrenOfType(ICElement.C_ENUMERATOR);
IEnumerator f = (IEnumerator) myEnumEnumerators.get(0);
assertEquals(f.getElementName(), new String("f"));
// enum ---> enumerator: second
IEnumerator s = (IEnumerator) myEnumEnumerators.get(1);
assertEquals(s.getElementName(), new String("s"));
// enum ---> enumerator: third
IEnumerator t = (IEnumerator) myEnumEnumerators.get(2);
assertEquals(t.getElementName(), new String("t"));
}
private void checkVariables(IParent namespace){
// MyPackage ---> int v
ArrayList nsVars = namespace.getChildrenOfType(ICElement.C_VARIABLE);
IVariable var1 = (IVariable) nsVars.get(0);
assertEquals(var1.getElementName(), new String("v"));
assertEquals(var1.getTypeName(), new String("int"));
checkLineNumbers((CElement)var1, 71, 71);
// MyPackage ---> unsigned long vuLong
IVariable var2 = (IVariable) nsVars.get(1);
assertEquals(var2.getElementName(), new String("vuLong"));
assertEquals(var2.getTypeName(), new String("unsigned long "));
checkLineNumbers((CElement)var2, 73, 73);
// MyPackage ---> unsigned short vuShort
IVariable var3 = (IVariable) nsVars.get(2);
assertEquals(var3.getElementName(), new String("vuShort"));
assertEquals(var3.getTypeName(), new String("unsigned short "));
checkLineNumbers((CElement)var3, 75, 75);
}
private void checkVariableDeclarations(IParent namespace){
// MyPackage ---> extern int evar
ArrayList nsVarDecls = namespace.getChildrenOfType(ICElement.C_VARIABLE_DECLARATION);
IVariableDeclaration vDecl1 = (IVariableDeclaration) nsVarDecls.get(0);
assertEquals(vDecl1.getElementName(), new String("evar"));
assertEquals(vDecl1.getTypeName(), new String("int"));
checkLineNumbers((CElement)vDecl1, 79, 79);
// // MyPackage ---> function pointer: orig_malloc_hook
// IVariableDeclaration vDecl2 = (IVariableDeclaration) nsVarDecls.get(1);
// assertEquals(vDecl2.getElementName(), new String("orig_malloc_hook"));
// assertEquals(vDecl2.getTypeName(), new String ("void*(*)(const char*, int, size_t)"));
// checkLineNumbers((CElement)vDecl2, 81, 81);
}
private void checkFunctions(IParent namespace){
// MyPackage ---> function: void foo()
ArrayList nsFunctionDeclarations = namespace.getChildrenOfType(ICElement.C_FUNCTION_DECLARATION);
IFunctionDeclaration f1 = (IFunctionDeclaration) nsFunctionDeclarations.get(0);
assertEquals(f1.getElementName(), new String("foo"));
assertEquals(f1.getReturnType(), new String("void"));
checkLineNumbers((CElement)f1, 85, 85);
// MyPackage ---> function: char* foo(int&, char**)
IFunctionDeclaration f2 = (IFunctionDeclaration) nsFunctionDeclarations.get(1);
assertEquals(f2.getElementName(), new String("foo"));
assertEquals(f2.getReturnType(), new String("char*"));
checkLineNumbers((CElement)f2, 87, 88);
int fooNumOfParam = f2.getNumberOfParameters();
if(fooNumOfParam != 2)
fail("foo should have two parameter!");
String[] paramTypes = f2.getParameterTypes();
assertEquals(paramTypes[0], new String("int&"));
assertEquals(paramTypes[1], new String("char**"));
// MyPackage ---> function: void boo() {}
ArrayList nsFunctions = namespace.getChildrenOfType(ICElement.C_FUNCTION);
IFunction f3 = (IFunction) nsFunctions.get(0);
assertEquals(f3.getElementName(), new String("boo"));
assertEquals(f3.getReturnType(), new String("void"));
checkLineNumbers((CElement)f3, 90, 92);
}
private void checkStructs(IParent namespace){
// struct with name
ArrayList nsStructs = namespace.getChildrenOfType(ICElement.C_STRUCT);
IStructure struct1 = (IStructure) nsStructs.get(0);
assertEquals(struct1.getElementName(), new String ("MyStruct"));
checkLineNumbers((CElement)struct1, 95, 97);
ArrayList struct1Fields = struct1.getChildrenOfType(ICElement.C_FIELD);
IField field1 = (IField) struct1Fields.get(0);
assertEquals(field1.getElementName(), new String("sint"));
assertEquals(field1.getTypeName(), new String("int"));
checkLineNumbers((CElement)field1, 96, 96);
if(field1.getVisibility() != IMember.V_PUBLIC)
fail("field visibility should be public!");
// struct no name
IStructure struct2 = (IStructure) nsStructs.get(1);
assertEquals(struct2.getElementName(), new String (""));
checkLineNumbers((CElement)struct2, 101, 103);
ArrayList struct2Fields = struct2.getChildrenOfType(ICElement.C_FIELD);
IField field2 = (IField) struct2Fields.get(0);
assertEquals(field2.getElementName(), new String("ss"));
assertEquals(field2.getTypeName(), new String("int"));
checkLineNumbers((CElement)field2, 102, 102);
if(field2.getVisibility() != IMember.V_PUBLIC)
fail("field visibility should be public!");
// typedefs
ArrayList nsTypeDefs = namespace.getChildrenOfType(ICElement.C_TYPEDEF);
ITypeDef td1 = (ITypeDef) nsTypeDefs.get(0);
assertEquals(td1.getElementName(), new String ("myStruct"));
assertEquals(td1.getTypeName(), new String ("struct MyStruct"));
checkLineNumbers((CElement)td1, 99, 99);
ITypeDef td2 = (ITypeDef) nsTypeDefs.get(1);
assertEquals(td2.getElementName(), new String ("myTypedef"));
assertEquals(td2.getTypeName(), new String (""));
checkLineNumbers((CElement)td2, 101, 103);
// union
ArrayList nsUnions = namespace.getChildrenOfType(ICElement.C_UNION);
IStructure u0 = (IStructure) nsUnions.get(0);
assertEquals(u0.getElementName(), new String("U"));
checkLineNumbers((CElement)u0, 105, 107);
ArrayList u0Fields = u0.getChildrenOfType(ICElement.C_FIELD);
IField field3 = (IField) u0Fields.get(0);
assertEquals(field3.getElementName(), new String("U1"));
assertEquals(field3.getTypeName(), new String("int"));
checkLineNumbers((CElement)field3, 106, 106);
if(field3.getVisibility() != IMember.V_PUBLIC)
fail("field visibility should be public!");
}
private void checkTemplates(IParent namespace){
// template function
ArrayList functionTemplates = namespace.getChildrenOfType(ICElement.C_TEMPLATE_FUNCTION);
FunctionTemplate ft = (FunctionTemplate)functionTemplates.get(0);
assertEquals(ft.getElementName(), new String("aTemplatedFunction"));
assertEquals(ft.getTemplateSignature(), new String("aTemplatedFunction<A, B>(B) : A"));
checkLineNumbers((CElement)ft, 112, 113);
// template method
ArrayList nsClasses = namespace.getChildrenOfType(ICElement.C_CLASS);
IStructure enclosingClass = (IStructure) nsClasses.get(1);
checkLineNumbers((CElement)enclosingClass, 114, 118);
ArrayList methodTemplates = enclosingClass.getChildrenOfType(ICElement.C_TEMPLATE_METHOD);
MethodTemplate mt = (MethodTemplate)methodTemplates.get(0);
assertEquals(mt.getElementName(), new String("aTemplatedMethod"));
assertEquals(mt.getTemplateSignature(), new String("aTemplatedMethod<A, B>(B) : A"));
checkLineNumbers((CElement)mt, 118, 119);
assertEquals(mt.getVisibility(), IMember.V_PUBLIC);
// template class
ArrayList classTemplates = namespace.getChildrenOfType(ICElement.C_TEMPLATE_CLASS);
StructureTemplate ct = (StructureTemplate)classTemplates.get(0);
assertEquals(ct.getElementName(), new String("myarray"));
assertEquals(ct.getTemplateSignature(), new String("myarray<T, Tibor>"));
checkLineNumbers((CElement)ct, 122, 123);
// template struct
ArrayList structTemplates = namespace.getChildrenOfType(ICElement.C_TEMPLATE_STRUCT);
StructureTemplate st = (StructureTemplate)structTemplates.get(0);
assertEquals(st.getElementName(), new String("mystruct"));
assertEquals(st.getTemplateSignature(), new String("mystruct<T, Tibor>"));
checkLineNumbers((CElement)st, 125, 126);
// template variable
ArrayList variableTemplates = namespace.getChildrenOfType(ICElement.C_TEMPLATE_VARIABLE);
VariableTemplate vt = (VariableTemplate)variableTemplates.get(0);
assertEquals(vt.getElementName(), new String("default_alloc_template<__threads,__inst>::_S_start_free"));
assertEquals(vt.getTemplateSignature(), new String("default_alloc_template<__threads,__inst>::_S_start_free<bool, int> : char*"));
checkLineNumbers((CElement)vt, 128, 129);
}
private void checkArrays(IParent tu){
// array variable
ArrayList variables = tu.getChildrenOfType(ICElement.C_VARIABLE);
IVariable arrayVar = (IVariable) variables.get(0);
assertEquals(arrayVar.getElementName(), new String("myArray"));
assertEquals(arrayVar.getTypeName(), new String("int[][]"));
checkLineNumbers((CElement)arrayVar, 133, 133);
// array parameter in function main
ArrayList functions = tu.getChildrenOfType(ICElement.C_FUNCTION);
IFunction mainFunction = (IFunction) functions.get(0);
assertEquals(mainFunction.getElementName(), new String("main"));
assertEquals(mainFunction.getReturnType(), new String("int"));
checkLineNumbers((CElement)mainFunction, 134, 136);
int NumOfParam = mainFunction.getNumberOfParameters();
if(NumOfParam != 2)
fail("main should have two parameter!");
String[] paramTypes = mainFunction.getParameterTypes();
assertEquals(paramTypes[0], new String("int"));
assertEquals(paramTypes[1], new String("char*[]"));
}
private void checkLineNumbers(CElement element, int startLine, int endLine){
// Remove comments when testBug36379() is fixed
// assertEquals(startLine, element.getStartLine());
// assertEquals(endLine, element.getEndLine());
}
}

View file

@ -0,0 +1,113 @@
package org.eclipse.cdt.core.model.tests;
/*
* (c) Copyright QNX Software Systems Ltd. 2002.
* All Rights Reserved.
*/
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.ICModelStatusConstants;
import org.eclipse.cdt.internal.core.model.CModelStatus;
import org.eclipse.core.runtime.CoreException;
/**
*
* CModelExceptionTest
*
* @author Judy N. Green
* @since Jul 19, 2002
*/
public class CModelExceptionTest extends TestCase {
// Shared values setup and torn down
private Throwable throwableException;
private CModelStatus cModelStatus;
private CoreException coreException;
/**
* Constructor for TestCModelException.
* @param name
*/
public CModelExceptionTest(String name) {
super(name);
}
/**
* Sets up the test fixture.
*
* Called before every test case method.
*
* Example code test the packages in the project
* "com.qnx.tools.ide.cdt.core"
*/
protected void setUp() {
// create shared resources and setup the test fixture
cModelStatus = new CModelStatus();
coreException = new CoreException(cModelStatus);
}
/**
* Tears down the test fixture.
*
* Called after every test case method.
*/
protected void tearDown() {
// release resources here and clean-up
}
public static TestSuite suite() {
return new TestSuite(CModelExceptionTest.class);
}
public static void main (String[] args){
junit.textui.TestRunner.run(suite());
}
public void testCreationNoStatus(){
CModelException testException = new CModelException(coreException);
// should not be null
assertTrue("TestException is null", (testException != null));
// should be the same object inside
assertTrue("Object compare failed", testException.getException() == coreException);
}
public void testCreationWithStatus(){
CModelException testException = new CModelException(coreException,
ICModelStatusConstants.INDEX_OUT_OF_BOUNDS);
// should not be null
assertTrue("TestException is null", (testException != null));
// should not be null
assertTrue("TestException.getStatus() is null", (testException.getStatus() != null));
// should have the same status as was set on creation
assertTrue("Object compare failed", testException.getStatus().getCode() == ICModelStatusConstants.INDEX_OUT_OF_BOUNDS);
}
public void testElementDoesNotExist(){
CModelException testException = new CModelException(coreException,
ICModelStatusConstants.ELEMENT_DOES_NOT_EXIST);
// should not be null
assertTrue("TestException is null", (testException != null));
// should not exist since this is the value we set on creation
assertTrue("Object unexpectedly exists", testException.doesNotExist());
}
public void testElementExists(){
CModelException testException = new CModelException(coreException,
ICModelStatusConstants.INVALID_CONTENTS);
// should not be null
assertTrue("TestException is null", (testException != null));
// should not exist since this is the value we set on creation
assertTrue("Object unexpectedly does not exist", testException.doesNotExist() == false);
}
}

View file

@ -0,0 +1,231 @@
package org.eclipse.cdt.core.model.tests;
/*
* (c) Copyright QNX Software Systems Ltd. 2002.
* All Rights Reserved.
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.CCProjectNature;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.testplugin.CProjectHelper;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
/**
* @author Peter Graves
*
* This file contains a set of generic tests for the core C model. Nothing
* exotic, but should be a small sanity set of tests.
*
*/
public class CModelTests extends TestCase {
IWorkspace workspace;
IWorkspaceRoot root;
IProject project_c, project_cc;
NullProgressMonitor monitor;
String pluginRoot;
/**
* Constructor for CModelTests.
* @param name
*/
public CModelTests(String name) {
super(name);
}
/**
* Sets up the test fixture.
*
* Called before every test case method.
*
* Example code test the packages in the project
* "com.qnx.tools.ide.cdt.core"
*/
protected void setUp() throws CoreException {
/***
* The test of the tests assume that they have a working workspace
* and workspace root object to use to create projects/files in,
* so we need to get them setup first.
*/
IWorkspaceDescription desc;
workspace= ResourcesPlugin.getWorkspace();
root= workspace.getRoot();
monitor = new NullProgressMonitor();
if (workspace==null)
fail("Workspace was not setup");
if (root==null)
fail("Workspace root was not setup");
pluginRoot=org.eclipse.core.runtime.Platform.getPlugin("org.eclipse.cdt.core.tests").find(new Path("/")).getFile();
desc=workspace.getDescription();
desc.setAutoBuilding(false);
workspace.setDescription(desc);
}
/**
* Tears down the test fixture.
*
* Called after every test case method.
*/
protected void tearDown() {
// release resources here and clean-up
}
public static TestSuite suite() {
return new TestSuite(CModelTests.class);
}
public static void main (String[] args){
junit.textui.TestRunner.run(suite());
}
/***
* The follow are a simple set of tests to make usre the HasC/CCNature calls
* seem to be sane.
*
* Assumes that the CProjectHelper.createCProject properly creates a C
* project with a C nature, but does not add the CC nature.
* It also assums that the AddCCNature call works
*
* @see CProjectHelper#createCProject
* @see CoreModel#addCCNature
*/
public void testHasNature() throws CoreException {
ICProject testProject;
testProject=CProjectHelper.createCProject("naturetest", "none");
if (testProject==null)
fail("Unable to create project");
assertTrue("hasCNature works", CoreModel.getDefault().hasCNature(testProject.getProject()));
assertTrue("hasCCNature works without ccnature", !(CoreModel.getDefault().hasCCNature(testProject.getProject())));
CCProjectNature.addCCNature(testProject.getProject(), monitor);
assertTrue("hasCCNature works", (CoreModel.getDefault().hasCCNature(testProject.getProject())));
CCProjectNature.removeCCNature(testProject.getProject(), monitor);
CCProjectNature.removeCNature(testProject.getProject(), monitor);
assertTrue("hasCNature works without cnature", !CoreModel.getDefault().hasCNature(testProject.getProject()));
assertTrue("hasCCNature works without ccnature or cnature", !(CoreModel.getDefault().hasCCNature(testProject.getProject())));
}
/***
* Simple tests to make sure the models file identification methods seem
* to work as expected.
*/
public void testFileType() throws CoreException,FileNotFoundException {
ICProject testProject;
testProject=CProjectHelper.createCProject("filetest", "none");
if (testProject==null)
fail("Unable to create project");
IFile file = testProject.getProject().getFile("exetest_g");
if (!file.exists()) {
file.create(new FileInputStream(pluginRoot+"resources/exe/x86/o.g/exe_g"),false, monitor);
}
/***
* file should be a binary, executable, not shared or archive
*/
assertTrue("isBinary", CoreModel.getDefault().isBinary(file));
assertTrue("isExecutable", CoreModel.getDefault().isExecutable(file));
assertTrue("isSharedLib", !CoreModel.getDefault().isSharedLib(file));
assertTrue("isArchive", !CoreModel.getDefault().isArchive(file));
assertTrue("isObject", !CoreModel.getDefault().isObject(file));
assertTrue("isTranslationUnit", !CoreModel.getDefault().isTranslationUnit(file));
file = testProject.getProject().getFile("exetest.c");
if (!file.exists()) {
file.create(new FileInputStream(pluginRoot+"resources/exe/main.c"),false, monitor);
}
/***
* file should be a translation unit
*/
assertTrue("isBinary", !CoreModel.getDefault().isBinary(file));
assertTrue("isExecutable", !CoreModel.getDefault().isExecutable(file));
assertTrue("isSharedLib", !CoreModel.getDefault().isSharedLib(file));
assertTrue("isArchive", !CoreModel.getDefault().isArchive(file));
assertTrue("isObject", !CoreModel.getDefault().isObject(file));
assertTrue("isTranslationUnit", CoreModel.getDefault().isTranslationUnit(file));
file = testProject.getProject().getFile("exetest.o");
if (!file.exists()) {
file.create(new FileInputStream(pluginRoot+"resources/exe/x86/o.g/main.o"),false, monitor);
}
/***
* file should be a object file unit
*/
assertTrue("isBinary", CoreModel.getDefault().isBinary(file));
assertTrue("isExecutable", !CoreModel.getDefault().isExecutable(file));
assertTrue("isSharedLib", !CoreModel.getDefault().isSharedLib(file));
assertTrue("isArchive", !CoreModel.getDefault().isArchive(file));
assertTrue("isObject", CoreModel.getDefault().isObject(file));
assertTrue("isTranslationUnit", !CoreModel.getDefault().isTranslationUnit(file));
file = testProject.getProject().getFile("liblibtest_g.so");
if (!file.exists()) {
file.create(new FileInputStream(pluginRoot+"resources/testlib/x86/so.g/libtestlib_g.so"),false, monitor);
}
/***
* file should be a sharedlib/binary file
*/
assertTrue("isBinary", CoreModel.getDefault().isBinary(file));
assertTrue("isExecutable", !CoreModel.getDefault().isExecutable(file));
assertTrue("isSharedLib", CoreModel.getDefault().isSharedLib(file));
assertTrue("isArchive", !CoreModel.getDefault().isArchive(file));
assertTrue("isObject", !CoreModel.getDefault().isObject(file));
assertTrue("isTranslationUnit", !CoreModel.getDefault().isTranslationUnit(file));
file = testProject.getProject().getFile("liblibtest_g.a");
if (!file.exists()) {
file.create(new FileInputStream(pluginRoot+"resources/testlib/x86/a.g/libtestlib_g.a"),false, monitor);
} else {
fail("Does not exist?");
}
/***
* file should be a archive file
*/
assertTrue("isArchive", CoreModel.getDefault().isArchive(file));
assertTrue("isBinary:", !CoreModel.getDefault().isBinary(file));
assertTrue("isExecutable", !CoreModel.getDefault().isExecutable(file));
assertTrue("isSharedLib", !CoreModel.getDefault().isSharedLib(file));
assertTrue("isArchive", CoreModel.getDefault().isArchive(file));
assertTrue("isObject", !CoreModel.getDefault().isObject(file));
assertTrue("isTranslationUnit", !CoreModel.getDefault().isTranslationUnit(file));
testProject.getProject().delete(true,true,monitor);
}
/****
* Some simple tests for isValidTranslationUnitName
*/
public void testIsValidTranslationUnitName() throws CoreException {
assertTrue("Invalid C file", !CoreModel.getDefault().isValidTranslationUnitName("notcfile"));
assertTrue("Invalid C file", !CoreModel.getDefault().isValidTranslationUnitName("not.c.file"));
assertTrue("Invalid C file", !CoreModel.getDefault().isValidTranslationUnitName("not.ca"));
assertTrue("Valid C file", CoreModel.getDefault().isValidTranslationUnitName("areal.c"));
}
}

View file

@ -0,0 +1,286 @@
package org.eclipse.cdt.core.model.tests;
/**********************************************************************
* Copyright (c) 2002,2003 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - Initial API and implementation
***********************************************************************/
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.Vector;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.CCProjectNature;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.ElementChangedEvent;
import org.eclipse.cdt.core.model.IBuffer;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICElementDelta;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.IElementChangedListener;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.internal.core.model.CModelManager;
import org.eclipse.cdt.internal.core.model.IWorkingCopy;
import org.eclipse.cdt.internal.core.model.TranslationUnit;
import org.eclipse.cdt.testplugin.CProjectHelper;
import org.eclipse.cdt.testplugin.TestPluginLauncher;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
/**
* Class for testing the C Element Delta Builder.
*/
public class ElementDeltaTests extends TestCase implements IElementChangedListener {
private ICProject fCProject;
private IFile headerFile;
private NullProgressMonitor monitor;
private Vector addedElements;
private Vector removedElements;
private Vector changedElements;
public static void main(String[] args) {
TestPluginLauncher.run(TestPluginLauncher.getLocationFromProperties(), WorkingCopyTests.class, args);
}
public static Test suite() {
TestSuite suite= new TestSuite(ElementDeltaTests.class.getName());
suite.addTest(new ElementDeltaTests("testElementDeltas"));
return suite;
}
public ElementDeltaTests(String name) {
super(name);
}
protected void setUp() throws Exception {
monitor = new NullProgressMonitor();
String pluginRoot=org.eclipse.core.runtime.Platform.getPlugin("org.eclipse.cdt.core.tests").find(new Path("/")).getFile();
fCProject= CProjectHelper.createCProject("TestProject1", "bin");
//Path filePath = new Path(ResourcesPlugin.getWorkspace().getRoot().getLocation().toString()+ fCProject.getPath().toString()+ "/WorkingCopyTest.h");
headerFile = fCProject.getProject().getFile("WorkingCopyTest.h");
if (!headerFile.exists()) {
try{
FileInputStream fileIn = new FileInputStream(pluginRoot+ "resources/cfiles/WorkingCopyTestStart.h");
headerFile.create(fileIn,false, monitor);
} catch (CoreException e) {
e.printStackTrace();
}
}
if (!fCProject.getProject().hasNature(CCProjectNature.CC_NATURE_ID)) {
addNatureToProject(fCProject.getProject(), CCProjectNature.CC_NATURE_ID, null);
}
// register with the model manager to listen to delta changes
CModelManager.getDefault().addElementChangedListener(this);
addedElements = new Vector(10);
removedElements = new Vector(10);
changedElements = new Vector(20);
CCorePlugin.getDefault().setUseNewParser(true);
}
private static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException {
IProjectDescription description = proj.getDescription();
String[] prevNatures= description.getNatureIds();
String[] newNatures= new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length]= natureId;
description.setNatureIds(newNatures);
proj.setDescription(description, monitor);
}
protected void tearDown() throws Exception {
CProjectHelper.delete(fCProject);
}
public void testElementDeltas() throws Exception {
ITranslationUnit tu = new TranslationUnit(fCProject, headerFile);
assertNotNull (tu);
IWorkingCopy wc = tu.getWorkingCopy();
assertNotNull (wc);
assertNotNull (wc.getBuffer());
assertTrue (wc.exists());
// add the class Hello
IBuffer wcBuf = wc.getBuffer();
wcBuf.setContents ("\n class Hello{ \n};");
wc.reconcile();
wc.commit(true, monitor);
assertChangedElement(ICElement.C_MODEL, "");
assertChangedElement(ICElement.C_PROJECT, "TestProject1");
assertChangedElement(ICElement.C_UNIT, "WorkingCopyTest.h");
assertAddedElement(ICElement.C_CLASS, "Hello");
assertRemovedElement(ICElement.C_INCLUDE, "stdio.h");
assertEmptyDelta();
// add the field x
wcBuf.setContents ("\n class Hello{\n int x; \n};");
wc.reconcile();
wc.commit(true, monitor);
assertChangedElement(ICElement.C_MODEL, "");
assertChangedElement(ICElement.C_PROJECT, "TestProject1");
assertChangedElement(ICElement.C_UNIT, "WorkingCopyTest.h");
assertChangedElement(ICElement.C_CLASS, "Hello");
assertAddedElement(ICElement.C_FIELD, "x");
assertEmptyDelta();
// add the method setValue
wcBuf.setContents ("\n class Hello{\n int x; \n void setValue(int val); \n};");
wc.reconcile();
wc.commit(true, monitor);
assertChangedElement(ICElement.C_MODEL, "");
assertChangedElement(ICElement.C_PROJECT, "TestProject1");
assertChangedElement(ICElement.C_UNIT, "WorkingCopyTest.h");
assertChangedElement(ICElement.C_CLASS, "Hello");
assertAddedElement(ICElement.C_METHOD_DECLARATION, "setValue");
assertEmptyDelta();
// rename x to y
// this is not a change, this is add and remove
wcBuf.setContents ("\n class Hello{\n int y; \n void setValue(int val); \n};");
wc.reconcile();
wc.commit(true, monitor);
assertChangedElement(ICElement.C_MODEL, "");
assertChangedElement(ICElement.C_PROJECT, "TestProject1");
assertChangedElement(ICElement.C_UNIT, "WorkingCopyTest.h");
assertChangedElement(ICElement.C_CLASS, "Hello");
assertAddedElement(ICElement.C_FIELD, "y");
assertRemovedElement(ICElement.C_FIELD, "x");
assertEmptyDelta();
// remove the method
wcBuf.setContents ("\n class Hello{\n String y; \n};");
wc.reconcile();
wc.commit(true, monitor);
assertChangedElement(ICElement.C_MODEL, "");
assertChangedElement(ICElement.C_PROJECT, "TestProject1");
assertChangedElement(ICElement.C_UNIT, "WorkingCopyTest.h");
assertChangedElement(ICElement.C_CLASS, "Hello");
assertChangedElement(ICElement.C_FIELD, "y");
assertRemovedElement(ICElement.C_METHOD_DECLARATION, "setValue");
assertEmptyDelta();
// remove the field
wcBuf.setContents ("\n class Hello{ \n};");
wc.reconcile();
wc.commit(true, monitor);
assertChangedElement(ICElement.C_MODEL, "");
assertChangedElement(ICElement.C_PROJECT, "TestProject1");
assertChangedElement(ICElement.C_UNIT, "WorkingCopyTest.h");
assertChangedElement(ICElement.C_CLASS, "Hello");
assertRemovedElement(ICElement.C_FIELD, "y");
assertEmptyDelta();
// remove the class
wcBuf.setContents ("");
wc.reconcile();
wc.commit(true, monitor);
assertChangedElement(ICElement.C_MODEL, "");
assertChangedElement(ICElement.C_PROJECT, "TestProject1");
assertChangedElement(ICElement.C_UNIT, "WorkingCopyTest.h");
assertRemovedElement(ICElement.C_CLASS, "Hello");
assertEmptyDelta();
wc.destroy();
assertFalse(wc.exists());
}
public void assertAddedElement(int elementType, String elementName){
if(!isElementInList(elementType, elementName, addedElements))
fail("Element NOT found in Added list");
}
public void assertRemovedElement(int elementType, String elementName){
if(!isElementInList(elementType, elementName, removedElements))
fail("Element NOT found in Removed list");
}
public void assertChangedElement(int elementType, String elementName){
if(!isElementInList(elementType, elementName, changedElements))
fail("Element NOT found in Changed list");
}
public void assertEmptyDelta() {
assertTrue(addedElements.isEmpty());
assertTrue(removedElements.isEmpty());
assertTrue(changedElements.isEmpty());
}
public boolean isElementInList(int elementType, String elementName, Vector elementList) {
boolean found = false;
Iterator i = elementList.iterator();
while( i.hasNext()){
ICElement element = (ICElement)i.next();
if ((element.getElementName().equals(elementName)) &&
(element.getElementType() == elementType)){
// return true;
// just to print the whole list
found = true;
// Remove the element
elementList.remove(element);
break;
}
}
//return false;
return found;
}
public void elementChanged(ElementChangedEvent event){
try {
addedElements.clear();
removedElements.clear();
changedElements.clear();
processDelta(event.getDelta());
} catch(CModelException e) {
}
}
protected void processDelta(ICElementDelta delta) throws CModelException {
// check the delta elements
int kind= delta.getKind();
int flags= delta.getFlags();
ICElement element= delta.getElement();
// handle open and closing of a solution or project
if ((flags & ICElementDelta.F_CLOSED) != 0) {
}
if ((flags & ICElementDelta.F_OPENED) != 0) {
}
if (kind == ICElementDelta.REMOVED) {
removedElements.add(element);
}
if (kind == ICElementDelta.ADDED) {
addedElements.add(element);
}
if (kind == ICElementDelta.CHANGED) {
changedElements.add(element);
if (flags == ICElementDelta.F_MODIFIERS) {
}
if (flags == ICElementDelta.F_CONTENT) {
}
if (flags == ICElementDelta.F_CHILDREN) {
}
}
ICElementDelta[] affectedChildren= delta.getAffectedChildren();
for (int i= 0; i < affectedChildren.length; i++) {
processDelta(affectedChildren[i]);
}
}
}

View file

@ -0,0 +1,212 @@
package org.eclipse.cdt.core.model.tests;
/*
* (c) Copyright QNX Software Systems Ltd. 2002.
* All Rights Reserved.
*/
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.model.Flags;
import org.eclipse.cdt.internal.core.model.IConstants;
/**
* @author Peter Graves
*
* This is a very simple set of sanity tests for the flags class to make sure
* there are no very silly problems in the class. It also verifies that there
* is no overlap in the IConstants.
*/
public class FlagTests extends TestCase {
int flags[];
/**
* Constructor for FlagTests.
* @param name
*/
public FlagTests(String name) {
super(name);
}
/**
* Sets up the test fixture.
*
* Called before every test case method.
*
* Example code test the packages in the project
* "com.qnx.tools.ide.cdt.core"
*/
protected void setUp() {
flags=new int[15];
flags[0]=IConstants.AccPublic;
flags[1]=IConstants.AccPrivate;
flags[2]=IConstants.AccProtected;
flags[3]=IConstants.AccStatic;
flags[4]=IConstants.AccExtern;
flags[5]=IConstants.AccInline;
flags[6]=IConstants.AccVolatile;
flags[7]=IConstants.AccRegister;
flags[8]=IConstants.AccExplicit;
flags[9]=IConstants.AccExport;
flags[10]=IConstants.AccAbstract;
flags[11]=IConstants.AccMutable;
flags[12]=IConstants.AccAuto;
flags[13]=IConstants.AccVirtual;
flags[14]=IConstants.AccTypename;
}
/**
* Tears down the test fixture.
*
* Called after every test case method.
*/
protected void tearDown() {
// release resources here and clean-up
}
public static TestSuite suite() {
return new TestSuite(FlagTests.class);
}
public static void main (String[] args){
junit.textui.TestRunner.run(suite());
}
public void testIsStatic()
{
int x;
assertTrue("isStatic with a static", Flags.isStatic(IConstants.AccStatic));
for (x=0;x<flags.length;x++) {
if (flags[x]!=IConstants.AccStatic)
assertTrue("isStatic with a non-static", !Flags.isStatic(flags[x]));
}
}
public void testIsAbstract()
{
int x;
assertTrue("isAbstract with a abstract", Flags.isAbstract(IConstants.AccAbstract));
for (x=0;x<flags.length;x++) {
if (flags[x]!=IConstants.AccAbstract)
assertTrue("isAbstract with a non-abstract", !Flags.isAbstract(flags[x]));
}
}
public void testIsExplicit()
{
int x;
assertTrue("isExplicit with a explicit", Flags.isExplicit(IConstants.AccExplicit));
for (x=0;x<flags.length;x++) {
if (flags[x]!=IConstants.AccExplicit)
assertTrue("isExplicit with a non-explicit", !Flags.isExplicit(flags[x]));
}
}
public void testIsExport()
{
int x;
assertTrue("isExport with a Export", Flags.isExport(IConstants.AccExport));
for (x=0;x<flags.length;x++) {
if (flags[x]!=IConstants.AccExport)
assertTrue("isExport with a non-Export", !Flags.isExport(flags[x]));
}
}
public void testIsExtern()
{
int x;
assertTrue("isExtern with a Extern", Flags.isExtern(IConstants.AccExtern));
for (x=0;x<flags.length;x++) {
if (flags[x]!=IConstants.AccExtern)
assertTrue("isExtern with a non-Extern", !Flags.isExtern(flags[x]));
}
}
public void testIsInline()
{
int x;
assertTrue("isInline with a Inline", Flags.isInline(IConstants.AccInline));
for (x=0;x<flags.length;x++) {
if (flags[x]!=IConstants.AccInline)
assertTrue("isInline with a non-Inline", !Flags.isInline(flags[x]));
}
}
public void testIsMutable()
{
int x;
assertTrue("isMutable with a Mutable", Flags.isMutable(IConstants.AccMutable));
for (x=0;x<flags.length;x++) {
if (flags[x]!=IConstants.AccMutable)
assertTrue("isMutable with a non-Mutable", !Flags.isMutable(flags[x]));
}
}
public void testIsPrivate()
{
int x;
assertTrue("isPrivate with a Private", Flags.isPrivate(IConstants.AccPrivate));
for (x=0;x<flags.length;x++) {
if (flags[x]!=IConstants.AccPrivate)
assertTrue("isPrivate with a non-Private", !Flags.isPrivate(flags[x]));
}
}
public void testIsPublic()
{
int x;
assertTrue("isPublic with a Public", Flags.isPublic(IConstants.AccPublic));
for (x=0;x<flags.length;x++) {
if (flags[x]!=IConstants.AccPublic)
assertTrue("isPublic with a non-Public", !Flags.isPublic(flags[x]));
}
}
public void testIsProtected()
{
int x;
assertTrue("isProtected with a Protected", Flags.isProtected(IConstants.AccProtected));
for (x=0;x<flags.length;x++) {
if (flags[x]!=IConstants.AccProtected)
assertTrue("isProtected with a non-Protected", !Flags.isProtected(flags[x]));
}
}
public void testIsRegister()
{
int x;
assertTrue("isRegister with a Register", Flags.isRegister(IConstants.AccRegister));
for (x=0;x<flags.length;x++) {
if (flags[x]!=IConstants.AccRegister)
assertTrue("isRegister with a non-Register", !Flags.isRegister(flags[x]));
}
}
public void testIsVirtual()
{
int x;
assertTrue("isVirtual with a Virtual", Flags.isVirtual(IConstants.AccVirtual));
for (x=0;x<flags.length;x++) {
if (flags[x]!=IConstants.AccVirtual)
assertTrue("isVirtual with a non-Virtual", !Flags.isVirtual(flags[x]));
}
}
public void testIsVolatile()
{
int x;
assertTrue("isVolatile with a Volatile", Flags.isVolatile(IConstants.AccVolatile));
for (x=0;x<flags.length;x++) {
if (flags[x]!=IConstants.AccVolatile)
assertTrue("isVolatile with a non-Volatile", !Flags.isVolatile(flags[x]));
}
}
}

View file

@ -0,0 +1,116 @@
/*
* Created on Jun 4, 2003
* by bnicolle
*/
package org.eclipse.cdt.core.model.tests;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.IInclude;
import org.eclipse.cdt.core.model.tests.IntegratedCModelTest;
/**
* @author bnicolle
*
*/
public class IIncludeTests extends IntegratedCModelTest {
/**
* @param string
*/
public IIncludeTests(String string) {
super( string );
}
/**
* @see org.eclipse.cdt.internal.core.model.IntegratedCModelTest
*/
public String getSourcefileSubdir() {
return "resources/cmodel/";
}
/**
* @see org.eclipse.cdt.internal.core.model.IntegratedCModelTest
*/
public String getSourcefileResource() {
return "IIncludeTest.h";
}
/**
* @returns a test suite named after this class
* containing all its public members named "test*"
*/
public static Test suite() {
TestSuite suite= new TestSuite(IIncludeTests.class);
return suite;
}
public void testGetIncludeName()
{
ITranslationUnit tu = getTU();
IInclude[] theIncludes = null;
try {
theIncludes = tu.getIncludes();
}
catch( CModelException c )
{
assertNotNull("CModelException thrown",c);
}
String getIncludeNameList[] = new String[] {
new String("stdio.h"),
new String("whatever.h"),
new String("src/slash.h"),
new String("src\\backslash.h"), // that's a single backslash, escaped
new String("Program Files/space.h"),
new String("../up1dir.h"),
new String("./samedir.h"),
new String("different_extension1.hpp"),
new String("different_extension2.hh"),
new String("different_extension3.x"),
new String("no_extension"),
new String("whitespace_after_hash"),
new String("whitespace_before_hash"),
new String("resync_after_bad_parse_1"),
new String("resync_after_bad_parse_2"),
new String("one"), // C-spec does not allow this, but that's OK for our present purposes
new String("resync_after_bad_parse_3"),
new String("invalid.h"), // C-spec does not allow this, but that's OK for our present purposes
// TODO: expect new String("MYINCFILE"),
// TODO: expect new String("xstr(INCFILE(2)).h")
};
assertEquals( getIncludeNameList.length, theIncludes.length );
for( int i=0; i<getIncludeNameList.length; i++ )
{
IInclude inc1 = theIncludes[i];
assertEquals( getIncludeNameList[i], inc1.getIncludeName() );
}
// checkLineNumbers((CElement)inc1, 2, 2);
}
public void testIsStandard()
{
ITranslationUnit tu = getTU();
IInclude[] theIncludes = null;
try {
theIncludes = tu.getIncludes();
}
catch( CModelException c )
{
assertNotNull("CModelException thrown",c);
}
boolean isStandardList[] = new boolean[] {
true, false
};
for( int i=0; i<isStandardList.length; i++ )
{
IInclude inc1 = theIncludes[i];
assertEquals( isStandardList[i], inc1.isStandard() );
}
}
}

View file

@ -0,0 +1,106 @@
/*
* Created on Jun 6, 2003
* by bnicolle
*/
package org.eclipse.cdt.core.model.tests;
import org.eclipse.cdt.core.model.IMacro;
import junit.framework.Test;
import junit.framework.TestSuite;
import java.util.ArrayList;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.model.tests.IntegratedCModelTest;
/**
* IMacroTest - Class for testing IMacro
*
* @author bnicolle
*
*/
public class IMacroTests extends IntegratedCModelTest {
/**
* @returns a test suite named after this class
* containing all its public members named "test*"
*/
public static Test suite() {
TestSuite suite= new TestSuite( IMacroTests.class.getName() );
suite.addTest( new IMacroTests("testGetElementName"));
// TODO Bug# 38740: suite.addTest( new IMacroTest("testGetIdentifierList"));
// TODO Bug# 38740: suite.addTest( new IMacroTest("testGetTokenSequence"));
return suite;
}
/**
* @param name
*/
public IMacroTests(String name) {
super(name);
}
/**
* @see org.eclipse.cdt.internal.core.model.IntegratedCModelTest
*/
public String getSourcefileSubdir() {
return "resources/cmodel/";
}
/**
* @see org.eclipse.cdt.internal.core.model.IntegratedCModelTest
*/
public String getSourcefileResource() {
return "IMacroTest.h";
}
public void testGetElementName() {
ITranslationUnit tu = getTU();
ArrayList arrayElements = tu.getChildrenOfType( ITranslationUnit.C_MACRO );
String expectedList[] = new String[] {
"SINGLETON",
"NUMBER",
"PRINT"
};
assertEquals( expectedList.length, arrayElements.size() );
for( int i=0; i<expectedList.length; i++ )
{
IMacro iMacro = (IMacro) arrayElements.get(i);
assertEquals( expectedList[i], iMacro.getElementName() );
}
}
public void testGetIdentifierList() {
ITranslationUnit tu = getTU();
ArrayList arrayElements = tu.getChildrenOfType( ITranslationUnit.C_MACRO );
String expectedList[] = new String[] {
"",
"",
"string,msg"
};
assertEquals( expectedList.length, arrayElements.size() );
for( int i=0; i<expectedList.length; i++ )
{
IMacro iMacro = (IMacro) arrayElements.get(i);
assertEquals( expectedList[i], iMacro.getIdentifierList() );
}
}
public void testGetTokenSequence() {
ITranslationUnit tu = getTU();
ArrayList arrayElements = tu.getChildrenOfType( ITranslationUnit.C_MACRO );
String expectedList[] = new String[] {
"",
"1",
"printf(string, msg)"
};
assertEquals( expectedList.length, arrayElements.size() );
for( int i=0; i<expectedList.length; i++ )
{
IMacro iMacro = (IMacro) arrayElements.get(i);
assertEquals( expectedList[i], iMacro.getTokenSequence() );
}
}
}

View file

@ -0,0 +1,422 @@
/*
* Created on Jun 9, 2003
* by bnicolle
*/
package org.eclipse.cdt.core.model.tests;
import org.eclipse.cdt.core.model.*;
import junit.framework.*;
import java.util.ArrayList;
/**
* @author bnicolle
*
*/
public class IStructureTests extends IntegratedCModelTest {
/**
* @param name
*/
public IStructureTests(String name) {
super(name);
}
/**
* @see org.eclipse.cdt.internal.core.model.IntegratedCModelTest
*/
public String getSourcefileSubdir() {
return "resources/cmodel/";
}
/**
* @see org.eclipse.cdt.internal.core.model.IntegratedCModelTest
*/
public String getSourcefileResource() {
return "IStructure.c";
}
/**
* @returns a test suite named after this class
* containing all its public members named "test*"
*/
public static Test suite() {
TestSuite suite= new TestSuite( IStructureTests.class.getName() );
// TODO check C-only behaviour using C_NATURE vs CC_NATURE
// Interface tests:
suite.addTest( new IStructureTests("testGetChildrenOfTypeStruct"));
suite.addTest( new IStructureTests("testGetChildrenOfTypeClass")); // C++ only
// TODO Bug# 38985: suite.addTest( new IStructureTests("testGetFields"));
suite.addTest( new IStructureTests("testGetFieldsHack"));
// TODO Bug# 38985: suite.addTest( new IStructureTests("testGetField"));
// TODO Bug# 38985: suite.addTest( new IStructureTests("testGetMethods")); // C++ only
suite.addTest( new IStructureTests("testGetMethodsHack")); // C++ only
// TODO Bug# 38985: suite.addTest( new IStructureTests("testGetMethod")); // C++ only
suite.addTest( new IStructureTests("testIsStruct"));
suite.addTest( new IStructureTests("testIsClass")); // C++ only
suite.addTest( new IStructureTests("testIsUnion"));
// TODO Bug# 38985: suite.addTest( new IStructureTests("testIsAbstract")); // C++ only
// TODO Bug# 38985: suite.addTest( new IStructureTests("testGetBaseTypes")); // C++ only
// TODO Bug# 38985: suite.addTest( new IStructureTests("testGetAccessControl")); // C++ only
// Language Specification tests:
suite.addTest( new IStructureTests("testAnonymousStructObject"));
suite.addTest( new IStructureTests("testInnerStruct"));
return suite;
}
public void testGetChildrenOfTypeStruct() {
ITranslationUnit tu = getTU();
ArrayList arrayStructs = tu.getChildrenOfType(ICElement.C_STRUCT);
String[] myExpectedStructs = {
"testStruct1", "testStruct2", "testStruct3",
/* 2 anonymous structs */ "", "", "testStruct7",
"testStruct8"
};
assertEquals(myExpectedStructs.length,arrayStructs.size());
for(int i=0; i<myExpectedStructs.length; i++) {
IStructure myIStruct = (IStructure) arrayStructs.get(i);
assertNotNull( "Failed on "+i, myIStruct);
assertEquals(myExpectedStructs[i], myIStruct.getElementName());
}
}
public void testGetChildrenOfTypeClass() {
ITranslationUnit tu = getTU();
ArrayList arrayClasses = tu.getChildrenOfType(ICElement.C_CLASS);
String[] myExpectedClasses = {
"testClass1", "testClass3", "testClass4Abstract",
"testClass5", "testClass6" };
assertEquals(myExpectedClasses.length,arrayClasses.size());
for(int i=0; i<myExpectedClasses.length; i++) {
IStructure myIStruct = (IStructure) arrayClasses.get(i);
assertNotNull( "Failed on "+i, myIStruct);
assertEquals(myExpectedClasses[i], myIStruct.getElementName());
}
}
public void testGetFields() {
ITranslationUnit tu = getTU();
ArrayList myArrayStructs = tu.getChildrenOfType(ICElement.C_STRUCT);
IStructure myIStruct = (IStructure) myArrayStructs.get(0);
IField[] myArrayIField = myIStruct.getFields();
String[] myExpectedFields = {
"m_field1","m_field2","m_field3",
"m_field4","m_field5","m_field6",
};
assertEquals(myExpectedFields.length, myArrayIField.length);
for(int i=0; i<myArrayIField.length; i++) {
assertNotNull( "Failed on "+i, myArrayIField[i]);
assertEquals("Failed on "+i,
myExpectedFields[i], myArrayIField[i].getElementName());
}
}
// TODO Bug# 38985: remove testGetFieldsHack()
public void testGetFieldsHack() {
ITranslationUnit tu = getTU();
ArrayList myArrayStructs = tu.getChildrenOfType(ICElement.C_STRUCT);
IStructure myIStruct = (IStructure) myArrayStructs.get(0);
String[] myExpectedFields = {
"m_field1","m_field2","m_field3",
"m_field4","m_field5","m_field6",
};
ArrayList myArrayIField = myIStruct.getChildrenOfType(ICElement.C_FIELD);
assertEquals(myExpectedFields.length, myArrayIField.size());
for(int i=0; i<myArrayIField.size(); i++) {
IField myIField = (IField) myArrayIField.get(i);
assertNotNull( "Failed on "+i, myIField );
assertEquals("Failed on "+i,
myExpectedFields[i], myIField.getElementName());
}
}
public void testGetField() {
ITranslationUnit tu = getTU();
ArrayList myArrayStructs = tu.getChildrenOfType(ICElement.C_STRUCT);
IStructure myIStruct = (IStructure) myArrayStructs.get(0);
String[] myExpectedFields = {
"m_field1","m_field2","m_field3",
"m_field4","m_field5","m_field6",
};
for(int i=0; i<myExpectedFields.length; i++) {
IField myIField = myIStruct.getField( myExpectedFields[i] );
assertNotNull( "Failed on "+i, myIField);
}
String[] myUnexpectedFields = {
"m_field7","m_field8","m_field9",
};
for(int i=0; i<myUnexpectedFields.length; i++) {
IField myIField = myIStruct.getField( myUnexpectedFields[i] );
assertNull( "Failed on "+i, myIField);
}
}
public void testGetMethods() {
ITranslationUnit tu = getTU();
ArrayList myArrayStructs = tu.getChildrenOfType(ICElement.C_STRUCT);
IStructure myIStruct = (IStructure) myArrayStructs.get(0);
IMethod[] myArrayIMethod = myIStruct.getMethods();
String[] myExpectedMethods = {
"method1","method2","testStruct1","~testStruct1"
};
assertEquals(myExpectedMethods.length, myArrayIMethod.length);
for(int i=0; i<myArrayIMethod.length; i++) {
assertNotNull( "Failed on "+i, myArrayIMethod[i]);
assertEquals("Failed on "+i,
myExpectedMethods[i], myArrayIMethod[i].getElementName());
}
}
// TODO Bug# 38985: remove testGetMethodsHack()
public void testGetMethodsHack() {
ITranslationUnit tu = getTU();
ArrayList myArrayStructs = tu.getChildrenOfType(ICElement.C_STRUCT);
IStructure myIStruct = (IStructure) myArrayStructs.get(0);
ArrayList myArrayIMethod = myIStruct.getChildrenOfType(ICElement.C_METHOD_DECLARATION);
myArrayIMethod.addAll( myIStruct.getChildrenOfType(ICElement.C_METHOD) );
String[] myExpectedMethods = {
"method1","method2","testStruct1","~testStruct1"
};
assertEquals(myExpectedMethods.length, myArrayIMethod.size());
for(int i=0; i<myArrayIMethod.size(); i++) {
IMethodDeclaration myIMethod = (IMethodDeclaration) myArrayIMethod.get(i);
assertNotNull( "Failed on "+i, myIMethod);
assertEquals("Failed on "+i,
myExpectedMethods[i], myIMethod.getElementName());
}
}
public void testGetMethod() {
ITranslationUnit tu = getTU();
ArrayList myArrayStructs = tu.getChildrenOfType(ICElement.C_STRUCT);
IStructure myIStruct = (IStructure) myArrayStructs.get(0);
String[] myExpectedMethods = {
"method1","method2","testStruct1","~testStruct1"
};
for(int i=0; i<myExpectedMethods.length; i++) {
IMethod myIMethod = myIStruct.getMethod( myExpectedMethods[i] );
assertNotNull( "Failed on "+i, myIMethod);
}
String[] myUnexpectedMethods = {
"method7","method8","method9",
};
for(int i=0; i<myUnexpectedMethods.length; i++) {
IMethod myIMethod = myIStruct.getMethod( myUnexpectedMethods[i] );
assertNull( "Failed on "+i, myIMethod);
}
}
public void testIsUnion() {
ITranslationUnit tu = getTU();
ICElement myElementUnion = null;
ICElement myElementNonUnion = null;
try {
myElementUnion = tu.getElement("testUnion1");
myElementNonUnion = tu.getElement("testStruct1");
}
catch( CModelException c )
{
assertNotNull("CModelException thrown",c);
}
assertNotNull( myElementUnion );
assertTrue( myElementUnion.getElementType()==ICElement.C_UNION );
IStructure myStructUnion = (IStructure) myElementUnion;
assertNotNull( myStructUnion );
assertTrue( myStructUnion.isUnion() );
assertNotNull( myElementNonUnion );
assertTrue( myElementNonUnion.getElementType()!=ICElement.C_UNION );
IStructure myStructNonUnion = (IStructure) myElementNonUnion;
assertNotNull( myStructNonUnion );
assertFalse( myStructNonUnion.isUnion() );
}
public void testIsStruct() {
ITranslationUnit tu = getTU();
ICElement myElementStruct = null;
ICElement myElementNonStruct = null;
try {
myElementStruct = tu.getElement("testStruct1");
myElementNonStruct = tu.getElement("testClass1");
}
catch( CModelException c )
{
assertNotNull("CModelException thrown",c);
}
assertNotNull( myElementStruct );
assertTrue( myElementStruct.getElementType()==ICElement.C_STRUCT );
IStructure myStructStruct = (IStructure) myElementStruct;
assertNotNull( myStructStruct );
assertTrue( myStructStruct.isStruct() );
assertNotNull( myElementNonStruct );
assertTrue( myElementNonStruct.getElementType()!=ICElement.C_STRUCT );
IStructure myStructNonStruct = (IStructure) myElementNonStruct;
assertNotNull( myStructNonStruct );
assertFalse( myStructNonStruct.isStruct() );
}
public void testIsClass() {
ITranslationUnit tu = getTU();
ICElement myElementClass = null;
ICElement myElementNonClass = null;
try {
myElementClass = tu.getElement("testClass1");
myElementNonClass = tu.getElement("testStruct1");
}
catch( CModelException c )
{
assertNotNull("CModelException thrown",c);
}
assertNotNull( myElementClass );
assertTrue( myElementClass.getElementType()==ICElement.C_CLASS );
IStructure myStructClass = (IStructure) myElementClass;
assertNotNull( myStructClass );
assertTrue( myStructClass.isClass() );
assertNotNull( myElementNonClass );
assertTrue( myElementNonClass.getElementType()!=ICElement.C_CLASS );
IStructure myStructNonClass = (IStructure) myElementNonClass;
assertNotNull( myStructNonClass );
assertFalse( myStructNonClass.isClass() );
}
public void testIsAbstract() {
ITranslationUnit tu = getTU();
ICElement myElementAbstract = null;
ICElement myElementNonAbstract = null;
try {
myElementAbstract = tu.getElement("testClass4Abstract");
myElementNonAbstract = tu.getElement("testClass1");
}
catch( CModelException c )
{
assertNotNull("CModelException thrown",c);
}
assertNotNull( myElementAbstract );
assertTrue( myElementAbstract.getElementType()==ICElement.C_CLASS );
IStructure myStructAbstract = (IStructure) myElementAbstract;
assertNotNull( myStructAbstract );
assertTrue( myStructAbstract.isAbstract() );
assertNotNull( myElementNonAbstract );
assertTrue( myElementNonAbstract.getElementType()!=ICElement.C_CLASS );
IStructure myStructNonAbstract = (IStructure) myElementNonAbstract;
assertNotNull( myStructNonAbstract );
assertFalse( myStructNonAbstract.isAbstract() );
}
// IInheritance
public void testGetBaseTypes() {
ITranslationUnit tu = getTU();
ICElement myElementDerived = null;
IStructure[] myBaseTypes = null;
try {
myElementDerived = tu.getElement("testClass5"); // throws
assertNotNull( myElementDerived );
assertTrue( myElementDerived.getElementType()==ICElement.C_CLASS );
IStructure myStructDerived = (IStructure) myElementDerived;
assertNotNull( myStructDerived );
myBaseTypes = myStructDerived.getBaseTypes(); // throws
}
catch( CModelException c )
{
assertNotNull("CModelException thrown",c);
}
String[] myExpectedBaseTypes = {
"testClass1","testClass3","testClass4"
};
assertEquals( myExpectedBaseTypes.length, myBaseTypes.length );
for(int i=0; i<myBaseTypes.length; i++) {
assertEquals( "Failed on "+i, myExpectedBaseTypes[i], myBaseTypes[i].getElementName() );
}
}
// tests IInheritance.getAccessControl(int),
// not IDeclaration.getAccessControl()
public void testGetAccessControl() {
ITranslationUnit tu = getTU();
ICElement myElementDerived = null;
IStructure[] myBaseTypes = null;
try {
myElementDerived = tu.getElement("testClass5"); // throws
assertNotNull( myElementDerived );
assertTrue( myElementDerived.getElementType()==ICElement.C_CLASS );
IStructure myStructDerived = (IStructure) myElementDerived;
assertNotNull( myStructDerived );
myBaseTypes = myStructDerived.getBaseTypes(); // throws
int[] myExpectedAccessControl = {
// TODO #38986: expect appropriate access control tags
ICElement.CPP_PUBLIC,
org.eclipse.cdt.core.index.TagFlags.T_PROTECTED,
ICElement.CPP_PRIVATE
};
assertEquals( myExpectedAccessControl.length, myBaseTypes.length );
for(int i=0; i<myBaseTypes.length; i++) {
int myAccessControl = myStructDerived.getAccessControl(i); // throws
assertEquals( "Failed on "+i, myExpectedAccessControl[i], myAccessControl );
}
}
catch( CModelException c )
{
assertNotNull("CModelException thrown",c);
}
}
// getStructureInfo
public void testGetStructureInfo() {
}
// TODO: Not tested; Bug# 38958. public void testGetInitializer()
// TODO: Not tested; Bug# 38958. public void testGetTypeName()
// TODO: Not tested; Bug# 38958. public void testIsConst()
// TODO: Not tested; Bug# 38958. public void testIsStatic()
// TODO: Not tested; Bug# 38958. public void testIsVolatile()
// TODO: Not tested; Bug# 38958. public void testGetAccessControl_Void()
//
// Language Specification Tests
//
public void testAnonymousStructObject() {
ITranslationUnit tu = getTU();
ICElement myElement = null;
try {
myElement = tu.getElement("testAnonymousStructObject1");
}
catch( CModelException c )
{
assertNotNull("CModelException thrown",c);
}
assertNotNull( myElement );
assertEquals( ICElement.C_VARIABLE, myElement.getElementType() );
}
public void testInnerStruct() {
ITranslationUnit tu = getTU();
ICElement myElement = null;
try {
myElement = tu.getElement("testStruct8");
}
catch( CModelException c )
{
assertNotNull("CModelException thrown",c);
}
assertNotNull( myElement );
IStructure myIStruct = (IStructure) myElement;
assertNotNull( myIStruct );
String[] myExpectedInnerStructs = {
"testStruct9Inner", "testStruct10Inner"
};
ArrayList myInnerStructs = myIStruct.getChildrenOfType(ICElement.C_STRUCT);
assertEquals( myExpectedInnerStructs.length, myInnerStructs.size() );
for(int i=0; i<myExpectedInnerStructs.length; i++) {
IStructure myInnerStruct = (IStructure) myInnerStructs.get(i);
assertNotNull( "Failed on "+i, myInnerStruct );
assertEquals( "Failed on "+i, myExpectedInnerStructs[i], myInnerStruct.getElementName() );
}
}
}

View file

@ -0,0 +1,104 @@
/*
* Created on Jun 3, 2003
* by bnicolle
*/
package org.eclipse.cdt.core.model.tests;
import junit.framework.TestCase;
import java.io.FileInputStream;
import java.util.Map;
import org.eclipse.cdt.testplugin.CProjectHelper;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.cdt.core.CCProjectNature;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.internal.core.model.TranslationUnit;
/**
* @author bnicolle
*
*/
public abstract class IntegratedCModelTest extends TestCase {
private ICProject fCProject;
private IFile sourceFile;
private NullProgressMonitor monitor;
/**
*
*/
public IntegratedCModelTest() {
super();
}
/**
* @param name
*/
public IntegratedCModelTest(String name) {
super(name);
}
/**
* @return the subdirectory (from the plugin root) containing the required
* test sourcefile (plus a trailing slash)
*/
abstract public String getSourcefileSubdir();
/**
* @return the name of the test source-file
*/
abstract public String getSourcefileResource();
public void setUp() throws Exception {
monitor = new NullProgressMonitor();
String pluginRoot=org.eclipse.core.runtime.Platform.getPlugin("org.eclipse.cdt.core.tests").find(new Path("/")).getFile();
fCProject= CProjectHelper.createCProject("TestProject1", "bin");
sourceFile = fCProject.getProject().getFile( getSourcefileResource() );
if (!sourceFile.exists()) {
try{
FileInputStream fileIn = new FileInputStream(pluginRoot+ getSourcefileSubdir() + getSourcefileResource() );
sourceFile.create(fileIn,false, monitor);
} catch (CoreException e) {
e.printStackTrace();
}
}
if (!fCProject.getProject().hasNature(CCProjectNature.CC_NATURE_ID)) {
addNatureToProject(fCProject.getProject(), CCProjectNature.CC_NATURE_ID, null);
}
CCorePlugin.getDefault().setUseNewParser(true);
}
protected void tearDown() throws Exception {
CProjectHelper.delete(fCProject);
}
private static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException {
IProjectDescription description = proj.getDescription();
String[] prevNatures= description.getNatureIds();
String[] newNatures= new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length]= natureId;
description.setNatureIds(newNatures);
proj.setDescription(description, monitor);
}
protected ITranslationUnit getTU() {
TranslationUnit tu = new TranslationUnit(fCProject, sourceFile);
// parse the translation unit to get the elements tree
Map newElement = tu.parse(false); // FALSE=require line numbers
return tu;
}
}

View file

@ -0,0 +1,362 @@
package org.eclipse.cdt.core.model.tests;
/*
* (c) Copyright QNX Software Systems Ltd. 2002.
* All Rights Reserved.
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Stack;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.IInclude;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.testplugin.CProjectHelper;
import org.eclipse.cdt.testplugin.util.ExpectedStrings;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
/**
* @author Peter Graves
*
* This file contains a set of generic tests for the core C model's TranslationUnit
* class. There is nothing exotic here, mostly just sanity type tests
*
*/
public class TranslationUnitTests extends TestCase {
IWorkspace workspace;
IWorkspaceRoot root;
ICProject testProject;
IFile cfile, exefile, libfile, archfile, objfile;
Path cpath, exepath, libpath, archpath, objpath;
NullProgressMonitor monitor;
/* This is a list of elements in the test .c file. It will be used
* in a number of places in the tests
*/
String[] expectedStringList= {"stdio.h", "unistd.h", "func2p",
"globalvar", "myenum", "mystruct", "mystruct_t", "myunion", "mytype",
"func1", "func2", "main", "func3"};
int[] expectedLines={ 12,14,17,20,23,28,32,35,42,47,53,58,65};
/* This is a list of that the types of the above list of elements is
* expected to be.
*/
int[] expectedTypes= { ICElement.C_INCLUDE, ICElement.C_INCLUDE,
ICElement.C_FUNCTION_DECLARATION, ICElement.C_VARIABLE,
ICElement.C_ENUMERATION, ICElement.C_STRUCT, ICElement.C_TYPEDEF,
ICElement.C_UNION, ICElement.C_TYPEDEF, ICElement.C_FUNCTION,
ICElement.C_FUNCTION, ICElement.C_FUNCTION,ICElement.C_FUNCTION};
/**
* Constructor for TranslationUnitTests
* @param name
*/
public TranslationUnitTests(String name) {
super(name);
}
/**
* Sets up the test fixture.
*
* Called before every test case method.
*
* Example code test the packages in the project
* "com.qnx.tools.ide.cdt.core"
*/
protected void setUp() throws CoreException,FileNotFoundException {
/***
* The rest of the tests assume that they have a working workspace
* and workspace root object to use to create projects/files in,
* so we need to get them setup first.
*/
IWorkspaceDescription desc;
String pluginRoot=org.eclipse.core.runtime.Platform.getPlugin("org.eclipse.cdt.core.tests").find(new Path("/")).getFile();
workspace= ResourcesPlugin.getWorkspace();
root= workspace.getRoot();
monitor = new NullProgressMonitor();
if (workspace==null)
fail("Workspace was not setup");
if (root==null)
fail("Workspace root was not setup");
desc=workspace.getDescription();
desc.setAutoBuilding(false);
workspace.setDescription(desc);
/***
* Setup the various files, paths and projects that are needed by the
* tests
*/
testProject=CProjectHelper.createCProject("filetest", "none");
if (testProject==null)
fail("Unable to create project");
cfile = testProject.getProject().getFile("exetest.c");
if (!cfile.exists()) {
cfile.create(new FileInputStream(pluginRoot+"resources/cfiles/TranslationUnits.c"),false, monitor);
}
cpath=new Path(workspace.getRoot().getLocation()+"/filetest/main.c");
objfile = testProject.getProject().getFile("exetest.o");
if (!objfile.exists()) {
objfile.create(new FileInputStream(pluginRoot+"resources/exe/x86/o.g/main.o"),false, monitor);
}
objpath=new Path(workspace.getRoot().getLocation()+"/filetest/main.o");
exefile = testProject.getProject().getFile("test_g");
if (!exefile.exists()) {
exefile.create(new FileInputStream(pluginRoot+"resources/exe/x86/o.g/exe_g"),false, monitor);
}
exepath=new Path(workspace.getRoot().getLocation()+"/filetest/exe_g");
archfile = testProject.getProject().getFile("libtestlib_g.a");
if (!archfile.exists()) {
archfile.create(new FileInputStream(pluginRoot+"resources/testlib/x86/a.g/libtestlib_g.a"),false, monitor);
}
libpath=new Path(workspace.getRoot().getLocation()+"/filetest/libtestlib_g.so");
libfile = testProject.getProject().getFile("libtestlib_g.so");
if (!libfile.exists()) {
libfile.create(new FileInputStream(pluginRoot+"resources/testlib/x86/so.g/libtestlib_g.so"),false, monitor);
}
archpath=new Path(workspace.getRoot().getLocation()+"/filetest/libtestlib_g.a");
}
/**
* Tears down the test fixture.
*
* Called after every test case method.
*/
protected void tearDown() throws CoreException {
// release resources here and clean-up
testProject.getProject().delete(true,true,monitor);
}
public static TestSuite suite() {
TestSuite suite= new TestSuite(TranslationUnitTests.class.getName());
suite.addTest(new TranslationUnitTests("testIsTranslationUnit"));
suite.addTest(new TranslationUnitTests("testGetChildren"));
suite.addTest(new TranslationUnitTests("testGetElement"));
suite.addTest(new TranslationUnitTests("testBug23478A"));
suite.addTest(new TranslationUnitTests("testBug23478B"));
// TODO: suite.addTest(new TranslationUnitTests("testGetElementAtLine"));
return suite;
}
public static void main (String[] args){
junit.textui.TestRunner.run(suite());
}
/***
* Simple sanity test to make sure TranslationUnit.isTranslationUnit returns true
*
*/
public void testIsTranslationUnit() throws CoreException,FileNotFoundException {
ITranslationUnit myTranslationUnit;
myTranslationUnit=CProjectHelper.findTranslationUnit(testProject,"exetest.c");
assertTrue("A TranslationUnit", myTranslationUnit != null);
}
/***
* Simple sanity tests to make sure TranslationUnit.getChildren seems to
* basicly work
*/
public void testGetChildren() {
ITranslationUnit myTranslationUnit;
ICElement[] elements;
int x;
ExpectedStrings expectedString=new ExpectedStrings(expectedStringList);
myTranslationUnit=CProjectHelper.findTranslationUnit(testProject,"exetest.c");
if (myTranslationUnit.hasChildren()) {
elements=myTranslationUnit.getChildren();
for (x=0;x<elements.length;x++) {
expectedString.foundString(elements[x].getElementName());
}
}
assertTrue("PR:23603 " +expectedString.getMissingString(),expectedString.gotAll());
assertTrue(expectedString.getExtraString(),!expectedString.gotExtra());
}
/***
* Simple sanity tests for the getElement() call
*/
public void testGetElement() throws CModelException {
ITranslationUnit myTranslationUnit;
ICElement myElement;
Stack missing=new Stack();
int x;
myTranslationUnit=CProjectHelper.findTranslationUnit(testProject,"exetest.c");
for (x=0;x<expectedStringList.length;x++) {
myElement=myTranslationUnit.getElement(expectedStringList[x]);
if (myElement==null)
missing.push(expectedStringList[x]);
else {
assertTrue("Expected:" + expectedStringList[x] + " Got:" + myElement.getElementName(),
expectedStringList[x].equals(myElement.getElementName()));
}
}
if (!missing.empty()) {
String output=new String("PR:23603 Could not get elements: ");
while (!missing.empty())
output+=missing.pop() + " ";
assertTrue(output, false);
}
}
/***
* Simple sanity tests for the getInclude call
*/
public void testBug23478A() {
IInclude myInclude;
int x;
String includes[]={"stdio.h", "unistd.h"};
ITranslationUnit myTranslationUnit=CProjectHelper.findTranslationUnit(testProject,"exetest.c");
for (x=0; x < includes.length; x++) {
myInclude=myTranslationUnit.getInclude(includes[x]);
if (myInclude==null)
fail("Unable to get include: " + includes[x]);
else {
// Failed test: Include.getIncludeName() always returns "";
// assertTrue
assertTrue("PR:23478 Expected:"+ new String("") +" Got:"+ myInclude.getIncludeName(), includes[x].equals(myInclude.getIncludeName()));
}
}
}
/***
* Simple sanity tests for the getIncludes call
*/
public void testBug23478B() throws CModelException {
IInclude myIncludes[];
String includes[]={"stdio.h", "unistd.h"};
ExpectedStrings myExp= new ExpectedStrings(includes);
int x;
ITranslationUnit myTranslationUnit=CProjectHelper.findTranslationUnit(testProject,"exetest.c");
myIncludes=myTranslationUnit.getIncludes();
for (x=0; x < myIncludes.length; x++) {
myExp.foundString(myIncludes[x].getIncludeName());
}
// Failed test: Include.getIncludeName() always returns "";
// assertTrue
assertTrue(myExp.getMissingString(), myExp.gotAll());
assertTrue(myExp.getExtraString(), !myExp.gotExtra());
}
/***
* Simple sanity tests for the getElementAtLine() call
*/
public void testGetElementAtLine() throws CoreException {
ITranslationUnit myTranslationUnit;
ICElement myElement;
Stack missing=new Stack();
int x;
myTranslationUnit=CProjectHelper.findTranslationUnit(testProject,"exetest.c");
for (x=0;x<expectedStringList.length;x++) {
myElement=myTranslationUnit.getElementAtLine(expectedLines[x]);
if (myElement==null)
missing.push(expectedStringList[x]);
else {
if (expectedStringList[x].equals("mystruct_t")) {
assertTrue("PR:23603 expected:" + expectedStringList[x] + " Got:" + myElement.getElementName(),
expectedStringList[x].equals(myElement.getElementName()));
} else {
assertTrue("Expected:" + expectedStringList[x] + " Got:" + myElement.getElementName(),
expectedStringList[x].equals(myElement.getElementName()));
}
}
}
if (!missing.empty()) {
String output=new String("PR: 23603 Could not get elements: ");
while (!missing.empty())
output+=missing.pop() + " ";
assertTrue(output, false);
}
}
/***
* Simple sanity tests for the getInclude call
*/
/* Reintroduce this test when Bug# 23478 is fixed
public void testGetInclude() {
IInclude myInclude;
int x;
String includes[]={"stdio.h", "unistd.h"};
ITranslationUnit myTranslationUnit=CProjectHelper.findTranslationUnit(testProject,"exetest.c");
for (x=0;x<includes.length;x++) {
myInclude=myTranslationUnit.getInclude(includes[x]);
if (myInclude==null)
fail("Unable to get include: " + includes[x]);
else
assertTrue("PR:23478 Expected:"+includes[x] +" Got:"+ myInclude.getIncludeName(), includes[x].equals(myInclude.getIncludeName()));
}
}
*/
/***
* Simple sanity tests for the getIncludes call
*/
/* Reintroduce this test when Bug# 23478 is fixed
public void testGetIncludes() throws CModelException {
IInclude myIncludes[];
String includes[]={"stdio.h", "unistd.h"};
ExpectedStrings myExp= new ExpectedStrings(includes);
int x;
ITranslationUnit myTranslationUnit=CProjectHelper.findTranslationUnit(testProject,"exetest.c");
fail("PR:23478 Unable to test because we can't get the name of an include file");
myIncludes=myTranslationUnit.getIncludes();
for (x=0;x<myIncludes.length;x++) {
myExp.foundString(myIncludes[x].getIncludeName());
}
assertTrue(myExp.getMissingString(), myExp.gotAll());
assertTrue(myExp.getExtraString(), !myExp.gotExtra());
}
*/
}

View file

@ -0,0 +1,125 @@
package org.eclipse.cdt.core.model.tests;
/**********************************************************************
* Copyright (c) 2002,2003 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - Initial API and implementation
***********************************************************************/
import java.io.FileInputStream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.CCProjectNature;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.model.IBuffer;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.internal.core.model.IWorkingCopy;
import org.eclipse.cdt.internal.core.model.TranslationUnit;
import org.eclipse.cdt.testplugin.CProjectHelper;
import org.eclipse.cdt.testplugin.TestPluginLauncher;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
/**
* Contains unit test cases for Working Copies. Run using JUnit Plugin Test
* configuration launcher.
*/
public class WorkingCopyTests extends TestCase {
private ICProject fCProject;
private IFile headerFile;
private NullProgressMonitor monitor;
public static void main(String[] args) {
TestPluginLauncher.run(TestPluginLauncher.getLocationFromProperties(), WorkingCopyTests.class, args);
}
public static Test suite() {
TestSuite suite= new TestSuite(WorkingCopyTests.class.getName());
suite.addTest(new WorkingCopyTests("testWorkingCopy"));
//suite.addTest(new WorkingCopyTests("testHashing"));
return suite;
}
public WorkingCopyTests(String name) {
super(name);
}
protected void setUp() throws Exception {
monitor = new NullProgressMonitor();
String pluginRoot=org.eclipse.core.runtime.Platform.getPlugin("org.eclipse.cdt.core.tests").find(new Path("/")).getFile();
fCProject= CProjectHelper.createCProject("TestProject1", "bin");
//Path filePath = new Path(ResourcesPlugin.getWorkspace().getRoot().getLocation().toString()+ fCProject.getPath().toString()+ "/WorkingCopyTest.h");
headerFile = fCProject.getProject().getFile("WorkingCopyTest.h");
if (!headerFile.exists()) {
try{
FileInputStream fileIn = new FileInputStream(pluginRoot+ "resources/cfiles/WorkingCopyTestStart.h");
headerFile.create(fileIn,false, monitor);
} catch (CoreException e) {
e.printStackTrace();
}
}
if (!fCProject.getProject().hasNature(CCProjectNature.CC_NATURE_ID)) {
addNatureToProject(fCProject.getProject(), CCProjectNature.CC_NATURE_ID, null);
}
CCorePlugin.getDefault().setUseNewParser(true);
}
private static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException {
IProjectDescription description = proj.getDescription();
String[] prevNatures= description.getNatureIds();
String[] newNatures= new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length]= natureId;
description.setNatureIds(newNatures);
proj.setDescription(description, monitor);
}
protected void tearDown() throws Exception {
CProjectHelper.delete(fCProject);
}
public void testWorkingCopy() throws Exception {
ITranslationUnit tu = new TranslationUnit(fCProject, headerFile);
// CreateWorkingCopy
assertNotNull (tu);
IWorkingCopy wc = tu.getWorkingCopy();
assertNotNull (wc);
assertNotNull (wc.getBuffer());
assertTrue (wc.exists());
// ModifyWorkingCopy
IBuffer wcBuf = wc.getBuffer();
wcBuf.append("\n class Hello{ int x; };");
if (tu.getBuffer().getContents().equals(wc.getBuffer().getContents() ) )
fail("Buffers should NOT be equal at this point!");
// ReconcileWorkingCopy
wc.reconcile();
// CommitWorkingCopy
wc.commit(true, monitor);
if(!tu.getBuffer().getContents().equals(wc.getBuffer().getContents()))
fail("Buffers should be equal at this point!");
// DestroyWorkingCopy
wc.destroy();
assertFalse(wc.exists());
}
}

View file

@ -0,0 +1,190 @@
/*******************************************************************************
* Copyright (c) 2001 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corp. - Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.core.parser.tests;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Properties;
import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.parser.IParserCallback;
import org.eclipse.cdt.internal.core.parser.NullSourceElementRequestor;
/**
* @author aniefer
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public abstract class AutomatedFramework extends TestCase {
public AutomatedFramework() {
super();
}
public AutomatedFramework(String name) {
super(name);
}
protected abstract AutomatedFramework newTest( String name );
protected abstract void loadProperties() throws Exception;
public abstract void doFile() throws Throwable;
private void fillSuite( TestSuite suite, File path ){
File files[] = null;
if( path.isFile() ){
files = new File[ 1 ];
files[0] = path;
}
else
files = path.listFiles();
File file = null;
String filePath = null;
int i = 0;
try{
file = files[ i++ ];
while( file != null )
{
if( file.isDirectory() )
fillSuite( suite, file );
else if( file.isFile() && nameFilter.accept( file.getParentFile(), file.getName() ) ){
try{
filePath = file.getCanonicalPath();
} catch ( Exception e ){
continue;
}
if( filePath.endsWith(".cpp") || filePath.endsWith(".hpp") ||
filePath.endsWith(".cc") || filePath.endsWith(".CC") ||
filePath.endsWith(".C") ||
filePath.endsWith(".hxx") || filePath.endsWith(".hh") )
{
AutomatedTest.natures.put( filePath, "cpp" );
} else if( filePath.endsWith(".c") ){
AutomatedTest.natures.put( filePath, "c" );
} else {
AutomatedTest.natures.put( filePath, AutomatedTest.defaultNature );
}
AutomatedTest.fileList.add( file );
suite.addTest( newTest( file.getName().replace(',', '_') ) );
}
file = files[ i++ ];
}
} catch( ArrayIndexOutOfBoundsException e ){
//done
}
}
public void reportFailed() {
fail( "Unable to open " + outputFile + "for output of results." );
}
public void propertiesFailed() {
fail( "Unable to load properties file." );
}
protected void runTest() throws Throwable {
String name = getName();
if( name.equals("propertiesFailed") )
propertiesFailed();
else if ( name.equals("reportFailed") )
reportFailed();
else
doFile();
}
public Test createSuite() {
TestSuite suite = new TestSuite();
try{
loadProperties();
} catch( Exception e ){
suite.addTest( newTest( "propertiesFailed") );
}
if( outputFile != null && !outputFile.equals("") ){
try{
File output = new File( outputFile );
if( output.exists() ){
output.delete();
}
output.createNewFile();
report = new FileOutputStream( output );
} catch( Exception e ) {
suite.addTest( newTest( "reportFailed" ) );
}
}
Set keys = testSources.keySet();
Iterator iter = keys.iterator();
int size = keys.size();
String item = null;
for( int i = size; i > 0; i-- )
{
item = (String) iter.next();
File file = new File( item );
if( file.exists() ){
defaultNature = (String) testSources.get( item );
fillSuite( suite, file );
}
}
return suite;
}
protected static IParserCallback nullCallback = new NullSourceElementRequestor();
protected static Properties properties = new Properties();
protected static String defaultNature;
protected static String outputFile = null;
protected static HashMap testSources = new HashMap();
protected static HashMap natures = new HashMap();
protected static LinkedList fileList = new LinkedList();
private static FilenameFilter nameFilter = new Filter();
protected static FileOutputStream report = null;
static private class Filter implements FilenameFilter
{
public boolean accept(File dir, String name) {
if( name.endsWith(".cpp") ||
name.endsWith(".c") ||
name.endsWith(".cc") ||
name.endsWith(".CC") ||
name.endsWith(".C") ||
name.endsWith(".h") ||
name.endsWith(".hh") ||
name.endsWith(".hpp") ||
name.endsWith(".hxx"))
{
return true;
}
else
return false;
}
}
}

View file

@ -0,0 +1,134 @@
/*******************************************************************************
* Copyright (c) 2001 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corp. - Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.core.parser.tests;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import junit.framework.AssertionFailedError;
import junit.framework.Test;
import org.eclipse.cdt.core.parser.IParser;
import org.eclipse.cdt.internal.core.parser.Parser;
import org.eclipse.core.runtime.Path;
/**
* @author aniefer
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class AutomatedTest extends AutomatedFramework {
public AutomatedTest() {
}
public AutomatedTest(String name){
super(name);
}
public void doFile() throws Throwable {
assertNotNull( fileList );
File file = null;
IParser parser = null;
try{
file = (File)fileList.removeFirst();
FileInputStream stream = new FileInputStream( file );
String filePath = file.getCanonicalPath();
String nature = (String)natures.get( filePath );
boolean cppNature = nature.equalsIgnoreCase("cpp");
parser = new Parser( stream, nullCallback, true);
parser.setCppNature( cppNature );
parser.mapLineNumbers(true);
assertTrue( parser.parse() );
}
catch( Throwable e )
{
String output = null;
if( e instanceof AssertionFailedError ){
output = file.getCanonicalPath() + ": Parse failed on line ";
output += parser.getLineNumberForOffset(parser.getLastErrorOffset()) + "\n";
} else {
output = file.getCanonicalPath() + ": " + e.getClass().toString();
output += " on line " + parser.getLineNumberForOffset(parser.getLastErrorOffset()) + "\n";
}
if( report != null ){
report.write( output.getBytes() );
}
fail( output );
}
}
protected AutomatedFramework newTest( String name ){
return new AutomatedTest( name );
}
public static Test suite()
{
AutomatedFramework frame = new AutomatedTest();
return frame.createSuite();
}
protected void tearDown () throws Exception {
if( fileList != null && fileList.size() == 0 && report != null ){
report.flush();
report.close();
}
}
protected void loadProperties() throws Exception{
String resourcePath = org.eclipse.core.runtime.Platform.getPlugin("org.eclipse.cdt.core.tests").find(new Path("/")).getFile();
resourcePath += "resources/parser/AutomatedTest";
try{
FileInputStream propertiesIn = new FileInputStream( resourcePath + "/AutomatedTest.properties");
properties.load( propertiesIn );
outputFile = properties.getProperty( "outputFile", "" );
String sourceInfo = properties.getProperty( "source", "" );
if( sourceInfo.equals("") )
throw new FileNotFoundException();
else{
StringTokenizer tokenizer = new StringTokenizer( sourceInfo, "," );
String str = null, val = null;
try{
while( tokenizer.hasMoreTokens() ){
str = tokenizer.nextToken().trim();
val = tokenizer.nextToken().trim();
testSources.put( str, val );
}
} catch ( NoSuchElementException e ){
//only way to get here is to have a missing val, assume cpp for that str
testSources.put( str, "cpp" );
}
}
} catch ( FileNotFoundException e ){
testSources.put( resourcePath + "/defaultCpp", "cpp" );
testSources.put( resourcePath + "/defaultC", "c" );
}
}
}

View file

@ -0,0 +1,61 @@
/*******************************************************************************
* Copyright (c) 2001 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corp. - Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.core.parser.tests;
import junit.framework.TestCase;
import org.eclipse.cdt.core.parser.IParser;
import org.eclipse.cdt.internal.core.dom.DOMBuilder;
import org.eclipse.cdt.internal.core.dom.TranslationUnit;
import org.eclipse.cdt.internal.core.parser.Parser;
import org.eclipse.cdt.internal.core.parser.ParserException;
/**
* @author jcamelon
*
*/
public class BaseDOMTest extends TestCase {
public BaseDOMTest( String arg )
{
super( arg );
}
public TranslationUnit parse( String code ) throws Exception
{
return parse( code, true, true );
}
public TranslationUnit parse(String code, boolean quickParse, boolean throwOnError ) throws Exception {
DOMBuilder domBuilder = new DOMBuilder();
IParser parser = new Parser(code, domBuilder, quickParse );
if( ! parser.parse() )
if( throwOnError ) throw new ParserException( "Parse failure" );
else domBuilder.getTranslationUnit().setParseSuccessful( false );
return domBuilder.getTranslationUnit();
}
public void failTest(String code) {
boolean testPassed = false;
try {
TranslationUnit tu = parse(code);
testPassed = true;
fail( "We should not reach this point");
} catch (Throwable e) {
if (!(e instanceof ParserException))
fail("Unexpected Error: " + e.getMessage());
}
if (testPassed)
fail("The expected error did not occur.");
}
}

View file

@ -0,0 +1,198 @@
/*******************************************************************************
* Copyright (c) 2001 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corp. - Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.core.parser.tests;
import java.io.StringReader;
import junit.framework.TestCase;
import org.eclipse.cdt.core.parser.IToken;
import org.eclipse.cdt.core.parser.ScannerException;
import org.eclipse.cdt.internal.core.parser.Parser;
import org.eclipse.cdt.internal.core.parser.Scanner;
/**
* @author jcamelon
*
*/
public class BaseScannerTest extends TestCase {
protected Scanner scanner;
public BaseScannerTest( String x )
{
super(x);
}
public void initializeScanner(String input)
{
scanner= new Scanner();
scanner.initialize( new StringReader(input),"TEXT");
}
public int fullyTokenize() throws Exception
{
try
{
IToken t= scanner.nextToken();
while (t != null)
{
if (verbose)
System.out.println("Token t = " + t);
if ((t.getType()> IToken.tLAST))
System.out.println("Unknown type for token " + t);
t= scanner.nextToken();
}
}
catch (Parser.EndOfFile e)
{
}
catch (ScannerException se)
{
throw se;
}
return scanner.getCount();
}
public void validateIdentifier(String expectedImage) throws ScannerException
{
try {
IToken t= scanner.nextToken();
assertTrue(t.getType() == IToken.tIDENTIFIER);
assertTrue(t.getImage().equals(expectedImage));
} catch (Parser.EndOfFile e) {
assertTrue(false);
}
}
public void validateInteger(String expectedImage) throws ScannerException
{
try {
IToken t= scanner.nextToken();
assertTrue(t.getType() == IToken.tINTEGER);
assertTrue(t.getImage().equals(expectedImage));
} catch (Parser.EndOfFile e) {
assertTrue(false);
}
}
public void validateFloatingPointLiteral(String expectedImage) throws ScannerException
{
try {
IToken t= scanner.nextToken();
assertTrue(t.getType() == IToken.tFLOATINGPT);
assertTrue(t.getImage().equals(expectedImage));
} catch (Parser.EndOfFile e) {
assertTrue(false);
}
}
public void validateChar( char expected )throws ScannerException
{
try {
IToken t= scanner.nextToken();
assertTrue(t.getType() == IToken.tCHAR );
Character c = new Character( expected );
assertEquals( t.getImage(), c.toString() );
} catch (Parser.EndOfFile e) {
assertTrue(false);
}
}
public void validateChar( String expected ) throws ScannerException
{
try {
IToken t= scanner.nextToken();
assertTrue(t.getType() == IToken.tCHAR );
assertEquals( t.getImage(), expected );
} catch (Parser.EndOfFile e) {
assertTrue(false);
}
}
public void validateString( String expectedImage ) throws ScannerException
{
validateString( expectedImage, false );
}
public void validateString(String expectedImage, boolean lString ) throws ScannerException
{
try {
IToken t= scanner.nextToken();
if( lString )
assertTrue(t.getType() == IToken.tLSTRING);
else
assertTrue(t.getType() == IToken.tSTRING);
assertTrue(t.getImage().equals(expectedImage));
} catch (Parser.EndOfFile e) {
assertTrue(false);
}
}
public void validateToken(int tokenType) throws ScannerException
{
try {
IToken t= scanner.nextToken();
assertTrue(t.getType() == tokenType);
} catch (Parser.EndOfFile e) {
assertTrue(false);
}
}
public void validateBalance(int expected)
{
assertTrue(scanner.getDepth() == expected);
}
public void validateBalance()
{
assertTrue(scanner.getDepth() == 0);
}
public void validateEOF() throws ScannerException
{
try {
assertNull(scanner.nextToken());
} catch (Parser.EndOfFile e) {
}
}
public void validateDefinition(String name, String value)
{
String definition= null;
definition= (String) scanner.getDefinition(name);
assertNotNull(definition);
assertTrue(definition.trim().equals(value));
}
public void validateDefinition(String name, int value)
{
String definition= null;
definition= (String) scanner.getDefinition(name);
assertNotNull(definition);
int intValue= (Integer.valueOf((String) definition)).intValue();
assertEquals(value, intValue);
}
public void validateAsUndefined(String name)
{
assertNull(scanner.getDefinition(name));
}
public static final String EXCEPTION_THROWN = "Exception thrown ";
public static final String EXPECTED_FAILURE = "This statement should not be reached "
+ "as we sent in bad preprocessor input to the scanner";
public static final boolean verbose = false;
}

View file

@ -0,0 +1,200 @@
package org.eclipse.cdt.core.parser.tests;
import junit.framework.TestCase;
import org.eclipse.cdt.core.parser.ScannerException;
import org.eclipse.cdt.internal.core.parser.BranchTracker;
/**
* @author jcamelon
*
* To change this generated comment edit the template variable "typecomment":
* Window>Preferences>Java>Templates.
* To enable and disable the creation of type comments go to
* Window>Preferences>Java>Code Generation.
*/
public class BranchTrackerTest extends TestCase {
public BranchTrackerTest( String ignoreMe )
{
super( ignoreMe );
}
public static void assertFalse( boolean input )
{
assertTrue( input == false );
}
public void testIgnore()
{
BranchTracker bt = new BranchTracker();
try
{
/*
* #if 0
* # if 1
* # elif 1
* # else
* # endif
* #else
* #endif
*/
assertFalse( bt.poundif( false ) );
assertFalse( bt.poundif( true ) );
assertFalse( bt.poundelif( true ) );
assertFalse( bt.poundelse() );
assertFalse( bt.poundendif() );
assertTrue( bt.poundelse() );
assertTrue( bt.poundendif() );
/*
* #if 0
* # if 1
* # elif 1
* # else
* # endif
* #else
* # if 0
* # elif 1
* # elif 0
* # elif 1
* # else
* # endif
* #endif
*/
bt = new BranchTracker();
assertFalse( bt.poundif( false ) );
assertFalse( bt.poundif( true ));
assertFalse( bt.poundelif( true ) );
assertFalse( bt.poundelse() );
assertFalse( bt.poundendif() );
assertTrue( bt.poundelse() );
assertFalse( bt.poundif( false ) );
assertTrue( bt.poundelif( true ) );
assertFalse( bt.poundelif( false ) );
assertFalse( bt.poundelif( true ) );
assertFalse( bt.poundelse() );
assertTrue( bt.poundendif() );
assertTrue( bt.poundendif() );
assertEquals( 0, bt.getDepth() );
/*
* #if 0
* # if 1
* # elif 0
* # elif 1
* # else
* # endif
* #elif 0
* # if 0
* # elif 0
* # elif 1
* # else
* # endif
* #elif 1
* # if 0
* # elif 0
* # elif 0
* # else
* # endif
* #else
* # if 1
* # elif 0
* # elif 1
* # else
* # endif
* #endif
*/
assertFalse(bt.poundif(false));
assertFalse(bt.poundif(true));
assertFalse(bt.poundelif(false));
assertFalse(bt.poundelif(true));
assertFalse(bt.poundelse());
assertFalse( bt.poundendif() );
assertFalse(bt.poundelif(false));
assertFalse(bt.poundif(false));
assertFalse(bt.poundelif(false));
assertFalse(bt.poundelif(true));
assertFalse(bt.poundelse());
assertFalse( bt.poundendif());
assertTrue(bt.poundelif(true));
assertFalse(bt.poundif(false));
assertFalse(bt.poundelif(false));
assertFalse(bt.poundelif(false));
assertTrue(bt.poundelse());
assertTrue( bt.poundendif() );
assertFalse(bt.poundelse());
assertFalse(bt.poundif(true));
assertFalse(bt.poundelif(false));
assertFalse(bt.poundelif(true));
assertFalse(bt.poundelse());
assertFalse( bt.poundendif() );
assertTrue( bt.poundendif() );
assertEquals(0, bt.getDepth());
} catch (ScannerException se) {
fail("Unexpected Scanner exception thrown");
}
}
public void testSimpleBranches()
{
try
{
/*
* code sequence is
* #if 1
* #else
* #endif
*/
BranchTracker bt = new BranchTracker();
assertTrue( bt.poundif( true ) );
assertFalse( bt.poundelse() );
assertTrue( bt.poundendif() );
/*
* code sequence is
* #if 1
* # if 0
* # elif 0
* # else
* # endif
* #else
* #endif
*/
bt = new BranchTracker();
assertTrue( bt.poundif( true ));
assertFalse( bt.poundif( false ));
assertFalse( bt.poundelif( false ));
assertTrue( bt.poundelse());
assertTrue( bt.poundendif() );
assertFalse( bt.poundelse() );
assertTrue( bt.poundendif() );
/*
* #if 1
* #elsif 1
* #elsif 0
* #else
* #endif
*/
bt = new BranchTracker();
assertTrue( bt.poundif( true ) );
assertFalse( bt.poundelif( true ));
assertFalse( bt.poundelif( false ));
assertFalse( bt.poundelse());
assertTrue( bt.poundendif() );
}
catch( ScannerException se )
{
fail( "Exception" );
}
}
}

View file

@ -0,0 +1,42 @@
package org.eclipse.cdt.core.parser.tests;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.parser.IParser;
import org.eclipse.cdt.internal.core.parser.ExpressionEvaluator;
import org.eclipse.cdt.internal.core.parser.Parser;
public class ExprEvalTest extends TestCase {
public static Test suite() {
return new TestSuite(ExprEvalTest.class);
}
public ExprEvalTest(String name) {
super(name);
}
public void runTest(String code, int expectedValue) throws Exception {
ExpressionEvaluator evaluator = new ExpressionEvaluator();
IParser parser = new Parser(code, evaluator);
parser.expression(null);
assertEquals(expectedValue, ((Integer)evaluator.getResult()).intValue());
}
public void testInteger() throws Exception {
runTest("5;", 5);
}
public void testRelational() throws Exception {
runTest("1 < 2;", 1);
runTest("2 < 1;", 0);
runTest("2 == 1 + 1;", 1);
runTest("2 != 1 + 1;", 0);
}
public void testBracketed() throws Exception {
runTest("2 * (3 + 4);", 14);
}
}

View file

@ -0,0 +1,252 @@
/*******************************************************************************
* Copyright (c) 2001 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corp. - Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.core.parser.tests;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import junit.framework.Test;
import org.eclipse.cdt.internal.core.parser.Parser;
import org.eclipse.core.runtime.Path;
/**
* @author aniefer
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class FractionalAutomatedTest extends AutomatedFramework {
public FractionalAutomatedTest() {
super();
}
public FractionalAutomatedTest(String name) {
super(name);
}
protected AutomatedFramework newTest( String name ){
return new FractionalAutomatedTest( name );
}
protected void loadProperties() throws Exception{
String resourcePath = org.eclipse.core.runtime.Platform.getPlugin("org.eclipse.cdt.core.tests").find(new Path("/")).getFile();
resourcePath += "resources/parser/AutomatedTest";
try{
FileInputStream propertiesIn = new FileInputStream( resourcePath + "/FractionalAutomatedTest.properties");
properties.load( propertiesIn );
outputFile = properties.getProperty( "outputFile", "" );
String sourceInfo = properties.getProperty( "source", "" );
stepSize = Integer.parseInt( properties.getProperty( "stepSize", "50" ) );
windowSize = Integer.parseInt( properties.getProperty( "windowSize", "200" ) );
timeOut = Integer.parseInt( properties.getProperty( "timeOut", "5000" ));
outputDir = properties.getProperty( "outDir", "" );
if( sourceInfo.equals("") )
throw new FileNotFoundException();
else{
StringTokenizer tokenizer = new StringTokenizer( sourceInfo, "," );
String str = null, val = null;
try{
while( tokenizer.hasMoreTokens() ){
str = tokenizer.nextToken().trim();
val = tokenizer.nextToken().trim();
testSources.put( str, val );
}
} catch ( NoSuchElementException e ){
//only way to get here is to have a missing val, assume cpp for that str
testSources.put( str, "cpp" );
}
}
} catch ( FileNotFoundException e ){
testSources.put( resourcePath + "/defaultCpp", "cpp" );
testSources.put( resourcePath + "/defaultC", "c" );
}
}
public static Test suite()
{
AutomatedFramework frame = new FractionalAutomatedTest();
return frame.createSuite();
}
static private String outputFile( String code ) {
if( outputDir == null || outputDir.equals("") )
return "";
File output = new File( outputDir );
try{
if( output.exists() ){
if( output.isFile() ){
output.delete();
output.createNewFile();
FileOutputStream stream = new FileOutputStream( output );
stream.write( code.getBytes() );
stream.flush();
stream.close();
return outputDir;
}
} else {
output.mkdir();
}
File file = new File( outputDir + "/" + failures++ + ".tmp" );
if( file.exists() )
file.delete();
file.createNewFile();
FileOutputStream stream = new FileOutputStream( file );
stream.write( code.getBytes() );
stream.flush();
stream.close();
return file.getCanonicalPath();
} catch ( Exception e )
{}
return "";
}
static public void reportHang( String code, String file ){
String output = outputFile( code.toString() );
if( output.equals("") )
output = "Parser hang while parsing " + file + "\n";
else
output = "Parser hang while parsing " + output + "\n";
if( report != null ){
try{
report.write( output.getBytes() );
} catch ( IOException e ) {}
}
fail( output );
}
static public void reportException( String code, String file, String exception ){
String output = outputFile( code.toString() );
if( output.equals("") )
output = exception.getClass().toString() + " encountered in " + file + "\n";
else
output = exception.getClass().toString() + " encountered in " + output + "\n";
if( report != null ){
try{
report.write( output.getBytes() );
} catch ( IOException e ) {}
}
fail( output );
}
public void doFile() throws Throwable {
assertNotNull( fileList );
File file = (File)fileList.removeFirst();
FileInputStream stream = new FileInputStream( file );
String filePath = file.getCanonicalPath();
String nature = (String)natures.get( filePath );
boolean cppNature = nature.equalsIgnoreCase("cpp");
StringWriter code = new StringWriter();
ParseThread thread = new ParseThread();
byte b[] = new byte[stepSize];
int n = stream.read( b );
while( n != -1 ){
code.write( new String( b ) );
thread.code = code.toString();
thread.cppNature = cppNature;
thread.start();
thread.join( timeOut );
if( thread.isAlive() ){
//Use deprecated Thread.stop() for now
//alternative is to create a callback which could stop the parse on a flag
//by throwing something, but that has the disadvantage of being unable to
//stop any loops that don't involve callbacks.
thread.stop();
reportHang( code.toString(), filePath );
} else if( thread.result != null ) {
reportException( code.toString(), filePath, thread.result );
}
n = stream.read( b );
}
String fullCode = code.toString();
String windowedCode = null;
int length = fullCode.length();
int curPos = 0;
while( curPos + windowSize < length){
windowedCode = fullCode.substring( 0, curPos );
windowedCode += "\n" + fullCode.substring( curPos + windowSize, length );
thread.code = windowedCode;
thread.cppNature = cppNature;
thread.file = filePath;
thread.start();
thread.join( timeOut );
if( thread.isAlive() )
{
thread.stop();
reportHang( windowedCode, filePath );
} else if( thread.result != null ) {
reportException( windowedCode, filePath, thread.result );
}
curPos += stepSize;
}
}
static class ParseThread extends Thread{
public String code;
public boolean cppNature;
public String file;
public String result;
public void run(){
try{
result = null;
Parser parser = new Parser( code, nullCallback, true);
parser.setCppNature( cppNature );
parser.mapLineNumbers(true);
parser.parse();
} catch ( Exception e ){
result = e.getClass().toString();
}
}
}
static protected int stepSize = 50;
static protected int windowSize = 200;
static protected int timeOut = 5000;
static protected String outputDir = null;
static protected int failures = 0;
}

View file

@ -0,0 +1,156 @@
/**********************************************************************
* Copyright (c) 2002,2003 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Rational Software - Initial API and implementation
***********************************************************************/
package org.eclipse.cdt.core.parser.tests;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.List;
import junit.framework.TestCase;
import org.eclipse.cdt.core.parser.IParser;
import org.eclipse.cdt.core.parser.IToken;
import org.eclipse.cdt.internal.core.dom.ClassSpecifier;
import org.eclipse.cdt.internal.core.dom.DOMBuilder;
import org.eclipse.cdt.internal.core.dom.EnumerationSpecifier;
import org.eclipse.cdt.internal.core.dom.IOffsetable;
import org.eclipse.cdt.internal.core.dom.NamespaceDefinition;
import org.eclipse.cdt.internal.core.dom.SimpleDeclaration;
import org.eclipse.cdt.internal.core.dom.TemplateDeclaration;
import org.eclipse.cdt.internal.core.parser.Parser;
import org.eclipse.cdt.internal.core.parser.Scanner;
import org.eclipse.core.runtime.Path;
/**
* @author jcamelon
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class LineNumberTest extends TestCase {
public LineNumberTest( String arg )
{
super( arg );
}
private InputStream fileIn;
protected void setUp() throws Exception {
String fileName =org.eclipse.core.runtime.Platform.getPlugin("org.eclipse.cdt.core.tests").find(new Path("/")).getFile() + "resources/parser/LineNumberTest.h";
fileIn = new FileInputStream(fileName);
}
public void testLineNos() throws Exception
{
Scanner scanner = new Scanner();
Reader reader = new StringReader( "int x = 3;\n foo\nfire\nfoe ");
scanner.initialize( reader, "string");
scanner.mapLineNumbers(true);
IToken t = scanner.nextToken();
assertEquals( t.getType(), IToken.t_int );
assertEquals( scanner.getLineNumberForOffset(t.getOffset()), 1 );
t = scanner.nextToken();
assertEquals( t.getImage(), "x");
assertEquals( scanner.getLineNumberForOffset(t.getOffset()), 1 );
t = scanner.nextToken();
assertEquals( t.getType(), IToken.tASSIGN );
assertEquals( scanner.getLineNumberForOffset(t.getOffset()), 1 );
t = scanner.nextToken();
assertEquals( t.getImage(), "3" );
assertEquals( scanner.getLineNumberForOffset(t.getOffset()), 1 );
t = scanner.nextToken();
assertEquals( t.getType(), IToken.tSEMI);
assertEquals( scanner.getLineNumberForOffset(t.getOffset()), 1 );
for( int i = 2; i < 5; ++i )
{
t = scanner.nextToken();
assertEquals( t.getType(), IToken.tIDENTIFIER);
assertEquals( scanner.getLineNumberForOffset(t.getOffset()), i );
}
try {
t = scanner.nextToken();
fail( "EOF");
}
catch (Parser.EndOfFile e) {
assertEquals( scanner.getLineNumberForOffset(29), 4 );
}
}
public void testDOMLineNos() throws Exception
{
DOMBuilder domBuilder = new DOMBuilder();
IParser parser = new Parser( fileIn, domBuilder, true );
parser.mapLineNumbers(true);
if( ! parser.parse() ) fail( "Parse of file failed");
List macros = domBuilder.getTranslationUnit().getMacros();
List inclusions = domBuilder.getTranslationUnit().getInclusions();
List declarations = domBuilder.getTranslationUnit().getDeclarations();
assertEquals( 3, macros.size() );
assertEquals( 1, inclusions.size() );
assertEquals( declarations.size(), 4 );
validateLineNumbers( (IOffsetable)inclusions.get(0), 2, 2 );
validateLineNumbers( (IOffsetable)macros.get(0), 5, 5 );
validateLineNumbers( (IOffsetable)macros.get(1), 6, 6 );
validateLineNumbers( (IOffsetable)macros.get(2), 30, 31 );
NamespaceDefinition namespaceDecl = (NamespaceDefinition)declarations.get(0);
validateLineNumbers( namespaceDecl, 8, 22 );
List namespaceMembers = namespaceDecl.getDeclarations();
assertEquals( namespaceMembers.size(), 1 );
ClassSpecifier Hello = (ClassSpecifier)((SimpleDeclaration)namespaceMembers.get(0)).getTypeSpecifier();
validateLineNumbers( Hello, 10, 21);
List classMembers = Hello.getDeclarations();
assertEquals( classMembers.size(), 3 );
for( int i = 0; i < 3; ++i )
{
SimpleDeclaration memberDeclaration = (SimpleDeclaration)Hello.getDeclarations().get(i);
switch( i )
{
case 0:
validateLineNumbers(memberDeclaration, 13, 13 );
break;
case 1:
validateLineNumbers(memberDeclaration, 15, 15 );
break;
case 2:
validateLineNumbers(memberDeclaration, 18, 20 );
break;
default:
break;
}
}
validateLineNumbers( (SimpleDeclaration)declarations.get(1), 25, 27);
validateLineNumbers( (TemplateDeclaration)declarations.get(2), 34, 35);
SimpleDeclaration d = (SimpleDeclaration)declarations.get(3);
validateLineNumbers( d, 38, 43);
validateLineNumbers( ((EnumerationSpecifier)d.getTypeSpecifier()), 38, 43);
}
protected void tearDown() throws Exception {
if( fileIn != null ) fileIn.close();
}
protected void validateLineNumbers( IOffsetable offsetable, int top, int bottom )
{
assertNotNull( offsetable );
assertEquals( offsetable.getTopLine(), top );
assertEquals( offsetable.getBottomLine(), bottom );
}
}

View file

@ -0,0 +1,38 @@
/**********************************************************************
* Copyright (c) 2002,2003 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Rational Software - Initial API and implementation
***********************************************************************/
package org.eclipse.cdt.core.parser.tests;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.model.tests.CModelElementsTests;
/**
* @author jcamelon
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class ParserTestSuite extends TestCase {
public static Test suite() {
TestSuite suite= new TestSuite(ParserTestSuite.class.getName());
suite.addTestSuite(BranchTrackerTest.class);
suite.addTestSuite(ScannerTestCase.class);
suite.addTestSuite(ExprEvalTest.class);
suite.addTestSuite(DOMTests.class);
suite.addTestSuite(ParserSymbolTableTest.class);
suite.addTestSuite(CModelElementsTests.class);
return suite;
}
}

View file

@ -0,0 +1,216 @@
/*******************************************************************************
* Copyright (c) 2001 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corp. - Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.core.parser.tests;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import junit.framework.AssertionFailedError;
import junit.framework.Test;
import org.eclipse.cdt.core.parser.IParser;
import org.eclipse.cdt.internal.core.dom.DOMBuilder;
import org.eclipse.cdt.internal.core.parser.Parser;
import org.eclipse.core.runtime.Path;
/**
* @author vmozgin
*
* Automated parser test framework, to use with GCC testsuites
*/
public class TortureTest extends FractionalAutomatedTest {
static protected boolean isEnabled = false;
static protected boolean quickParse = true;
public TortureTest () {
super();
}
public TortureTest (String name) {
super(name);
}
protected AutomatedFramework newTest (String name){
return new TortureTest (name);
}
protected void loadProperties() throws Exception{
String resourcePath = org.eclipse.core.runtime.Platform.getPlugin("org.eclipse.cdt.core.tests").find(new Path("/")).getFile();
resourcePath += "resources/parser/TortureTest";
try {
FileInputStream propertiesIn = new FileInputStream(resourcePath + "/TortureTest.properties");
properties.load (propertiesIn);
isEnabled = properties.getProperty("enabled", "false").equalsIgnoreCase("true");
quickParse = properties.getProperty("quickParse", "true").equalsIgnoreCase("true");
String sourceInfo = properties.getProperty("source", "");
stepSize = Integer.parseInt(properties.getProperty("stepSize", "25000"));
outputFile = properties.getProperty("outputFile", "");
timeOut = Integer.parseInt(properties.getProperty("timeOut", "60000"));
outputDir = properties.getProperty("outDir", "");
if (sourceInfo.equals(""))
throw new FileNotFoundException();
else {
StringTokenizer tokenizer = new StringTokenizer(sourceInfo, ",");
String str = null, val = null;
try {
while (tokenizer.hasMoreTokens()) {
str = tokenizer.nextToken().trim();
val = tokenizer.nextToken().trim();
testSources.put(str, val);
}
} catch (NoSuchElementException e){
//only way to get here is to have a missing val, assume cpp for that str
testSources.put(str, "cpp");
}
}
} catch (FileNotFoundException e){
testSources.put(resourcePath + "/default", "cpp");
}
if (!isEnabled) testSources.clear();
}
public static Test suite()
{
AutomatedFramework frame = new TortureTest();
return frame.createSuite();
}
static protected void reportException (Throwable e, String file, IParser parser){
String output = null;
int lineNumber = -1;
try {
lineNumber = parser.getLineNumberForOffset(parser.getLastErrorOffset());
} catch (Exception ex) {}
if (e instanceof AssertionFailedError) {
output = file + ": Parse failed on line ";
output += lineNumber + "\n";
} else {
output = file + ": " + e.getClass().toString();
output += " on line " + lineNumber + "\n";
}
try {
if (report != null) {
report.write(output.getBytes());
}
} catch (IOException ex) {}
fail(output);
}
static protected boolean isExpectedToPass (String testCode)
{
// Process some DejaGNU instructions
if (testCode.indexOf("{ dg-do run") >= 0) return true;
if (testCode.indexOf("{ dg-do link") >= 0) return true;
if (testCode.indexOf("{ dg-error") >= 0) return false;
if (testCode.indexOf("// ERROR") >= 0) return false;
if (testCode.indexOf("- ERROR") >= 0) return false;
if (testCode.indexOf("// XFAIL") >= 0) return false;
if (testCode.indexOf("{ xfail") >= 0) return false;
if (testCode.indexOf("{ dg-preprocess") >= 0) return false;
return true;
}
public void doFile() throws Throwable {
assertNotNull (fileList);
File file = (File)fileList.removeFirst();
FileInputStream stream = new FileInputStream(file);
String filePath = file.getCanonicalPath();
String nature = (String)natures.get(filePath);
StringWriter code = new StringWriter();
byte b[] = new byte[stepSize];
int n = stream.read(b);
while( n != -1 ){
code.write(new String(b));
n = stream.read(b);
}
String testCode = code.toString();
if (isExpectedToPass(testCode)) {
ParseThread thread = new ParseThread();
thread.quickParse = quickParse;
thread.code = testCode;
thread.cppNature = nature.equalsIgnoreCase("cpp");
thread.file = filePath;
thread.start();
thread.join(timeOut);
if (thread.isAlive()) {
thread.stop();
reportHang(testCode, filePath);
} else if (thread.result != null) {
reportException(thread.result, filePath, thread.parser);
}
} else {
// gcc probably didn't expect this test to pass.
// It doesn't mean that it should pass CDT parser,
// as it is more relaxed
// Result - 'inconclusive', but we report 'pass'
assertTrue(true);
}
}
static class ParseThread extends Thread {
public String code;
public boolean cppNature;
public String file;
public Throwable result = null;
public IParser parser = null;
public boolean quickParse = true;
public void run(){
try {
DOMBuilder domBuilder = new DOMBuilder();
parser = new Parser(code.toString(), domBuilder, quickParse);
parser.setCppNature(cppNature);
parser.mapLineNumbers(true);
assertTrue(parser.parse());
}
catch( Throwable e )
{
result = e;
}
}
}
}

View file

@ -0,0 +1,138 @@
package org.eclipse.cdt.core.parser.tests;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* This class implements a utility that will walk through an object
* and it's children and create an XML file for it.
*/
public class XMLDumper {
public static class Test {
private String msg = "hi";
public String getMsg() {
return msg;
}
public Test self = this;
}
public static void main(String [] args) {
Test test = new Test();
XMLDumper dumper = new XMLDumper(test);
Document document = dumper.getDocument();
OutputFormat format = new OutputFormat( document ); //Serialize DOM
StringWriter stringOut = new StringWriter(); //Writer will be a String
XMLSerializer serial = new XMLSerializer( stringOut, format );
try {
serial.asDOMSerializer(); // As a DOM Serializer
serial.serialize( document.getDocumentElement() );
System.out.println( "STRXML = " + stringOut.toString() ); //Spit out DOM as a String
} catch (IOException e) {
System.out.println(e);
}
}
private int id = 0;
private HashMap map = new HashMap();
private Document document = new DocumentImpl();
public Document getDocument() {
return document;
}
public XMLDumper(Object obj) {
document.appendChild(createObject(obj));
}
private Element createObject(Object obj) {
Class cls = obj.getClass();
String clsName = cls.getName();
clsName = clsName.replace('$', '.');
Element element = document.createElement(clsName);
map.put(obj, new Integer(id));
element.setAttribute("id",String.valueOf(id++));
Field [] fields = cls.getDeclaredFields();
for (int i = 0; i < fields.length; ++i) {
Field field = fields[i];
int modifiers = field.getModifiers();
// Skip over static fields
if (Modifier.isStatic(modifiers))
continue;
// Skip fields that start with an underscore
if (field.getName().charAt(0) == '_')
continue;
Object value = null;
String fieldName = field.getName();
if (Modifier.isPublic(modifiers)) {
try {
value = field.get(obj);
} catch (Exception e) {
value = e;
}
} else {
String methodName = "get" +
fieldName.substring(0, 1).toUpperCase() +
fieldName.substring(1);
Method method = null;
try {
method = cls.getMethod(methodName, null);
} catch (NoSuchMethodException e) {
continue;
}
try {
value = method.invoke(obj, null);
} catch (Exception e) {
value = e;
}
}
Element fieldElement = document.createElement(fieldName);
element.appendChild(fieldElement);
if (value == null)
return element;
Class type = field.getType();
if (String.class.isAssignableFrom(type))
fieldElement.appendChild(document.createTextNode((String)value));
else if (Integer.class.isAssignableFrom(type))
fieldElement.appendChild(document.createTextNode(((Integer)value).toString()));
else if (Exception.class.isAssignableFrom(type))
fieldElement.appendChild(document.createTextNode(value.toString()));
else {
Object v = map.get(value);
if (v != null)
fieldElement.setAttribute("refid", v.toString());
else
fieldElement.appendChild(createObject(value));
}
}
return element;
}
}

View file

@ -0,0 +1,128 @@
<?xml version="1.0" encoding="UTF-8"?>
<plugin
id="org.eclipse.cdt.core.tests"
name="org.eclipse.cdt.core.tests"
version="1.2.0.5"
class="org.eclipse.cdt.testplugin.CTestPlugin">
<runtime>
<library name="cdtcoretests.jar">
<export name="*"/>
</library>
</runtime>
<requires>
<import plugin="org.apache.xerces"/>
<import plugin="org.eclipse.core.resources"/>
<import plugin="org.eclipse.core.runtime"/>
<import plugin="org.eclipse.cdt.core"/>
<import plugin="org.eclipse.cdt.ui"/>
<import plugin="org.eclipse.swt"/>
<import plugin="org.eclipse.ui"/>
<import plugin="org.junit"/>
</requires>
<extension
id="buildTest"
name="Tools for Build Test"
point="org.eclipse.cdt.core.ManagedBuildInfo">
<target
isTest="true"
name="Test Root"
defaultExtension="toor"
isAbstract="false"
id="test.root">
<tool
sources="foo,bar"
name="Root Tool"
outputs="toor"
command="doIt"
id="root.tool">
<optionCategory
owner="root.tool"
name="Category"
id="category">
</optionCategory>
<option
name="List Option in Top"
command="-L"
valueType="stringList"
id="list.option">
<optionValue
value="a">
</optionValue>
<optionValue
value="b">
</optionValue>
</option>
<option
defaultValue="false"
name="Boolean Option in Top"
command="-b"
valueType="boolean"
id="boolean.option">
</option>
<option
defaultValue="x"
name="String Option in Category"
category="category"
valueType="string"
id="string.option">
</option>
<option
name="Enumerated Option in Category"
category="category"
valueType="enumerated"
id="enumerated.option">
<optionEnum
name="Default Enum"
isDefault="true"
command="-e1"
id="default.enum.option">
</optionEnum>
<optionEnum
name="Another Enum"
command="-e2"
id="another.enum.option">
</optionEnum>
</option>
</tool>
<configuration
name="Root Config"
id="root.config">
</configuration>
<configuration
name="Root Override Config"
id="root.override.config">
<toolRef
id="root.tool">
<optionRef
defaultValue="y"
id="string.option">
</optionRef>
<optionRef
defaultValue="true"
id="boolean.option">
</optionRef>
</toolRef>
</configuration>
</target>
<target
isTest="true"
name="Test Sub"
parent="test.root"
defaultExtension="bus"
isAbstract="false"
id="test.sub">
<configuration
name="Sub Config"
id="sub.config">
</configuration>
<tool
name="Sub Tool"
id="tool.sub">
</tool>
</target>
</extension>
</plugin>

View file

@ -0,0 +1,138 @@
// include
#include <stdio.h>
// macro
#define PRINT(string,msg) printf(string, msg)
//namespace
namespace MyPackage
{
// check class
// class
class Hello
{
// protected visibility
protected:
// field
int x;
// method
inline void setX(int X)
{
x = X;
};
// check nested pachage
// nested namespace
namespace MyNestedPackage {
// check parent nested class
// nested class
class Y
{ // public visibility
public:
// constructor
Y();
// virtual destructor
virtual ~Y();
};
// check derived nested class
// derived class
class X : public Y {
// private visibility
private:
// private field
B b;
public:
// constructor chain
X(int x) : yy(x) {
cout << "In consturctor\n";
}
// method declaration
int doNothing();
};
}
};
// check enums
// enum without name
enum {
first,
second,
third
}
;
// enum with name
enum MyEnum {
f,
s,
t };
// check variables
// variable
int v;
// unsigned long variable
unsigned long vuLong;
// unsigned short variable
unsigned short vuShort;
// check variable declarations
// variable declaration
extern int evar;
// function pointer
static void * (*orig_malloc_hook)(const char *file, int line, size_t size);
// check functions
// simple function declaration
void foo();
// function declaration with parameters
char* foo(int& x,
char**y);
// simple function definition
void boo(){
int g = 0;
};
// check Structs
// struct
struct MyStruct{
int sint;
};
// typedef and elaborated types
typedef struct MyStruct myStruct;
// typedef
typedef struct{
int ss;
} myTypedef;
// unions
union U{
int U1;
};
// check templates
// template function
template<class A, typename B=C>
A aTemplatedFunction( B bInstance );
// template method
class enclosing {
// public visibility
public:
template<class A, typename B=C>
A aTemplatedMethod( B bInstance );
};
// template class
template<class T, typename Tibor = junk>
class myarray { /* */ };
// template struct
template<class T, typename Tibor = junk>
struct mystruct { /* */ };
// template variable
template <bool __threads, int __inst>
char* default_alloc_template<__threads, __inst>::_S_start_free = 0;
};
// check arrays
// arrays
int myArray [5][];
int main(int argc, char * argv[])
{
}

View file

@ -0,0 +1,68 @@
/*
* (c) Copyright QNX Software Systems Ltd. 2002.
* All Rights Reserved.
*/
/********
* This is a sample C file that will be used in testing the TranslationUnit
* class. It has a specific structure that will be looked for within the
* test case.
* This file is only ment to contain various C elements, and may not compile
* into a running application (but should be valid C)
*/
#include <stdio.h>
#include <unistd.h>
/* A function prototype */
int func2p(void);
/* A global variable */
int globalvar;
/* A enumeration */
enum myenum {ENUM_A=1, ENUM_B=2, ENUM_C=3, ENUM_D=4};
/* A structure. This also includes a typedef around the strcture def
* which at the time of writing was not picked up.
*/
typedef struct mystruct {
int a;
char b;
long c;
} mystruct_t;
/* A union */
union myunion {
int x;
char y;
long z;
};
/* A typedef */
typedef struct mystruct mytype;
/* A couple functions */
void * func1(void)
{
return(NULL);
}
int func2(void)
{
return(0);
}
int main(int argc, char ** argv)
{
int var1;
printf("Hello world\n");
}
void func3()
{
printf("This is not really here\n");
}

View file

@ -0,0 +1,2 @@
#include <stdio.h>

View file

@ -0,0 +1,42 @@
// include
#include <stdio.h>
#include "whatever.h"
#include <src/slash.h>
#include <src\backslash.h>
#include "Program Files/space.h"
#include "../up1dir.h"
#include "./samedir.h"
#include "different_extension1.hpp"
#include "different_extension2.hh"
#include "different_extension3.x"
#include <no_extension>
# include "whitespace_after_hash"
#include "whitespace_before_hash"
// failure cases:
#include garbage
#include "resync_after_bad_parse_1"
#include
#include "resync_after_bad_parse_2"
#include "one" "two" "three"
#include "resync_after_bad_parse_3"
// from the Spec:
// from [C, 6.10.p8]
// should fail
#define EMPTY
EMPTY #include "invalid.h"
// from [C, 6.10.2.p8]:
// should equal #include "myInclude1.h"
#define MYINCFILE "myInclude1.h"
#include MYINCFILE
// from [C, 6.10.3.5.p6]:
// should equal #include "vers2.h"
#define INCFILE(x) vers ## x
#define xstr(x) str(x)
#define str(x) #x
#include xstr(INCFILE(2)).h

View file

@ -0,0 +1,4 @@
// macro
#define SINGLETON
#define NUMBER 1
#define PRINT(string,msg) printf(string, msg)

View file

@ -0,0 +1,88 @@
// IStructure
struct testStruct1 {
char m_field1;
char* m_field2;
unsigned char m_field3;
int m_field4;
unsigned m_field5;
void* m_field6;
void method1();
struct testStruct1 method2( char* in_field2, int in_field4 ) {}
// this is very C++:
testStruct1( char* in_field2, int in_field4 ) {}
~testStruct1() {}
};
struct testStruct2 {
};
struct testStruct3 {
} aTestStruct3;
// no semicolon, parser should recover
struct testStruct4NoSemicolon {
}
// forward declaration
struct testStruct5;
// variable declaration using predefined struct.
struct testStruct6 aTestStruct6;
struct {
int x;
} testAnonymousStructObject1;
struct {
int x;
} testAnonymousStructObject2= {1};
// to resync the parser if necessary
struct testStruct7 {
};
// an inner struct
struct testStruct8 {
struct testStruct9Inner {
int x;
};
struct testStruct10Inner {
int y;
struct testStruct11Inner {
int z;
};
};
};
union testUnion1 {
char m_field1;
char* m_field2;
unsigned char m_field3;
int m_field4;
unsigned m_field5;
void* m_field6;
};
class testClass1 {
};
class testClass2NoSemicolon {
}
class testClass3 {
};
class testClass4Abstract {
void aNonVirtual();
virtual void aVirtual();
virtual void aPureVirtual()=0;
};
class testClass5
: public testClass1, protected testClass3, private testClass4Abstract {
};
// to resync the parser if necessary
class testClass6 {
};

View file

@ -0,0 +1,15 @@
int z;
template<T> class nonVector {
public:
int x;
int y;
T* head;
vector<T>() { head =new T(); }
int length() { return 1; }
T& first() { return *head; }
const T& first() const { return *head; }
};

View file

@ -0,0 +1,8 @@
LIST=VARIANT
ifndef QRECURSE
QRECURSE=recurse.mk
ifdef QCONFIG
QRDIR=$(dir $(QCONFIG))
endif
endif
include $(QRDIR)$(QRECURSE)

View file

@ -0,0 +1,7 @@
ifndef QCONFIG
QCONFIG=qconfig.mk
endif
include $(QCONFIG)
USEFILE=
LIBS+=socket
include $(MKFILES_ROOT)/qtargets.mk

View file

@ -0,0 +1,7 @@
#include <stdio.h>
int main()
{
printf("Hello there\n");
return(0);
}

View file

@ -0,0 +1,8 @@
LIST=VARIANT
ifndef QRECURSE
QRECURSE=recurse.mk
ifdef QCONFIG
QRDIR=$(dir $(QCONFIG))
endif
endif
include $(QRDIR)$(QRECURSE)

View file

@ -0,0 +1 @@
include ../../common.mk

View file

@ -0,0 +1,14 @@
#include <stdio.h>
int func1 (void)
{
printf("This is func1\n");
return(1);
}
char * func2(void)
{
printf("This is func2\n");
return(0);
}

View file

@ -0,0 +1,13 @@
#include <stdio.h>
int test2func1(void)
{
printf("This is a function in the second object\n");
return(1);
}
int test2func2(void)
{
printf("This is another function in the second object\n");
return(2);
}

View file

@ -0,0 +1,8 @@
LIST=VARIANT
ifndef QRECURSE
QRECURSE=recurse.mk
ifdef QCONFIG
QRDIR=$(dir $(QCONFIG))
endif
endif
include $(QRDIR)$(QRECURSE)

View file

@ -0,0 +1 @@
include ../../common.mk

View file

@ -0,0 +1 @@
include ../../common.mk

View file

@ -0,0 +1,8 @@
LIST=VARIANT
ifndef QRECURSE
QRECURSE=recurse.mk
ifdef QCONFIG
QRDIR=$(dir $(QCONFIG))
endif
endif
include $(QRDIR)$(QRECURSE)

View file

@ -0,0 +1,7 @@
ifndef QCONFIG
QCONFIG=qconfig.mk
endif
include $(QCONFIG)
USEFILE=
include $(MKFILES_ROOT)/qtargets.mk

View file

@ -0,0 +1,8 @@
#include <stdio.h>
int bigArray[100];
int x[10]={1,2,3,4,5,6,7,8,9,0};
int main()
{
printf("Hello there\n");
return(0);
}

View file

@ -0,0 +1,8 @@
LIST=VARIANT
ifndef QRECURSE
QRECURSE=recurse.mk
ifdef QCONFIG
QRDIR=$(dir $(QCONFIG))
endif
endif
include $(QRDIR)$(QRECURSE)

View file

@ -0,0 +1 @@
include ../../common.mk

View file

@ -0,0 +1,13 @@
# Format of this property file is:
# outputFile = <path for report>
# source = <path to top of project>, <c or cpp>
# Multiple source properties may be concatenated.
# By default, no outputFile is produced.
# By default, the test will use:
# source = ./defaultC, c
# source = ./defaultCpp, cpp
#outputFile = Z:\\CDT\\reportRTS.txt
#source = Z:/V651/Release/C++/TargetRTS, cpp
#source = D:/temp/test, cpp

View file

@ -0,0 +1,17 @@
# Format of this property file is:
# outputFile = <path for report>
# source = <path to top of project>, <c or cpp>
# Multiple source properties may be concatenated.
# By default, no outputFile is produced.
# By default, the test will use:
# source = ./defaultC, c
# source = ./defaultCpp, cpp
#
# outputFile = Z:\\CDT\\reportFrac.txt
#source = Z:/V651/Release/C++/TargetRTS, cpp
#source = D:/temp/test, cpp
#source = Z:/CDT/test/include, cpp \
# Z:/CDT/test/src, cpp
#source = D:\\ACE+TAO\\ACE_wrappers, cpp
# source = D:\\ACE+TAO\\ACE_wrappers\\ace\\config-psos-diab-mips.h, cpp
# outDir = Z:\\CDT\\temp

View file

@ -0,0 +1,43 @@
#include <Simple.h>
const SimpleStruct simpleStruct =
{
1
, "mySimple"
, 0.1232
};
#define SIZEOF( A, B ) sizeof( A.B )
const OtherStruct array[] =
{
{
#if FOO
"foo"
#else
"bar"
#endif
, SIZEOF( simpleStruct, num )
, &t_int
, 0
}
, {
"name"
, SIZEOF( simpleStruct, floatnum )
, &t_float
, 1
}
};
void SimpleStruct_construct( struct SimpleStruct * const this )
{
this->num = 1;
this->name = "boo";
this->floatNum = 1.5;
}
int ConnectParams_doSomething( const struct SimpleStruct * const this )
{
return 1;
}

View file

@ -0,0 +1,17 @@
#ifndef SIMPLE_H
#define SIMPLE_H
struct SimpleStruct
{
int num;
char name[ ];
float floatNum;
};
void SimpleStruct_construct( struct SimpleStruct * const this );
int SimpleStruct_doSomething( const struct SimpleStruct * const this );
#endif /* SIMPLE_H */

View file

@ -0,0 +1,37 @@
#include <Simple.h>
#include <iostream>
#define NULL (void *)0
SimpleClass::SimpleClass( void )
{
init( NULL );
}
SimpleClass::~SimpleClass( void )
{
}
SimpleClass::SimpleClass( const SimpleClass & arg )
{
//TODO: copy constructor
}
SimpleClass & SimpleClass::operator=( const SimpleClass & arg )
{
if( this != &arg )
{
}
return *this;
}
void SimpleClass::init( void * foo)
{
}
InnerStruct & SimpleClass::getInner( void )
{
return inner;
}

View file

@ -0,0 +1,32 @@
#ifndef SIMPLE_H
#define SIMPLE_H
class OtherClass;
class SimpleClass
{
public:
SimpleClass( void );
SimpleClass( const SimpleClass & arg );
virtual ~SimpleClass( void );
SimpleClass & operator=( const SimpleClass & arg );
private:
struct InnerStruct
{
inline InnerStruct( int a ){ _a = a; }
inline ~InnerStruct( void ){}
unsigned int _a;
};
InnerStruct inner;
void init( void * );
public:
InnerStruct & getInner( void );
};
#endif /* SIMPLE_H */

View file

@ -0,0 +1,43 @@
// inclusion begins and ends on line 2
#include <stdio.h>
// simple macro begins and ends on line 5; ANOTHER on line 6
#define SIMPLE_MACRO simple
#define ANOTHER
// namespace begins on line 7, ends on line 22
namespace MyPackage{
// class specification begins on line 10, ends on line 21
class Hello{
protected:
// simple declaration begins and ends on line 13
int x;
// simple declaration begins and ends on line 15
void setX(int X);
public:
// simple declaration begins on line 18 and ends on line 20
Hello( void ) : x
( 5 ) {
}
};
}
// simple declaration begins on line 25 and ends on line 27
int *
y =
0;
// complex macro begins on line 30 and ends on line 31
#define COMPLEX_MACRO 33 \
+ 44
// template declaration begins on line 34 and ends on line 35
template <class A >
A createA( void );
// enumeration begins on line 38 and ends on line 43
enum {
one, // enumerator begins and ends on line 39
two, // enumerator begins and ends on line 40
three // enumerator begins on line 41, ends on line 42
= 4
};

View file

@ -0,0 +1,31 @@
Usage:
By default, torture testing is disabled. To enable it, create a 'TortureTest.properties' in 'org.eclipse.cdt.ui.tests\parser\org\eclipse\cdt\core\parser\resources'.
If you don't have GCC testsuites, it does nothing. Then go and grab your latest version of GCC testsuites
(for instance, ftp://ftp.fu-berlin.de/unix/gnu/gcc/gcc-3.3/gcc-testsuite-3.3.tar.gz).
Unpack testsuites under
org.eclipse.cdt.core.tests/resources/parser/TortureTest/default
or elsewhere, but then you'll need to create a 'TortureTest.properties'.
That's it, you can run TortureTest in JUnit Plugin mode. Don't run all ui.tests with torture-test enabled, as apparently it is included several times (anyone knows why?)
, and it's A LOT of test cases.
You can copy the rest of the file to create a TortureTest.properties and uncomment out/edit the default values as specified here.
# By default, torture testing is disabled
# Uncomment to enable
#enabled=true
# Default location is org.eclipse.cdt.core.tests/resources/parser/TortureTest/default
#source=/your/gcc/testsuite/installation/directory
# Chunks for reading files
#stepSize=25000
# Timeout for individual cases, ms
# Need a large enough value, as some files are non-trivial
#timeOut=60000
# Quick parse, or not
#quickParse=true

View file

@ -0,0 +1,31 @@
#Usage:
#By default, torture testing is disabled. To enable it, create a 'TortureTest.properties' in 'org.eclipse.cdt.ui.tests\parser\org\eclipse\cdt\core\parser\resources'.
#
#If you don't have GCC testsuites, it does nothing. Then go and grab your latest version of GCC testsuites
#(for instance, ftp://ftp.fu-berlin.de/unix/gnu/gcc/gcc-3.3/gcc-testsuite-3.3.tar.gz).
#Unpack testsuites under
#
# org.eclipse.cdt.core.tests/resources/parser/TortureTest/default
#
#or elsewhere, but then you'll need to create a 'TortureTest.properties'.
#That's it, you can run TortureTest in JUnit Plugin mode. Don't run all ui.tests with torture-test enabled, as apparently it is included several times (anyone knows why?)
#, and it's A LOT of test cases.
#
#You can copy the rest of the file to create a TortureTest.properties and uncomment out/edit the default values as specified here.
#
# By default, torture testing is disabled
# Uncomment to enable
enabled=true
# Default location is org.eclipse.cdt.core.tests/resources/parser/TortureTest/default
#source=/your/gcc/testsuite/installation/directory
# Chunks for reading files
#stepSize=25000
# Timeout for individual cases, ms
# Need a large enough value, as some files are non-trivial
#timeOut=60000
# Quick parse, or not
#quickParse=true

View file

@ -0,0 +1,8 @@
LIST=VARIANT
ifndef QRECURSE
QRECURSE=recurse.mk
ifdef QCONFIG
QRDIR=$(dir $(QCONFIG))
endif
endif
include $(QRDIR)$(QRECURSE)

View file

@ -0,0 +1,6 @@
ifndef QCONFIG
QCONFIG=qconfig.mk
endif
include $(QCONFIG)
include $(MKFILES_ROOT)/qtargets.mk

View file

@ -0,0 +1,14 @@
#include <stdio.h>
int func1 (void)
{
printf("This is func1\n");
return(1);
}
char * func2(void)
{
printf("This is func2\n");
return(0);
}

View file

@ -0,0 +1,13 @@
#include <stdio.h>
int test2func1(void)
{
printf("This is a function in the second object\n");
return(1);
}
int test2func2(void)
{
printf("This is another function in the second object\n");
return(2);
}

View file

@ -0,0 +1,8 @@
LIST=VARIANT
ifndef QRECURSE
QRECURSE=recurse.mk
ifdef QCONFIG
QRDIR=$(dir $(QCONFIG))
endif
endif
include $(QRDIR)$(QRECURSE)

View file

@ -0,0 +1 @@
include ../../common.mk

View file

@ -0,0 +1 @@
include ../../common.mk

View file

@ -0,0 +1,53 @@
/*
* Created on Jun 5, 2003
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package org.eclipse.cdt.core.suite;
import java.io.PrintStream;
import junit.framework.AssertionFailedError;
import junit.framework.Test;
import junit.textui.ResultPrinter;
/**
* @author vhirsl
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class AISResultPrinter extends ResultPrinter {
/**
* @param writer
*/
public AISResultPrinter(PrintStream writer) {
super(writer);
}
/* (non-Javadoc)
* @see junit.framework.TestListener#addFailure(junit.framework.Test, junit.framework.AssertionFailedError)
*/
public void addFailure(Test test, AssertionFailedError t) {
super.addFailure(test, t);
getWriter().print("---> ");
}
/* (non-Javadoc)
* @see junit.framework.TestListener#addError(junit.framework.Test, java.lang.Throwable)
*/
public void addError(Test test, Throwable t) {
super.addError(test, t);
getWriter().print("---> ");
}
/* (non-Javadoc)
* @see junit.framework.TestListener#startTest(junit.framework.Test)
*/
public void startTest(Test test) {
getWriter().print(".");
}
}

View file

@ -0,0 +1,306 @@
/*
* Created on May 16, 2003
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package org.eclipse.cdt.core.suite;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.framework.TestResult;
import junit.framework.TestListener;
import junit.framework.AssertionFailedError;
import junit.textui.TestRunner;
import java.text.DecimalFormat;
import java.util.ArrayList;
import org.eclipse.core.boot.IPlatformRunnable;
import org.eclipse.cdt.core.build.managed.tests.AllBuildTests;
import org.eclipse.cdt.core.model.tests.AllCoreTests;
import org.eclipse.cdt.core.model.tests.BinaryTests;
import org.eclipse.cdt.core.model.tests.ElementDeltaTests;
import org.eclipse.cdt.core.model.tests.WorkingCopyTests;
import org.eclipse.cdt.core.parser.failedTests.*;
import org.eclipse.cdt.core.parser.tests.ParserTestSuite;
import org.eclipse.cdt.core.model.failedTests.*;
/**
* @author vhirsl
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class AutomatedIntegrationSuite extends TestSuite
implements TestListener, IPlatformRunnable {
private TestResult testResult = null;
private String currentTestName;
// success tests
private int numberOfSuccessTests = 0;
private int numberOfFailedSuccessTests = 0;
// failed tests for open bug reports
private int numberOfFailedTests = 0;
private int numberOfFailedFailedTests = 0;
// switching to failed tests
private boolean failedTests = false;
private boolean skipTest = false;
public AutomatedIntegrationSuite() {}
public AutomatedIntegrationSuite(Class theClass, String name) {
super(theClass, name);
}
public AutomatedIntegrationSuite(Class theClass) {
super(theClass);
}
public AutomatedIntegrationSuite(String name) {
super(name);
}
public static Test suite() {
final AutomatedIntegrationSuite suite = new AutomatedIntegrationSuite();
// First test to trigger report generation
suite.addTest(suite.new GenerateReport("startSuccessTests"));
// Add all success tests
suite.addTest(AllBuildTests.suite());
suite.addTest(ParserTestSuite.suite());
suite.addTest(AllCoreTests.suite());
suite.addTest(BinaryTests.suite());
suite.addTest(ElementDeltaTests.suite());
suite.addTest(WorkingCopyTests.suite());
// Last test to trigger report generation
suite.addTest(suite.new GenerateReport("startFailedTests"));
// Add all failed tests
suite.addTestSuite(DOMFailedTest.class);
suite.addTestSuite(LokiFailures.class);
suite.addTestSuite(STLFailedTests.class);
suite.addTestSuite(CModelElementsFailedTests.class);
// Last test to trigger report generation
suite.addTest(suite.new GenerateReport("generateReport"));
return suite;
}
/**
* Runs the tests and collects their result in a TestResult.
* Overloaded method
*/
public void run(TestResult result) {
// To get counts from the result
testResult = result;
// Add oneself as a listener
result.addListener(this);
// Call a base class method
super.run(result);
// Remove a listener
result.removeListener(this);
}
/**
* An error occurred.
*/
public void addError(Test test, Throwable t) {
// System.out.println("Error : " + test);
// System.out.println("\tReason : " + t);
// System.out.println("\tStack trace : ");
// t.printStackTrace(System.out);
}
/**
* A failure occurred.
*/
public void addFailure(Test test, AssertionFailedError t) {
if (failedTests) {
++numberOfFailedFailedTests;
}
else {
++numberOfFailedSuccessTests;
}
// System.out.println("Failure : " + test);
// System.out.println("\tReason : " + t);
// System.out.println("\tStackTrace : ");
// t.printStackTrace(System.out);
}
/**
* A test ended.
*/
public void endTest(Test test) {
if (currentTestName == null) {
System.out.println("Internal error - endTest: currentTestName == null");
}
else {
if (skipTest) {
skipTest = false;
}
else {
if (failedTests) {
++numberOfFailedTests;
// System.out.println(test);
}
else {
++numberOfSuccessTests;
}
System.out.println(test);
}
currentTestName = null;
}
}
/**
* A test started.
*/
public void startTest(Test test) {
if (currentTestName != null) {
System.out.println("Internal error - startTest: currentTestName != null");
}
else {
currentTestName = test.toString();
}
}
/*
* generateReport
*
* @author vhirsl
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
protected void generateReport() {
int numberOfRuns = testResult.runCount();
int numberOfFailures = testResult.failureCount();
int numberOfErrors = testResult.errorCount();
System.out.println();
System.out.println("*** Generating report: ***");
System.out.println();
System.out.println("\tNumber of runs: " + numberOfRuns);
System.out.println("\tNumber of failures: " + numberOfFailures);
System.out.println("\tNumber of errors: " + numberOfErrors);
float successRate = (numberOfRuns-numberOfFailures-numberOfErrors)/(float)numberOfRuns;
DecimalFormat df = new DecimalFormat("##.##%");
System.out.println("Sanity success rate : " + df.format(successRate));
System.out.println("\tNumber of success tests: " + numberOfSuccessTests);
System.out.println("\tNumber of failed tests: " + numberOfFailedTests);
successRate = numberOfSuccessTests/(float)(numberOfSuccessTests+numberOfFailedTests);
System.out.println("Expected success test rate : " + df.format(successRate));
successRate = (numberOfSuccessTests-numberOfFailedSuccessTests)/
(float)(numberOfSuccessTests+numberOfFailedTests-numberOfFailedFailedTests);
System.out.print("Observed success test rate : " + df.format(successRate));
System.out.println(" (failed success tests = " + numberOfFailedSuccessTests + ", failed failed tests = " + numberOfFailedFailedTests + ")");
System.out.println();
}
private void startSuccessTests() {
failedTests = false;
System.out.println();
System.out.println("*** Starting success tests ***");
System.out.println();
}
private void startFailedTests() {
failedTests = true;
System.out.println();
System.out.println("*** Starting failed tests ***");
System.out.println();
}
/*
* Public inner class to invoke generateReport
*
* @author vhirsl
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class GenerateReport extends TestCase {
public GenerateReport(String name) {
super(name);
}
public GenerateReport(){}
public void generateReport() {
// skip this one
AutomatedIntegrationSuite.this.skipTest = true;
// Calls a method of the outer class
AutomatedIntegrationSuite.this.generateReport();
}
public void startSuccessTests() {
// skip this one
AutomatedIntegrationSuite.this.skipTest = true;
// Calls a method of the outer class
AutomatedIntegrationSuite.this.startSuccessTests();
}
public void startFailedTests() {
// skip this one
AutomatedIntegrationSuite.this.skipTest = true;
// Calls a method of the outer class
AutomatedIntegrationSuite.this.startFailedTests();
}
/* (non-Javadoc)
* @see junit.framework.Test#countTestCases()
* We don't want these test cases to be counted
*/
public int countTestCases() {
return 0;
}
}
/* (non-Javadoc)
* @see org.eclipse.core.boot.IPlatformRunnable#run(java.lang.Object)
*/
public Object run(Object args) throws Exception {
// Used when started from as a regression test suite after the build
TestRunner testRunner = new TestRunner(new AISResultPrinter(System.out));
TestResult testResult = testRunner.doRun(suite());
return prepareReport(testResult);
}
protected ArrayList prepareReport(TestResult testResult) {
// TestRunner.run(suite());
ArrayList efMessages = new ArrayList();
int errorCount = testResult.errorCount();
int failureCount = testResult.failureCount();
if (errorCount > 0) {
String em = new String("There ");
em += (errorCount == 1)?"is ":"are ";
em += Integer.toString(errorCount);
em += " error";
em += (errorCount == 1)?"!":"s!";
efMessages.add(em);
}
if (failureCount > 0) {
String fm = new String("There ");
fm += (failureCount == 1)?"is ":"are ";
fm += Integer.toString(failureCount);
fm += " failure";
fm += (failureCount == 1)?"!":"s!";
efMessages.add(fm);
}
if (efMessages.isEmpty()) {
efMessages.add(new String("Regression test run SUCCESSFUL!"));
}
else {
efMessages.add(new String("Please see raw test suite output for details."));
}
return efMessages;
}
}

View file

@ -0,0 +1,30 @@
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.cdt.testplugin;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.LabelProvider;
/**
* Allows to test decorators for Java elements
*/
public class CElementDecorator extends LabelProvider implements ILabelDecorator {
/*
* @see ILabelDecorator#decorateImage(Image, Object)
*/
public Image decorateImage(Image image, Object element) {
return null;
}
/*
* @see ILabelDecorator#decorateText(String, Object)
*/
public String decorateText(String text, Object element) {
return text + "*";
}
}

View file

@ -0,0 +1,244 @@
package org.eclipse.cdt.testplugin;
import java.lang.reflect.InvocationTargetException;
import java.util.zip.ZipFile;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.CProjectNature;
import org.eclipse.cdt.core.model.IArchiveContainer;
import org.eclipse.cdt.core.model.IBinaryContainer;
import org.eclipse.cdt.core.model.ICContainer;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.IArchive;
import org.eclipse.cdt.core.model.IBinary;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.ui.dialogs.IOverwriteQuery;
import org.eclipse.ui.wizards.datatransfer.ImportOperation;
import org.eclipse.ui.wizards.datatransfer.ZipFileStructureProvider;
/**
* Helper methods to set up a ICProject.
*/
public class CProjectHelper {
/**
* Creates a ICProject.
*/
public static ICProject createCProject(String projectName, String binFolderName) throws CoreException {
IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
IProject project= root.getProject(projectName);
if (!project.exists()) {
project.create(null);
} else {
project.refreshLocal(IResource.DEPTH_INFINITE, null);
}
if (!project.isOpen()) {
project.open(null);
}
if (!project.hasNature(CProjectNature.C_NATURE_ID)) {
addNatureToProject(project, CProjectNature.C_NATURE_ID, null);
}
ICProject cproject = CCorePlugin.getDefault().getCoreModel().create(project);
return cproject;
}
/**
* Removes a ICProject.
*/
public static void delete(ICProject cproject) throws CoreException {
cproject.getProject().delete(true, true, null);
}
/**
* Adds a source container to a ICProject.
*/
public static ICContainer addSourceContainer(ICProject cproject, String containerName) throws CoreException {
IProject project= cproject.getProject();
IContainer container= null;
if (containerName == null || containerName.length() == 0) {
container= project;
} else {
IFolder folder= project.getFolder(containerName);
if (!folder.exists()) {
folder.create(false, true, null);
}
container= folder;
}
return (ICContainer)container;
}
/**
* Adds a source container to a ICProject and imports all files contained
* in the given Zip file.
*/
public static ICContainer addSourceContainerWithImport(ICProject cproject, String containerName, ZipFile zipFile) throws InvocationTargetException, CoreException {
ICContainer root= addSourceContainer(cproject, containerName);
importFilesFromZip(zipFile, root.getPath(), null);
return root;
}
/**
* Removes a source folder from a ICProject.
*/
public static void removeSourceContainer(ICProject cproject, String containerName) throws CoreException {
IFolder folder= cproject.getProject().getFolder(containerName);
folder.delete(true, null);
}
/**
* Attempts to find an archive with the given name in the workspace
*/
public static IArchive findArchive(ICProject testProject,String name) {
int x;
IArchive[] myArchives;
IArchiveContainer archCont;
/***
* Since ArchiveContainer.getArchives does not wait until
* all the archives in the project have been parsed before
* returning the list, we have to do a sync ArchiveContainer.getChildren
* first to make sure we find all the archives.
*/
archCont=testProject.getArchiveContainer();
myArchives=archCont.getArchives();
if (myArchives.length<1)
return(null);
for (x=0;x<myArchives.length;x++) {
if (myArchives[x].getElementName().equals(name))
return(myArchives[x]);
}
return(null);
}
/**
* Attempts to find a binary with the given name in the workspace
*/
public static IBinary findBinary(ICProject testProject,String name) {
IBinaryContainer binCont;
int x;
IBinary[] myBinaries;
binCont=testProject.getBinaryContainer();
myBinaries=binCont.getBinaries();
if (myBinaries.length<1)
return(null);
for (x=0;x<myBinaries.length;x++) {
if (myBinaries[x].getElementName().equals(name))
return(myBinaries[x]);
}
return(null);
}
/**
* Attempts to find an object with the given name in the workspace
*/
public static IBinary findObject(ICProject testProject,String name) {
int x;
ICElement[] myElements;
myElements=testProject.getChildren();
if (myElements.length<1)
return(null);
for (x=0;x<myElements.length;x++) {
if (myElements[x].getElementName().equals(name))
if (myElements[x] instanceof ICElement) {
if (myElements[x] instanceof IBinary) {
return((IBinary) myElements[x]);
}
}
}
return(null);
}
/**
* Attempts to find a TranslationUnit with the given name in the workspace
*/
public static ITranslationUnit findTranslationUnit(ICProject testProject,String name) {
int x;
ICElement[] myElements;
myElements=testProject.getChildren();
if (myElements.length<1)
return(null);
for (x=0;x<myElements.length;x++) {
if (myElements[x].getElementName().equals(name))
if (myElements[x] instanceof ICElement) {
if (myElements[x] instanceof ITranslationUnit) {
return((ITranslationUnit) myElements[x]);
}
}
}
return(null);
}
/**
* Attempts to find an element with the given name in the workspace
*/
public static ICElement findElement(ICProject testProject,String name) {
int x;
ICElement[] myElements;
myElements=testProject.getChildren();
if (myElements.length<1)
return(null);
for (x=0;x<myElements.length;x++) {
if (myElements[x].getElementName().equals(name))
if (myElements[x] instanceof ICElement) {
return((ICElement) myElements[x]);
}
}
return(null);
}
private static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException {
IProjectDescription description = proj.getDescription();
String[] prevNatures= description.getNatureIds();
String[] newNatures= new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length]= natureId;
description.setNatureIds(newNatures);
proj.setDescription(description, monitor);
}
private static void importFilesFromZip(ZipFile srcZipFile, IPath destPath, IProgressMonitor monitor) throws InvocationTargetException {
ZipFileStructureProvider structureProvider= new ZipFileStructureProvider(srcZipFile);
try {
ImportOperation op= new ImportOperation(destPath, structureProvider.getRoot(), structureProvider, new ImportOverwriteQuery());
op.run(monitor);
} catch (InterruptedException e) {
// should not happen
}
}
private static class ImportOverwriteQuery implements IOverwriteQuery {
public String queryOverwrite(String file) {
return ALL;
}
}
}

Some files were not shown because too many files have changed in this diff Show more