[526348] Suppress unwanted Ecore test console output
diff --git a/tests/org.eclipse.ocl.ecore.tests/META-INF/MANIFEST.MF b/tests/org.eclipse.ocl.ecore.tests/META-INF/MANIFEST.MF
index f3d8fbc..013d0ee 100644
--- a/tests/org.eclipse.ocl.ecore.tests/META-INF/MANIFEST.MF
+++ b/tests/org.eclipse.ocl.ecore.tests/META-INF/MANIFEST.MF
@@ -2,7 +2,7 @@
Bundle-ManifestVersion: 2
Bundle-Name: %pluginName
Bundle-SymbolicName: org.eclipse.ocl.ecore.tests;singleton:=true
-Bundle-Version: 3.3.400.qualifier
+Bundle-Version: 3.9.0.qualifier
Bundle-ClassPath: .
Bundle-Vendor: %providerName
Bundle-Localization: plugin
diff --git a/tests/org.eclipse.ocl.ecore.tests/pom.xml b/tests/org.eclipse.ocl.ecore.tests/pom.xml
index 693cfcd..08f27bc 100644
--- a/tests/org.eclipse.ocl.ecore.tests/pom.xml
+++ b/tests/org.eclipse.ocl.ecore.tests/pom.xml
@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.eclipse.ocl</groupId>
<artifactId>org.eclipse.ocl.ecore.tests</artifactId>
- <version>3.3.400-SNAPSHOT</version>
+ <version>3.9.0-SNAPSHOT</version>
<packaging>eclipse-test-plugin</packaging>
<parent>
<groupId>org.eclipse.ocl</groupId>
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/helper/tests/ParsingTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/helper/tests/ParsingTest.java
index d8e2b35..5f69ad4 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/helper/tests/ParsingTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/helper/tests/ParsingTest.java
@@ -25,144 +25,144 @@
*/
@SuppressWarnings("nls")
public class ParsingTest
- extends AbstractTestSuite {
-
+extends AbstractTestSuite {
+
public void test_createQuery_125684() {
helper.setContext(fruit);
-
+
try {
// constraint-type expressions (boolean-valued) are OK
OCLExpression<EClassifier> expr = helper.createQuery("color <> Color::black");
-
+
assertNotNull(expr);
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
-
+
try {
// as are non-booleans
OCLExpression<EClassifier> expr = helper.createQuery("color");
-
+
assertNotNull(expr);
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
public void test_createInvariant() {
helper.setContext(fruit);
-
+
try {
Constraint constraint = helper.createInvariant("color <> Color::black");
-
+
assertNotNull(constraint);
assertNotNull(constraint.getSpecification().getBodyExpression());
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
public void test_createInvariant_nonBoolean_125684() {
helper.setContext(fruit);
-
+
try {
helper.createInvariant("color");
-
+
fail("Parse should not have succeeded");
} catch (Exception e) {
// success case
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
}
-
+
public void test_createPrecondition() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
Constraint constraint = helper.createPrecondition(
- "color <> Color::black");
-
+ "color <> Color::black");
+
assertNotNull(constraint);
assertNotNull(constraint.getSpecification().getBodyExpression());
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
public void test_createPostcondition() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
Constraint constraint = helper.createPostcondition(
- "color <> self.color@pre implies self.color = color ");
-
+ "color <> self.color@pre implies self.color = color ");
+
assertNotNull(constraint);
assertNotNull(constraint.getSpecification().getBodyExpression());
constraint = helper.createPostcondition(
"self->asSequence@pre()->notEmpty()");
assertTrue(((OperationCallExp<?,?>)((OperationCallExp<?,?>)constraint.getSpecification().getBodyExpression()).getSource()).isMarkedPre());
-
+
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
public void test_createBodyCondition() {
helper.setOperationContext(fruit, fruit_preferredColor);
-
+
try {
Constraint constraint = helper.createBodyCondition(
- "result = (if true then Color::red else Color::brown endif)");
-
+ "result = (if true then Color::red else Color::brown endif)");
+
assertNotNull(constraint);
assertNotNull(constraint.getSpecification().getBodyExpression());
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the support for data types as context classifiers, rather than
* EClasses. The parser now supports arbitrary EClassifiers.
*/
public void test_dataTypeAsContext() {
helper.setContext(ecore.getEString());
-
+
try {
final String constraint = "self.toUpper() <> self.toLower()";
-
+
assertTrue(check(helper, "anything", constraint));
assertTrue(check(helper, "ANYTHING", constraint));
-
+
assertEquals("ANYTHING",
evaluate(helper, "anything", "self.toUpper()"));
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the support for data types as context classifiers by inference from
* the context object.
*/
public void test_dataTypeAsContext_inferred() {
- EcoreEnvironment env =
- (EcoreEnvironment) EcoreEnvironmentFactory.INSTANCE.createInstanceContext(
- ocl.getEnvironment(), "anything"); // inferred type is EString
-
- helper.setContext(env.getContextClassifier());
-
+ EcoreEnvironment env =
+ (EcoreEnvironment) EcoreEnvironmentFactory.INSTANCE.createInstanceContext(
+ ocl.getEnvironment(), "anything"); // inferred type is EString
+
+ helper.setContext(env.getContextClassifier());
+
try {
final String constraint = "self.toUpper() <> self.toLower()";
-
+
assertTrue(check(helper, "anything", constraint));
assertTrue(check(helper, "ANYTHING", constraint));
-
+
assertEquals("ANYTHING",
evaluate(helper, "anything", "self.toUpper()"));
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
}
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/helper/tests/SyntaxHelpTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/helper/tests/SyntaxHelpTest.java
index 87a0c71..a29bb8d 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/helper/tests/SyntaxHelpTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/helper/tests/SyntaxHelpTest.java
@@ -29,253 +29,253 @@
*/
@SuppressWarnings("nls")
public class SyntaxHelpTest
- extends AbstractTestSuite {
-
+extends AbstractTestSuite {
+
/**
* Basic completion test for metamodel level.
*/
public void testMetaModelCompletionsForOppositePropertyCallExp() {
helper.setContext(apple);
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "self.");
-
+
assertChoice(choices, ChoiceKind.PROPERTY, "droppedUnderTree");
assertChoice(choices, ChoiceKind.PROPERTY, "tree");
-
+
choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "self.tree.");
-
+
assertChoice(choices, ChoiceKind.PROPERTY, "fruits");
helper.setContext(stem);
choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "self.");
assertChoice(choices, ChoiceKind.PROPERTY, "stemOfApple");
}
-
+
/**
* Basic completion test for metamodel level.
*/
public void testMetaModelCompletions() {
helper.setContext(EcorePackage.eINSTANCE.getEClass());
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "self.");
-
+
assertChoice(choices, ChoiceKind.PROPERTY, "eAttributes");
-
+
choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "self.name.");
-
+
assertChoice(choices, ChoiceKind.OPERATION, "toLower");
}
-
+
/**
* Tests completion of enumeration literals in classifier invariant
* constraints.
*/
public void test_completeInvariant_enumLiteral() {
helper.setContext(fruit);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT,
- "color <> Color::");
+ ConstraintKind.INVARIANT,
+ "color <> Color::");
assertNotNull(choices);
-
+
assertChoice(choices, ChoiceKind.ENUMERATION_LITERAL, "red");
assertChoice(choices, ChoiceKind.ENUMERATION_LITERAL, "brown");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests completion of attributes in classifier invariant
* constraints.
*/
public void test_completeInvariant_attribute() {
helper.setContext(fruit);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "self.");
assertNotNull(choices);
-
+
assertChoice(choices, ChoiceKind.PROPERTY, "color");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests completion of references (association ends) in classifier invariant
* constraints.
*/
public void test_completeInvariant_reference() {
helper.setContext(apple);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "self.");
assertNotNull(choices);
-
+
assertChoice(choices, ChoiceKind.PROPERTY, "stem");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests completion of operations in classifier invariant
* constraints.
*/
public void test_completeInvariant_operation() {
helper.setContext(fruit);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "self.");
assertNotNull(choices);
-
+
assertChoice(choices, ChoiceKind.OPERATION, "preferredColor");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests completion of enumeration literals in operation precondition
* constraints.
*/
public void test_completePrecondition_enumLiteral() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.PRECONDITION,
- "color <> Color::");
+ ConstraintKind.PRECONDITION,
+ "color <> Color::");
assertNotNull(choices);
-
+
assertChoice(choices, ChoiceKind.ENUMERATION_LITERAL, "red");
assertChoice(choices, ChoiceKind.ENUMERATION_LITERAL, "brown");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests completion of attributes in operation body conditions.
*/
public void test_completeBodyCondition_attribute() {
helper.setOperationContext(fruit, fruit_preferredColor);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.BODYCONDITION,
- "self.");
+ ConstraintKind.BODYCONDITION,
+ "self.");
assertNotNull(choices);
-
+
assertChoice(choices, ChoiceKind.PROPERTY, "color");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests completion of references (association ends) in operation precondition
* constraints.
*/
public void test_completePrecondition_reference() {
helper.setOperationContext(apple, apple_labelOper);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.PRECONDITION,
- "self.");
+ ConstraintKind.PRECONDITION,
+ "self.");
assertNotNull(choices);
-
+
assertChoice(choices, ChoiceKind.PROPERTY, "stem");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests completion of operations in operation postcondition
* constraints.
*/
public void test_completePostcondition_operation() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.POSTCONDITION,
- "self.");
+ ConstraintKind.POSTCONDITION,
+ "self.");
assertNotNull(choices);
-
+
assertChoice(choices, ChoiceKind.OPERATION, "preferredColor");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests completion of parameters in operation precondition
* constraints.
*/
public void test_completePrecondition_parameter() {
helper.setOperationContext(fruit, apple_labelOper);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.PRECONDITION,
- "text.");
+ ConstraintKind.PRECONDITION,
+ "text.");
assertNotNull(choices);
-
+
assertChoice(choices, ChoiceKind.OPERATION, "toLower");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests completion of the result variable in operation postcondition
* constraints.
*/
public void test_completePostcondition_result() {
helper.setOperationContext(fruit, fruit_preferredColor);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.POSTCONDITION,
- "result.");
+ ConstraintKind.POSTCONDITION,
+ "result.");
assertNotNull(choices);
-
+
assertChoice(choices, ChoiceKind.OPERATION, "oclIsUndefined");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests that allInstances() is only suggested for type expressions.
*/
public void test_allInstances() {
helper.setContext(apple);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "self.");
assertNotNull(choices);
-
+
assertNotChoice(choices, ChoiceKind.OPERATION, "allInstances");
-
+
choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "Apple.");
assertNotNull(choices);
-
+
assertChoice(choices, ChoiceKind.OPERATION, "allInstances");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Obtains all of the choices for the OclAny type and prints them out.
*/
public void test_anyChoices() {
helper.setContext(apple);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "self.oclAsType(OclAny).");
dumpChoices(choices);
@@ -283,13 +283,13 @@
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Obtains all of the choices for a UML class and prints them out.
*/
public void test_eclassChoices() {
helper.setContext(apple);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "self.");
dumpChoices(choices);
@@ -297,13 +297,13 @@
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Obtains all of the choices for a tuple type and prints them out.
*/
public void test_tupleChoices() {
helper.setContext(apple);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT,
"Tuple{s : String = null, a : Apple = null}.");
@@ -312,13 +312,13 @@
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Obtains all of the choices for the OclType type and prints them out.
*/
public void test_typeChoices() {
helper.setContext(apple);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "Apple.");
dumpChoices(choices);
@@ -326,13 +326,13 @@
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Obtains all of the choices for the Integer type and prints them out.
*/
public void test_integerChoices() {
helper.setContext(apple);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "1.");
dumpChoices(choices);
@@ -340,13 +340,13 @@
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Obtains all of the choices for the Real type and prints them out.
*/
public void test_realChoices() {
helper.setContext(apple);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "1.0.");
dumpChoices(choices);
@@ -354,13 +354,13 @@
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Obtains all of the choices for the String type and prints them out.
*/
public void test_stringChoices() {
helper.setContext(apple);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "'foo'.");
dumpChoices(choices);
@@ -368,85 +368,85 @@
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Obtains all of the choices for the Set type and prints them out.
*/
public void test_setChoices() {
helper.setContext(apple);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "Set{self}->");
- assertNotNull(choices);
+ assertNotNull(choices);
dumpChoices(choices);
-
- assertChoice(choices, ChoiceKind.OPERATION, "union");
- assertChoice(choices, ChoiceKind.OPERATION, "forAll");
+
+ assertChoice(choices, ChoiceKind.OPERATION, "union");
+ assertChoice(choices, ChoiceKind.OPERATION, "forAll");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Obtains all of the choices for the OrderedSet type and prints them out.
*/
public void test_orderedSetChoices() {
helper.setContext(apple);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "OrderedSet{self}->");
- assertNotNull(choices);
+ assertNotNull(choices);
dumpChoices(choices);
-
- assertChoice(choices, ChoiceKind.OPERATION, "subOrderedSet");
- assertChoice(choices, ChoiceKind.OPERATION, "forAll");
+
+ assertChoice(choices, ChoiceKind.OPERATION, "subOrderedSet");
+ assertChoice(choices, ChoiceKind.OPERATION, "forAll");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Obtains all of the choices for the Sequence type and prints them out.
*/
public void test_sequenceChoices() {
helper.setContext(apple);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "Sequence{self}->");
- assertNotNull(choices);
- dumpChoices(choices);
-
- assertChoice(choices, ChoiceKind.OPERATION, "subSequence");
- assertChoice(choices, ChoiceKind.OPERATION, "forAll");
+ assertNotNull(choices);
+ dumpChoices(choices);
+
+ assertChoice(choices, ChoiceKind.OPERATION, "subSequence");
+ assertChoice(choices, ChoiceKind.OPERATION, "forAll");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Obtains all of the choices for the Bag type and prints them out.
*/
public void test_bagChoices() {
helper.setContext(apple);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "Bag{self}->");
- assertNotNull(choices);
- dumpChoices(choices);
-
- assertChoice(choices, ChoiceKind.OPERATION, "intersection");
- assertChoice(choices, ChoiceKind.OPERATION, "forAll");
+ assertNotNull(choices);
+ dumpChoices(choices);
+
+ assertChoice(choices, ChoiceKind.OPERATION, "intersection");
+ assertChoice(choices, ChoiceKind.OPERATION, "forAll");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Obtains all of the choices for a nested collection type and prints them out.
*/
public void test_nestedCollectionChoices() {
helper.setContext(apple);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(ConstraintKind.INVARIANT, "Set{Sequence{self}}->");
dumpChoices(choices);
@@ -454,7 +454,7 @@
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Obtains all of the choices for a state expression and prints them out.
*/
@@ -464,22 +464,22 @@
helper = ocl.createOCLHelper();
helper.setContext(apple);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "self.oclIsInState(");
+ ConstraintKind.INVARIANT, "self.oclIsInState(");
dumpChoices(choices);
-
- System.out.println("----");
-
+
+ debugPrintln("----");
+
choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "self.oclIsInState(Bad::");
+ ConstraintKind.INVARIANT, "self.oclIsInState(Bad::");
dumpChoices(choices);
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Obtains all of the choices for a message expression and prints them out.
*/
@@ -490,152 +490,152 @@
helper = ocl.createOCLHelper();
helper.setOperationContext(apple, fruit_ripen);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.POSTCONDITION, "self^^");
+ ConstraintKind.POSTCONDITION, "self^^");
dumpChoices(choices);
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
- public void test_completeOperationCallFollowedByArrow() {
- helper.setContext(apple);
-
- try {
- List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "true and false implies preferredLabel(label)->");
-
- // iterators and collection operations
- assertChoice(choices, ChoiceKind.OPERATION, "forAll");
- assertChoice(choices, ChoiceKind.OPERATION, "size");
-
- // not features of Apple
- assertNotChoice(choices, ChoiceKind.PROPERTY, "label");
- assertNotChoice(choices, ChoiceKind.OPERATION, "preferredLabel");
- } catch (Exception e) {
- fail("Parse failed: " + e.getLocalizedMessage());
- }
- }
-
- public void test_completeAfterOpeningParenthesis() {
- helper.setContext(apple);
-
- try {
- List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "preferredLabel((label).");
-
- // features of String
- assertChoice(choices, ChoiceKind.OPERATION, "concat");
- assertChoice(choices, ChoiceKind.OPERATION, "toUpper");
-
- // not features of Apple
- assertNotChoice(choices, ChoiceKind.PROPERTY, "label");
- assertNotChoice(choices, ChoiceKind.OPERATION, "preferredLabel");
-
- // try unmatched brace
- choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "Set{label.");
-
- // features of String
- assertChoice(choices, ChoiceKind.OPERATION, "concat");
- assertChoice(choices, ChoiceKind.OPERATION, "toUpper");
-
- // not features of Apple
- assertNotChoice(choices, ChoiceKind.PROPERTY, "label");
- assertNotChoice(choices, ChoiceKind.OPERATION, "preferredLabel");
-
- // a little more complex
- choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "preferredLabel(Set{label}->");
-
- // iterators and collection operations
- assertChoice(choices, ChoiceKind.OPERATION, "union");
- assertChoice(choices, ChoiceKind.OPERATION, "size");
-
- // not features of String
- assertNotChoice(choices, ChoiceKind.PROPERTY, "concat");
-
- // not features of Apple
- assertNotChoice(choices, ChoiceKind.PROPERTY, "label");
- assertNotChoice(choices, ChoiceKind.OPERATION, "preferredLabel");
- } catch (Exception e) {
- fail("Parse failed: " + e.getLocalizedMessage());
- }
- }
-
- public void test_completeAfterInfixOperation() {
- helper.setContext(apple);
-
- try {
- List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "true and 3 * label.");
-
- // String operations
- assertChoice(choices, ChoiceKind.OPERATION, "concat");
- assertChoice(choices, ChoiceKind.OPERATION, "size");
-
- // not numeric operations
- assertNotChoice(choices, ChoiceKind.PROPERTY, "abs");
-
- // not features of Apple
- assertNotChoice(choices, ChoiceKind.PROPERTY, "label");
- assertNotChoice(choices, ChoiceKind.OPERATION, "preferredLabel");
- } catch (Exception e) {
- fail("Parse failed: " + e.getLocalizedMessage());
- }
- }
-
- public void test_completeAfterThen() {
- helper.setContext(apple);
-
- try {
- // note that 'foo' isn't even valid; it is irrelevant
- List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "if foo then label.");
-
- // String operations
- assertChoice(choices, ChoiceKind.OPERATION, "concat");
- assertChoice(choices, ChoiceKind.OPERATION, "size");
-
- // not features of Apple
- assertNotChoice(choices, ChoiceKind.PROPERTY, "label");
- assertNotChoice(choices, ChoiceKind.OPERATION, "preferredLabel");
- } catch (Exception e) {
- fail("Parse failed: " + e.getLocalizedMessage());
- }
- }
-
- public void test_parentheseEscapeLeftBoundaries() {
- helper.setContext(apple);
-
- try {
- // note that 'and' isn't even valid here; it is irrelevant
- List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "and (if true then (label) else '' endif).");
-
- // String operations
- assertChoice(choices, ChoiceKind.OPERATION, "concat");
- assertChoice(choices, ChoiceKind.OPERATION, "size");
-
- // not features of Apple
- assertNotChoice(choices, ChoiceKind.PROPERTY, "label");
- assertNotChoice(choices, ChoiceKind.OPERATION, "preferredLabel");
- } catch (Exception e) {
- fail("Parse failed: " + e.getLocalizedMessage());
- }
- }
-
+
+ public void test_completeOperationCallFollowedByArrow() {
+ helper.setContext(apple);
+
+ try {
+ List<Choice> choices = helper.getSyntaxHelp(
+ ConstraintKind.INVARIANT, "true and false implies preferredLabel(label)->");
+
+ // iterators and collection operations
+ assertChoice(choices, ChoiceKind.OPERATION, "forAll");
+ assertChoice(choices, ChoiceKind.OPERATION, "size");
+
+ // not features of Apple
+ assertNotChoice(choices, ChoiceKind.PROPERTY, "label");
+ assertNotChoice(choices, ChoiceKind.OPERATION, "preferredLabel");
+ } catch (Exception e) {
+ fail("Parse failed: " + e.getLocalizedMessage());
+ }
+ }
+
+ public void test_completeAfterOpeningParenthesis() {
+ helper.setContext(apple);
+
+ try {
+ List<Choice> choices = helper.getSyntaxHelp(
+ ConstraintKind.INVARIANT, "preferredLabel((label).");
+
+ // features of String
+ assertChoice(choices, ChoiceKind.OPERATION, "concat");
+ assertChoice(choices, ChoiceKind.OPERATION, "toUpper");
+
+ // not features of Apple
+ assertNotChoice(choices, ChoiceKind.PROPERTY, "label");
+ assertNotChoice(choices, ChoiceKind.OPERATION, "preferredLabel");
+
+ // try unmatched brace
+ choices = helper.getSyntaxHelp(
+ ConstraintKind.INVARIANT, "Set{label.");
+
+ // features of String
+ assertChoice(choices, ChoiceKind.OPERATION, "concat");
+ assertChoice(choices, ChoiceKind.OPERATION, "toUpper");
+
+ // not features of Apple
+ assertNotChoice(choices, ChoiceKind.PROPERTY, "label");
+ assertNotChoice(choices, ChoiceKind.OPERATION, "preferredLabel");
+
+ // a little more complex
+ choices = helper.getSyntaxHelp(
+ ConstraintKind.INVARIANT, "preferredLabel(Set{label}->");
+
+ // iterators and collection operations
+ assertChoice(choices, ChoiceKind.OPERATION, "union");
+ assertChoice(choices, ChoiceKind.OPERATION, "size");
+
+ // not features of String
+ assertNotChoice(choices, ChoiceKind.PROPERTY, "concat");
+
+ // not features of Apple
+ assertNotChoice(choices, ChoiceKind.PROPERTY, "label");
+ assertNotChoice(choices, ChoiceKind.OPERATION, "preferredLabel");
+ } catch (Exception e) {
+ fail("Parse failed: " + e.getLocalizedMessage());
+ }
+ }
+
+ public void test_completeAfterInfixOperation() {
+ helper.setContext(apple);
+
+ try {
+ List<Choice> choices = helper.getSyntaxHelp(
+ ConstraintKind.INVARIANT, "true and 3 * label.");
+
+ // String operations
+ assertChoice(choices, ChoiceKind.OPERATION, "concat");
+ assertChoice(choices, ChoiceKind.OPERATION, "size");
+
+ // not numeric operations
+ assertNotChoice(choices, ChoiceKind.PROPERTY, "abs");
+
+ // not features of Apple
+ assertNotChoice(choices, ChoiceKind.PROPERTY, "label");
+ assertNotChoice(choices, ChoiceKind.OPERATION, "preferredLabel");
+ } catch (Exception e) {
+ fail("Parse failed: " + e.getLocalizedMessage());
+ }
+ }
+
+ public void test_completeAfterThen() {
+ helper.setContext(apple);
+
+ try {
+ // note that 'foo' isn't even valid; it is irrelevant
+ List<Choice> choices = helper.getSyntaxHelp(
+ ConstraintKind.INVARIANT, "if foo then label.");
+
+ // String operations
+ assertChoice(choices, ChoiceKind.OPERATION, "concat");
+ assertChoice(choices, ChoiceKind.OPERATION, "size");
+
+ // not features of Apple
+ assertNotChoice(choices, ChoiceKind.PROPERTY, "label");
+ assertNotChoice(choices, ChoiceKind.OPERATION, "preferredLabel");
+ } catch (Exception e) {
+ fail("Parse failed: " + e.getLocalizedMessage());
+ }
+ }
+
+ public void test_parentheseEscapeLeftBoundaries() {
+ helper.setContext(apple);
+
+ try {
+ // note that 'and' isn't even valid here; it is irrelevant
+ List<Choice> choices = helper.getSyntaxHelp(
+ ConstraintKind.INVARIANT, "and (if true then (label) else '' endif).");
+
+ // String operations
+ assertChoice(choices, ChoiceKind.OPERATION, "concat");
+ assertChoice(choices, ChoiceKind.OPERATION, "size");
+
+ // not features of Apple
+ assertNotChoice(choices, ChoiceKind.PROPERTY, "label");
+ assertNotChoice(choices, ChoiceKind.OPERATION, "preferredLabel");
+ } catch (Exception e) {
+ fail("Parse failed: " + e.getLocalizedMessage());
+ }
+ }
+
//
// Test framework
//
-
+
private void dumpChoices(Collection<Choice> choices) {
assertNotNull(choices);
-
+
for (Choice next : choices) {
- System.out.println(" " + next);
+ debugPrintln(" " + next);
}
}
}
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/AssociationTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/AssociationTest.java
index edcb7ea..5361025 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/AssociationTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/AssociationTest.java
@@ -14,8 +14,6 @@
import java.util.Collections;
import java.util.List;
-import junit.framework.AssertionFailedError;
-
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
@@ -48,6 +46,8 @@
import org.eclipse.ocl.helper.ConstraintKind;
import org.eclipse.ocl.utilities.UMLReflection;
+import junit.framework.AssertionFailedError;
+
/**
* Tests for association navigation.
@@ -56,19 +56,19 @@
*/
@SuppressWarnings("nls")
public class AssociationTest
- extends AbstractTestSuite {
+extends AbstractTestSuite {
EReference stem_apple;
EReference stem_tree;
- EAttribute stem_thickness;
- EReference apple_tree;
-// EClass tree;
- EReference tree_apples;
+ EAttribute stem_thickness;
+ EReference apple_tree;
+ // EClass tree;
+ EReference tree_apples;
EClass forest;
- EReference forest_trees;
+ EReference forest_trees;
EStructuralFeature q1;
EStructuralFeature q2;
-
+
/**
* Tests support for association end qualifiers.
*/
@@ -76,57 +76,57 @@
// allowed to specify no qualifiers
parse(
"package ocltest context Forest " +
- "inv: self.trees->forAll(t : Tree | not t.apples->isEmpty())" +
- " endpackage");
-
+ "inv: self.trees->forAll(t : Tree | not t.apples->isEmpty())" +
+ " endpackage");
+
// allowed to specify both qualifiers
parse(
"package ocltest context Forest " +
- "inv: not self.trees['foo', 3].apples->isEmpty()" +
- " endpackage");
-
+ "inv: not self.trees['foo', 3].apples->isEmpty()" +
+ " endpackage");
+
AssertionFailedError err = null;
-
+
try {
// must specify both qualifiers or none
parse(
"package ocltest context Forest " +
- "inv: not self.trees['foo'].apples->isEmpty()" +
- " endpackage");
+ "inv: not self.trees['foo'].apples->isEmpty()" +
+ " endpackage");
} catch (AssertionFailedError e) {
// this is expected (success case)
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
assertNotNull("Parse should have failed", err);
-
+
try {
// qualifiers must conform
parse(
"package ocltest context Forest " +
- "inv: not self.trees[3, 'foo'].apples->isEmpty()" +
- " endpackage");
+ "inv: not self.trees[3, 'foo'].apples->isEmpty()" +
+ " endpackage");
} catch (AssertionFailedError e) {
// this is expected (success case)
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
assertNotNull("Parse should have failed", err);
-
+
try {
// too many qualifiers
parse(
"package ocltest context Forest " +
- "inv: not self.trees['foo', 3, 'bar'].apples->isEmpty()" +
- " endpackage");
+ "inv: not self.trees['foo', 3, 'bar'].apples->isEmpty()" +
+ " endpackage");
} catch (AssertionFailedError e) {
// this is expected (success case)
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
assertNotNull("Parse should have failed", err);
}
-
+
/**
* Tests support for association class navigation.
*/
@@ -134,16 +134,16 @@
// navigate the association end as usual
parse(
"package ocltest context Tree " +
- "inv: self.apples->forAll(a : Apple | a.color <> Color::black)" +
- " endpackage");
-
+ "inv: self.apples->forAll(a : Apple | a.color <> Color::black)" +
+ " endpackage");
+
// navigate to the association class, itself
parse(
"package ocltest context Tree " +
- "inv: self.stem->forAll(s : Stem | s.thickness > 0)" +
- " endpackage");
+ "inv: self.stem->forAll(s : Stem | s.thickness > 0)" +
+ " endpackage");
}
-
+
/**
* Tests support for association class navigation qualifiers.
*/
@@ -151,51 +151,51 @@
// navigate to the association class using the optional qualifier
parse(
"package ocltest context Tree " +
- "inv: self.stem[apples]->forAll(s : Stem | s.thickness > 0)" +
- " endpackage");
-
+ "inv: self.stem[apples]->forAll(s : Stem | s.thickness > 0)" +
+ " endpackage");
+
AssertionFailedError err = null;
-
+
try {
// cannot use role name "tree" as a qualifier
parse(
"package ocltest context Tree " +
- "inv: self.stem[tree]->forAll(s : Stem | s.thickness > 0)" +
- " endpackage");
+ "inv: self.stem[tree]->forAll(s : Stem | s.thickness > 0)" +
+ " endpackage");
} catch (AssertionFailedError e) {
// this is expected (success case)
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
assertNotNull("Parse should have failed", err);
-
+
try {
// cannot use other expressions as qualifiers
parse(
"package ocltest context Tree " +
- "inv: self.stem[3]->forAll(s : Stem | s.thickness > 0)" +
- " endpackage");
+ "inv: self.stem[3]->forAll(s : Stem | s.thickness > 0)" +
+ " endpackage");
} catch (AssertionFailedError e) {
// this is expected (success case)
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
assertNotNull("Parse should have failed", err);
-
+
try {
// only one qualifier is allowed
parse(
"package ocltest context Tree " +
- "inv: self.stem[apples, apples]->forAll(s : Stem | s.thickness > 0)" +
- " endpackage");
+ "inv: self.stem[apples, apples]->forAll(s : Stem | s.thickness > 0)" +
+ " endpackage");
} catch (AssertionFailedError e) {
// this is expected (success case)
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
assertNotNull("Parse should have failed", err);
}
-
+
/**
* Tests support for association class navigation in the case of a
* reflexive association.
@@ -205,69 +205,69 @@
EClass ac = EcoreFactory.eINSTANCE.createEClass();
ac.setName("AC");
fruitPackage.getEClassifiers().add(ac);
-
+
EAttribute x = EcoreFactory.eINSTANCE.createEAttribute();
x.setName("x");
x.setEType(EcorePackage.eINSTANCE.getEInt());
ac.getEStructuralFeatures().add(x);
-
+
EReference parent = EcoreFactory.eINSTANCE.createEReference();
parent.setName("parent");
parent.setEType(tree);
tree.getEStructuralFeatures().add(parent);
-
+
EReference children = EcoreFactory.eINSTANCE.createEReference();
children.setName("children");
children.setEType(tree);
children.setUpperBound(-1);
tree.getEStructuralFeatures().add(children);
-
+
EReference parentTree = EcoreFactory.eINSTANCE.createEReference();
parentTree.setName("parentTree");
parentTree.setEType(tree);
parentTree.setEOpposite(parent);
ac.getEStructuralFeatures().add(parentTree);
-
+
EReference childTree = EcoreFactory.eINSTANCE.createEReference();
childTree.setName("childTree");
childTree.setEType(tree);
childTree.setEOpposite(children);
ac.getEStructuralFeatures().add(childTree);
-
+
// navigate the association end as usual
parse(
"package ocltest context Tree " +
- "inv: self.children->forAll(t : Tree | not t.apples->isEmpty())" +
- " endpackage");
-
+ "inv: self.children->forAll(t : Tree | not t.apples->isEmpty())" +
+ " endpackage");
+
// navigate to the association class, itself, using the role qualifier
parse(
"package ocltest context Tree " +
- "inv: self.aC[children]->forAll(ac : AC | ac.x > 0)" +
- " endpackage");
-
+ "inv: self.aC[children]->forAll(ac : AC | ac.x > 0)" +
+ " endpackage");
+
// this direction is a scalar reference
parse(
"package ocltest context Tree " +
- "inv: self.aC[parent].x > 0" +
- " endpackage");
-
+ "inv: self.aC[parent].x > 0" +
+ " endpackage");
+
AssertionFailedError err = null;
-
+
try {
// ambiguous navigation to association class
parse(
"package ocltest context Tree " +
- "inv: self.aC->forAll(ac : AC | ac.x > 0)" +
- " endpackage");
+ "inv: self.aC->forAll(ac : AC | ac.x > 0)" +
+ " endpackage");
} catch (AssertionFailedError e) {
// this is expected (success case)
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
assertNotNull("Parse should have failed", err);
}
-
+
/**
* Tests support for navigation from association class to its ends.
*/
@@ -276,36 +276,36 @@
// definition
parse(
"package ocltest context Stem " +
- "inv: self.apple.color <> Color::black" +
- " endpackage");
-
+ "inv: self.apple.color <> Color::black" +
+ " endpackage");
+
// this end, too, is 1..1
parse(
"package ocltest context Stem " +
- "inv: self.tree.apples->forAll(a : Apple | a.color <> Color::black)" +
- " endpackage");
-
+ "inv: self.tree.apples->forAll(a : Apple | a.color <> Color::black)" +
+ " endpackage");
+
// I have my own attributes, too
parse(
"package ocltest context Stem " +
- "inv: self.thickness > 0" +
- " endpackage");
+ "inv: self.thickness > 0" +
+ " endpackage");
}
-
+
/**
* Tests that content-assist suggests association class navigation.
*/
public void test_associationClass_contextAssist_RATLC00538077() {
helper.setContext(tree);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "self.");
+ ConstraintKind.INVARIANT, "self.");
assertNotNull(choices);
-
+
// regular reference feature
assertChoice(choices, ChoiceKind.PROPERTY, "apples");
-
+
// association class navigation
assertChoice(choices, ChoiceKind.ASSOCIATION_CLASS, "stem");
} catch (Exception e) {
@@ -319,14 +319,14 @@
*/
public void test_propertyPositions_associationClassEndCall() {
final String exprString =
- "self.apples->notEmpty()";
+ "self.apples->notEmpty()";
OCLExpression<EClassifier> constraint = createQuery(tree, exprString);
-
+
OperationCallExp<EClassifier, EOperation> notEmptyExp = LocationInformationTest.asOperationCall(
constraint);
FeatureCallExp<EClassifier> mpcExp = LocationInformationTest.asFeatureCall(
notEmptyExp.getSource());
-
+
LocationInformationTest.assertPropertyLocation(mpcExp,
exprString.indexOf("apples"),
exprString.indexOf("->"));
@@ -338,15 +338,15 @@
*/
public void test_propertyPositions_associationClassCall() {
final String exprString =
- "self.stem[apples]->notEmpty()";
+ "self.stem[apples]->notEmpty()";
OCLExpression<EClassifier> constraint = createQuery(tree, exprString);
-
+
OperationCallExp<EClassifier, EOperation> notEmptyExp = LocationInformationTest.asOperationCall(
constraint);
-
+
FeatureCallExp<EClassifier> mpcExp = LocationInformationTest.asFeatureCall(
- notEmptyExp.getSource());
-
+ notEmptyExp.getSource());
+
LocationInformationTest.assertPropertyLocation(mpcExp,
exprString.indexOf("stem"),
exprString.indexOf("["));
@@ -359,19 +359,19 @@
*/
public void test_propertyPositions_associationClassCall_implicitCollect() {
final String exprString =
- "Tree.allInstances().stem[apples]->notEmpty()";
+ "Tree.allInstances().stem[apples]->notEmpty()";
OCLExpression<EClassifier> constraint = createQuery(tree, exprString);
-
+
OperationCallExp<EClassifier, EOperation> notEmptyExp = LocationInformationTest.asOperationCall(
constraint);
-
+
// the OCL is implicitly ->collect(stem[apples])->notEmpty()
LoopExp<EClassifier, EParameter> loopExp = LocationInformationTest.asLoop(
notEmptyExp.getSource());
-
+
FeatureCallExp<EClassifier> mpcExp = LocationInformationTest.asFeatureCall(
loopExp.getBody());
-
+
LocationInformationTest.assertPropertyLocation(mpcExp,
exprString.indexOf("stem"),
exprString.indexOf("["));
@@ -383,20 +383,20 @@
*/
public void test_propertyPositions_associationClassQualified() {
final String exprString =
- "self.stem[apples]->notEmpty()";
+ "self.stem[apples]->notEmpty()";
OCLExpression<EClassifier> constraint = createQuery(tree, exprString);
-
+
OperationCallExp<EClassifier, EOperation> notEmptyExp = LocationInformationTest.asOperationCall(
constraint);
-
+
AssociationClassCallExp<EClassifier, EStructuralFeature> accExp = LocationInformationTest.asAssociationClassCall(
- notEmptyExp.getSource());
-
+ notEmptyExp.getSource());
+
List<OCLExpression<EClassifier>> qualifiers = accExp.getQualifier();
assertEquals(1, qualifiers.size());
-
+
OCLExpression<EClassifier> qualifier = qualifiers.get(0);
-
+
LocationInformationTest.assertLocation(qualifier,
exprString.indexOf("apples"),
exprString.indexOf("]->"));
@@ -409,29 +409,29 @@
*/
public void test_propertyPositions_associationClassQualified_implicitCollect() {
final String exprString =
- "Tree.allInstances().stem[apples]->notEmpty()";
+ "Tree.allInstances().stem[apples]->notEmpty()";
OCLExpression<EClassifier> constraint = createQuery(tree, exprString);
-
+
OperationCallExp<EClassifier, EOperation> notEmptyExp = LocationInformationTest.asOperationCall(
constraint);
-
+
// the OCL is implicitly ->collect(stem[apples])->notEmpty()
LoopExp<EClassifier, EParameter> loopExp = LocationInformationTest.asLoop(
notEmptyExp.getSource());
-
+
AssociationClassCallExp<EClassifier, EStructuralFeature> accExp = LocationInformationTest.asAssociationClassCall(
loopExp.getBody());
-
+
List<OCLExpression<EClassifier>> qualifiers = accExp.getQualifier();
assertEquals(1, qualifiers.size());
-
+
OCLExpression<EClassifier> qualifier = qualifiers.get(0);
-
+
LocationInformationTest.assertLocation(qualifier,
exprString.indexOf("apples"),
exprString.indexOf("]->"));
}
-
+
/**
* Tests that navigation through association ends does not throws NPE
* in case that at least one end in the navigation path
@@ -443,7 +443,7 @@
epackage.setNsPrefix("mypkg");
epackage.setNsURI("http:///mypkg.ecore");
resourceSet.getPackageRegistry().put(epackage.getNsURI(), epackage);
-
+
// Employee class
EClass employee = EcoreFactory.eINSTANCE.createEClass();
employee.setName("Employee");
@@ -457,20 +457,20 @@
employee.getEStructuralFeatures().add(manager);
EFactory efactory = epackage.getEFactoryInstance();
-
+
// create our test instance
EObject emp1 = efactory.create(employee);
// parse & evaluate expression
OCLExpression<EClassifier> expr = parse(
- "package mypkg context Employee " +
- "inv: self.manager.manager" +
+ "package mypkg context Employee " +
+ "inv: self.manager.manager" +
" endpackage");
Object result = evaluate(expr, emp1);
assertInvalid(result);
}
-
+
/**
* Tests that the result of qualifying an association navigation is a
* scalar value (not a collection).
@@ -478,96 +478,96 @@
public void test_qualifiedAssociation_scalar_133435() {
// unqualified navigation
OCLExpression<EClassifier> expr = parse(
- "package ocltest context Forest " +
- "inv: self.trees" +
+ "package ocltest context Forest " +
+ "inv: self.trees" +
" endpackage");
-
+
assertTrue(expr.getType() instanceof CollectionType);
CollectionType collType = (CollectionType) expr.getType();
assertSame(tree, collType.getElementType());
-
+
// qualified navigation
expr = parse(
"package ocltest context Forest " +
- "inv: self.trees['foo', 3]" +
- " endpackage");
-
+ "inv: self.trees['foo', 3]" +
+ " endpackage");
+
assertSame(tree, expr.getType());
}
//
// Fixture methods
//
-
+
/**
* Sets up a common fixture for the association class tests.
*/
@Override
- public void setUp() {
+ public void setUp() {
super.setUp();
expectModified = true;
initFruitExtensions();
}
-
+
private void initFruitExtensions() {
if (q1 != null) {
// already inited
return;
}
-
+
fruitPackage.getEClassifiers().remove(stem);
-
+
// "stem" is more appropriately modeled as an association class
stem = EcoreFactory.eINSTANCE.createEClass();
stem.setName("Stem");
-
+
// tree already created by initFruitPackage
-// tree = EcoreFactory.eINSTANCE.createEClass();
-// tree.setName("Tree");
-
+ // tree = EcoreFactory.eINSTANCE.createEClass();
+ // tree.setName("Tree");
+
fruitPackage.getEClassifiers().add(stem);
-// fruitPackage.getEClassifiers().add(tree);
-
+ // fruitPackage.getEClassifiers().add(tree);
+
apple.getEStructuralFeatures().remove(apple_stem);
apple_stem = null;
-
+
apple_tree = EcoreFactory.eINSTANCE.createEReference();
apple_tree.setName("tree");
apple_tree.setEType(tree);
apple.getEStructuralFeatures().add(apple_tree);
-
+
tree_apples = EcoreFactory.eINSTANCE.createEReference();
tree_apples.setName("apples");
tree_apples.setEType(apple);
tree_apples.setUpperBound(-1);
tree.getEStructuralFeatures().add(tree_apples);
-
+
stem_thickness = EcoreFactory.eINSTANCE.createEAttribute();
stem_thickness.setName("thickness");
stem_thickness.setEType(EcorePackage.eINSTANCE.getEInt());
stem.getEStructuralFeatures().add(stem_thickness);
-
+
stem_apple = EcoreFactory.eINSTANCE.createEReference();
stem_apple.setName("apple");
stem_apple.setEType(apple);
stem.getEStructuralFeatures().add(stem_apple);
-
+
stem_tree = EcoreFactory.eINSTANCE.createEReference();
stem_tree.setName("tree");
stem_tree.setEType(tree);
stem.getEStructuralFeatures().add(stem_tree);
-
+
// add a Forest::trees association with qualifiers
forest = EcoreFactory.eINSTANCE.createEClass();
forest.setName("Forest");
fruitPackage.getEClassifiers().add(forest);
-
+
forest_trees = EcoreFactory.eINSTANCE.createEReference();
forest_trees.setName("trees");
forest_trees.setEType(tree);
forest_trees.setUpperBound(-1);
forest.getEStructuralFeatures().add(forest_trees);
-
+
q1 = EcoreFactory.eINSTANCE.createEAttribute();
q1.setName("q1");
q1.setEType(EcorePackage.eINSTANCE.getEString());
@@ -575,119 +575,119 @@
q2.setName("q2");
q2.setEType(EcorePackage.eINSTANCE.getEInt());
}
-
+
@Override
protected OCL createOCL() {
return OCL.newInstance(new AssocClassFruitEnvironmentFactory());
}
-
+
@Override
- protected void tearDown()
- throws Exception {
-
+ protected void tearDown()
+ throws Exception {
+
super.tearDown();
-
+
// delete customizations, to re-initialize schema for subsequent tests
fruitPackage = null;
}
-
+
private class AssocClassFruitEnvironmentFactory extends EcoreEnvironmentFactory {
public AssocClassFruitEnvironmentFactory() {
super(resourceSet.getPackageRegistry());
}
-
+
@Override
- public EcoreEnvironment createEnvironment() {
+ public EcoreEnvironment createEnvironment() {
return new AssocClassFruitEnvironment(this);
}
@Override
- public EcoreEnvironment createEnvironment(
+ public EcoreEnvironment createEnvironment(
Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent) {
return new AssocClassFruitEnvironment(parent);
}
}
-
+
private class AssocClassFruitEnvironment extends EcoreEnvironment implements InitEnvironment {
private List<EStructuralFeature> stemEnds =
- new java.util.ArrayList<EStructuralFeature>(2);
-
+ new java.util.ArrayList<EStructuralFeature>(2);
+
private List<EStructuralFeature> qualifiers =
- new java.util.ArrayList<EStructuralFeature>(2);
-
+ new java.util.ArrayList<EStructuralFeature>(2);
+
public AssocClassFruitEnvironment(AssocClassFruitEnvironmentFactory factory) {
super(factory, null);
setContextPackage(fruitPackage);
-
- // init();
+
+ // init();
}
-
+
public AssocClassFruitEnvironment(
Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent) {
super(parent);
-
- // init();
+
+ // init();
}
public void init() {
initFruitExtensions();
-
+
stemEnds.add(stem_tree);
stemEnds.add(stem_apple);
-
+
qualifiers.add(q1);
qualifiers.add(q2);
}
-
- @Override
- public UMLReflection<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint> getUMLReflection() {
- return new UMLReflectionImpl() {
- @Override
- public boolean isAssociationClass(EClassifier eclass) {
- return eclass == stem || eclass.getName().equals("AC");
- }
-
- @Override
- public EClass getAssociationClass(EStructuralFeature reference) {
- if (reference == tree_apples || reference == apple_tree) {
- return stem;
- } else if (reference.getName().equals("parent")
- || reference.getName().equals("children")) {
- return (EClass) fruitPackage.getEClassifier("AC");
- }
-
- return null;
- }
-
- @Override
- public List<EStructuralFeature> getMemberEnds(
- EClassifier associationClass) {
-
- if (associationClass == stem) {
- return stemEnds;
- } else if (associationClass.getName().equals("AC")) {
- EClass ac = (EClass) associationClass;
-
- List<EStructuralFeature> result = new java.util.ArrayList<EStructuralFeature>(2);
- result.add(ac.getEStructuralFeature("parentTree"));
- result.add(ac.getEStructuralFeature("childTree"));
-
- return result;
- }
-
- return Collections.emptyList();
- }
-
- @Override
- public List<EStructuralFeature> getQualifiers(EStructuralFeature property) {
- if (property == forest_trees) {
- return qualifiers;
- }
-
- return Collections.emptyList();
- }};
- }
+
+ @Override
+ public UMLReflection<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint> getUMLReflection() {
+ return new UMLReflectionImpl() {
+ @Override
+ public boolean isAssociationClass(EClassifier eclass) {
+ return eclass == stem || eclass.getName().equals("AC");
+ }
+
+ @Override
+ public EClass getAssociationClass(EStructuralFeature reference) {
+ if (reference == tree_apples || reference == apple_tree) {
+ return stem;
+ } else if (reference.getName().equals("parent")
+ || reference.getName().equals("children")) {
+ return (EClass) fruitPackage.getEClassifier("AC");
+ }
+
+ return null;
+ }
+
+ @Override
+ public List<EStructuralFeature> getMemberEnds(
+ EClassifier associationClass) {
+
+ if (associationClass == stem) {
+ return stemEnds;
+ } else if (associationClass.getName().equals("AC")) {
+ EClass ac = (EClass) associationClass;
+
+ List<EStructuralFeature> result = new java.util.ArrayList<EStructuralFeature>(2);
+ result.add(ac.getEStructuralFeature("parentTree"));
+ result.add(ac.getEStructuralFeature("childTree"));
+
+ return result;
+ }
+
+ return Collections.emptyList();
+ }
+
+ @Override
+ public List<EStructuralFeature> getQualifiers(EStructuralFeature property) {
+ if (property == forest_trees) {
+ return qualifiers;
+ }
+
+ return Collections.emptyList();
+ }};
+ }
}
}
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ComparisonTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ComparisonTest.java
index 294e28f..dbd2446 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ComparisonTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ComparisonTest.java
@@ -49,7 +49,7 @@
*/
@SuppressWarnings("nls")
public class ComparisonTest
- extends AbstractTestSuite {
+extends AbstractTestSuite {
EPackage pkg;
EClass thingType;
@@ -58,17 +58,17 @@
EAttribute biValue;
EDataType valueType;
EClass numeroType;
- EReference numeros;
+ EReference numeros;
EClass comparable;
- EDataType myDataType;
+ EDataType myDataType;
EObject thing;
-
+
/**
* Tests the < operator.
*/
public void test_lessThan() {
helper.setContext(thingType);
-
+
try {
// primitives
assertTrue(check(helper, thing, "1 < 2"));
@@ -103,29 +103,29 @@
@SuppressWarnings("unchecked")
List<Value> valuesList = (List<Value>) thing.eGet(values);
-
+
valuesList.add(new Value("a"));
valuesList.add(new Value("b"));
-
- ParsingOptions.setOption(helper.getOCL().getEnvironment(),
- ParsingOptions.USE_COMPARE_TO_OPERATION, true);
-
+
+ ParsingOptions.setOption(helper.getOCL().getEnvironment(),
+ ParsingOptions.USE_COMPARE_TO_OPERATION, true);
+
assertTrue(check(helper, thing,
- "values->at(1) < values->at(2)"));
+ "values->at(1) < values->at(2)"));
assertFalse(check(helper, thing,
- "values->at(2) < values->at(1)"));
+ "values->at(2) < values->at(1)"));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the <= operator.
*/
public void test_lessThanOrEqual() {
helper.setContext(thingType);
-
+
try {
// primitives
assertTrue(check(helper, thing, "1 <= 2"));
@@ -157,7 +157,7 @@
assertTrue(check(helper, thing, "bdValue <= 1.1"));
assertTrue(check(helper, thing, "bdValue <= 2.0"));
assertTrue(check(helper, thing, "bdValue <= 2"));
-
+
// BigInteger tests
thing.eSet(biValue, new BigInteger("1"));
assertTrue(check(helper, thing, "biValue <= 1"));
@@ -166,32 +166,32 @@
@SuppressWarnings("unchecked")
List<Value> valuesList = (List<Value>) thing.eGet(values);
-
+
valuesList.add(new Value("a"));
valuesList.add(new Value("b"));
-
- ParsingOptions.setOption(helper.getOCL().getEnvironment(),
- ParsingOptions.USE_COMPARE_TO_OPERATION, true);
-
- assertTrue(check(helper, thing,
- "values->at(1) <= values->at(2)"));
+
+ ParsingOptions.setOption(helper.getOCL().getEnvironment(),
+ ParsingOptions.USE_COMPARE_TO_OPERATION, true);
assertTrue(check(helper, thing,
- "values->at(1) <= values->at(1)"));
+ "values->at(1) <= values->at(2)"));
+
+ assertTrue(check(helper, thing,
+ "values->at(1) <= values->at(1)"));
assertFalse(check(helper, thing,
- "values->at(2) <= values->at(1)"));
+ "values->at(2) <= values->at(1)"));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the > operator.
*/
public void test_greaterThan() {
helper.setContext(thingType);
-
+
try {
// primitives
assertTrue(check(helper, thing, "2 > 1"));
@@ -226,29 +226,29 @@
@SuppressWarnings("unchecked")
List<Value> valuesList = (List<Value>) thing.eGet(values);
-
+
valuesList.add(new Value("b"));
valuesList.add(new Value("a"));
-
- ParsingOptions.setOption(helper.getOCL().getEnvironment(),
- ParsingOptions.USE_COMPARE_TO_OPERATION, true);
-
+
+ ParsingOptions.setOption(helper.getOCL().getEnvironment(),
+ ParsingOptions.USE_COMPARE_TO_OPERATION, true);
+
assertTrue(check(helper, thing,
- "values->at(1) > values->at(2)"));
+ "values->at(1) > values->at(2)"));
assertFalse(check(helper, thing,
- "values->at(2) > values->at(1)"));
+ "values->at(2) > values->at(1)"));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the >= operator.
*/
public void test_greaterThanOrEqual() {
helper.setContext(thingType);
-
+
try {
// primitives
assertTrue(check(helper, thing, "2 >= 1"));
@@ -289,59 +289,59 @@
@SuppressWarnings("unchecked")
List<Value> valuesList = (List<Value>) thing.eGet(values);
-
+
valuesList.add(new Value("b"));
valuesList.add(new Value("a"));
-
- ParsingOptions.setOption(helper.getOCL().getEnvironment(),
- ParsingOptions.USE_COMPARE_TO_OPERATION, true);
-
- assertTrue(check(helper, thing,
- "values->at(1) >= values->at(2)"));
+
+ ParsingOptions.setOption(helper.getOCL().getEnvironment(),
+ ParsingOptions.USE_COMPARE_TO_OPERATION, true);
assertTrue(check(helper, thing,
- "values->at(1) >= values->at(1)"));
+ "values->at(1) >= values->at(2)"));
+
+ assertTrue(check(helper, thing,
+ "values->at(1) >= values->at(1)"));
assertFalse(check(helper, thing,
- "values->at(2) >= values->at(1)"));
+ "values->at(2) >= values->at(1)"));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the sortedby iterator.
*/
public void test_sortedBy() {
helper.setContext(thingType);
-
+
try {
@SuppressWarnings("unchecked")
List<Value> valuesList = (List<Value>) thing.eGet(values);
-
+
valuesList.add(new Value("b"));
valuesList.add(new Value("c"));
valuesList.add(new Value("a"));
-
+
LinkedHashSet<Value> expected = new LinkedHashSet<Value>();
expected.add(valuesList.get(2));
expected.add(valuesList.get(0));
expected.add(valuesList.get(1));
-
+
assertEquals(expected, evaluate(helper, thing,
- "values->sortedBy(e | e)"));
+ "values->sortedBy(e | e)"));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the <code>=</code> and <code><></code> operators for the
* Invalid type.
*/
public void test_invalid_equality() {
helper.setContext(thingType);
-
+
try {
assertFalse(check(helper, thing, "OclInvalid = 'a'"));
assertTrue(check(helper, thing, "OclInvalid <> 'a'"));
@@ -351,14 +351,14 @@
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the <code>=</code> and <code><></code> operators for the
* OclVoid type.
*/
public void test_void_equality() {
helper.setContext(thingType);
-
+
try {
assertFalse(check(helper, thing, "null = 'a'"));
assertTrue(check(helper, thing, "null <> 'a'"));
@@ -368,13 +368,13 @@
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests evaluation of the arithmetic operations on integers.
*/
public void test_integerArithmetic() {
helper.setContext(thingType);
-
+
try {
assertEquals(new Integer(1), evaluate(helper, thing, "3 - 2"));
assertEquals(new Integer(3), evaluate(helper, thing, "1 + 2"));
@@ -390,13 +390,13 @@
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests evaluation of the arithmetic operations on reals.
*/
public void test_realArithmetic() {
helper.setContext(thingType);
-
+
try {
assertEquals(new Double(1.0), evaluate(helper, thing, "3.0 - 2.0"));
assertEquals(new Double(3.0), evaluate(helper, thing, "1.0 + 2.0"));
@@ -410,14 +410,14 @@
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests evaluation of the arithmetic operations on integers, with real
* arguments.
*/
public void test_mixedArithmetic() {
helper.setContext(thingType);
-
+
try {
assertEquals(new Double(1.0), evaluate(helper, thing, "3 - 2.0"));
assertEquals(new Double(3.0), evaluate(helper, thing, "1 + 2.0"));
@@ -429,18 +429,18 @@
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
public void test_dotNotationForSymbolicOperationNames() {
- ParsingOptions.setOption(helper.getEnvironment(), ProblemOption.CONCEPTUAL_OPERATION_NAME, ProblemHandler.Severity.OK);
+ ParsingOptions.setOption(helper.getEnvironment(), ProblemOption.CONCEPTUAL_OPERATION_NAME, ProblemHandler.Severity.OK);
helper.setContext(EcorePackage.Literals.EINT);
-
+
Integer minusOne = new Integer(-1);
Integer one = new Integer(1);
Integer two = new Integer(2);
Double doubleTwo = new Double(2.0);
Integer three = new Integer(3);
Integer six = new Integer(6);
-
+
try {
// new NUMERIC_OPERATION token
assertEquals(one, evaluate(helper, one, "3.-(2)"));
@@ -451,7 +451,7 @@
assertTrue(check(helper, one, "1.<=(2)"));
assertTrue(check(helper, one, "2.>=(1)"));
assertTrue(check(helper, one, "2.>(1)"));
-
+
// new operationCallExpCS rule
assertEquals(one, evaluate(helper, three, "self.-(2)"));
assertEquals(three, evaluate(helper, one, "self.+(2)"));
@@ -461,7 +461,7 @@
assertTrue(check(helper, one, "self.<=(2)"));
assertTrue(check(helper, two, "self.>=(1)"));
assertTrue(check(helper, two, "self.>(1)"));
-
+
// unary minus
assertEquals(minusOne, evaluate(helper, one, "-1"));
assertEquals(minusOne, evaluate(helper, one, "-self"));
@@ -471,7 +471,7 @@
assertEquals(one, evaluate(helper, one, "- self.-()"));
assertEquals(one, evaluate(helper, one, "- -1"));
assertEquals(one, evaluate(helper, one, "- -self"));
-
+
// unary not
helper.setContext(EcorePackage.Literals.EBOOLEAN);
assertEquals(Boolean.FALSE, evaluate(helper, Boolean.TRUE, "not self"));
@@ -480,26 +480,26 @@
assertEquals(Boolean.TRUE, evaluate(helper, Boolean.TRUE, "not not self"));
assertEquals(Boolean.TRUE, evaluate(helper, Boolean.TRUE, "not self._not()"));
assertEquals(Boolean.TRUE, evaluate(helper, Boolean.TRUE, "not self.not()"));
-
+
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
- ParsingOptions.setOption(helper.getEnvironment(), ProblemOption.CONCEPTUAL_OPERATION_NAME, ProblemHandler.Severity.ERROR);
+ ParsingOptions.setOption(helper.getEnvironment(), ProblemOption.CONCEPTUAL_OPERATION_NAME, ProblemHandler.Severity.ERROR);
try {
assertEquals(one, evaluate(helper, one, "3.-(2)"));
fail("Missing exception");
} catch (Exception e) {
}
}
-
+
public void test_javaImplementationsOfInfixOperators() {
helper.setContext(thingType);
-
+
Numero three = new Numero(3);
Numero four = new Numero(4);
Numero eight = new Numero(8);
Numero twelve = new Numero(12);
-
+
try {
assertEquals(four, evaluate(helper, thing, "numeros->at(1) - numeros->at(2)"));
assertEquals(eight, evaluate(helper, thing, "numeros->at(1) + numeros->at(2)"));
@@ -513,14 +513,14 @@
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
public void test_comparisonOfBooleanOperations_137487() {
- EClass ctx = EcorePackage.eINSTANCE.getEClass();
- helper.setContext(ctx.eClass());
+ EClass ctx = EcorePackage.eINSTANCE.getEClass();
+ helper.setContext(ctx.eClass());
try {
assertTrue(check(helper, ctx, "self.isSuperTypeOf(self)"));
-
+
assertTrue(check(helper, ctx, "self.isSuperTypeOf(self) and true"));
assertTrue(check(helper, ctx, "self.isSuperTypeOf(self) or false"));
assertTrue(check(helper, ctx, "self.isSuperTypeOf(self) xor false"));
@@ -534,21 +534,21 @@
}
public void test_enumerationLiteralEquality_137546() {
- // test all of the collection kinds for bug 176308
- for (CollectionKind kind : CollectionKind.values()) {
- CollectionLiteralExp<EClassifier> ctx = oclFactory.createCollectionLiteralExp();
- ctx.setKind(kind);
- helper.setInstanceContext(ctx);
-
- try {
- assertTrue(check(helper, ctx,
- "ocl::expressions::CollectionKind::\"" + kind.getLiteral() + "\" = self.kind"));
- assertTrue(check(helper, ctx,
- "self.kind = ocl::expressions::CollectionKind::\"" + kind.getLiteral() + '"'));
- } catch (Exception e) {
- fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
- }
- }
+ // test all of the collection kinds for bug 176308
+ for (CollectionKind kind : CollectionKind.values()) {
+ CollectionLiteralExp<EClassifier> ctx = oclFactory.createCollectionLiteralExp();
+ ctx.setKind(kind);
+ helper.setInstanceContext(ctx);
+
+ try {
+ assertTrue(check(helper, ctx,
+ "ocl::expressions::CollectionKind::\"" + kind.getLiteral() + "\" = self.kind"));
+ assertTrue(check(helper, ctx,
+ "self.kind = ocl::expressions::CollectionKind::\"" + kind.getLiteral() + '"'));
+ } catch (Exception e) {
+ fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
+ }
+ }
}
/**
@@ -569,185 +569,185 @@
epackage.getEClassifiers().add(edatatype);
eoperation.setEType(edatatype);
eclass.getEOperations().add(eoperation);
-
+
helper.setContext(eclass);
-
+
try {
OCLExpression<EClassifier> expr = helper.createQuery("self.f()");
-
+
EClassifier type = expr.getType();
assertSame(edatatype, type);
-
+
eoperation.setUpperBound(ETypedElement.UNBOUNDED_MULTIPLICITY);
-
+
expr = helper.createQuery("self.f()");
-
+
type = expr.getType();
assertTrue(type instanceof CollectionType<?, ?>);
type = ((org.eclipse.ocl.ecore.CollectionType) type).getElementType();
assertSame(edatatype, type);
-
+
eoperation.setUpperBound(1);
eoperation.setEType(EcorePackage.Literals.EJAVA_OBJECT);
-
+
expr = helper.createQuery("self.f()");
-
+
type = expr.getType();
assertSame(getOCLStandardLibrary().getOclAny(), type);
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests support for attributes of ELong type.
*/
- public void test_supportForELongAttributes_198451() {
- helper.setContext(thingType);
-
- long maxInt = Integer.MAX_VALUE;
- long maxIntMinusOne = (long) Integer.MAX_VALUE - 1;
- long maxIntSquared = ((long) Integer.MAX_VALUE) * ((long) Integer.MAX_VALUE);
- double quotient = (double) maxIntSquared / (double) maxIntMinusOne;
-
- Numero maxIntN = new Numero(maxInt);
- Numero maxIntMinusOneN = new Numero(maxIntMinusOne);
- Numero maxIntSquaredN = new Numero(maxIntSquared);
-
- @SuppressWarnings("unchecked")
- EList<Numero> list = (EList<Numero>) thing.eGet(numeros);
- list.clear();
- list.add(maxIntN);
- list.add(maxIntMinusOneN);
- list.add(maxIntSquaredN);
- list.add(new Numero(1));
-
- try {
- // this should be OK because both values can be represented as integers
- assertEquals(1, evaluate(helper, thing, "numeros->at(1).asLong() - numeros->at(2).asLong()"));
-
- // same number represented in different precision
- assertTrue(check(helper, thing, "numeros->at(4).asLong() = 1"));
-
- // different numbers represented in different precision
- assertTrue(check(helper, thing, "numeros->at(4).asLong() <> 2"));
-
- // this is also OK, because we compute in high precision and coerce
- // the result to lower precision
- assertEquals(quotient, evaluate(helper, thing, "numeros->at(3).asLong() / numeros->at(2).asLong()"));
-
- // this is another case where the intermediate result is high-precision but
- // the result is low
- assertEquals((int) maxIntMinusOne, evaluate(helper, thing,
- String.format("(%d + %d).div(2) - 1", maxInt, maxInt)));
-
- // finally, a case where the result is in high precision (new capability)
- assertEquals(maxIntSquared, evaluate(helper, thing,
- String.format("%d * %d", maxInt, maxInt)));
- } catch (Exception e) {
- fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * Tests that the <tt>OclAny::=</tt> operation does not require the source
- * and argument types to be related.
- */
- public void test_OclAny_equals_unrelatedArgumentTypes() {
- helper.setContext(fruit);
-
- try {
- // this should be OK anyways
- helper.createInvariant(
- "not Apple.allInstances()->exists(a | a = self)");
-
- helper.createInvariant(
- "not ecore::EClass.allInstances()->exists(c | c = self)");
- } catch (Exception e) {
- fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * Tests that the <tt>OclAny::<></tt> operation does not require the
- * source and argument types to be related.
- */
- public void test_OclAny_notEquals_unrelatedArgumentTypes() {
- helper.setContext(fruit);
-
- try {
- // this should be OK anyways
- helper.createInvariant(
- "Apple.allInstances()->forAll(a | a <> self)");
-
- helper.createInvariant(
- "ecore::EClass.allInstances()->forAll(c | c <> self)");
- } catch (Exception e) {
- fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * The compareTo() method is a Java-ism that should not be supported by
- * OCL as a definition of the relational comparison operations.
- */
- public void test_compareToOnlyUsedByJavaImplementation_212804() {
- helper.setContext(comparable);
-
- try {
- // this should not parse because the >= operation is not defined
- helper.createInvariant(
- "Comparable.allInstances()->forAll(c | self >= c)");
-
- fail("Should not have parsed");
- } catch (ParserException e) {
- // success
- System.out.println("Got expected exception: " + e.getLocalizedMessage());
- } catch (Exception e) {
- fail("Unexpected exception during parse: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * The compareTo() method is a Java-ism that should not be supported by
- * OCL as a definition of the relational comparison operations.
- */
- public void test_comparableDataTypes_212804() {
- helper.setContext(myDataType);
-
- try {
- // this should not parse because the >= operation is not defined
- helper.createInvariant(
- "MyDataType.allInstances()->forAll(d | self >= d)");
-
- fail("Should not have parsed");
- } catch (ParserException e) {
- // success
- System.out.println("Got expected exception: " + e.getLocalizedMessage());
- } catch (Exception e) {
- fail("Unexpected exception during parse: " + e.getLocalizedMessage());
- }
- }
-
+ public void test_supportForELongAttributes_198451() {
+ helper.setContext(thingType);
+
+ long maxInt = Integer.MAX_VALUE;
+ long maxIntMinusOne = (long) Integer.MAX_VALUE - 1;
+ long maxIntSquared = ((long) Integer.MAX_VALUE) * ((long) Integer.MAX_VALUE);
+ double quotient = (double) maxIntSquared / (double) maxIntMinusOne;
+
+ Numero maxIntN = new Numero(maxInt);
+ Numero maxIntMinusOneN = new Numero(maxIntMinusOne);
+ Numero maxIntSquaredN = new Numero(maxIntSquared);
+
+ @SuppressWarnings("unchecked")
+ EList<Numero> list = (EList<Numero>) thing.eGet(numeros);
+ list.clear();
+ list.add(maxIntN);
+ list.add(maxIntMinusOneN);
+ list.add(maxIntSquaredN);
+ list.add(new Numero(1));
+
+ try {
+ // this should be OK because both values can be represented as integers
+ assertEquals(1, evaluate(helper, thing, "numeros->at(1).asLong() - numeros->at(2).asLong()"));
+
+ // same number represented in different precision
+ assertTrue(check(helper, thing, "numeros->at(4).asLong() = 1"));
+
+ // different numbers represented in different precision
+ assertTrue(check(helper, thing, "numeros->at(4).asLong() <> 2"));
+
+ // this is also OK, because we compute in high precision and coerce
+ // the result to lower precision
+ assertEquals(quotient, evaluate(helper, thing, "numeros->at(3).asLong() / numeros->at(2).asLong()"));
+
+ // this is another case where the intermediate result is high-precision but
+ // the result is low
+ assertEquals((int) maxIntMinusOne, evaluate(helper, thing,
+ String.format("(%d + %d).div(2) - 1", maxInt, maxInt)));
+
+ // finally, a case where the result is in high precision (new capability)
+ assertEquals(maxIntSquared, evaluate(helper, thing,
+ String.format("%d * %d", maxInt, maxInt)));
+ } catch (Exception e) {
+ fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests that the <tt>OclAny::=</tt> operation does not require the source
+ * and argument types to be related.
+ */
+ public void test_OclAny_equals_unrelatedArgumentTypes() {
+ helper.setContext(fruit);
+
+ try {
+ // this should be OK anyways
+ helper.createInvariant(
+ "not Apple.allInstances()->exists(a | a = self)");
+
+ helper.createInvariant(
+ "not ecore::EClass.allInstances()->exists(c | c = self)");
+ } catch (Exception e) {
+ fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests that the <tt>OclAny::<></tt> operation does not require the
+ * source and argument types to be related.
+ */
+ public void test_OclAny_notEquals_unrelatedArgumentTypes() {
+ helper.setContext(fruit);
+
+ try {
+ // this should be OK anyways
+ helper.createInvariant(
+ "Apple.allInstances()->forAll(a | a <> self)");
+
+ helper.createInvariant(
+ "ecore::EClass.allInstances()->forAll(c | c <> self)");
+ } catch (Exception e) {
+ fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * The compareTo() method is a Java-ism that should not be supported by
+ * OCL as a definition of the relational comparison operations.
+ */
+ public void test_compareToOnlyUsedByJavaImplementation_212804() {
+ helper.setContext(comparable);
+
+ try {
+ // this should not parse because the >= operation is not defined
+ helper.createInvariant(
+ "Comparable.allInstances()->forAll(c | self >= c)");
+
+ fail("Should not have parsed");
+ } catch (ParserException e) {
+ // success
+ debugPrintln("Got expected exception: " + e.getLocalizedMessage());
+ } catch (Exception e) {
+ fail("Unexpected exception during parse: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * The compareTo() method is a Java-ism that should not be supported by
+ * OCL as a definition of the relational comparison operations.
+ */
+ public void test_comparableDataTypes_212804() {
+ helper.setContext(myDataType);
+
+ try {
+ // this should not parse because the >= operation is not defined
+ helper.createInvariant(
+ "MyDataType.allInstances()->forAll(d | self >= d)");
+
+ fail("Should not have parsed");
+ } catch (ParserException e) {
+ // success
+ debugPrintln("Got expected exception: " + e.getLocalizedMessage());
+ } catch (Exception e) {
+ fail("Unexpected exception during parse: " + e.getLocalizedMessage());
+ }
+ }
+
//
// Framework methods
//
-
+
@Override
- protected void setUp() {
+ protected void setUp() {
super.setUp();
-
+
pkg = EcoreFactory.eINSTANCE.createEPackage();
pkg.setName("pkg");
-
+
EFactory factory = EcoreFactory.eINSTANCE.createEFactory();
pkg.setEFactoryInstance(factory);
-
+
valueType = EcoreFactory.eINSTANCE.createEDataType();
valueType.setName("Value");
valueType.setInstanceClass(Value.class);
pkg.getEClassifiers().add(valueType);
-
+
thingType = EcoreFactory.eINSTANCE.createEClass();
thingType.setName("Thing");
pkg.getEClassifiers().add(thingType);
@@ -769,12 +769,12 @@
values.setEType(valueType);
values.setUpperBound(ETypedElement.UNBOUNDED_MULTIPLICITY);
thingType.getEStructuralFeatures().add(values);
-
+
numeroType = EcoreFactory.eINSTANCE.createEClass();
numeroType.setName("Numero");
numeroType.setInstanceClass(Numero.class);
- pkg.getEClassifiers().add(numeroType);
-
+ pkg.getEClassifiers().add(numeroType);
+
EOperation oper = EcoreFactory.eINSTANCE.createEOperation();
oper.setName("+");
EParameter parm = EcoreFactory.eINSTANCE.createEParameter();
@@ -783,7 +783,7 @@
oper.getEParameters().add(parm);
oper.setEType(numeroType);
numeroType.getEOperations().add(oper);
-
+
oper = EcoreFactory.eINSTANCE.createEOperation();
oper.setName("-");
parm = EcoreFactory.eINSTANCE.createEParameter();
@@ -792,7 +792,7 @@
oper.getEParameters().add(parm);
oper.setEType(numeroType);
numeroType.getEOperations().add(oper);
-
+
oper = EcoreFactory.eINSTANCE.createEOperation();
oper.setName("*");
parm = EcoreFactory.eINSTANCE.createEParameter();
@@ -801,7 +801,7 @@
oper.getEParameters().add(parm);
oper.setEType(numeroType);
numeroType.getEOperations().add(oper);
-
+
oper = EcoreFactory.eINSTANCE.createEOperation();
oper.setName("/");
parm = EcoreFactory.eINSTANCE.createEParameter();
@@ -810,12 +810,12 @@
oper.getEParameters().add(parm);
oper.setEType(numeroType);
numeroType.getEOperations().add(oper);
-
+
oper = EcoreFactory.eINSTANCE.createEOperation();
oper.setName("-");
oper.setEType(numeroType);
numeroType.getEOperations().add(oper);
-
+
oper = EcoreFactory.eINSTANCE.createEOperation();
oper.setName("<");
parm = EcoreFactory.eINSTANCE.createEParameter();
@@ -824,7 +824,7 @@
oper.getEParameters().add(parm);
oper.setEType(EcorePackage.Literals.EBOOLEAN);
numeroType.getEOperations().add(oper);
-
+
oper = EcoreFactory.eINSTANCE.createEOperation();
oper.setName("<=");
parm = EcoreFactory.eINSTANCE.createEParameter();
@@ -833,7 +833,7 @@
oper.getEParameters().add(parm);
oper.setEType(EcorePackage.Literals.EBOOLEAN);
numeroType.getEOperations().add(oper);
-
+
oper = EcoreFactory.eINSTANCE.createEOperation();
oper.setName(">");
parm = EcoreFactory.eINSTANCE.createEParameter();
@@ -842,7 +842,7 @@
oper.getEParameters().add(parm);
oper.setEType(EcorePackage.Literals.EBOOLEAN);
numeroType.getEOperations().add(oper);
-
+
oper = EcoreFactory.eINSTANCE.createEOperation();
oper.setName(">=");
parm = EcoreFactory.eINSTANCE.createEParameter();
@@ -851,59 +851,59 @@
oper.getEParameters().add(parm);
oper.setEType(EcorePackage.Literals.EBOOLEAN);
numeroType.getEOperations().add(oper);
-
- oper = EcoreFactory.eINSTANCE.createEOperation();
- oper.setName("asLong");
- oper.setEType(EcorePackage.Literals.ELONG);
- numeroType.getEOperations().add(oper);
-
+
+ oper = EcoreFactory.eINSTANCE.createEOperation();
+ oper.setName("asLong");
+ oper.setEType(EcorePackage.Literals.ELONG);
+ numeroType.getEOperations().add(oper);
+
numeros = EcoreFactory.eINSTANCE.createEReference();
numeros.setName("numeros");
numeros.setEType(numeroType);
numeros.setUpperBound(ETypedElement.UNBOUNDED_MULTIPLICITY);
numeros.setOrdered(true);
thingType.getEStructuralFeatures().add(numeros);
-
+
thing = factory.create(thingType);
- comparable = EcoreFactory.eINSTANCE.createEClass();
- comparable.setName("Comparable");
- comparable.setAbstract(true);
- pkg.getEClassifiers().add(comparable);
-
- oper = EcoreFactory.eINSTANCE.createEOperation();
- oper.setName("compareTo");
- parm = EcoreFactory.eINSTANCE.createEParameter();
- parm.setName("c");
- parm.setEType(comparable);
- oper.getEParameters().add(parm);
- oper.setEType(EcorePackage.Literals.EINT);
- comparable.getEOperations().add(oper);
-
- myDataType = EcoreFactory.eINSTANCE.createEDataType();
- myDataType.setName("MyDataType");
- myDataType.setInstanceClass(Thread.State.class); // enums are comparable
- pkg.getEClassifiers().add(myDataType);
-
+ comparable = EcoreFactory.eINSTANCE.createEClass();
+ comparable.setName("Comparable");
+ comparable.setAbstract(true);
+ pkg.getEClassifiers().add(comparable);
+
+ oper = EcoreFactory.eINSTANCE.createEOperation();
+ oper.setName("compareTo");
+ parm = EcoreFactory.eINSTANCE.createEParameter();
+ parm.setName("c");
+ parm.setEType(comparable);
+ oper.getEParameters().add(parm);
+ oper.setEType(EcorePackage.Literals.EINT);
+ comparable.getEOperations().add(oper);
+
+ myDataType = EcoreFactory.eINSTANCE.createEDataType();
+ myDataType.setName("MyDataType");
+ myDataType.setInstanceClass(Thread.State.class); // enums are comparable
+ pkg.getEClassifiers().add(myDataType);
+
@SuppressWarnings("unchecked")
EList<Numero> list = (EList<Numero>) thing.eGet(numeros);
list.add(new Numero(6));
list.add(new Numero(2));
}
-
+
private static class Value implements Comparable<Value> {
private final String value;
-
+
Value(String value) {
this.value = value;
}
-
+
public int compareTo(Value arg0) {
return value.compareTo((arg0).value);
}
@Override
- public int hashCode() {
+ public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((value == null) ? 0 : value.hashCode());
@@ -911,81 +911,81 @@
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(Object obj) {
if (this == obj) {
- return true;
- }
+ return true;
+ }
if (obj == null) {
- return false;
- }
+ return false;
+ }
if (getClass() != obj.getClass()) {
- return false;
- }
+ return false;
+ }
final Value other = (Value) obj;
if (value == null) {
if (other.value != null) {
- return false;
- }
+ return false;
+ }
} else if (!value.equals(other.value)) {
- return false;
- }
+ return false;
+ }
return true;
}
}
-
+
public static class Numero extends EObjectImpl {
private long value;
-
+
Numero() {
super();
}
-
+
Numero(long value) {
this.value = value;
}
-
+
public Numero plus(Numero n) {
return new Numero(value + n.value);
}
-
+
public Numero minus(Numero n) {
return new Numero(value - n.value);
}
-
+
public Numero times(Numero n) {
return new Numero(value * n.value);
}
-
+
public Numero divide(Numero n) {
return new Numero(value / n.value);
}
-
+
public Numero minus() {
return new Numero(-value);
}
-
+
public boolean lessThan(Numero n) {
return value < n.value;
}
-
+
public boolean lessThanEqual(Numero n) {
return value <= n.value;
}
-
+
public boolean greaterThan(Numero n) {
return value > n.value;
}
-
+
public boolean greaterThanEqual(Numero n) {
return value >= n.value;
}
-
+
public long asLong() {
- return value;
+ return value;
}
@Override
- public int hashCode() {
+ public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + (int) (value & 0xFFFF);
@@ -993,25 +993,25 @@
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(Object obj) {
if (this == obj) {
- return true;
- }
+ return true;
+ }
if (obj == null) {
- return false;
- }
+ return false;
+ }
if (getClass() != obj.getClass()) {
- return false;
- }
+ return false;
+ }
final Numero other = (Numero) obj;
if (value != other.value) {
- return false;
- }
+ return false;
+ }
return true;
}
-
+
@Override
- public String toString() {
+ public String toString() {
return "Numero(" + value + ")";
}
}
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/DefExpressionTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/DefExpressionTest.java
index d690741..de65f7d 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/DefExpressionTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/DefExpressionTest.java
@@ -44,8 +44,8 @@
*/
@SuppressWarnings("nls")
public class DefExpressionTest
- extends AbstractTestSuite {
-
+extends AbstractTestSuite {
+
/**
* Tests the parsing the def expression for an operation from raw text.
*/
@@ -53,61 +53,61 @@
try {
OCLExpression<EClassifier> expr = parseDef(
"package ocltest context Fruit " +
- "def: bestColor(c : Color) : Color = if self.color = Color::black then c else self.color endif" +
- " endpackage");
-
+ "def: bestColor(c : Color) : Color = if self.color = Color::black then c else self.color endif" +
+ " endpackage");
+
Constraint constraint = (Constraint) expr.eContainer().eContainer();
assertNotNull(constraint);
-
+
assertEquals(UMLReflection.DEFINITION, constraint.getStereotype());
-
+
assertSame(color, expr.getType());
-
+
expr = parse(
- "package ocltest context Fruit " +
- "inv: bestColor(Color::red) = Color::red" +
+ "package ocltest context Fruit " +
+ "inv: bestColor(Color::red) = Color::red" +
" endpackage");
-
+
EObject anApple = fruitFactory.create(apple);
anApple.eSet(fruit_color, color_black);
-
+
assertTrue(ocl.check(anApple, expr));
-
+
anApple.eSet(fruit_color, color_green);
-
+
assertFalse(ocl.check(anApple, expr));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the parsing the def expression for an operation using the helper.
*/
public void test_defExpression_helper_operation() {
helper.setContext(fruit);
-
+
try {
helper.defineOperation(
- "bestColor(c : Color) : Color = " +
+ "bestColor(c : Color) : Color = " +
"if self.color = Color::black then c else self.color endif");
-
+
Constraint expr = helper.createInvariant(
"bestColor(Color::red) = Color::red");
-
+
EObject anApple = fruitFactory.create(apple);
anApple.eSet(fruit_color, color_black);
-
+
assertTrue(ocl.check(anApple, expr));
-
+
anApple.eSet(fruit_color, color_green);
-
+
assertFalse(ocl.check(anApple, expr));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the parsing the def expression for an attribute from raw text.
*/
@@ -115,60 +115,60 @@
try {
OCLExpression<EClassifier> expr = parseDef(
"package ocltest context Apple " +
- "def: fallen : Boolean = stem.oclIsUndefined()" +
- " endpackage");
-
+ "def: fallen : Boolean = stem.oclIsUndefined()" +
+ " endpackage");
+
Constraint constraint = (Constraint) expr.eContainer().eContainer();
assertNotNull(constraint);
-
+
assertEquals(UMLReflection.DEFINITION, constraint.getStereotype());
-
+
assertSame(getOCLStandardLibrary().getBoolean(), expr.getType());
-
+
expr = parse(
- "package ocltest context Apple " +
- "inv: not fallen" +
+ "package ocltest context Apple " +
+ "inv: not fallen" +
" endpackage");
-
+
EObject anApple = fruitFactory.create(apple);
anApple.eSet(apple_stem, fruitFactory.create(stem));
-
+
assertTrue(ocl.check(anApple, expr));
-
+
anApple.eSet(apple_stem, null);
-
+
assertFalse(ocl.check(anApple, expr));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the parsing the def expression for an attribute using the helper.
*/
public void test_defExpression_helper_attribute() {
helper.setContext(apple);
-
+
try {
helper.defineAttribute(
- "fallen : Boolean = " +
+ "fallen : Boolean = " +
"stem.oclIsUndefined()");
-
+
Constraint expr = helper.createInvariant("not fallen");
-
+
EObject anApple = fruitFactory.create(apple);
anApple.eSet(apple_stem, fruitFactory.create(stem));
-
+
assertTrue(ocl.check(anApple, expr));
-
+
anApple.eSet(apple_stem, null);
-
+
assertFalse(ocl.check(anApple, expr));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the parsing the def expression for a reference from raw text.
*/
@@ -176,24 +176,24 @@
try {
OCLExpression<EClassifier> expr = parseDef(
"package ocltest context Apple " +
- "def: otherApples : Set(Apple) = Apple.allInstances()->excluding(self)" +
- " endpackage");
-
+ "def: otherApples : Set(Apple) = Apple.allInstances()->excluding(self)" +
+ " endpackage");
+
Constraint constraint = (Constraint) expr.eContainer().eContainer();
assertNotNull(constraint);
-
+
assertEquals(UMLReflection.DEFINITION, constraint.getStereotype());
-
+
assertTrue(expr.getType() instanceof SetType<?, ?>);
assertSame(
- ((org.eclipse.ocl.ecore.SetType) expr.getType()).getElementType(),
- apple);
-
+ ((org.eclipse.ocl.ecore.SetType) expr.getType()).getElementType(),
+ apple);
+
expr = parse(
- "package ocltest context Apple " +
- "inv: self.otherApples" +
+ "package ocltest context Apple " +
+ "inv: self.otherApples" +
" endpackage");
-
+
EObject anApple = fruitFactory.create(apple);
EObject anotherApple = fruitFactory.create(apple);
Map<EClass, Set<EObject>> extentMap = new java.util.HashMap<EClass, Set<EObject>>();
@@ -202,29 +202,29 @@
allApples.add(anotherApple);
extentMap.put(apple, allApples);
ocl.setExtentMap(extentMap);
-
+
Object otherApples = ocl.evaluate(anApple, expr);
-
+
assertEquals(Collections.singleton(anotherApple), otherApples);
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
public void test_defExpression_inheritance_operation() {
helper.setContext(EcorePackage.Literals.ECLASSIFIER);
-
+
try {
helper.defineOperation(
- "allParents() : Set(EClassifier) = " +
+ "allParents() : Set(EClassifier) = " +
"if self.oclIsKindOf(EClass) then self.oclAsType(EClass)->closure(eSuperTypes) else Set{} endif");
-
+
OCLExpression<EClassifier> expr = helper.createQuery("self.allParents()");
-
+
Object allParents = ocl.evaluate(apple, expr);
assertTrue(allParents instanceof Set<?>);
assertTrue(((Set<?>) allParents).contains(fruit));
-
+
allParents = ocl.evaluate(color, expr);
assertTrue(allParents instanceof Set<?>);
assertTrue(((Set<?>) allParents).isEmpty());
@@ -232,21 +232,21 @@
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
public void test_defExpression_inheritance_attribute() {
helper.setContext(EcorePackage.Literals.ECLASSIFIER);
-
+
try {
helper.defineAttribute(
- "allParents : Set(EClassifier) = " +
+ "allParents : Set(EClassifier) = " +
"if self.oclIsKindOf(EClass) then self.oclAsType(EClass)->closure(eSuperTypes) else Set{} endif");
-
+
OCLExpression<EClassifier> expr = helper.createQuery("self.allParents");
-
+
Object allParents = ocl.evaluate(apple, expr);
assertTrue(allParents instanceof Set<?>);
assertTrue(((Set<?>) allParents).contains(fruit));
-
+
allParents = ocl.evaluate(color, expr);
assertTrue(allParents instanceof Set<?>);
assertTrue(((Set<?>) allParents).isEmpty());
@@ -254,7 +254,7 @@
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the parsing the def expression for static attributes and operations.
*/
@@ -263,262 +263,262 @@
ParsingOptions.setOption(ocl.getEnvironment(), ParsingOptions.SUPPORT_STATIC_FEATURES, true);
try {
ocl.parse(new OCLInput("package ocltest context Fruit " +
- "def: bestColor1() : Color = null " +
- "static def: bestColor2() : Color = null " +
- "def: goodColor1 : Color = null " +
- "static def: goodColor2 : Color = null " +
- "endpackage"));
- fail("Should have failed to parse the unimplemented static");
- } catch (ParserException e) {
- // success!
- assertEquals(OCLMessages.UnimplementedStatic_ERROR_, e.getMessage());
- System.out.println("Got the expected exception: " + e.getLocalizedMessage());
- }
-
- ParsingOptions.setOption(ocl.getEnvironment(), ParsingOptions.SUPPORT_STATIC_FEATURES, false);
+ "def: bestColor1() : Color = null " +
+ "static def: bestColor2() : Color = null " +
+ "def: goodColor1 : Color = null " +
+ "static def: goodColor2 : Color = null " +
+ "endpackage"));
+ fail("Should have failed to parse the unimplemented static");
+ } catch (ParserException e) {
+ // success!
+ assertEquals(OCLMessages.UnimplementedStatic_ERROR_, e.getMessage());
+ debugPrintln("Got the expected exception: " + e.getLocalizedMessage());
+ }
+
+ ParsingOptions.setOption(ocl.getEnvironment(), ParsingOptions.SUPPORT_STATIC_FEATURES, false);
try {
ocl.parse(new OCLInput("package ocltest context Fruit " +
- "def: bestColor3() : Color = null " +
- "static def: bestColor4() : Color = null " +
- "endpackage"));
- fail("Should have failed to parse the unsupported static");
- } catch (ParserException e) {
- // success!
- assertEquals(OCLMessages.UnsupportedStatic_ERROR_, e.getMessage());
- System.out.println("Got the expected exception: " + e.getLocalizedMessage());
- }
+ "def: bestColor3() : Color = null " +
+ "static def: bestColor4() : Color = null " +
+ "endpackage"));
+ fail("Should have failed to parse the unsupported static");
+ } catch (ParserException e) {
+ // success!
+ assertEquals(OCLMessages.UnsupportedStatic_ERROR_, e.getMessage());
+ debugPrintln("Got the expected exception: " + e.getLocalizedMessage());
+ }
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
public void test_malformedDefExpression_attribute() {
helper.setContext(EcorePackage.Literals.ECLASSIFIER);
-
+
try {
// non-conformant expression type
helper.defineAttribute(
"allParents : Set(EClassifier) = " +
- "if self.oclIsKindOf(EClass) then self.name else '' endif");
-
+ "if self.oclIsKindOf(EClass) then self.name else '' endif");
+
fail("Should not have parsed");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
try {
// missing type declaration
helper.defineAttribute(
"myName = " +
- "if self.oclIsKindOf(EClass) then self.name else '' endif");
-
+ "if self.oclIsKindOf(EClass) then self.name else '' endif");
+
fail("Should not have parsed");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
}
-
+
public void test_malformedDefExpression_operation() {
helper.setContext(EcorePackage.Literals.ECLASSIFIER);
-
+
try {
// non-conformant expression type
helper.defineOperation(
"allParents() : Set(EClassifier) = " +
- "if self.oclIsKindOf(EClass) then self.name else '' endif");
-
+ "if self.oclIsKindOf(EClass) then self.name else '' endif");
+
fail("Should not have parsed");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
try {
// missing type declaration
helper.defineOperation(
"bestName(s : String) = " +
- "if self.oclIsKindOf(EClass) then self.name else s endif");
-
+ "if self.oclIsKindOf(EClass) then self.name else s endif");
+
fail("Should not have parsed");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
try {
// missing type declaration in parameter
helper.defineOperation(
"bestName(s) : String = " +
- "if self.oclIsKindOf(EClass) then self.name else s endif");
-
+ "if self.oclIsKindOf(EClass) then self.name else s endif");
+
fail("Should not have parsed");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
}
-
+
public void test_duplicateDefinition_attribute() {
helper.setContext(EcorePackage.Literals.ECLASSIFIER);
-
+
try {
// same name and type as existing property
helper.defineAttribute(
"name : String = " +
- "if self.oclIsKindOf(EClass) then 'foo' else '' endif");
-
+ "if self.oclIsKindOf(EClass) then 'foo' else '' endif");
+
fail("Should not have parsed");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
try {
// same name but different type
helper.defineAttribute(
"eAnnotations : Set(String) = " +
- "Set{'a', 'b', 'c'}");
-
+ "Set{'a', 'b', 'c'}");
+
fail("Should not have parsed");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
}
-
+
public void test_duplicateDefinition_operation() {
helper.setContext(apple);
-
+
try {
// same signature as existing operation (note different param name)
helper.defineOperation(
"preferredLabel(s : String) : String = " +
- "if self.oclIsKindOf(EClass) then 'foo' else s endif");
-
+ "if self.oclIsKindOf(EClass) then 'foo' else s endif");
+
fail("Should not have parsed");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
try {
// same signature as existing operation (note different return type)
helper.defineOperation(
"preferredLabel(s : String) : Integer = " +
- "if self.oclIsKindOf(EClass) then 0 else s.size() endif");
-
+ "if self.oclIsKindOf(EClass) then 0 else s.size() endif");
+
fail("Should not have parsed");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
try {
// same name but different signature is OK
helper.defineOperation(
"preferredLabel(text : Integer) : String = " +
- "if text > 0 then 'foo' else 'bar' endif");
+ "if text > 0 then 'foo' else 'bar' endif");
} catch (Exception e) {
fail("Failed to parse: " + e.getLocalizedMessage());
}
}
-
+
public void test_undefine_property_152018() {
helper.setContext(EcorePackage.Literals.ECLASS);
-
+
EStructuralFeature property = null;
-
+
try {
// define some additional property
property = helper.defineAttribute(
"other : EClass = " +
- "if eSuperTypes->notEmpty() then eSuperTypes->first() else null endif");
+ "if eSuperTypes->notEmpty() then eSuperTypes->first() else null endif");
} catch (Exception e) {
fail("Failed to parse: " + e.getLocalizedMessage());
}
-
+
assertNotNull(property);
-
+
// now, undefine this property
ocl.getEnvironment().undefine(property);
-
+
assertNull(property.eContainer());
assertNull(property.eResource());
-
+
try {
// try to define this property again. We should succeed
property = helper.defineAttribute(
- "other : EClass = " +
+ "other : EClass = " +
"if eSuperTypes->notEmpty() then eSuperTypes->first() else null endif");
} catch (Exception e) {
fail("Failed to parse: " + e.getLocalizedMessage());
}
}
-
+
public void test_undefine_operation_152018() {
helper.setContext(EcorePackage.Literals.ECLASS);
-
+
EOperation operation = null;
-
+
try {
// define some additional property
operation = helper.defineOperation(
"other(x : Integer) : EClass = " +
- "if eSuperTypes->notEmpty() then eSuperTypes->at(x) else null endif");
+ "if eSuperTypes->notEmpty() then eSuperTypes->at(x) else null endif");
} catch (Exception e) {
fail("Failed to parse: " + e.getLocalizedMessage());
}
-
+
assertNotNull(operation);
-
+
// now, undefine this operation
ocl.getEnvironment().undefine(operation);
-
+
assertNull(operation.eContainer());
assertNull(operation.eResource());
-
+
try {
// try to define this property again. We should succeed
operation = helper.defineOperation(
- "other(x : Integer) : EClass = " +
+ "other(x : Integer) : EClass = " +
"if eSuperTypes->size() >= x then eSuperTypes->at(x) else null endif");
} catch (Exception e) {
fail("Failed to parse: " + e.getLocalizedMessage());
}
}
-
+
public void test_recursive_property_152018() {
helper.setContext(EcorePackage.Literals.ECLASS);
-
+
EStructuralFeature property = null;
-
+
try {
// first, attempt a definition with an invalid body
property = helper.defineAttribute(
- "friend : EClass = " +
+ "friend : EClass = " +
"if eSuperTypes->notEmpty() then ePackage else self endif");
-
+
fail("Should not have parsed");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
try {
// now, attempt a correct definition. This should not find that
// 'other' is already defined, because it should have been
// undefined when we failed to parse, above
property = helper.defineAttribute(
"friend : EClass = " +
- "if eSuperTypes->notEmpty() then eSuperTypes->first().friend else self endif");
+ "if eSuperTypes->notEmpty() then eSuperTypes->first().friend else self endif");
} catch (Exception e) {
fail("Failed to parse: " + e.getLocalizedMessage());
}
-
+
assertNotNull(property);
-
+
try {
// now, attempt to use this additional property
helper.createInvariant(
@@ -527,37 +527,37 @@
fail("Failed to parse: " + e.getLocalizedMessage());
}
}
-
+
public void test_recursive_operation_152018() {
helper.setContext(EcorePackage.Literals.ECLASS);
-
+
EOperation operation = null;
-
+
try {
// first, attempt a definition with an invalid body
operation = helper.defineOperation(
- "friend(x : Integer) : EClass = " +
+ "friend(x : Integer) : EClass = " +
"if eSuperTypes->size() >= x then ePackage else self endif");
-
+
fail("Should not have parsed");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
try {
// now, attempt a correct definition. This should not find that
// 'other' is already defined, because it should have been
// undefined when we failed to parse, above
operation = helper.defineOperation(
"friend(x : Integer) : EClass = " +
- "if eSuperTypes->size() >= x then eSuperTypes->at(x).friend(x) else self endif");
+ "if eSuperTypes->size() >= x then eSuperTypes->at(x).friend(x) else self endif");
} catch (Exception e) {
fail("Failed to parse: " + e.getLocalizedMessage());
}
-
+
assertNotNull(operation);
-
+
try {
// now, attempt to use this additional property
helper.createInvariant(
@@ -566,397 +566,397 @@
fail("Failed to parse: " + e.getLocalizedMessage());
}
}
-
+
public void test_defExpression_completion_operation() {
helper.setContext(EcorePackage.Literals.ECLASSIFIER);
-
+
try {
helper.defineOperation(
- "allParents() : Set(EClassifier) = " +
+ "allParents() : Set(EClassifier) = " +
"if self.oclIsKindOf(EClass) then self.oclAsType(EClass)->closure(eSuperTypes) else Set{} endif");
-
+
Collection<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "self.");
-
+ ConstraintKind.INVARIANT, "self.");
+
assertChoice(choices, ChoiceKind.OPERATION, "allParents");
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
public void test_defExpression_completion_attribute() {
helper.setContext(EcorePackage.Literals.ECLASSIFIER);
-
+
try {
helper.defineAttribute(
- "allParents : Set(EClassifier) = " +
+ "allParents : Set(EClassifier) = " +
"if self.oclIsKindOf(EClass) then self.oclAsType(EClass)->closure(eSuperTypes) else Set{} endif");
-
+
Collection<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "self.");
-
+ ConstraintKind.INVARIANT, "self.");
+
assertChoice(choices, ChoiceKind.PROPERTY, "allParents");
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
- /**
- * Tests the definition of additional attributes on the metamodel's
- * representation of a primitive type for which OCL has a counterpart.
- */
- public void test_defAttributeOnPrimitiveType_172782() {
- // context is the Ecore metamodel's EString data type
- helper.setContext(EcorePackage.Literals.ESTRING);
-
- try {
- EStructuralFeature feature = helper.defineAttribute(
- "reverse : String = " +
- "Sequence{1..size()}->sortedBy(i | -i)->iterate(i; s : String = '' |" +
- " s.concat(self.substring(i, i)))");
-
- // the other representation of 'String'
- helper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getString());
-
- Collection<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "self.");
-
- assertChoice(choices, ChoiceKind.PROPERTY, "reverse");
-
- OCLExpression<EClassifier> expr = helper.createQuery(
- "self.reverse");
-
- assertEquals(
- "ablE was i ere I saw elbA",
- ocl.evaluate("Able was I ere i saw Elba", expr));
-
- // verify that TypeUtil produces the correct result
- assertTrue(TypeUtil.getAttributes(ocl.getEnvironment(), ocl.getEnvironment().getOCLStandardLibrary().getString())
- .contains(feature));
- assertTrue(TypeUtil.getAttributes(ocl.getEnvironment(), EcorePackage.Literals.ESTRING)
- .contains(feature));
- } catch (Exception e) {
- fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
- }
-
- // now, make sure that this definition was local to the OCL that
- // parsed it (that it is not shared via the standard library package)
- OCL localOCL = OCL.newInstance();
- OCL.Helper localHelper = localOCL.createOCLHelper();
- localHelper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getString());
-
- try {
- Collection<Choice> choices = localHelper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "self.");
-
- assertNotChoice(choices, ChoiceKind.PROPERTY, "reverse");
-
- localHelper.createQuery("self.reverse");
-
- fail("Should have failed to parse the undefined attribute");
- } catch (ParserException e) {
- // success!
- System.out.println("Got the expected exception: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * Tests the definition of additional operations on the metamodel's
- * representation of a primitive type for which OCL has a counterpart.
- */
- public void test_defOperationOnPrimitiveType_172782() {
- // context is the Ecore metamodel's EString data type
- helper.setContext(EcorePackage.Literals.ESTRING);
-
- try {
- EOperation feature = helper.defineOperation(
- "reversed() : String = " +
- "Sequence{1..size()}->sortedBy(i | -i)->iterate(i; s : String = '' |" +
- " s.concat(self.substring(i, i)))");
-
- // the other representation of 'String'
- helper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getString());
-
- Collection<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "self.");
-
- assertChoice(choices, ChoiceKind.OPERATION, "reversed");
-
- OCLExpression<EClassifier> expr = helper.createQuery(
- "self.reversed()");
-
- assertEquals(
- "ablE was i ere I saw elbA",
- ocl.evaluate("Able was I ere i saw Elba", expr));
-
- // verify that TypeUtil produces the correct result
- assertTrue(TypeUtil.getOperations(ocl.getEnvironment(), ocl.getEnvironment().getOCLStandardLibrary().getString())
- .contains(feature));
- assertTrue(TypeUtil.getOperations(ocl.getEnvironment(), EcorePackage.Literals.ESTRING)
- .contains(feature));
- } catch (Exception e) {
- fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
- }
-
- // now, make sure that this definition was local to the OCL that
- // parsed it (that it is not shared via the standard library package)
- OCL localOCL = OCL.newInstance();
- OCL.Helper localHelper = localOCL.createOCLHelper();
- localHelper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getString());
-
- try {
- Collection<Choice> choices = localHelper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "self.");
-
- assertNotChoice(choices, ChoiceKind.OPERATION, "reversed");
-
- localHelper.createQuery("self.reversed()");
-
- fail("Should have failed to parse the undefined operation");
- } catch (ParserException e) {
- // success!
- System.out.println("Got the expected exception: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * Tests the definition of additional attributes on an OCL pre-defined type.
- */
- public void test_defAttributeOnPredefinedType_172782() {
- // context is the predefined OCL String type
- helper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getString());
-
- try {
- EStructuralFeature feature = helper.defineAttribute(
- "reverse : String = " +
- "Sequence{1..size()}->sortedBy(i | -i)->iterate(i; s : String = '' |" +
- " s.concat(self.substring(i, i)))");
-
- // the other representation of 'String'
- helper.setContext(EcorePackage.Literals.ESTRING);
-
- Collection<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "self.");
-
- assertChoice(choices, ChoiceKind.PROPERTY, "reverse");
-
- OCLExpression<EClassifier> expr = helper.createQuery(
- "self.reverse");
-
- assertEquals(
- "ablE was i ere I saw elbA",
- ocl.evaluate("Able was I ere i saw Elba", expr));
-
- // verify that TypeUtil produces the correct result
- assertTrue(TypeUtil.getAttributes(ocl.getEnvironment(), ocl.getEnvironment().getOCLStandardLibrary().getString())
- .contains(feature));
- assertTrue(TypeUtil.getAttributes(ocl.getEnvironment(), EcorePackage.Literals.ESTRING)
- .contains(feature));
- } catch (Exception e) {
- fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
- }
-
- // now, make sure that this definition was local to the OCL that
- // parsed it (that it is not shared via the standard library package)
- OCL localOCL = OCL.newInstance();
- OCL.Helper localHelper = localOCL.createOCLHelper();
- localHelper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getString());
-
- try {
- Collection<Choice> choices = localHelper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "self.");
-
- assertNotChoice(choices, ChoiceKind.PROPERTY, "reverse");
-
- localHelper.createQuery("self.reverse");
-
- fail("Should have failed to parse the undefined attribute");
- } catch (ParserException e) {
- // success!
- System.out.println("Got the expected exception: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * Tests the definition of additional operations on an OCL pre-defined type.
- */
- public void test_defOperationOnPredefinedType_172782() {
- // context is the predefined OCL String type
- helper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getString());
-
- try {
- EOperation feature = helper.defineOperation(
- "reversed() : String = " +
- "Sequence{1..size()}->sortedBy(i | -i)->iterate(i; s : String = '' |" +
- " s.concat(self.substring(i, i)))");
-
- // the other representation of 'String'
- helper.setContext(EcorePackage.Literals.ESTRING);
-
- Collection<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "self.");
-
- assertChoice(choices, ChoiceKind.OPERATION, "reversed");
-
- OCLExpression<EClassifier> expr = helper.createQuery(
- "self.reversed()");
-
- assertEquals(
- "ablE was i ere I saw elbA",
- ocl.evaluate("Able was I ere i saw Elba", expr));
-
- // verify that TypeUtil produces the correct result
- assertTrue(TypeUtil.getOperations(ocl.getEnvironment(), ocl.getEnvironment().getOCLStandardLibrary().getString())
- .contains(feature));
- assertTrue(TypeUtil.getOperations(ocl.getEnvironment(), EcorePackage.Literals.ESTRING)
- .contains(feature));
- } catch (Exception e) {
- fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
- }
-
- // now, make sure that this definition was local to the OCL that
- // parsed it (that it is not shared via the standard library package)
- OCL localOCL = OCL.newInstance();
- OCL.Helper localHelper = localOCL.createOCLHelper();
- localHelper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getString());
-
- try {
- Collection<Choice> choices = localHelper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "self.");
-
- assertNotChoice(choices, ChoiceKind.OPERATION, "reversed");
-
- localHelper.createQuery("self.reversed()");
-
- fail("Should have failed to parse the undefined operation");
- } catch (ParserException e) {
- // success!
- System.out.println("Got the expected exception: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * Tests that the {@link UMLReflection} API provides the correct owner of an
- * additional operation.
- */
- public void test_defExpression_operation_owner() {
- helper.setContext(fruit);
-
- try {
- EOperation o = helper.defineOperation(
- "bestColor(c : Color) : Color = " +
- "if self.color = Color::black then c else self.color endif");
-
- UMLReflection<?, EClassifier, ?, ?, ?, ?, ?, ?, ?, ?> uml =
- ocl.getEnvironment().getUMLReflection();
-
- // sanity check
- assertSame(fruit, uml.getOwningClassifier(fruit_ripen));
-
- // check the owner of the additional operation
- assertSame(fruit, uml.getOwningClassifier(o));
- } catch (Exception e) {
- fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * Tests that the {@link UMLReflection} API provides the correct owner of an
- * additional attribute.
- */
- public void test_defExpression_attribute_owner() {
- helper.setContext(fruit);
-
- try {
- EStructuralFeature p = helper.defineAttribute(
- "isBlack : Boolean = " +
- "color = Color::black");
-
- UMLReflection<?, EClassifier, ?, ?, ?, ?, ?, ?, ?, ?> uml =
- ocl.getEnvironment().getUMLReflection();
-
- // sanity check
- assertSame(fruit, uml.getOwningClassifier(fruit_color));
-
- // check the owner of the additional operation
- assertSame(fruit, uml.getOwningClassifier(p));
- } catch (Exception e) {
- fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * Tests that when we define additional operations on the <code>OclAny</code>
- * type, they can be invoked on user model types.
- */
- public void test_def_operation_OclAny_192892() {
- // define an operation on OclAny
- helper.setContext(getOCLStandardLibrary().getOclAny());
-
- try {
- helper.defineOperation("isBlack() : Boolean = true");
- } catch (Exception e) {
- fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
- }
-
- // switch to context of a user model classifier
- helper.setContext(fruit);
-
- try {
- EObject instance = fruitFactory.create(apple);
- assertTrue(check(helper, instance, "self.isBlack()"));
- } catch (Exception e) {
- fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * Tests that when we define additional attributes on the <code>OclAny</code>
- * type, they can be invoked on user model types.
- */
- public void test_def_attribute_OclAny_192892() {
- // define an operation on OclAny
- helper.setContext(getOCLStandardLibrary().getOclAny());
-
- try {
- helper.defineAttribute("isBlack : Boolean = true");
- } catch (Exception e) {
- fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
- }
-
- // switch to context of a user model classifier
- helper.setContext(fruit);
-
- try {
- EObject instance = fruitFactory.create(apple);
- assertTrue(check(helper, instance, "self.isBlack"));
- } catch (Exception e) {
- fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
- }
- }
-
+
+ /**
+ * Tests the definition of additional attributes on the metamodel's
+ * representation of a primitive type for which OCL has a counterpart.
+ */
+ public void test_defAttributeOnPrimitiveType_172782() {
+ // context is the Ecore metamodel's EString data type
+ helper.setContext(EcorePackage.Literals.ESTRING);
+
+ try {
+ EStructuralFeature feature = helper.defineAttribute(
+ "reverse : String = " +
+ "Sequence{1..size()}->sortedBy(i | -i)->iterate(i; s : String = '' |" +
+ " s.concat(self.substring(i, i)))");
+
+ // the other representation of 'String'
+ helper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getString());
+
+ Collection<Choice> choices = helper.getSyntaxHelp(
+ ConstraintKind.INVARIANT, "self.");
+
+ assertChoice(choices, ChoiceKind.PROPERTY, "reverse");
+
+ OCLExpression<EClassifier> expr = helper.createQuery(
+ "self.reverse");
+
+ assertEquals(
+ "ablE was i ere I saw elbA",
+ ocl.evaluate("Able was I ere i saw Elba", expr));
+
+ // verify that TypeUtil produces the correct result
+ assertTrue(TypeUtil.getAttributes(ocl.getEnvironment(), ocl.getEnvironment().getOCLStandardLibrary().getString())
+ .contains(feature));
+ assertTrue(TypeUtil.getAttributes(ocl.getEnvironment(), EcorePackage.Literals.ESTRING)
+ .contains(feature));
+ } catch (Exception e) {
+ fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
+ }
+
+ // now, make sure that this definition was local to the OCL that
+ // parsed it (that it is not shared via the standard library package)
+ OCL localOCL = OCL.newInstance();
+ OCL.Helper localHelper = localOCL.createOCLHelper();
+ localHelper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getString());
+
+ try {
+ Collection<Choice> choices = localHelper.getSyntaxHelp(
+ ConstraintKind.INVARIANT, "self.");
+
+ assertNotChoice(choices, ChoiceKind.PROPERTY, "reverse");
+
+ localHelper.createQuery("self.reverse");
+
+ fail("Should have failed to parse the undefined attribute");
+ } catch (ParserException e) {
+ // success!
+ debugPrintln("Got the expected exception: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests the definition of additional operations on the metamodel's
+ * representation of a primitive type for which OCL has a counterpart.
+ */
+ public void test_defOperationOnPrimitiveType_172782() {
+ // context is the Ecore metamodel's EString data type
+ helper.setContext(EcorePackage.Literals.ESTRING);
+
+ try {
+ EOperation feature = helper.defineOperation(
+ "reversed() : String = " +
+ "Sequence{1..size()}->sortedBy(i | -i)->iterate(i; s : String = '' |" +
+ " s.concat(self.substring(i, i)))");
+
+ // the other representation of 'String'
+ helper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getString());
+
+ Collection<Choice> choices = helper.getSyntaxHelp(
+ ConstraintKind.INVARIANT, "self.");
+
+ assertChoice(choices, ChoiceKind.OPERATION, "reversed");
+
+ OCLExpression<EClassifier> expr = helper.createQuery(
+ "self.reversed()");
+
+ assertEquals(
+ "ablE was i ere I saw elbA",
+ ocl.evaluate("Able was I ere i saw Elba", expr));
+
+ // verify that TypeUtil produces the correct result
+ assertTrue(TypeUtil.getOperations(ocl.getEnvironment(), ocl.getEnvironment().getOCLStandardLibrary().getString())
+ .contains(feature));
+ assertTrue(TypeUtil.getOperations(ocl.getEnvironment(), EcorePackage.Literals.ESTRING)
+ .contains(feature));
+ } catch (Exception e) {
+ fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
+ }
+
+ // now, make sure that this definition was local to the OCL that
+ // parsed it (that it is not shared via the standard library package)
+ OCL localOCL = OCL.newInstance();
+ OCL.Helper localHelper = localOCL.createOCLHelper();
+ localHelper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getString());
+
+ try {
+ Collection<Choice> choices = localHelper.getSyntaxHelp(
+ ConstraintKind.INVARIANT, "self.");
+
+ assertNotChoice(choices, ChoiceKind.OPERATION, "reversed");
+
+ localHelper.createQuery("self.reversed()");
+
+ fail("Should have failed to parse the undefined operation");
+ } catch (ParserException e) {
+ // success!
+ debugPrintln("Got the expected exception: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests the definition of additional attributes on an OCL pre-defined type.
+ */
+ public void test_defAttributeOnPredefinedType_172782() {
+ // context is the predefined OCL String type
+ helper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getString());
+
+ try {
+ EStructuralFeature feature = helper.defineAttribute(
+ "reverse : String = " +
+ "Sequence{1..size()}->sortedBy(i | -i)->iterate(i; s : String = '' |" +
+ " s.concat(self.substring(i, i)))");
+
+ // the other representation of 'String'
+ helper.setContext(EcorePackage.Literals.ESTRING);
+
+ Collection<Choice> choices = helper.getSyntaxHelp(
+ ConstraintKind.INVARIANT, "self.");
+
+ assertChoice(choices, ChoiceKind.PROPERTY, "reverse");
+
+ OCLExpression<EClassifier> expr = helper.createQuery(
+ "self.reverse");
+
+ assertEquals(
+ "ablE was i ere I saw elbA",
+ ocl.evaluate("Able was I ere i saw Elba", expr));
+
+ // verify that TypeUtil produces the correct result
+ assertTrue(TypeUtil.getAttributes(ocl.getEnvironment(), ocl.getEnvironment().getOCLStandardLibrary().getString())
+ .contains(feature));
+ assertTrue(TypeUtil.getAttributes(ocl.getEnvironment(), EcorePackage.Literals.ESTRING)
+ .contains(feature));
+ } catch (Exception e) {
+ fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
+ }
+
+ // now, make sure that this definition was local to the OCL that
+ // parsed it (that it is not shared via the standard library package)
+ OCL localOCL = OCL.newInstance();
+ OCL.Helper localHelper = localOCL.createOCLHelper();
+ localHelper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getString());
+
+ try {
+ Collection<Choice> choices = localHelper.getSyntaxHelp(
+ ConstraintKind.INVARIANT, "self.");
+
+ assertNotChoice(choices, ChoiceKind.PROPERTY, "reverse");
+
+ localHelper.createQuery("self.reverse");
+
+ fail("Should have failed to parse the undefined attribute");
+ } catch (ParserException e) {
+ // success!
+ debugPrintln("Got the expected exception: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests the definition of additional operations on an OCL pre-defined type.
+ */
+ public void test_defOperationOnPredefinedType_172782() {
+ // context is the predefined OCL String type
+ helper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getString());
+
+ try {
+ EOperation feature = helper.defineOperation(
+ "reversed() : String = " +
+ "Sequence{1..size()}->sortedBy(i | -i)->iterate(i; s : String = '' |" +
+ " s.concat(self.substring(i, i)))");
+
+ // the other representation of 'String'
+ helper.setContext(EcorePackage.Literals.ESTRING);
+
+ Collection<Choice> choices = helper.getSyntaxHelp(
+ ConstraintKind.INVARIANT, "self.");
+
+ assertChoice(choices, ChoiceKind.OPERATION, "reversed");
+
+ OCLExpression<EClassifier> expr = helper.createQuery(
+ "self.reversed()");
+
+ assertEquals(
+ "ablE was i ere I saw elbA",
+ ocl.evaluate("Able was I ere i saw Elba", expr));
+
+ // verify that TypeUtil produces the correct result
+ assertTrue(TypeUtil.getOperations(ocl.getEnvironment(), ocl.getEnvironment().getOCLStandardLibrary().getString())
+ .contains(feature));
+ assertTrue(TypeUtil.getOperations(ocl.getEnvironment(), EcorePackage.Literals.ESTRING)
+ .contains(feature));
+ } catch (Exception e) {
+ fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
+ }
+
+ // now, make sure that this definition was local to the OCL that
+ // parsed it (that it is not shared via the standard library package)
+ OCL localOCL = OCL.newInstance();
+ OCL.Helper localHelper = localOCL.createOCLHelper();
+ localHelper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getString());
+
+ try {
+ Collection<Choice> choices = localHelper.getSyntaxHelp(
+ ConstraintKind.INVARIANT, "self.");
+
+ assertNotChoice(choices, ChoiceKind.OPERATION, "reversed");
+
+ localHelper.createQuery("self.reversed()");
+
+ fail("Should have failed to parse the undefined operation");
+ } catch (ParserException e) {
+ // success!
+ debugPrintln("Got the expected exception: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests that the {@link UMLReflection} API provides the correct owner of an
+ * additional operation.
+ */
+ public void test_defExpression_operation_owner() {
+ helper.setContext(fruit);
+
+ try {
+ EOperation o = helper.defineOperation(
+ "bestColor(c : Color) : Color = " +
+ "if self.color = Color::black then c else self.color endif");
+
+ UMLReflection<?, EClassifier, ?, ?, ?, ?, ?, ?, ?, ?> uml =
+ ocl.getEnvironment().getUMLReflection();
+
+ // sanity check
+ assertSame(fruit, uml.getOwningClassifier(fruit_ripen));
+
+ // check the owner of the additional operation
+ assertSame(fruit, uml.getOwningClassifier(o));
+ } catch (Exception e) {
+ fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests that the {@link UMLReflection} API provides the correct owner of an
+ * additional attribute.
+ */
+ public void test_defExpression_attribute_owner() {
+ helper.setContext(fruit);
+
+ try {
+ EStructuralFeature p = helper.defineAttribute(
+ "isBlack : Boolean = " +
+ "color = Color::black");
+
+ UMLReflection<?, EClassifier, ?, ?, ?, ?, ?, ?, ?, ?> uml =
+ ocl.getEnvironment().getUMLReflection();
+
+ // sanity check
+ assertSame(fruit, uml.getOwningClassifier(fruit_color));
+
+ // check the owner of the additional operation
+ assertSame(fruit, uml.getOwningClassifier(p));
+ } catch (Exception e) {
+ fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests that when we define additional operations on the <code>OclAny</code>
+ * type, they can be invoked on user model types.
+ */
+ public void test_def_operation_OclAny_192892() {
+ // define an operation on OclAny
+ helper.setContext(getOCLStandardLibrary().getOclAny());
+
+ try {
+ helper.defineOperation("isBlack() : Boolean = true");
+ } catch (Exception e) {
+ fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
+ }
+
+ // switch to context of a user model classifier
+ helper.setContext(fruit);
+
+ try {
+ EObject instance = fruitFactory.create(apple);
+ assertTrue(check(helper, instance, "self.isBlack()"));
+ } catch (Exception e) {
+ fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests that when we define additional attributes on the <code>OclAny</code>
+ * type, they can be invoked on user model types.
+ */
+ public void test_def_attribute_OclAny_192892() {
+ // define an operation on OclAny
+ helper.setContext(getOCLStandardLibrary().getOclAny());
+
+ try {
+ helper.defineAttribute("isBlack : Boolean = true");
+ } catch (Exception e) {
+ fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
+ }
+
+ // switch to context of a user model classifier
+ helper.setContext(fruit);
+
+ try {
+ EObject instance = fruitFactory.create(apple);
+ assertTrue(check(helper, instance, "self.isBlack"));
+ } catch (Exception e) {
+ fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
+ }
+ }
+
/**
* Tests def expression for an operations with multiple parameters of
* the same type.
*/
public void test_defExpression_operation_similarParams_238050() {
helper.setContext(fruit);
-
+
try {
helper.defineOperation(
- "displayName(first : String, last : String) : String = " +
+ "displayName(first : String, last : String) : String = " +
"if self.color = Color::red then first else last endif");
-
+
OCLExpression<EClassifier> expr = helper.createQuery(
"self.displayName('Roger', 'Bacon')");
-
+
EObject anApple = fruitFactory.create(apple);
anApple.eSet(fruit_color, color_black);
-
+
assertEquals("Bacon", ocl.evaluate(anApple, expr));
-
+
anApple.eSet(fruit_color, color_red);
-
+
assertEquals("Roger", ocl.evaluate(anApple, expr));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/DelegatesTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/DelegatesTest.java
index 39dc7bb..1d278f9 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/DelegatesTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/DelegatesTest.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* C.Damus, K.Hussey, E.D.Willink - Initial API and implementation
* E.D.Willink - Bug 306079, 322159, 353171
@@ -98,7 +98,7 @@
@SuppressWarnings("nls")
public class DelegatesTest extends AbstractTestSuite
{
- protected static final String COMPANY_XMI = "/model/Company.xmi";
+ protected static final String COMPANY_XMI = "/model/Company.xmi";
protected static final String NO_REFLECTION_COMPANY_XMI = "/model/NoReflectionCompany.xmi";
protected static final String MODEL_WITH_ERRORS_XMI = "/model/ModelWithErrors.xmi";
@@ -136,8 +136,8 @@
eclipseIsRunning = EMFPlugin.IS_ECLIPSE_RUNNING;
usedLocalRegistry = false;
- initializeResourceSet(OCLConstants.OCL_DELEGATE_URI_LPG);
- OCLDelegateDomain.initializeMappingFrom(null, OCLConstants.OCL_DELEGATE_URI);
+ initializeResourceSet(OCLConstants.OCL_DELEGATE_URI_LPG);
+ OCLDelegateDomain.initializeMappingFrom(null, OCLConstants.OCL_DELEGATE_URI);
}
protected void initializeResourceSet(String oclDelegateURI) {
@@ -151,8 +151,8 @@
QueryDelegate.Factory.Registry.INSTANCE.put(oclDelegateURI,
new OCLQueryDelegateFactory.Global());
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(
- "xmi", new EcoreResourceFactoryImpl());
- EPackage.Registry.INSTANCE.remove(CompanyPackage.eNS_URI); // Reference and nullify the side effect of the reference
+ "xmi", new EcoreResourceFactoryImpl());
+ EPackage.Registry.INSTANCE.remove(CompanyPackage.eNS_URI); // Reference and nullify the side effect of the reference
resourceSet.getPackageRegistry().remove(CompanyPackage.eNS_URI); // In case previous test failed
EPackage.Registry.INSTANCE.remove(NoreflectioncompanyPackage.eNS_URI); // Reference and nullify the side effect of the reference
resourceSet.getPackageRegistry().remove(NoreflectioncompanyPackage.eNS_URI); // In case previous test failed
@@ -163,13 +163,13 @@
// Install a local DelegateDomain.Factory
DelegateDomain.Factory.Registry.Impl delegateDomainFactory =
- new DelegateDomain.Factory.Registry.Impl();
+ new DelegateDomain.Factory.Registry.Impl();
delegateDomainFactory.put(oclDelegateURI, new OCLDelegateDomainFactory());
adapter.putRegistry(DelegateDomain.Factory.Registry.class, delegateDomainFactory);
-
+
// Install a local ValidationDelegate.Factory
ValidationDelegate.Factory.Registry validationDelegateFactoryRegistry =
- new ValidationDelegate.Factory.Registry.Impl();
+ new ValidationDelegate.Factory.Registry.Impl();
validationDelegateFactoryRegistry.put(oclDelegateURI, new OCLValidationDelegateFactory(oclDelegateURI) {
@Override
@@ -177,13 +177,13 @@
usedLocalRegistry = true;
return super.createValidationDelegate(classifier);
}
-
+
});
adapter.putRegistry(ValidationDelegate.Factory.Registry.class, validationDelegateFactoryRegistry);
// Install a local SettingDelegate.Factory
EStructuralFeature.Internal.SettingDelegate.Factory.Registry settingDelegateFactoryRegistry =
- new EStructuralFeature.Internal.SettingDelegate.Factory.Registry.Impl();
+ new EStructuralFeature.Internal.SettingDelegate.Factory.Registry.Impl();
settingDelegateFactoryRegistry.put(oclDelegateURI, new OCLSettingDelegateFactory(oclDelegateURI) {
@Override
@@ -191,26 +191,26 @@
usedLocalRegistry = true;
return super.createSettingDelegate(structuralFeature);
}
-
+
});
adapter.putRegistry(EStructuralFeature.Internal.SettingDelegate.Factory.Registry.class, settingDelegateFactoryRegistry);
// Install a local InvocationDelegate.Factory
EOperation.Internal.InvocationDelegate.Factory.Registry invocationDelegateFactoryRegistry =
- new EOperation.Internal.InvocationDelegate.Factory.Registry.Impl();
+ new EOperation.Internal.InvocationDelegate.Factory.Registry.Impl();
invocationDelegateFactoryRegistry.put(oclDelegateURI, new OCLInvocationDelegateFactory(oclDelegateURI) {
@Override
public InvocationDelegate createInvocationDelegate(EOperation operation) {
usedLocalRegistry = true;
return super.createInvocationDelegate(operation);
}
-
+
});
- adapter.putRegistry(EOperation.Internal.InvocationDelegate.Factory.Registry.class, invocationDelegateFactoryRegistry);
+ adapter.putRegistry(EOperation.Internal.InvocationDelegate.Factory.Registry.class, invocationDelegateFactoryRegistry);
// Install a local QueryDelegate.Factory
QueryDelegate.Factory.Registry queryDelegateFactoryRegistry =
- new QueryDelegate.Factory.Registry.Impl();
+ new QueryDelegate.Factory.Registry.Impl();
queryDelegateFactoryRegistry.put(oclDelegateURI, new OCLQueryDelegateFactory(oclDelegateURI) {
@Override
public QueryDelegate createQueryDelegate(EClassifier context,
@@ -224,7 +224,7 @@
protected void initModel(String testModelName) {
URI uri = getTestModelURI(testModelName);
testResource = resourceSet.getResource(uri, true);
-
+
acme = testResource.getContents().get(0);
companyClass = acme.eClass();
@@ -233,17 +233,17 @@
companyName = (EAttribute) companyClass.getEStructuralFeature("name");
companyEmployees = (EReference) companyClass
- .getEStructuralFeature("employees");
+ .getEStructuralFeature("employees");
companySize = (EAttribute) companyClass.getEStructuralFeature("size");
employeeClass = companyEmployees.getEReferenceType();
employeeName = (EAttribute) employeeClass.getEStructuralFeature("name");
employeeManager = (EReference) employeeClass
- .getEStructuralFeature("manager");
+ .getEStructuralFeature("manager");
employeeDirectReports = (EReference) employeeClass
- .getEStructuralFeature("directReports");
+ .getEStructuralFeature("directReports");
employeeAllReports = (EReference) employeeClass
- .getEStructuralFeature("allReports");
+ .getEStructuralFeature("allReports");
employeeReportsTo = getOperation(employeeClass, "reportsTo");
sizeKind = (EEnum) companySize.getEAttributeType();
@@ -296,7 +296,7 @@
EObject employee = create(acme, companyEmployees, employeeClass, null);
set(employee, employeeManager, employee("Bob"));
validateConstraintWithError("mustHaveName", employee);
-
+
set(employee, employeeName, "Joe");
validateWithoutError(employee);
@@ -372,7 +372,7 @@
initModel(modelName);
QueryDelegate.Factory factory = QueryDelegate.Factory.Registry.INSTANCE
- .getFactory(OCLConstants.OCL_DELEGATE_URI_LPG);
+ .getFactory(OCLConstants.OCL_DELEGATE_URI_LPG);
String n = "n";
String expression = "self.employees->select(employee | employee.manager <> null and employee.manager.name = n)";
@@ -420,7 +420,7 @@
initModel(modelName);
QueryDelegate.Factory factory = QueryDelegate.Factory.Registry.INSTANCE
- .getFactory(OCLConstants.OCL_DELEGATE_URI_LPG);
+ .getFactory(OCLConstants.OCL_DELEGATE_URI_LPG);
String okName = "ok";
String badName = "xyzzy";
@@ -435,7 +435,7 @@
//
delegate = factory.createQueryDelegate(companyClass, null, "n=");
executeWithException(delegate, amy, null,
- "2:2:2:2 \"relationalNotLetCS\" expected after \"=\"");
+ "2:2:2:2 \"relationalNotLetCS\" expected after \"=\"");
//
// Undeclared variable
//
@@ -552,7 +552,7 @@
* Ensures that {@link InvocationBehavior#getOperationBody(OCL, EOperation)}
* consistently returns <code>null</code> for stdlib operations that don't
* have a body defined at all instead of returning an <code>invalid</code> literal.
- * @throws ParserException
+ * @throws ParserException
*/
public void test_attributeNotDefinedInOCLRemainsNull() throws ParserException {
helper.setContext(EcorePackage.eINSTANCE.getEClassifier());
@@ -616,8 +616,8 @@
/**
* Caches an operation AST in the annotation used by the {@link SettingBehavior} implementation
* and ensures that it's used by the delegate as well as the {@link EvaluationVisitorImpl}
- * @throws ParserException
- * @throws InvocationTargetException
+ * @throws ParserException
+ * @throws InvocationTargetException
*/
public void test_eReferenceDerivationUsedFromCache() throws ParserException, InvocationTargetException {
initModel(COMPANY_XMI);
@@ -674,7 +674,7 @@
Object o = sup2Obj.eInvoke(getUnrelated, null);
assertEquals(unrelatedObj, o);
}
-
+
public static class LocalOppositeEndFinder extends DefaultOppositeEndFinder {
public static boolean localOppositeEndFinderUsed = false;
public LocalOppositeEndFinder(Registry registry) {
@@ -682,7 +682,7 @@
localOppositeEndFinderUsed = true;
}
}
-
+
public static class LocalEnvironmentFactory extends EcoreEnvironmentFactoryWithHiddenOpposites {
public static boolean localEnvironmentFactoryUsed = false;
public LocalEnvironmentFactory(Registry registry) {
@@ -727,7 +727,7 @@
initPackageRegistrations();
initModel(COMPANY_XMI);
EAnnotation annotation = OCLCommon.getDelegateAnnotation(employeeClass);
-
+
DiagnosticChain diagnostics = new BasicDiagnostic();
// first ensure that contents are padded up to where we need it:
assertTrue("Expecting \"Amy\" to be a valid name",
@@ -751,7 +751,7 @@
ValidationBehavior.INSTANCE.cacheOCLExpression(employeeClass, constraintName, null);
}
}
-
+
public void test_invariantCachingForFirst() {
initPackageRegistrations();
initModel(COMPANY_XMI);
@@ -762,7 +762,7 @@
assertTrue("Expected to find compiled expression in cache",
cached != null && !ValidationBehavior.isNoOCLDefinition(cached));
}
-
+
public void test_invariantCachingForSecond() {
initPackageRegistrations();
initModel(COMPANY_XMI);
@@ -773,7 +773,7 @@
assertTrue("Expected to find compiled expression in cache",
cached != null && !ValidationBehavior.isNoOCLDefinition(cached));
}
-
+
public void test_invariantValidation() {
doTest_invariantValidation(COMPANY_XMI, true);
assertEquals(!eclipseIsRunning, usedLocalRegistry);
@@ -864,7 +864,7 @@
* Ensures that {@link InvocationBehavior#getOperationBody(OCL, EOperation)}
* consistently returns <code>null</code> for stdlib operations that don't
* have a body defined at all instead of returning an <code>invalid</code> literal.
- * @throws ParserException
+ * @throws ParserException
*/
public void test_operationDefinedInStdlibBodyRemainsNull() throws ParserException {
helper.setContext(EcorePackage.eINSTANCE.getEClassifier());
@@ -878,16 +878,16 @@
OCLExpression bodyStillNull = InvocationBehavior.INSTANCE.getOperationBody((OCL) ocl, o);;
assertTrue(bodyStillNull == null || InvocationBehavior.isNoOCLDefinition(bodyStillNull));
}
-
+
/**
* Caches an operation AST in the annotation used by the {@link InvocationBehavior} implementation
* and ensures that it's used by the delegate as well as the {@link EvaluationVisitorImpl}.
* Implicitly, the test ensures that no modification is applied to the original textual annotation,
* so that the annotation's contents are <em>not</em> used to cache the compiled AST because that
* may make some clients expecting the metamodel resources to remain unchanged angry.
- *
- * @throws ParserException
- * @throws InvocationTargetException
+ *
+ * @throws ParserException
+ * @throws InvocationTargetException
*/
public void test_operationUsedFromCache() throws ParserException, InvocationTargetException {
initModel(COMPANY_XMI);
@@ -914,7 +914,7 @@
InvocationBehavior.INSTANCE.cacheOCLExpression(reportsToOp, null);
}
}
-
+
public void test_performanceOfCacheRetrieval() throws ParserException {
initModel(COMPANY_XMI);
EObject manager = companyFactory.create(employeeClass);
@@ -933,7 +933,7 @@
ocl.evaluate(employee, expr);
}
long end = System.currentTimeMillis();
- System.out.println("Executing " + expression + " " + TIMES
+ debugPrintln("Executing " + expression + " " + TIMES
+ " times took " + (end - start) + "ms");
}
}
@@ -965,7 +965,7 @@
*/
public void test_queryExecution_Bug353171() {
QueryDelegate.Factory factory = QueryDelegate.Factory.Registry.INSTANCE
- .getFactory(OCLConstants.OCL_DELEGATE_URI_LPG);
+ .getFactory(OCLConstants.OCL_DELEGATE_URI_LPG);
String n = "n";
String expression = "self.name";
Library library = EXTLibraryFactory.eINSTANCE.createLibrary();
@@ -988,7 +988,7 @@
EObject badClassInstance = create(acme, companyDetritus, badClassClass, null);
validateConstraintWithError("MissingConstraint", badClassInstance);
} */
-
+
/**
* EObjectValidator .validateDelegatedConstraints just skips over null bodies.
*
@@ -997,7 +997,7 @@
EObject badClassInstance = create(acme, companyDetritus, (EClass) companyPackage.getEClassifier("MissingConstraintBody"), null);
validateConstraintWithError("MissingConstraint", badClassInstance);
} */
-
+
public void test_validationEvaluatingToInvalid() {
initModelWithErrors();
EObject badClassInstance = create(acme, companyDetritus, (EClass) companyPackage.getEClassifier("ValidationEvaluatingToInvalid"), null);
@@ -1006,7 +1006,7 @@
"evaluatingToInvalid", EObjectValidator.getObjectLabel(badClassInstance, context), message,
org.eclipse.ocl.ecore.delegate.OCLDelegateException.class.getName());
}
-
+
public void test_validationEvaluatingToNull() {
initModelWithErrors();
EObject badClassInstance = create(acme, companyDetritus, (EClass) companyPackage.getEClassifier("ValidationEvaluatingToNull"), null);
@@ -1015,7 +1015,7 @@
"evaluatingToNull", EObjectValidator.getObjectLabel(badClassInstance, context), message,
org.eclipse.ocl.ecore.delegate.OCLDelegateException.class.getName());
}
-
+
public void test_validationEvaluatingToWrongType() {
initModelWithErrors();
EObject badClassInstance = create(acme, companyDetritus, (EClass) companyPackage.getEClassifier("ValidationEvaluatingToWrongType"), null);
@@ -1024,7 +1024,7 @@
"evaluatingToWrongType", EObjectValidator.getObjectLabel(badClassInstance, context), message,
org.eclipse.ocl.ecore.delegate.OCLDelegateException.class.getName());
}
-
+
public void test_validationParsingToLexicalError() {
initModelWithErrors();
EObject badClassInstance = create(acme, companyDetritus, (EClass) companyPackage.getEClassifier("ValidationParsingToLexicalError"), null);
@@ -1033,7 +1033,7 @@
"parsingToLexicalError", EObjectValidator.getObjectLabel(badClassInstance, context), message,
org.eclipse.ocl.ecore.delegate.OCLDelegateException.class.getName());
}
-
+
public void test_validationParsingToSemanticError() {
initModelWithErrors();
EObject badClassInstance = create(acme, companyDetritus, (EClass) companyPackage.getEClassifier("ValidationParsingToSemanticError"), null);
@@ -1042,7 +1042,7 @@
"parsingToSemanticError", EObjectValidator.getObjectLabel(badClassInstance, context), message,
org.eclipse.ocl.ecore.delegate.OCLDelegateException.class.getName());
}
-
+
public void test_validationParsingToSyntacticError() {
initModelWithErrors();
EObject badClassInstance = create(acme, companyDetritus, (EClass) companyPackage.getEClassifier("ValidationParsingToSyntacticError"), null);
@@ -1130,15 +1130,15 @@
} catch (OCLDelegateException e) {
assertEquals("OCLDelegateException: ", expectedMessage, e.getLocalizedMessage());
}
- }
+ }
@SuppressWarnings("unchecked")
<T> T invoke(EObject target, EOperation operation, Object... arguments) {
try {
return (T) target.eInvoke(operation, (arguments.length == 0)
? ECollections.<Object> emptyEList()
- : new BasicEList.UnmodifiableEList<Object>(arguments.length,
- arguments));
+ : new BasicEList.UnmodifiableEList<Object>(arguments.length,
+ arguments));
} catch (InvocationTargetException ite) {
fail("Failed to invoke operation: " + ite.getLocalizedMessage());
return null;
@@ -1198,8 +1198,8 @@
String name(EObject employeeOrCompany) {
EAttribute name = employeeClass.isInstance(employeeOrCompany)
- ? employeeName
- : companyName;
+ ? employeeName
+ : companyName;
return get(employeeOrCompany, name);
}
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/DocumentationExamples.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/DocumentationExamples.java
index bc26605..6185422 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/DocumentationExamples.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/DocumentationExamples.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* E.D.Willink - Initial API and implementation
*******************************************************************************/
@@ -58,7 +58,7 @@
URL url = new URL(uri.toString());
return url.openStream();
}
-
+
private List<Library> getLibraries() {
return Collections.emptyList();
}
@@ -70,7 +70,7 @@
library.getBooks().add(aBook);
return library;
}
-
+
/*
* This 'test' provides the source text for the 'Parsing OCL Document' example
* in org.eclipse.ocl.doc/doc/5120-parsing-constraints.textile
@@ -87,17 +87,17 @@
helper.setContext(EXTLibraryPackage.Literals.LIBRARY);
Constraint invariant = helper.createInvariant(
- "books->forAll(b1, b2 | b1 <> b2 implies b1.title <> b2.title)");
-
+ "books->forAll(b1, b2 | b1 <> b2 implies b1.title <> b2.title)");
+
OCLExpression<EClassifier> query = helper.createQuery(
- "books->collect(b : Book | b.category)->asSet()");
+ "books->collect(b : Book | b.category)->asSet()");
EOperation oper = null;
for (EOperation next : EcorePackage.Literals.EMODEL_ELEMENT.getEOperations()) {
- if ("getEAnnotation".equals(next.getName())) {
- oper = next;
- break;
- }
+ if ("getEAnnotation".equals(next.getName())) {
+ oper = next;
+ break;
+ }
}
// define a post-condition specifying the value of EModelElement::getEAnnotation(EString).
@@ -105,19 +105,19 @@
// parameters (in this case, only "source : String") and the operation result
helper.setOperationContext(EcorePackage.Literals.ECLASS, oper);
Constraint body = helper.createPostcondition(
- "result = self.eAnnotations->any(ann | ann.source = source)");
+ "result = self.eAnnotations->any(ann | ann.source = source)");
// define a derivation constraint for the EReference::eReferenceType property
helper.setAttributeContext(
- EcorePackage.Literals.EREFERENCE,
- EcorePackage.Literals.EREFERENCE__EREFERENCE_TYPE);
+ EcorePackage.Literals.EREFERENCE,
+ EcorePackage.Literals.EREFERENCE__EREFERENCE_TYPE);
Constraint derive = helper.createDerivedValueExpression(
- "self.eType->any(true).oclAsType(EClass)");
-
+ "self.eType->any(true).oclAsType(EClass)");
+
if ((body == derive) && (invariant == query)) { /* the yellow markers go away */ }
}
-
-
+
+
/*
* This 'test' provides the source text for the 'Parsing OCL Document' example
* in org.eclipse.ocl.doc/doc/5115-evaluating-constraints.textile
@@ -128,9 +128,9 @@
helper.setContext(EXTLibraryPackage.Literals.LIBRARY);
Constraint invariant = helper.createInvariant(
- "books->forAll(b1, b2 | b1 <> b2 implies b1.title <> b2.title)");
+ "books->forAll(b1, b2 | b1 <> b2 implies b1.title <> b2.title)");
OCLExpression<EClassifier> query = helper.createQuery(
- "books->collect(b : Book | b.category)->asSet()");
+ "books->collect(b : Book | b.category)->asSet()");
// create a Query to evaluate our query expression
Query queryEval = ocl.createQuery(query);
@@ -142,31 +142,31 @@
// only print the set of book categories for valid libraries
for (Library next : libraries) {
- if (constraintEval.check(next)) {
- // the OCL result type of our query expression is Set(BookCategory)
- @SuppressWarnings("unchecked")
- Set<BookCategory> categories = (Set<BookCategory>) queryEval.evaluate(next);
-
- System.out.printf("%s: %s%n", next.getName(), categories);
- }
+ if (constraintEval.check(next)) {
+ // the OCL result type of our query expression is Set(BookCategory)
+ @SuppressWarnings("unchecked")
+ Set<BookCategory> categories = (Set<BookCategory>) queryEval.evaluate(next);
+
+ if (!noDebug) System.out.printf("%s: %s\n", next.getName(), categories);
+ }
}
// Check one
-
+
// check a single library
Library lib = getLibrary(); // hypothetical source of a library
// check whether it satisfies the constraint
- System.out.printf("%s valid: %b", lib.getName(), ocl.check(lib, invariant));
+ if (!noDebug) System.out.printf("%s valid: %b\n", lib.getName(), ocl.check(lib, invariant));
// MoreSuccinct
// only print the set of book categories for valid libraries
for (Library next : constraintEval.select(libraries)) {
- @SuppressWarnings("unchecked")
- Set<BookCategory> categories = (Set<BookCategory>) queryEval.evaluate(next);
-
- System.out.printf("%s: %s%n", next.getName(), categories);
+ @SuppressWarnings("unchecked")
+ Set<BookCategory> categories = (Set<BookCategory>) queryEval.evaluate(next);
+
+ if (!noDebug) System.out.printf("%s: %s%n", next.getName(), categories);
}
}
@@ -190,17 +190,17 @@
// parse the contents as an OCL document
try {
- OCLInput document = new OCLInput(in);
-
- List<Constraint> constraints = ocl.parse(document);
- for (Constraint next : constraints) {
- constraintMap.put(next.getName(), next);
-
- OCLExpression<EClassifier> body = next.getSpecification().getBodyExpression();
- System.out.printf("%s: %s%n", next.getName(), body);
- }
+ OCLInput document = new OCLInput(in);
+
+ List<Constraint> constraints = ocl.parse(document);
+ for (Constraint next : constraints) {
+ constraintMap.put(next.getName(), next);
+
+ OCLExpression<EClassifier> body = next.getSpecification().getBodyExpression();
+ if (!noDebug) System.out.printf("%s: %s%n", next.getName(), body);
+ }
} finally {
- in.close();
+ in.close();
}
//-------------------------------------------------------------------------
// Accessing the Constraints
@@ -214,22 +214,22 @@
// use the getBooks() additional operation to find a book
helper.setContext(EXTLibraryPackage.Literals.LIBRARY);
OCLExpression<EClassifier> query = helper.createQuery(
- "getBooks('Bleak House')->asSequence()->first()");
+ "getBooks('Bleak House')->asSequence()->first()");
Book book = (Book) ocl.evaluate(library, query);
- System.out.printf("Got book: %s%n", book);
+ if (!noDebug) System.out.printf("Got book: %s%n", book);
// use the unique_title constraint to validate the book
- System.out.printf("Validate book: %b%n",
- ocl.check(book, constraintMap.get("unique_title")));
+ if (!noDebug) System.out.printf("Validate book: %b%n",
+ ocl.check(book, constraintMap.get("unique_title")));
}
-
+
private class MyOppositeEndFinder extends DefaultOppositeEndFinder {
public MyOppositeEndFinder() {
super(EPackage.Registry.INSTANCE);
}
}
-
+
/**
* The following is documented in doc/org.eclipse.ocl.doc/doc/5160-customization.textile
* in section "Customizing Hidden Opposite Lookup and Navigation"
@@ -237,7 +237,7 @@
public void testCustomizingOppositeEndFinder() {
OppositeEndFinder oef = new MyOppositeEndFinder();
OCL ocl = OCL.newInstance(new EcoreEnvironmentFactoryWithHiddenOpposites(
- EPackage.Registry.INSTANCE, oef));
+ EPackage.Registry.INSTANCE, oef));
assertSame(oef, ((EcoreEnvironment) ocl.getEnvironment()).getOppositeEndFinder());
}
}
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ExpressionsValidatorTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ExpressionsValidatorTest.java
index 52dc3d3..0106d41 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ExpressionsValidatorTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ExpressionsValidatorTest.java
@@ -67,291 +67,291 @@
public class ExpressionsValidatorTest extends AbstractTestSuite {
private final EcoreFactory factory = EcoreFactory.eINSTANCE;
-
+
public void test_BooleanLiteralExp_checkBooleanType() {
BooleanLiteralExp bl = factory.createBooleanLiteralExp();
bl.setBooleanSymbol(true);
bl.setType(apple);
-
+
assertProblem(bl, ExpressionsValidator.BOOLEAN_LITERAL_EXP__BOOLEAN_TYPE);
-
+
bl.setType(getOCLStandardLibrary().getInteger());
-
+
assertProblem(bl, ExpressionsValidator.BOOLEAN_LITERAL_EXP__BOOLEAN_TYPE);
-
+
bl.setType(getOCLStandardLibrary().getBoolean());
-
+
assertOK(bl, ExpressionsValidator.BOOLEAN_LITERAL_EXP__BOOLEAN_TYPE);
}
-
+
public void test_CollectionItem_checkItemType() {
CollectionItem i = factory.createCollectionItem();
CollectionType ctype = factory.createCollectionType();
ctype.setElementType(fruit);
i.setType(ctype);
-
+
CollectionLiteralExp item = factory.createCollectionLiteralExp();
CollectionType itemType = factory.createCollectionType();
itemType.setElementType(apple);
item.setType(itemType);
-
+
i.setItem(item);
-
+
assertProblem(i, ExpressionsValidator.COLLECTION_ITEM__ITEM_TYPE);
-
+
item.setType(ctype);
-
+
assertOK(i, ExpressionsValidator.COLLECTION_ITEM__ITEM_TYPE);
}
-
+
public void test_CollectionLiteralExp_checkNoCollectionInstances() {
CollectionLiteralExp cl = factory.createCollectionLiteralExp();
cl.setKind(CollectionKind.COLLECTION_LITERAL);
-
+
assertProblem(cl, ExpressionsValidator.COLLECTION_LITERAL_EXP__NO_COLLECTION_INSTANCES);
-
+
cl.setKind(CollectionKind.BAG_LITERAL);
-
+
assertOK(cl, ExpressionsValidator.COLLECTION_LITERAL_EXP__NO_COLLECTION_INSTANCES);
}
-
+
public void test_CollectionLiteralExp_checkSetKind() {
CollectionLiteralExp cl = factory.createCollectionLiteralExp();
cl.setKind(CollectionKind.COLLECTION_LITERAL);
cl.setType(factory.createBagType());
-
+
assertOK(cl, ExpressionsValidator.COLLECTION_LITERAL_EXP__SET_KIND);
-
+
cl.setKind(CollectionKind.SET_LITERAL);
-
+
assertProblem(cl, ExpressionsValidator.COLLECTION_LITERAL_EXP__SET_KIND);
-
+
cl.setType(factory.createSetType());
-
+
assertOK(cl, ExpressionsValidator.COLLECTION_LITERAL_EXP__SET_KIND);
}
-
+
public void test_CollectionLiteralExp_checkSequenceKind() {
CollectionLiteralExp cl = factory.createCollectionLiteralExp();
cl.setKind(CollectionKind.COLLECTION_LITERAL);
cl.setType(factory.createBagType());
-
+
assertOK(cl, ExpressionsValidator.COLLECTION_LITERAL_EXP__SEQUENCE_KIND);
-
+
cl.setKind(CollectionKind.SEQUENCE_LITERAL);
-
+
assertProblem(cl, ExpressionsValidator.COLLECTION_LITERAL_EXP__SEQUENCE_KIND);
-
+
cl.setType(factory.createSequenceType());
-
+
assertOK(cl, ExpressionsValidator.COLLECTION_LITERAL_EXP__SEQUENCE_KIND);
}
-
+
public void test_CollectionLiteralExp_checkBagKind() {
CollectionLiteralExp cl = factory.createCollectionLiteralExp();
cl.setKind(CollectionKind.COLLECTION_LITERAL);
cl.setType(factory.createSetType());
-
+
assertOK(cl, ExpressionsValidator.COLLECTION_LITERAL_EXP__BAG_KIND);
-
+
cl.setKind(CollectionKind.BAG_LITERAL);
-
+
assertProblem(cl, ExpressionsValidator.COLLECTION_LITERAL_EXP__BAG_KIND);
-
+
cl.setType(factory.createBagType());
-
+
assertOK(cl, ExpressionsValidator.COLLECTION_LITERAL_EXP__BAG_KIND);
}
-
+
public void test_CollectionLiteralExp_checkElementType() {
CollectionLiteralExp cl = factory.createCollectionLiteralExp();
cl.setKind(CollectionKind.SET_LITERAL);
CollectionType ctype = factory.createSetType();
ctype.setElementType(fruit);
cl.setType(ctype);
-
+
CollectionItem item1 = factory.createCollectionItem();
item1.setType(apple);
CollectionItem item2 = factory.createCollectionItem();
item2.setType(color);
-
+
cl.getPart().add(item1);
cl.getPart().add(item2);
-
+
assertProblem(cl, ExpressionsValidator.COLLECTION_LITERAL_EXP__ELEMENT_TYPE);
-
+
item2.setType(fruit);
-
+
assertOK(cl, ExpressionsValidator.COLLECTION_LITERAL_EXP__ELEMENT_TYPE);
}
-
+
public void test_CollectionLiteralExp_checkElementType_emptySet() {
CollectionLiteralExp cl = factory.createCollectionLiteralExp();
cl.setKind(CollectionKind.SET_LITERAL);
CollectionType ctype = factory.createSetType();
ctype.setElementType(fruit);
cl.setType(ctype);
-
+
assertProblem(cl, ExpressionsValidator.COLLECTION_LITERAL_EXP__ELEMENT_TYPE);
-
+
ctype.setElementType(getOCLStandardLibrary().getOclVoid());
-
+
assertOK(cl, ExpressionsValidator.COLLECTION_LITERAL_EXP__ELEMENT_TYPE);
}
-
+
public void test_CollectionRange_checkRangeType() {
CollectionRange r = factory.createCollectionRange();
r.setType(fruit);
-
+
IntegerLiteralExp first = factory.createIntegerLiteralExp();
first.setType(apple);
TupleLiteralExp last = factory.createTupleLiteralExp();
last.setType(color);
-
+
r.setFirst(first);
r.setLast(last);
-
+
assertProblem(r, ExpressionsValidator.COLLECTION_RANGE__RANGE_TYPE);
-
+
last.setType(fruit);
-
+
assertOK(r, ExpressionsValidator.COLLECTION_RANGE__RANGE_TYPE);
}
-
+
public void test_EnumLiteralExp_checkEnumType() {
EnumLiteralExp el = factory.createEnumLiteralExp();
el.setType(fruit);
el.setReferredEnumLiteral(color_red);
-
+
assertProblem(el, ExpressionsValidator.ENUM_LITERAL_EXP__ENUM_TYPE);
-
+
el.setType(color);
-
+
assertOK(el, ExpressionsValidator.ENUM_LITERAL_EXP__ENUM_TYPE);
}
-
+
public void test_IfExp_checkBooleanCondition() {
IfExp ie = factory.createIfExp();
OCLExpression cond = factory.createBooleanLiteralExp();
cond.setType(getOCLStandardLibrary().getInteger());
-
+
ie.setCondition(cond);
-
+
assertProblem(ie, ExpressionsValidator.IF_EXP__BOOLEAN_CONDITION);
-
+
cond.setType(getOCLStandardLibrary().getBoolean());
-
+
assertOK(ie, ExpressionsValidator.IF_EXP__BOOLEAN_CONDITION);
}
-
+
public void test_IfExp_checkIfType() {
IfExp ie = factory.createIfExp();
ie.setType(fruit);
-
+
OCLExpression thenPart = factory.createBooleanLiteralExp();
thenPart.setType(apple);
OCLExpression elsePart = factory.createTupleLiteralExp();
elsePart.setType(color);
-
+
ie.setThenExpression(thenPart);
ie.setElseExpression(elsePart);
-
+
assertProblem(ie, ExpressionsValidator.IF_EXP__IF_TYPE);
-
+
elsePart.setType(fruit);
-
+
assertOK(ie, ExpressionsValidator.IF_EXP__IF_TYPE);
}
-
+
public void test_IntegerLiteralExp_checkIntegerType() {
IntegerLiteralExp il = factory.createIntegerLiteralExp();
il.setLongSymbol(42L);
il.setType(apple);
-
+
assertProblem(il, ExpressionsValidator.INTEGER_LITERAL_EXP__INTEGER_TYPE);
-
+
il.setType(getOCLStandardLibrary().getBoolean());
-
+
assertProblem(il, ExpressionsValidator.INTEGER_LITERAL_EXP__INTEGER_TYPE);
-
+
il.setType(getOCLStandardLibrary().getInteger());
-
+
assertOK(il, ExpressionsValidator.INTEGER_LITERAL_EXP__INTEGER_TYPE);
}
-
+
public void test_IterateExp_checkIterateType() {
IterateExp i = factory.createIterateExp();
i.setType(fruit);
-
+
Variable resultVar = factory.createVariable();
resultVar.setType(color);
i.setResult(resultVar);
-
+
assertProblem(i, ExpressionsValidator.ITERATE_EXP__ITERATE_TYPE);
-
+
resultVar.setType(apple);
-
+
assertProblem(i, ExpressionsValidator.ITERATE_EXP__ITERATE_TYPE);
-
+
i.setType(apple);
-
+
assertOK(i, ExpressionsValidator.ITERATE_EXP__ITERATE_TYPE);
}
-
+
public void test_IterateExp_checkBodyType() {
IterateExp i = factory.createIterateExp();
i.setType(fruit);
-
+
Variable resultVar = factory.createVariable();
resultVar.setType(fruit);
i.setResult(resultVar);
-
+
OCLExpression body = factory.createBooleanLiteralExp();
body.setType(color);
i.setBody(body);
-
+
assertProblem(i, ExpressionsValidator.ITERATE_EXP__BODY_TYPE);
-
+
body.setType(apple);
-
+
assertOK(i, ExpressionsValidator.ITERATE_EXP__BODY_TYPE);
}
-
+
public void test_IterateExp_checkResultInit() {
IterateExp i = factory.createIterateExp();
i.setType(fruit);
-
+
Variable resultVar = factory.createVariable();
resultVar.setType(fruit);
i.setResult(resultVar);
-
+
assertProblem(i, ExpressionsValidator.ITERATE_EXP__RESULT_INIT);
-
+
resultVar.setInitExpression(factory.createUnspecifiedValueExp());
-
+
assertOK(i, ExpressionsValidator.ITERATE_EXP__RESULT_INIT);
}
-
+
public void test_IteratorExp_checkBooleanType() {
IteratorExp i = factory.createIteratorExp();
i.setType(apple);
-
+
i.setName("select");
assertOK(i, ExpressionsValidator.ITERATOR_EXP__BOOLEAN_TYPE);
-
+
for (String name : Arrays.asList("forAll", "exists", "isUnique")) {
i.setName(name);
assertProblem(i, ExpressionsValidator.ITERATOR_EXP__BOOLEAN_TYPE);
}
-
+
i.setType(getOCLStandardLibrary().getBoolean());
-
+
for (String name : Arrays.asList("forAll", "exists", "isUnique")) {
i.setName(name);
assertOK(i, ExpressionsValidator.ITERATOR_EXP__BOOLEAN_TYPE);
}
}
-
+
public void test_IteratorExp_checkCollectType() {
EClassifier set = getOCLStandardLibrary().getSet();
EClassifier orderedSet = getOCLStandardLibrary().getOrderedSet();
@@ -363,175 +363,175 @@
badPairs.add(new EClassifier[] {sequence, bag});
badPairs.add(new EClassifier[] {sequence, set});
badPairs.add(new EClassifier[] {orderedSet, bag});
- List<EClassifier[]> goodPairs = new java.util.ArrayList<EClassifier[]>();
+ List<EClassifier[]> goodPairs = new java.util.ArrayList<EClassifier[]>();
goodPairs.add(new EClassifier[] {set, bag});
goodPairs.add(new EClassifier[] {bag, bag});
goodPairs.add(new EClassifier[] {sequence, sequence});
goodPairs.add(new EClassifier[] {orderedSet, sequence});
-
+
IteratorExp i = factory.createIteratorExp();
i.setName("collect");
-
+
OCLExpression source = factory.createBooleanLiteralExp();
i.setSource(source);
-
+
for (EClassifier[] pair : badPairs) {
source.setType(pair[0]);
i.setType(pair[1]);
assertProblem(i, ExpressionsValidator.ITERATOR_EXP__COLLECT_TYPE);
}
-
+
for (EClassifier[] pair : goodPairs) {
source.setType(pair[0]);
i.setType(pair[1]);
assertOK(i, ExpressionsValidator.ITERATOR_EXP__COLLECT_TYPE);
}
}
-
+
public void test_IteratorExp_checkSelectRejectType() {
IteratorExp i = factory.createIteratorExp();
i.setType(getOCLStandardLibrary().getSet());
-
+
OCLExpression source = factory.createBooleanLiteralExp();
source.setType(getOCLStandardLibrary().getBag());
i.setSource(source);
-
+
for (String name : Arrays.asList("select", "reject")) {
i.setName(name);
assertProblem(i, ExpressionsValidator.ITERATOR_EXP__SELECT_REJECT_TYPE);
}
-
+
i.setType(getOCLStandardLibrary().getBag());
-
+
for (String name : Arrays.asList("select", "reject")) {
i.setName(name);
assertOK(i, ExpressionsValidator.ITERATOR_EXP__SELECT_REJECT_TYPE);
}
}
-
+
public void test_IteratorExp_checkBooleanBodyType() {
List<String> names = Arrays.asList("select", "reject", "forAll", "exists", "any", "one");
IteratorExp i = factory.createIteratorExp();
i.setType(getOCLStandardLibrary().getSet());
-
+
OCLExpression body = factory.createBooleanLiteralExp();
body.setType(getOCLStandardLibrary().getBag());
i.setBody(body);
-
+
i.setName("collect");
assertOK(i, ExpressionsValidator.ITERATOR_EXP__BOOLEAN_BODY_TYPE);
-
+
for (String name : names) {
i.setName(name);
assertProblem(i, ExpressionsValidator.ITERATOR_EXP__BOOLEAN_BODY_TYPE);
}
-
+
body.setType(getOCLStandardLibrary().getBoolean());
-
+
for (String name : names) {
i.setName(name);
assertOK(i, ExpressionsValidator.ITERATOR_EXP__BOOLEAN_BODY_TYPE);
}
}
-
+
public void test_LetExp_checkLetType() {
LetExp l = factory.createLetExp();
l.setType(getOCLStandardLibrary().getBag());
-
+
OCLExpression in = factory.createBooleanLiteralExp();
in.setType(getOCLStandardLibrary().getBoolean());
l.setIn(in);
-
+
assertProblem(l, ExpressionsValidator.LET_EXP__LET_TYPE);
-
+
l.setType(in.getType());
-
+
assertOK(l, ExpressionsValidator.LET_EXP__LET_TYPE);
}
-
+
public void test_LoopExp_checkSourceCollection() {
LoopExp l = factory.createIterateExp();
-
+
OCLExpression source = factory.createBooleanLiteralExp();
l.setSource(source);
-
+
source.setType(getOCLStandardLibrary().getBoolean());
-
+
assertProblem(l, ExpressionsValidator.LOOP_EXP__SOURCE_COLLECTION);
-
+
source.setType(getOCLStandardLibrary().getSet());
-
+
assertOK(l, ExpressionsValidator.LOOP_EXP__SOURCE_COLLECTION);
}
-
+
public void test_LoopExp_checkLoopVariableInit() {
LoopExp l = factory.createIterateExp();
-
+
Variable iter = factory.createVariable();
l.getIterator().add(iter);
-
+
iter = factory.createVariable();
l.getIterator().add(iter);
-
+
assertOK(l, ExpressionsValidator.LOOP_EXP__LOOP_VARIABLE_INIT);
-
+
iter.setInitExpression(factory.createBooleanLiteralExp());
-
+
assertProblem(l, ExpressionsValidator.LOOP_EXP__LOOP_VARIABLE_INIT);
}
-
+
public void test_LoopExp_checkLoopVariableType() {
LoopExp l = factory.createIterateExp();
-
+
CollectionType ctype = factory.createCollectionType();
ctype.setElementType(fruit);
OCLExpression source = factory.createCollectionLiteralExp();
source.setType(ctype);
l.setSource(source);
-
+
Variable iter = factory.createVariable();
iter.setType(fruit);
l.getIterator().add(iter);
-
+
iter = factory.createVariable();
iter.setType(apple);
l.getIterator().add(iter);
-
+
assertProblem(l, ExpressionsValidator.LOOP_EXP__LOOP_VARIABLE_TYPE);
-
+
iter.setType(fruit);
-
+
assertOK(l, ExpressionsValidator.LOOP_EXP__LOOP_VARIABLE_TYPE);
}
-
+
public void test_MessageExp_checkOperationArguments() {
MessageExp m = factory.createMessageExp();
-
+
CallOperationAction action = factory.createCallOperationAction();
m.setCalledOperation(action);
action.setOperation(fruit_ripen);
-
+
UnspecifiedValueExp arg = factory.createUnspecifiedValueExp();
arg.setType(getOCLStandardLibrary().getBoolean());
m.getArgument().add(arg);
-
+
assertProblem(m, ExpressionsValidator.MESSAGE_EXP__OPERATION_ARGUMENTS);
-
+
arg.setType(color);
-
+
assertOK(m, ExpressionsValidator.MESSAGE_EXP__OPERATION_ARGUMENTS);
-
+
// no-arg operation
action.setOperation(fruit_newFruit);
-
+
// wrong number of message args
assertProblem(m, ExpressionsValidator.MESSAGE_EXP__OPERATION_ARGUMENTS);
-
+
m.getArgument().clear();
-
+
assertOK(m, ExpressionsValidator.MESSAGE_EXP__OPERATION_ARGUMENTS);
}
-
+
public void test_MessageExp_checkSignalArguments() {
expectModified = true;
MessagingFruitEnvironmentFactory envFactory = new MessagesTest.MessagingFruitEnvironmentFactory(this);
@@ -539,131 +539,131 @@
ocl = OCL.newInstance(envFactory);
helper = ocl.createOCLHelper();
((InitEnvironment) ocl.getEnvironment()).init();
-
+
MessageExp m = factory.createMessageExp();
-
+
SendSignalAction action = factory.createSendSignalAction();
m.setSentSignal(action);
-
+
EClass drop = (EClass) fruitPackage.getEClassifier("Drop");
assertNotNull(drop);
action.setSignal(drop);
-
+
UnspecifiedValueExp arg = factory.createUnspecifiedValueExp();
arg.setType(getOCLStandardLibrary().getInteger());
m.getArgument().add(arg);
-
+
arg = factory.createUnspecifiedValueExp();
arg.setType(getOCLStandardLibrary().getBoolean());
m.getArgument().add(arg);
-
+
assertProblem(m, ExpressionsValidator.MESSAGE_EXP__SIGNAL_ARGUMENTS);
-
+
arg.setType(stem);
-
+
assertOK(m, ExpressionsValidator.MESSAGE_EXP__SIGNAL_ARGUMENTS);
-
+
// wrong number of arguments
m.getArgument().remove(arg);
-
+
assertProblem(m, ExpressionsValidator.MESSAGE_EXP__SIGNAL_ARGUMENTS);
}
-
+
public void test_MessageExp_checkTargetDefinesOperation() {
MessageExp m = factory.createMessageExp();
-
+
CallOperationAction action = factory.createCallOperationAction();
m.setCalledOperation(action);
action.setOperation(fruit_ripen);
-
+
UnspecifiedValueExp arg = factory.createUnspecifiedValueExp();
arg.setType(color);
m.getArgument().add(arg);
-
+
OCLExpression target = factory.createBooleanLiteralExp();
m.setTarget(target);
target.setType(color);
-
+
assertProblem(m, ExpressionsValidator.MESSAGE_EXP__TARGET_DEFINES_OPERATION);
-
+
target.setType(fruit);
-
+
assertOK(m, ExpressionsValidator.MESSAGE_EXP__TARGET_DEFINES_OPERATION);
}
-
+
public void test_MessageExp_checkHasOperationOrSignal() {
MessageExp m = factory.createMessageExp();
-
+
CallOperationAction coa = factory.createCallOperationAction();
coa.setOperation(fruit_ripen);
-
+
SendSignalAction ssa = factory.createSendSignalAction();
ssa.setSignal(stem);
-
+
m.setCalledOperation(coa);
-
+
assertOK(m, ExpressionsValidator.MESSAGE_EXP__HAS_OPERATION_OR_SIGNAL);
-
+
m.setSentSignal(ssa);
-
+
assertProblem(m, ExpressionsValidator.MESSAGE_EXP__HAS_OPERATION_OR_SIGNAL);
-
+
m.setCalledOperation(null);
-
+
assertOK(m, ExpressionsValidator.MESSAGE_EXP__HAS_OPERATION_OR_SIGNAL);
-
+
m.setSentSignal(null);
-
+
assertProblem(m, ExpressionsValidator.MESSAGE_EXP__HAS_OPERATION_OR_SIGNAL);
-
+
}
-
+
public void test_MessageExp_checkTargetNotCollection() {
MessageExp m = factory.createMessageExp();
-
+
CallOperationAction action = factory.createCallOperationAction();
m.setCalledOperation(action);
action.setOperation(fruit_ripen);
-
+
UnspecifiedValueExp arg = factory.createUnspecifiedValueExp();
arg.setType(color);
m.getArgument().add(arg);
-
+
OCLExpression target = factory.createBooleanLiteralExp();
m.setTarget(target);
target.setType(factory.createSequenceType());
-
+
assertProblem(m, ExpressionsValidator.MESSAGE_EXP__TARGET_NOT_COLLECTION);
-
+
target.setType(fruit);
-
+
assertOK(m, ExpressionsValidator.MESSAGE_EXP__TARGET_NOT_COLLECTION);
}
-
+
public void test_OperationCallExp_checkArgumentsConform() {
OperationCallExp o = factory.createOperationCallExp();
-
+
EClass fruitUtil = (EClass) fruitPackage.getEClassifier("FruitUtil");
EOperation oper = fruitUtil.getEOperations().get(0);
o.setReferredOperation(oper);
-
+
OCLExpression arg = factory.createUnspecifiedValueExp();
o.getArgument().add(arg);
CollectionType ctype = factory.createOrderedSetType();
ctype.setElementType(color);
arg.setType(ctype);
-
+
OCLExpression source = factory.createUnspecifiedValueExp();
source.setType(fruitUtil);
o.setSource(source);
-
+
assertProblem(o, ExpressionsValidator.OPERATION_CALL_EXP__ARGUMENTS_CONFORM);
-
+
ctype.setElementType(fruit);
-
+
assertOK(o, ExpressionsValidator.OPERATION_CALL_EXP__ARGUMENTS_CONFORM);
}
-
+
/**
* Tests that operation call expressions involving generic arguments
* pass the constraint. These are the generic <tt>T</tt> and <tt>T2</tt>
@@ -671,134 +671,134 @@
*/
public void test_OperationCallExp_checkArgumentsConform_generic_232028() {
OperationCallExp o = (OperationCallExp) parseUnvalidated(
- "context ecore::EString inv: Set{}->including('foo')");
-
+ "context ecore::EString inv: Set{}->including('foo')");
+
OCLExpression arg = factory.createUnspecifiedValueExp();
arg.setType(getOCLStandardLibrary().getInteger());
o.getArgument().add(arg);
-
+
// wrong number of arguments does not trigger this constraint
assertOK(o, ExpressionsValidator.OPERATION_CALL_EXP__ARGUMENTS_CONFORM);
-
+
o.getArgument().remove(arg);
-
+
// this is a well-formed expression
assertOK(o, ExpressionsValidator.OPERATION_CALL_EXP__ARGUMENTS_CONFORM);
-
+
o.getArgument().set(0, arg);
-
+
assertOK(o, ExpressionsValidator.OPERATION_CALL_EXP__ARGUMENTS_CONFORM);
}
/**
* Tests that operation call expressions involving standard library operations
* which have a generic collection as parameter pass the constraint.
- *
+ *
*/
public void test_OperationCallExp_checkArgumentsConform_generic_collections_236247() {
OperationCallExp o = (OperationCallExp) parseUnvalidated(
- "context ecore::EString inv: Set{'foo'}->includesAll(Set{'bar'})");
+ "context ecore::EString inv: Set{'foo'}->includesAll(Set{'bar'})");
assertOK(o);
}
-
+
public void test_OperationCallExp_checkArgumentCount() {
OperationCallExp o = factory.createOperationCallExp();
-
+
EClass fruitUtil = (EClass) fruitPackage.getEClassifier("FruitUtil");
EOperation oper = fruitUtil.getEOperations().get(0);
o.setReferredOperation(oper);
-
+
OCLExpression arg = factory.createUnspecifiedValueExp();
o.getArgument().add(arg);
CollectionType ctype = factory.createOrderedSetType();
ctype.setElementType(color);
arg.setType(ctype);
-
+
assertOK(o, ExpressionsValidator.OPERATION_CALL_EXP__ARGUMENT_COUNT);
o.getArgument().add(factory.createCollectionLiteralExp());
-
+
assertProblem(o, ExpressionsValidator.OPERATION_CALL_EXP__ARGUMENT_COUNT);
o.getArgument().clear();
-
+
assertProblem(o, ExpressionsValidator.OPERATION_CALL_EXP__ARGUMENT_COUNT);
}
-
+
/**
* Tests the case of a null operation (that it doesn't throw an NPE).
*/
public void test_OperationCallExp_checkArgumentCount_nullOperation_231515() {
OperationCallExp o = factory.createOperationCallExp();
-
+
o.setReferredOperation(null); // be explicit on the purpose of the test
-
+
OCLExpression arg = factory.createUnspecifiedValueExp();
o.getArgument().add(arg);
CollectionType ctype = factory.createOrderedSetType();
ctype.setElementType(color);
arg.setType(ctype);
-
+
assertOK(o, ExpressionsValidator.OPERATION_CALL_EXP__ARGUMENT_COUNT);
o.getArgument().add(factory.createCollectionLiteralExp());
-
+
assertOK(o, ExpressionsValidator.OPERATION_CALL_EXP__ARGUMENT_COUNT);
o.getArgument().clear();
-
+
assertOK(o, ExpressionsValidator.OPERATION_CALL_EXP__ARGUMENT_COUNT);
}
-
+
public void test_PropertyCallExp_checkPropertyType() {
PropertyCallExp p = factory.createPropertyCallExp();
-
+
p.setReferredProperty(apple_label);
p.setType(getOCLStandardLibrary().getBoolean());
-
+
OCLExpression source = factory.createUnspecifiedValueExp();
source.setType(apple);
p.setSource(source);
-
+
assertProblem(p, ExpressionsValidator.PROPERTY_CALL_EXP__PROPERTY_TYPE);
p.setType(getOCLStandardLibrary().getString());
-
+
assertOK(p, ExpressionsValidator.PROPERTY_CALL_EXP__PROPERTY_TYPE);
}
-
+
public void test_RealLiteralExp_checkRealType() {
RealLiteralExp rl = factory.createRealLiteralExp();
rl.setRealSymbol(42.0);
rl.setType(apple);
-
+
assertProblem(rl, ExpressionsValidator.REAL_LITERAL_EXP__REAL_TYPE);
-
+
rl.setType(getOCLStandardLibrary().getInteger());
-
+
assertProblem(rl, ExpressionsValidator.REAL_LITERAL_EXP__REAL_TYPE);
-
+
rl.setType(getOCLStandardLibrary().getReal());
-
+
assertOK(rl, ExpressionsValidator.REAL_LITERAL_EXP__REAL_TYPE);
}
-
+
public void test_StringLiteralExp_checkStringType() {
StringLiteralExp sl = factory.createStringLiteralExp();
sl.setStringSymbol("42");
sl.setType(apple);
-
+
assertProblem(sl, ExpressionsValidator.STRING_LITERAL_EXP__STRING_TYPE);
-
+
sl.setType(getOCLStandardLibrary().getInteger());
-
+
assertProblem(sl, ExpressionsValidator.STRING_LITERAL_EXP__STRING_TYPE);
-
+
sl.setType(getOCLStandardLibrary().getString());
-
+
assertOK(sl, ExpressionsValidator.STRING_LITERAL_EXP__STRING_TYPE);
}
-
+
public void test_TupleLiteralExp_checkTupleType() {
TupleLiteralExp t = factory.createTupleLiteralExp();
TupleLiteralPart part1 = factory.createTupleLiteralPart();
@@ -809,31 +809,31 @@
part2.setName("b");
part2.setType(getOCLStandardLibrary().getInteger());
t.getPart().add(part2);
-
+
t.setType(getOCLStandardLibrary().getBag());
-
+
assertProblem(t, ExpressionsValidator.TUPLE_LITERAL_EXP__TUPLE_TYPE);
-
+
TupleType tt = factory.createTupleType();
t.setType(tt);
-
+
assertProblem(t, ExpressionsValidator.TUPLE_LITERAL_EXP__TUPLE_TYPE);
-
+
EStructuralFeature a = ocl.getEnvironment().getUMLReflection()
.createProperty("a", getOCLStandardLibrary().getString());
tt.getEStructuralFeatures().add(a);
part1.setAttribute(a);
-
+
assertProblem(t, ExpressionsValidator.TUPLE_LITERAL_EXP__TUPLE_TYPE);
-
+
EStructuralFeature b = ocl.getEnvironment().getUMLReflection()
.createProperty("b", getOCLStandardLibrary().getInteger());
tt.getEStructuralFeatures().add(b);
part2.setAttribute(b);
-
+
assertOK(t, ExpressionsValidator.TUPLE_LITERAL_EXP__TUPLE_TYPE);
}
-
+
public void test_TupleLiteralExp_checkPartsUnique() {
TupleLiteralExp t = factory.createTupleLiteralExp();
TupleLiteralPart part1 = factory.createTupleLiteralPart();
@@ -844,79 +844,79 @@
part2.setName("a");
part2.setType(getOCLStandardLibrary().getInteger());
t.getPart().add(part2);
-
+
assertProblem(t, ExpressionsValidator.TUPLE_LITERAL_EXP__PARTS_UNIQUE);
-
+
part2.setName("b");
-
+
assertOK(t, ExpressionsValidator.TUPLE_LITERAL_EXP__PARTS_UNIQUE);
}
-
+
public void test_TupleLiteralExp_checkValueType() {
TupleLiteralPart p = factory.createTupleLiteralPart();
p.setName("a");
p.setType(fruit);
-
+
OCLExpression value = factory.createUnspecifiedValueExp();
value.setType(apple);
p.setValue(value);
-
+
EStructuralFeature a = ocl.getEnvironment().getUMLReflection()
.createProperty("a", fruit);
p.setAttribute(a);
-
+
assertProblem(p, ExpressionsValidator.TUPLE_LITERAL_PART__VALUE_TYPE);
-
+
value.setType(fruit);
-
+
assertOK(p, ExpressionsValidator.TUPLE_LITERAL_PART__VALUE_TYPE);
}
-
+
public void test_UnlimitedNaturalLiteralExp_checkNaturalType() {
UnlimitedNaturalLiteralExp ul = factory.createUnlimitedNaturalLiteralExp();
ul.setIntegerSymbol(42);
ul.setType(apple);
-
+
assertProblem(ul, ExpressionsValidator.UNLIMITED_NATURAL_LITERAL_EXP__NATURAL_TYPE);
-
+
ul.setType(getOCLStandardLibrary().getString());
-
+
assertProblem(ul, ExpressionsValidator.UNLIMITED_NATURAL_LITERAL_EXP__NATURAL_TYPE);
-
+
ul.setType(getOCLStandardLibrary().getUnlimitedNatural());
-
+
assertOK(ul, ExpressionsValidator.UNLIMITED_NATURAL_LITERAL_EXP__NATURAL_TYPE);
}
-
+
public void test_VariableExp_checkVarType() {
VariableExp v = factory.createVariableExp();
v.setType(fruit);
-
+
Variable var = factory.createVariable();
var.setName("a");
var.setType(apple);
v.setReferredVariable(var);
-
+
assertProblem(v, ExpressionsValidator.VARIABLE_EXP__VAR_TYPE);
-
+
var.setType(fruit);
assertOK(v, ExpressionsValidator.VARIABLE_EXP__VAR_TYPE);
}
-
+
public void test_Variable_checknitType() {
Variable v = factory.createVariable();
v.setName("a");
v.setType(fruit);
assertOK(v, ExpressionsValidator.VARIABLE__INIT_TYPE);
-
+
OCLExpression init = factory.createUnspecifiedValueExp();
init.setType(color);
v.setInitExpression(init);
-
+
assertProblem(v, ExpressionsValidator.VARIABLE__INIT_TYPE);
-
+
init.setType(apple);
assertOK(v, ExpressionsValidator.VARIABLE__INIT_TYPE);
@@ -925,74 +925,74 @@
//
// Fixture methods
//
-
+
protected Diagnostic validate(EObject target) {
Map<Object, Object> ctx = new java.util.HashMap<Object, Object>();
ctx.put(Environment.class, ocl.getEnvironment());
return Diagnostician.INSTANCE.validate(target, ctx);
}
-
+
protected void assertProblem(EObject target, int code) {
assertProblem(validate(target), target, code);
}
-
+
protected void assertProblem(Diagnostic diagnostic, EObject target, int code) {
Diagnostic problem = findProblem(diagnostic, target, code);
assertNotNull("Problem not found", problem);
- System.out.println("Found expected problem: " + problem.getMessage());
+ debugPrintln("Found expected problem: " + problem.getMessage());
}
-
+
protected Diagnostic findProblem(Diagnostic diagnostic, EObject target, int code) {
if (ExpressionsValidator.DIAGNOSTIC_SOURCE.equals(diagnostic
- .getSource())
+ .getSource())
&& (diagnostic.getSeverity() != Diagnostic.OK)
&& diagnostic.getData().contains(target)
&& (diagnostic.getCode() == code)) {
return diagnostic;
}
-
+
for (Diagnostic child : diagnostic.getChildren()) {
Diagnostic result = findProblem(child, target, code);
-
+
if (result != null) {
return result;
}
}
-
+
return null;
}
-
+
protected Diagnostic findProblem(Diagnostic diagnostic, EObject target) {
if (ExpressionsValidator.DIAGNOSTIC_SOURCE.equals(diagnostic
- .getSource())
+ .getSource())
&& (diagnostic.getSeverity() != Diagnostic.OK)
&& diagnostic.getData().contains(target)) {
return diagnostic;
}
-
+
for (Diagnostic child : diagnostic.getChildren()) {
Diagnostic result = findProblem(child, target);
-
+
if (result != null) {
return result;
}
}
-
+
return null;
}
-
+
protected void assertOK(EObject target, int code) {
assertOK(validate(target), target, code);
}
-
+
protected void assertOK(Diagnostic diagnostic, EObject target, int code) {
assertNull("Problem found", findProblem(diagnostic, target, code));
}
-
+
protected void assertOK(EObject target) {
assertOK(validate(target), target);
}
-
+
protected void assertOK(Diagnostic diagnostic, EObject target) {
assertNull("Problem found", findProblem(diagnostic, target));
}
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ExtensibilityTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ExtensibilityTest.java
index 6e6610d..feedc3b 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ExtensibilityTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ExtensibilityTest.java
@@ -63,359 +63,359 @@
*/
@SuppressWarnings("nls")
public class ExtensibilityTest
- extends AbstractTestSuite {
+extends AbstractTestSuite {
- /**
- * Tests that we can successfully parse with an environment that does not
- * implement the optional adapter protocols.
- */
- public void test_noAdapters_parseSuccessfully() {
- helper.setContext(EcorePackage.Literals.EPACKAGE);
-
- try {
- helper.createInvariant("not self.eClassifiers->isEmpty()");
- } catch (ParserException e) {
- fail("Failed to parse: " + e.getLocalizedMessage());
- }
-
- try {
- ocl.parse(new OCLInput(
- "context ecore::EPackage\n" +
- "inv: not self.eClassifiers->isEmpty()"));
- } catch (ParserException e) {
- fail("Failed to parse: " + e.getLocalizedMessage());
- }
- }
+ /**
+ * Tests that we can successfully parse with an environment that does not
+ * implement the optional adapter protocols.
+ */
+ public void test_noAdapters_parseSuccessfully() {
+ helper.setContext(EcorePackage.Literals.EPACKAGE);
- /**
- * Tests that we can produce warnings with an environment that does not
- * implement the optional adapter protocols.
- */
- public void test_noAdapters_parseWithWarning() {
- helper.setContext(EcorePackage.Literals.EPACKAGE);
-
- try {
- helper.createInvariant("not self.\"eClassifiers\"->isEmpty()");
-
- Diagnostic diag = helper.getProblems();
- assertNotNull(diag);
- assertEquals(Diagnostic.WARNING, diag.getSeverity());
-
- System.out.println("Got expected warning: " + diag.getMessage());
- } catch (ParserException e) {
- fail("Failed to parse: " + e.getLocalizedMessage());
- }
-
- try {
- ocl.parse(new OCLInput(
- "context ecore::EPackage\n" +
- "inv: not self.\"eClassifiers\"->isEmpty()"));
-
- Diagnostic diag = ocl.getProblems();
- assertNotNull(diag);
- assertEquals(Diagnostic.WARNING, diag.getSeverity());
-
- System.out.println("Got expected warning: " + diag.getMessage());
- } catch (ParserException e) {
- fail("Failed to parse: " + e.getLocalizedMessage());
- }
- }
+ try {
+ helper.createInvariant("not self.eClassifiers->isEmpty()");
+ } catch (ParserException e) {
+ fail("Failed to parse: " + e.getLocalizedMessage());
+ }
- /**
- * Tests that we can produce errors with an environment that does not
- * implement the optional adapter protocols.
- */
- public void test_noAdapters_parseWithError() {
- helper.setContext(EcorePackage.Literals.EPACKAGE);
-
- try {
- helper.createInvariant("not self.classifiers->isEmpty()");
- fail("Should not have parsed");
- } catch (ParserException e) {
- // success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
- }
-
- try {
- ocl.parse(new OCLInput(
- "context ecore::EPackage\n" +
- "inv: not self.classifiers->isEmpty()"));
- fail("Should not have parsed");
- } catch (ParserException e) {
- // success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
- }
- }
+ try {
+ ocl.parse(new OCLInput(
+ "context ecore::EPackage\n" +
+ "inv: not self.eClassifiers->isEmpty()"));
+ } catch (ParserException e) {
+ fail("Failed to parse: " + e.getLocalizedMessage());
+ }
+ }
- /**
- * Tests that we can report lexer problems with an environment that does not
- * implement the optional adapter protocols.
- */
- public void test_noAdapters_parseWithTokenError() {
- helper.setContext(EcorePackage.Literals.EPACKAGE);
-
- try {
- helper.createInvariant("not self.;->isEmpty()");
- fail("Should not have parsed");
- } catch (ParserException e) {
- // success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
- }
-
- try {
- ocl.parse(new OCLInput(
- "context ecore::EPackage\n" +
- "inv: not self.;->isEmpty()"));
- fail("Should not have parsed");
- } catch (ParserException e) {
- // success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
- }
- }
-
+ /**
+ * Tests that we can produce warnings with an environment that does not
+ * implement the optional adapter protocols.
+ */
+ public void test_noAdapters_parseWithWarning() {
+ helper.setContext(EcorePackage.Literals.EPACKAGE);
+
+ try {
+ helper.createInvariant("not self.\"eClassifiers\"->isEmpty()");
+
+ Diagnostic diag = helper.getProblems();
+ assertNotNull(diag);
+ assertEquals(Diagnostic.WARNING, diag.getSeverity());
+
+ debugPrintln("Got expected warning: " + diag.getMessage());
+ } catch (ParserException e) {
+ fail("Failed to parse: " + e.getLocalizedMessage());
+ }
+
+ try {
+ ocl.parse(new OCLInput(
+ "context ecore::EPackage\n" +
+ "inv: not self.\"eClassifiers\"->isEmpty()"));
+
+ Diagnostic diag = ocl.getProblems();
+ assertNotNull(diag);
+ assertEquals(Diagnostic.WARNING, diag.getSeverity());
+
+ debugPrintln("Got expected warning: " + diag.getMessage());
+ } catch (ParserException e) {
+ fail("Failed to parse: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests that we can produce errors with an environment that does not
+ * implement the optional adapter protocols.
+ */
+ public void test_noAdapters_parseWithError() {
+ helper.setContext(EcorePackage.Literals.EPACKAGE);
+
+ try {
+ helper.createInvariant("not self.classifiers->isEmpty()");
+ fail("Should not have parsed");
+ } catch (ParserException e) {
+ // success
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
+ }
+
+ try {
+ ocl.parse(new OCLInput(
+ "context ecore::EPackage\n" +
+ "inv: not self.classifiers->isEmpty()"));
+ fail("Should not have parsed");
+ } catch (ParserException e) {
+ // success
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests that we can report lexer problems with an environment that does not
+ * implement the optional adapter protocols.
+ */
+ public void test_noAdapters_parseWithTokenError() {
+ helper.setContext(EcorePackage.Literals.EPACKAGE);
+
+ try {
+ helper.createInvariant("not self.;->isEmpty()");
+ fail("Should not have parsed");
+ } catch (ParserException e) {
+ // success
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
+ }
+
+ try {
+ ocl.parse(new OCLInput(
+ "context ecore::EPackage\n" +
+ "inv: not self.;->isEmpty()"));
+ fail("Should not have parsed");
+ } catch (ParserException e) {
+ // success
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
+ }
+ }
+
//
// Framework methods
//
-
+
@Override
protected OCL createOCL() {
- return OCL.newInstance(new WrapperEnvironmentFactory());
+ return OCL.newInstance(new WrapperEnvironmentFactory());
}
-
+
class WrapperEnvironment implements EnvironmentWithHiddenOpposites {
-
- private final EnvironmentWithHiddenOpposites
- delegate;
-
- private final EnvironmentWithHiddenOpposites
- parent;
-
- private final WrapperEnvironmentFactory factory;
-
- WrapperEnvironment(WrapperEnvironmentFactory factory,
- Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> delegate) {
- this(factory, delegate, null);
- }
- WrapperEnvironment(WrapperEnvironmentFactory factory,
- Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> delegate,
- Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent) {
-
- this.factory = factory;
- this.delegate = (EnvironmentWithHiddenOpposites) delegate;
- this.parent = (EnvironmentWithHiddenOpposites) parent;
- }
-
- public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> getParent() {
- return parent;
- }
+ private final EnvironmentWithHiddenOpposites
+ delegate;
- public EnvironmentFactory<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> getFactory() {
- return factory;
- }
+ private final EnvironmentWithHiddenOpposites
+ parent;
- public boolean addElement(String name,
- Variable<EClassifier, EParameter> elem, boolean explicit) {
- return delegate.addElement(name, elem, explicit);
- }
+ private final WrapperEnvironmentFactory factory;
- public EStructuralFeature defineAttribute(EClassifier owner,
- Variable<EClassifier, EParameter> variable,
- Constraint constraint) {
- return delegate.defineAttribute(owner, variable, constraint);
- }
+ WrapperEnvironment(WrapperEnvironmentFactory factory,
+ Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> delegate) {
+ this(factory, delegate, null);
+ }
- public EOperation defineOperation(EClassifier owner, String name,
- EClassifier type,
- List<Variable<EClassifier, EParameter>> params,
- Constraint constraint) {
- return delegate.defineOperation(owner, name, type, params,
- constraint);
- }
+ WrapperEnvironment(WrapperEnvironmentFactory factory,
+ Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> delegate,
+ Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent) {
- public void deleteElement(String name) {
- delegate.deleteElement(name);
- }
+ this.factory = factory;
+ this.delegate = (EnvironmentWithHiddenOpposites) delegate;
+ this.parent = (EnvironmentWithHiddenOpposites) parent;
+ }
- public List<EStructuralFeature> getAdditionalAttributes(
- EClassifier classifier) {
- return delegate.getAdditionalAttributes(classifier);
- }
+ public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> getParent() {
+ return parent;
+ }
- public List<EOperation> getAdditionalOperations(EClassifier classifier) {
- return delegate.getAdditionalOperations(classifier);
- }
+ public EnvironmentFactory<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> getFactory() {
+ return factory;
+ }
- public Constraint getBodyCondition(EOperation operation) {
- return delegate.getBodyCondition(operation);
- }
+ public boolean addElement(String name,
+ Variable<EClassifier, EParameter> elem, boolean explicit) {
+ return delegate.addElement(name, elem, explicit);
+ }
- public EClassifier getContextClassifier() {
- return delegate.getContextClassifier();
- }
+ public EStructuralFeature defineAttribute(EClassifier owner,
+ Variable<EClassifier, EParameter> variable,
+ Constraint constraint) {
+ return delegate.defineAttribute(owner, variable, constraint);
+ }
- public EOperation getContextOperation() {
- return delegate.getContextOperation();
- }
+ public EOperation defineOperation(EClassifier owner, String name,
+ EClassifier type,
+ List<Variable<EClassifier, EParameter>> params,
+ Constraint constraint) {
+ return delegate.defineOperation(owner, name, type, params,
+ constraint);
+ }
- public EPackage getContextPackage() {
- return delegate.getContextPackage();
- }
+ public void deleteElement(String name) {
+ delegate.deleteElement(name);
+ }
- public EStructuralFeature getContextProperty() {
- return delegate.getContextProperty();
- }
+ public List<EStructuralFeature> getAdditionalAttributes(
+ EClassifier classifier) {
+ return delegate.getAdditionalAttributes(classifier);
+ }
- public Constraint getDefinition(Object feature) {
- return delegate.getDefinition(feature);
- }
+ public List<EOperation> getAdditionalOperations(EClassifier classifier) {
+ return delegate.getAdditionalOperations(classifier);
+ }
- public Constraint getDeriveConstraint(EStructuralFeature property) {
- return delegate.getDeriveConstraint(property);
- }
+ public Constraint getBodyCondition(EOperation operation) {
+ return delegate.getBodyCondition(operation);
+ }
- public Constraint getInitConstraint(EStructuralFeature property) {
- return delegate.getInitConstraint(property);
- }
+ public EClassifier getContextClassifier() {
+ return delegate.getContextClassifier();
+ }
- public OCLFactory getOCLFactory() {
- return delegate.getOCLFactory();
- }
+ public EOperation getContextOperation() {
+ return delegate.getContextOperation();
+ }
- public OCLStandardLibrary<EClassifier> getOCLStandardLibrary() {
- return delegate.getOCLStandardLibrary();
- }
+ public EPackage getContextPackage() {
+ return delegate.getContextPackage();
+ }
- public Variable<EClassifier, EParameter> getSelfVariable() {
- return delegate.getSelfVariable();
- }
+ public EStructuralFeature getContextProperty() {
+ return delegate.getContextProperty();
+ }
- public List<EObject> getStates(EClassifier owner,
- List<String> pathPrefix) {
- return delegate.getStates(owner, pathPrefix);
- }
+ public Constraint getDefinition(Object feature) {
+ return delegate.getDefinition(feature);
+ }
- public TypeResolver<EClassifier, EOperation, EStructuralFeature> getTypeResolver() {
- return delegate.getTypeResolver();
- }
+ public Constraint getDeriveConstraint(EStructuralFeature property) {
+ return delegate.getDeriveConstraint(property);
+ }
- public UMLReflection<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint> getUMLReflection() {
- return delegate.getUMLReflection();
- }
+ public Constraint getInitConstraint(EStructuralFeature property) {
+ return delegate.getInitConstraint(property);
+ }
- public Collection<Variable<EClassifier, EParameter>> getVariables() {
- return delegate.getVariables();
- }
+ public OCLFactory getOCLFactory() {
+ return delegate.getOCLFactory();
+ }
- public boolean isEmpty() {
- return delegate.isEmpty();
- }
+ public OCLStandardLibrary<EClassifier> getOCLStandardLibrary() {
+ return delegate.getOCLStandardLibrary();
+ }
- public boolean isInPostcondition(OCLExpression<EClassifier> exp) {
- return delegate.isInPostcondition(exp);
- }
+ public Variable<EClassifier, EParameter> getSelfVariable() {
+ return delegate.getSelfVariable();
+ }
- public Variable<EClassifier, EParameter> lookup(String name) {
- return delegate.lookup(name);
- }
+ public List<EObject> getStates(EClassifier owner,
+ List<String> pathPrefix) {
+ return delegate.getStates(owner, pathPrefix);
+ }
- public EClassifier lookupAssociationClassReference(EClassifier owner,
- String name) {
- return delegate.lookupAssociationClassReference(owner, name);
- }
+ public TypeResolver<EClassifier, EOperation, EStructuralFeature> getTypeResolver() {
+ return delegate.getTypeResolver();
+ }
- public EClassifier lookupClassifier(List<String> names) {
- return delegate.lookupClassifier(names);
- }
+ public UMLReflection<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint> getUMLReflection() {
+ return delegate.getUMLReflection();
+ }
- public Variable<EClassifier, EParameter> lookupImplicitSourceForAssociationClass(
- String name) {
- return delegate.lookupImplicitSourceForAssociationClass(name);
- }
+ public Collection<Variable<EClassifier, EParameter>> getVariables() {
+ return delegate.getVariables();
+ }
- public Variable<EClassifier, EParameter> lookupImplicitSourceForOperation(
- String name, List<? extends TypedElement<EClassifier>> args) {
- return delegate.lookupImplicitSourceForOperation(name, args);
- }
+ public boolean isEmpty() {
+ return delegate.isEmpty();
+ }
- public Variable<EClassifier, EParameter> lookupImplicitSourceForProperty(
- String name) {
- return delegate.lookupImplicitSourceForProperty(name);
- }
+ public boolean isInPostcondition(OCLExpression<EClassifier> exp) {
+ return delegate.isInPostcondition(exp);
+ }
- public Variable<EClassifier, EParameter> lookupImplicitSourceForSignal(
- String name, List<? extends TypedElement<EClassifier>> args) {
- return delegate.lookupImplicitSourceForSignal(name, args);
- }
+ public Variable<EClassifier, EParameter> lookup(String name) {
+ return delegate.lookup(name);
+ }
- public Variable<EClassifier, EParameter> lookupImplicitSourceForState(
- List<String> path)
- throws LookupException, SemanticException {
- return delegate.lookupImplicitSourceForState(path);
- }
+ public EClassifier lookupAssociationClassReference(EClassifier owner,
+ String name) {
+ return delegate.lookupAssociationClassReference(owner, name);
+ }
- public Variable<EClassifier, EParameter> lookupLocal(String name) {
- return delegate.lookupLocal(name);
- }
+ public EClassifier lookupClassifier(List<String> names) {
+ return delegate.lookupClassifier(names);
+ }
- public EOperation lookupOperation(EClassifier owner, String name,
- List<? extends TypedElement<EClassifier>> args) {
- return delegate.lookupOperation(owner, name, args);
- }
+ public Variable<EClassifier, EParameter> lookupImplicitSourceForAssociationClass(
+ String name) {
+ return delegate.lookupImplicitSourceForAssociationClass(name);
+ }
- public EPackage lookupPackage(List<String> names) {
- return delegate.lookupPackage(names);
- }
+ public Variable<EClassifier, EParameter> lookupImplicitSourceForOperation(
+ String name, List<? extends TypedElement<EClassifier>> args) {
+ return delegate.lookupImplicitSourceForOperation(name, args);
+ }
- public EStructuralFeature lookupProperty(EClassifier owner, String name) {
- return delegate.lookupProperty(owner, name);
- }
+ public Variable<EClassifier, EParameter> lookupImplicitSourceForProperty(
+ String name) {
+ return delegate.lookupImplicitSourceForProperty(name);
+ }
- public EReference lookupOppositeProperty(EClassifier owner, String name)
- throws LookupException {
- return delegate.lookupOppositeProperty(owner, name);
- }
+ public Variable<EClassifier, EParameter> lookupImplicitSourceForSignal(
+ String name, List<? extends TypedElement<EClassifier>> args) {
+ return delegate.lookupImplicitSourceForSignal(name, args);
+ }
- public EClassifier getOppositePropertyType(EClassifier owner, EReference property) {
- return delegate.getOppositePropertyType(owner, property);
- }
+ public Variable<EClassifier, EParameter> lookupImplicitSourceForState(
+ List<String> path)
+ throws LookupException, SemanticException {
+ return delegate.lookupImplicitSourceForState(path);
+ }
- public EClassifier lookupSignal(EClassifier owner, String name,
- List<? extends TypedElement<EClassifier>> args) {
- return delegate.lookupSignal(owner, name, args);
- }
+ public Variable<EClassifier, EParameter> lookupLocal(String name) {
+ return delegate.lookupLocal(name);
+ }
- public EObject lookupState(EClassifier owner, List<String> path)
- throws LookupException, SemanticException {
- return delegate.lookupState(owner, path);
- }
+ public EOperation lookupOperation(EClassifier owner, String name,
+ List<? extends TypedElement<EClassifier>> args) {
+ return delegate.lookupOperation(owner, name, args);
+ }
- public void setBodyCondition(EOperation operation, Constraint constraint) {
- delegate.setBodyCondition(operation, constraint);
- }
+ public EPackage lookupPackage(List<String> names) {
+ return delegate.lookupPackage(names);
+ }
- public void setDeriveConstraint(EStructuralFeature property,
- Constraint constraint) {
- delegate.setDeriveConstraint(property, constraint);
- }
+ public EStructuralFeature lookupProperty(EClassifier owner, String name) {
+ return delegate.lookupProperty(owner, name);
+ }
- public void setInitConstraint(EStructuralFeature property,
- Constraint constraint) {
- delegate.setInitConstraint(property, constraint);
- }
+ public EReference lookupOppositeProperty(EClassifier owner, String name)
+ throws LookupException {
+ return delegate.lookupOppositeProperty(owner, name);
+ }
- public void setParent(
- Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> env) {
- delegate.setParent(env);
- }
+ public EClassifier getOppositePropertyType(EClassifier owner, EReference property) {
+ return delegate.getOppositePropertyType(owner, property);
+ }
- public void setSelfVariable(Variable<EClassifier, EParameter> var) {
- delegate.setSelfVariable(var);
- }
+ public EClassifier lookupSignal(EClassifier owner, String name,
+ List<? extends TypedElement<EClassifier>> args) {
+ return delegate.lookupSignal(owner, name, args);
+ }
- public void undefine(Object feature) {
- delegate.undefine(feature);
- }
+ public EObject lookupState(EClassifier owner, List<String> path)
+ throws LookupException, SemanticException {
+ return delegate.lookupState(owner, path);
+ }
+
+ public void setBodyCondition(EOperation operation, Constraint constraint) {
+ delegate.setBodyCondition(operation, constraint);
+ }
+
+ public void setDeriveConstraint(EStructuralFeature property,
+ Constraint constraint) {
+ delegate.setDeriveConstraint(property, constraint);
+ }
+
+ public void setInitConstraint(EStructuralFeature property,
+ Constraint constraint) {
+ delegate.setInitConstraint(property, constraint);
+ }
+
+ public void setParent(
+ Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> env) {
+ delegate.setParent(env);
+ }
+
+ public void setSelfVariable(Variable<EClassifier, EParameter> var) {
+ delegate.setSelfVariable(var);
+ }
+
+ public void undefine(Object feature) {
+ delegate.undefine(feature);
+ }
public Map<String, EReference> getHiddenOppositeProperties(
EClassifier classifier) {
@@ -429,112 +429,112 @@
}
class WrapperEnvironmentFactory implements EnvironmentFactory<
- EPackage, EClassifier, EOperation, EStructuralFeature,
- EEnumLiteral, EParameter,
- EObject, CallOperationAction, SendSignalAction, Constraint,
- EClass, EObject> {
-
- private final EnvironmentFactory<
- EPackage, EClassifier, EOperation, EStructuralFeature,
- EEnumLiteral, EParameter,
- EObject, CallOperationAction, SendSignalAction, Constraint,
- EClass, EObject> delegate;
-
- WrapperEnvironmentFactory(EnvironmentFactory<
- EPackage, EClassifier, EOperation, EStructuralFeature,
- EEnumLiteral, EParameter,
- EObject, CallOperationAction, SendSignalAction, Constraint,
- EClass, EObject> delegate) {
- this.delegate = delegate;
- }
-
- WrapperEnvironmentFactory() {
- this(new EcoreEnvironmentFactory());
- }
+ EPackage, EClassifier, EOperation, EStructuralFeature,
+ EEnumLiteral, EParameter,
+ EObject, CallOperationAction, SendSignalAction, Constraint,
+ EClass, EObject> {
- private Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject>
- getWrappedEnvironment(Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> env) {
- if (env instanceof WrapperEnvironment) {
- return ((WrapperEnvironment) env).delegate;
- } else {
- return env;
- }
- }
-
- public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createAttributeContext(
- Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent,
- EStructuralFeature property) {
- return new WrapperEnvironment(this, delegate.createAttributeContext(getWrappedEnvironment(parent), property), parent);
- }
+ private final EnvironmentFactory<
+ EPackage, EClassifier, EOperation, EStructuralFeature,
+ EEnumLiteral, EParameter,
+ EObject, CallOperationAction, SendSignalAction, Constraint,
+ EClass, EObject> delegate;
- public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createClassifierContext(
- Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent,
- EClassifier context) {
- return new WrapperEnvironment(this, delegate.createClassifierContext(getWrappedEnvironment(parent), context), parent);
- }
+ WrapperEnvironmentFactory(EnvironmentFactory<
+ EPackage, EClassifier, EOperation, EStructuralFeature,
+ EEnumLiteral, EParameter,
+ EObject, CallOperationAction, SendSignalAction, Constraint,
+ EClass, EObject> delegate) {
+ this.delegate = delegate;
+ }
- public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createEnvironment() {
- return new WrapperEnvironment(this, delegate.createEnvironment());
- }
+ WrapperEnvironmentFactory() {
+ this(new EcoreEnvironmentFactory());
+ }
- public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createEnvironment(
- Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent) {
- return new WrapperEnvironment(this, delegate.createEnvironment(getWrappedEnvironment(parent)), parent);
- }
+ private Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject>
+ getWrappedEnvironment(Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> env) {
+ if (env instanceof WrapperEnvironment) {
+ return ((WrapperEnvironment) env).delegate;
+ } else {
+ return env;
+ }
+ }
- public EvaluationEnvironment<EClassifier, EOperation, EStructuralFeature, EClass, EObject> createEvaluationEnvironment() {
- return delegate.createEvaluationEnvironment();
- }
+ public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createAttributeContext(
+ Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent,
+ EStructuralFeature property) {
+ return new WrapperEnvironment(this, delegate.createAttributeContext(getWrappedEnvironment(parent), property), parent);
+ }
- public EvaluationEnvironment<EClassifier, EOperation, EStructuralFeature, EClass, EObject> createEvaluationEnvironment(
- EvaluationEnvironment<EClassifier, EOperation, EStructuralFeature, EClass, EObject> parent) {
- return delegate.createEvaluationEnvironment(parent);
- }
+ public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createClassifierContext(
+ Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent,
+ EClassifier context) {
+ return new WrapperEnvironment(this, delegate.createClassifierContext(getWrappedEnvironment(parent), context), parent);
+ }
- public EvaluationVisitor<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createEvaluationVisitor(
- Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> env,
- EvaluationEnvironment<EClassifier, EOperation, EStructuralFeature, EClass, EObject> evalEnv,
- Map<? extends EClass, ? extends Set<? extends EObject>> extentMap) {
- return delegate.createEvaluationVisitor(env, evalEnv, extentMap);
- }
+ public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createEnvironment() {
+ return new WrapperEnvironment(this, delegate.createEnvironment());
+ }
- public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createInstanceContext(
- Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent,
- Object context) {
- return new WrapperEnvironment(this, delegate.createInstanceContext(getWrappedEnvironment(parent), context), parent);
- }
+ public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createEnvironment(
+ Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent) {
+ return new WrapperEnvironment(this, delegate.createEnvironment(getWrappedEnvironment(parent)), parent);
+ }
- public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createOperationContext(
- Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent,
- EOperation operation) {
- return new WrapperEnvironment(this, delegate.createOperationContext(getWrappedEnvironment(parent), operation), parent);
- }
+ public EvaluationEnvironment<EClassifier, EOperation, EStructuralFeature, EClass, EObject> createEvaluationEnvironment() {
+ return delegate.createEvaluationEnvironment();
+ }
- public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createPackageContext(
- Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent,
- List<String> pathname) {
- return new WrapperEnvironment(this, delegate.createPackageContext(getWrappedEnvironment(parent), pathname), parent);
- }
+ public EvaluationEnvironment<EClassifier, EOperation, EStructuralFeature, EClass, EObject> createEvaluationEnvironment(
+ EvaluationEnvironment<EClassifier, EOperation, EStructuralFeature, EClass, EObject> parent) {
+ return delegate.createEvaluationEnvironment(parent);
+ }
- public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> loadEnvironment(
- Resource resource) {
- return new WrapperEnvironment(this, delegate.loadEnvironment(resource));
- }
+ public EvaluationVisitor<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createEvaluationVisitor(
+ Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> env,
+ EvaluationEnvironment<EClassifier, EOperation, EStructuralFeature, EClass, EObject> evalEnv,
+ Map<? extends EClass, ? extends Set<? extends EObject>> extentMap) {
+ return delegate.createEvaluationVisitor(env, evalEnv, extentMap);
+ }
+
+ public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createInstanceContext(
+ Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent,
+ Object context) {
+ return new WrapperEnvironment(this, delegate.createInstanceContext(getWrappedEnvironment(parent), context), parent);
+ }
+
+ public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createOperationContext(
+ Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent,
+ EOperation operation) {
+ return new WrapperEnvironment(this, delegate.createOperationContext(getWrappedEnvironment(parent), operation), parent);
+ }
+
+ public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createPackageContext(
+ Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent,
+ List<String> pathname) {
+ return new WrapperEnvironment(this, delegate.createPackageContext(getWrappedEnvironment(parent), pathname), parent);
+ }
+
+ public Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> loadEnvironment(
+ Resource resource) {
+ return new WrapperEnvironment(this, delegate.loadEnvironment(resource));
+ }
public Visitor<Boolean, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint> createValidationVisitor(
Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> env) {
- return delegate.createValidationVisitor(env);
+ return delegate.createValidationVisitor(env);
}
public OCLAnalyzer<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createOCLAnalyzer(
Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> env,
String input) {
- return delegate.createOCLAnalyzer(env, input);
+ return delegate.createOCLAnalyzer(env, input);
}
public OCLAnalyzer<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createOCLAnalyzer(
AbstractOCLParser parser) {
- return delegate.createOCLAnalyzer(parser);
+ return delegate.createOCLAnalyzer(parser);
}
public OCLFactoryWithHistory createOCLFactoryWithHistory(
@@ -544,7 +544,7 @@
public OCLSyntaxHelper createOCLSyntaxHelper(
Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> env) {
- return delegate.createOCLSyntaxHelper(env);
+ return delegate.createOCLSyntaxHelper(env);
}
}
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/InitOrDerExpressionTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/InitOrDerExpressionTest.java
index 172b4c4..8a83857 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/InitOrDerExpressionTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/InitOrDerExpressionTest.java
@@ -15,8 +15,6 @@
import java.util.Map;
import java.util.Set;
-import junit.framework.AssertionFailedError;
-
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
@@ -28,6 +26,8 @@
import org.eclipse.ocl.expressions.OCLExpression;
import org.eclipse.ocl.utilities.UMLReflection;
+import junit.framework.AssertionFailedError;
+
/**
* Tests for def expressions (additional properties and operations).
*
@@ -35,15 +35,15 @@
*/
@SuppressWarnings("nls")
public class InitOrDerExpressionTest
- extends AbstractTestSuite {
-
- EClass banana;
+extends AbstractTestSuite {
+
+ EClass banana;
Set<EObject> allApples;
- Map<EClass, Set<EObject>> extents;
+ Map<EClass, Set<EObject>> extents;
EObject aFruit;
EObject anApple;
EObject anotherApple;
-
+
/**
* Tests the parsing the init expression for an attribute from raw text.
*/
@@ -51,19 +51,19 @@
try {
OCLExpression<EClassifier> expr = parseDef(
"package ocltest context Fruit::name : String " +
- "init: ''" +
- " endpackage");
-
+ "init: ''" +
+ " endpackage");
+
Constraint constraint = (Constraint) expr.eContainer().eContainer();
assertNotNull(constraint);
-
+
assertEquals(UMLReflection.INITIAL, constraint.getStereotype());
assertSame(getOCLStandardLibrary().getString(), expr.getType());
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the parsing the derive expression for an attribute from raw text.
*/
@@ -71,30 +71,30 @@
try {
OCLExpression<EClassifier> expr = parseDef(
"package ocltest context Fruit::name : String " +
- "derive: if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif" +
- " endpackage");
-
+ "derive: if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif" +
+ " endpackage");
+
Constraint constraint = (Constraint) expr.eContainer().eContainer();
assertNotNull(constraint);
-
+
assertEquals(UMLReflection.DERIVATION, constraint.getStereotype());
-
+
assertSame(getOCLStandardLibrary().getString(), expr.getType());
-
+
expr = parse(
- "package ocltest context Fruit " +
- "inv: name" +
+ "package ocltest context Fruit " +
+ "inv: name" +
" endpackage");
-
+
assertEquals("unknown fruit", ocl.evaluate(aFruit, expr));
-
+
assertEquals("apple", ocl.evaluate(anApple, expr));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
-
+
+
/**
* Tests the parsing the init expression for a reference from raw text.
*/
@@ -102,12 +102,12 @@
try {
OCLExpression<EClassifier> expr = parseDef(
"package ocltest context Fruit::relatedFruits : Set(Fruit) " +
- "init: Set{self}" +
- " endpackage");
-
+ "init: Set{self}" +
+ " endpackage");
+
Constraint constraint = (Constraint) expr.eContainer().eContainer();
assertNotNull(constraint);
-
+
assertEquals(UMLReflection.INITIAL, constraint.getStereotype());
assertTrue(expr.getType() instanceof SetType);
assertSame(fruit, ((SetType) expr.getType()).getElementType());
@@ -115,7 +115,7 @@
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the parsing the derive expression for a reference from raw text.
*/
@@ -123,93 +123,93 @@
try {
OCLExpression<EClassifier> expr = parseDef(
"package ocltest context Fruit::relatedFruits : Set(Fruit) " +
- "derive: if self.oclIsKindOf(Apple) then " +
- "Apple.allInstances()->excluding(self.oclAsType(Apple)) " +
- "else Fruit.allInstances()->excluding(self) endif" +
- " endpackage");
-
+ "derive: if self.oclIsKindOf(Apple) then " +
+ "Apple.allInstances()->excluding(self.oclAsType(Apple)) " +
+ "else Fruit.allInstances()->excluding(self) endif" +
+ " endpackage");
+
Constraint constraint = (Constraint) expr.eContainer().eContainer();
assertNotNull(constraint);
-
+
assertEquals(UMLReflection.DERIVATION, constraint.getStereotype());
-
+
assertTrue(expr.getType() instanceof SetType);
assertSame(fruit, ((SetType) expr.getType()).getElementType());
-
+
expr = parse(
- "package ocltest context Fruit " +
- "inv: relatedFruits" +
+ "package ocltest context Fruit " +
+ "inv: relatedFruits" +
" endpackage");
-
+
ocl.setExtentMap(extents);
-
+
assertEquals(allApples, ocl.evaluate(aFruit, expr));
-
+
assertEquals(Collections.singleton(anotherApple),
- ocl.evaluate(anApple, expr));
+ ocl.evaluate(anApple, expr));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
-
+
+
/**
* Tests the parsing the init expression for an attribute using the helper.
*/
public void test_init_attribute_helper() {
helper.setAttributeContext(fruit, fruit.getEStructuralFeature("name"));
-
+
try {
Constraint constraint = helper.createInitialValueExpression("''");
-
+
assertNotNull(constraint);
-
+
assertEquals(UMLReflection.INITIAL, constraint.getStereotype());
assertSame(getOCLStandardLibrary().getString(), constraint.getSpecification().getBodyExpression().getType());
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the parsing the derive expression for an attribute using the helper.
*/
public void test_derive_attribute_helper() {
helper.setAttributeContext(fruit, fruit.getEStructuralFeature("name"));
-
+
try {
Constraint constraint = helper.createDerivedValueExpression(
- "if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif");
-
+ "if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif");
+
assertNotNull(constraint);
-
+
assertEquals(UMLReflection.DERIVATION, constraint.getStereotype());
-
+
assertSame(getOCLStandardLibrary().getString(), constraint.getSpecification().getBodyExpression().getType());
-
+
OCLExpression<EClassifier> expr = helper.createQuery("name");
-
+
assertEquals("unknown fruit", ocl.evaluate(aFruit, expr));
-
+
assertEquals("apple", ocl.evaluate(anApple, expr));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
-
+
+
/**
* Tests the parsing the init expression for a reference using the helper.
*/
public void test_init_reference_helper() {
helper.setAttributeContext(fruit, fruit.getEStructuralFeature("relatedFruits"));
-
+
try {
Constraint constraint = helper.createInitialValueExpression("Set{self}");
-
+
assertNotNull(constraint);
OCLExpression<EClassifier> expr = constraint.getSpecification().getBodyExpression();
-
+
assertEquals(UMLReflection.INITIAL, constraint.getStereotype());
assertTrue(expr.getType() instanceof SetType);
assertSame(fruit, ((SetType) expr.getType()).getElementType());
@@ -217,194 +217,194 @@
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the parsing the derive expression for a reference using the helper.
*/
public void test_derive_reference_helper() {
helper.setAttributeContext(fruit, fruit.getEStructuralFeature("relatedFruits"));
-
+
try {
Constraint constraint = helper.createDerivedValueExpression(
"if self.oclIsKindOf(Apple) then " +
- "Apple.allInstances()->excluding(self.oclAsType(Apple)) " +
+ "Apple.allInstances()->excluding(self.oclAsType(Apple)) " +
"else Fruit.allInstances()->excluding(self) endif");
-
+
assertNotNull(constraint);
OCLExpression<EClassifier> expr = constraint.getSpecification().getBodyExpression();
-
+
assertEquals(UMLReflection.DERIVATION, constraint.getStereotype());
-
+
assertTrue(expr.getType() instanceof SetType);
assertSame(fruit, ((SetType) expr.getType()).getElementType());
-
+
expr = helper.createQuery("relatedFruits");
-
+
assertEquals(allApples, ocl.evaluate(aFruit, expr));
-
+
assertEquals(Collections.singleton(anotherApple), ocl.evaluate(anApple, expr));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
public void test_malformedInitExpression() {
helper.setAttributeContext(fruit, fruit.getEStructuralFeature("relatedFruits"));
-
+
try {
helper.createInitialValueExpression(
- "if self.oclIsKindOf(Apple) then 'apple' else 'fruit' endif");
-
+ "if self.oclIsKindOf(Apple) then 'apple' else 'fruit' endif");
+
fail("Should not have parsed");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
}
-
+
public void test_malformedDeriveExpression() {
helper.setAttributeContext(fruit, fruit.getEStructuralFeature("relatedFruits"));
-
+
try {
helper.createDerivedValueExpression(
- "if self.oclIsKindOf(Apple) then 'apple' else 'fruit' endif");
-
+ "if self.oclIsKindOf(Apple) then 'apple' else 'fruit' endif");
+
fail("Should not have parsed");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
}
-
+
public void test_bothInitAndDeriveExpressions() {
try {
parseDef(
"package ocltest context Fruit::name : String " +
- "init: 'not a fruit' " +
- "derive: if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif " +
- " endpackage");
-
+ "init: 'not a fruit' " +
+ "derive: if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif " +
+ " endpackage");
+
// either order is OK
parseDef(
"package ocltest context Fruit::name : String " +
- "derive: if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif " +
- "init: 'not a fruit' " +
- " endpackage");
+ "derive: if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif " +
+ "init: 'not a fruit' " +
+ " endpackage");
} catch (Exception e) {
fail("Should not have failed to parse: " + e.getLocalizedMessage());
}
}
-
+
public void test_tooManyInitAndDeriveExpressions() {
AssertionFailedError err = null;
-
+
try {
parseDef(
"package ocltest context Fruit::name : String " +
- "init: 'not a fruit' " +
- "init: 'not a fruit' " +
- " endpackage");
+ "init: 'not a fruit' " +
+ "init: 'not a fruit' " +
+ " endpackage");
} catch (AssertionFailedError e) {
// success
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
assertNotNull("Should not have successfully parsed", err);
err = null;
-
+
try {
parseDef(
"package ocltest context Fruit::name : String " +
- "derive: if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif " +
- "derive: if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif " +
- " endpackage");
+ "derive: if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif " +
+ "derive: if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif " +
+ " endpackage");
} catch (AssertionFailedError e) {
// success
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
assertNotNull("Should not have successfully parsed", err);
err = null;
-
+
try {
parseDef(
"package ocltest context Fruit::name : String " +
- "init: 'not a fruit' " +
- "derive: if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif " +
- "init: 'not a fruit' " +
- " endpackage");
+ "init: 'not a fruit' " +
+ "derive: if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif " +
+ "init: 'not a fruit' " +
+ " endpackage");
} catch (AssertionFailedError e) {
// success
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
assertNotNull("Should not have successfully parsed", err);
err = null;
-
+
try {
parseDef(
"package ocltest context Fruit::name : String " +
- "derive: if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif " +
- "init: 'not a fruit' " +
- "derive: if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif " +
- " endpackage");
+ "derive: if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif " +
+ "init: 'not a fruit' " +
+ "derive: if self.oclIsKindOf(Apple) then 'apple' else 'unknown fruit' endif " +
+ " endpackage");
} catch (AssertionFailedError e) {
// success
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
assertNotNull("Should not have successfully parsed", err);
err = null;
}
-
+
//
// Framework methods
//
-
+
@Override
- protected void setUp() {
+ protected void setUp() {
super.setUp();
expectModified = true;
banana = EcoreFactory.eINSTANCE.createEClass();
banana.setName("Banana");
banana.getESuperTypes().add(fruit);
fruitPackage.getEClassifiers().add(banana);
-
+
aFruit = fruitFactory.create(banana);
-
+
anApple = fruitFactory.create(apple);
anotherApple = fruitFactory.create(apple);
-
+
allApples = new java.util.HashSet<EObject>();
allApples.add(anApple);
allApples.add(anotherApple);
-
+
extents = new java.util.HashMap<EClass, Set<EObject>>();
extents.put(apple, allApples);
extents.put(banana, Collections.singleton(aFruit));
-
+
Set<EObject> allFruits = new java.util.HashSet<EObject>();
allFruits.addAll(allApples);
allFruits.add(aFruit);
extents.put(fruit, allFruits);
-
+
// for evaluation in the helper, to find all instances of an EClass
Resource res = new ResourceImpl();
res.getContents().addAll(allFruits);
}
-
+
@Override
- protected void tearDown() throws Exception {
+ protected void tearDown() throws Exception {
extents = null;
allApples = null;
-
+
fruitPackage.getEClassifiers().remove(banana);
banana = null;
-
+
super.tearDown();
}
}
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/MessagesTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/MessagesTest.java
index e20de93..a436ed3 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/MessagesTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/MessagesTest.java
@@ -44,14 +44,14 @@
*/
@SuppressWarnings("nls")
public class MessagesTest
- extends AbstractTestSuite {
-
+extends AbstractTestSuite {
+
/**
* Tests the parsing of the hasSent ("^") expression for operations.
*/
public void test_hasSent_operation() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
// test query operation calls without any arguments
helper.createPostcondition("self^preferredColor()");
@@ -63,19 +63,19 @@
// interesting expression as the target
helper.createPostcondition(
"Apple.allInstances()->any(true) ^ripen(Color::yellow)");
-
+
// test operation calls with multiple arguments
helper.createPostcondition(
"Fruit.allInstances()->forAll(f | self^setColor(f, Color::red))");
-
+
// test operation signature conformance matching
helper.createPostcondition(
"Apple.allInstances()->forAll(a | self^setColor(a, Color::red))");
-
+
// test operation signature conformance matching with null object type
helper.createPostcondition(
"Apple.allInstances()->forAll(a | self^setColor(null, Color::red))");
-
+
// test operation signature conformance matching with null data type
helper.createPostcondition(
"Apple.allInstances()->forAll(a | self^setColor(a, null))");
@@ -83,92 +83,92 @@
fail("Failed to parse: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the validation of the hasSent ("^") expression for operations.
*/
public void test_hasSent_operation_validation() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
// non-existent operation
helper.createPostcondition("self^label('foo')");
-
+
fail("Should have failed to parse unknown operation");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
try {
// non-conformant argument
helper.createPostcondition("self^setColor(self, 'red')");
-
+
fail("Should have failed to parse non-conformant arg");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests parsing of the hasSent ("^") expression with unspecified value
* expressions for operations.
*/
public void test_hasSent_operation_unspecifiedValue() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
helper.createPostcondition(
"Apple.allInstances()->any(true)^ripen(? : Color)");
-
+
helper.createPostcondition(
"Fruit.allInstances()->forAll(f | self^setColor(? : Fruit, ? : Color))");
-
+
helper.createPostcondition(
"Apple.allInstances()->any(true)^ripen(?)");
-
+
helper.createPostcondition(
"Fruit.allInstances()->forAll(f | self^setColor(?, ?))");
} catch (Exception e) {
fail("Failed to parse: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests validation of the hasSent ("^") expression with unspecified value
* expressions for operations.
*/
public void test_hasSent_operation_unspecifiedValue_validation() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
// non-existent operation
helper.createPostcondition("self^label(?)");
-
+
fail("Should have failed to parse unknown operation");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
try {
// non-conformant argument
helper.createPostcondition("self^setColor(self, ? : String)");
-
+
fail("Should have failed to parse non-conformant arg");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the parsing of the sentMessages ("^^") expression for operations.
*/
public void test_sentMessages_operation() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
// test query operation calls without any arguments
helper.createPostcondition(
@@ -181,19 +181,19 @@
// interesting expression as the target
helper.createPostcondition(
"Apple.allInstances()->any(true)^^ripen(Color::yellow)->notEmpty()");
-
+
// test operation calls with multiple arguments
helper.createPostcondition(
"Fruit.allInstances()->collect(f | self^^setColor(f, Color::red))->notEmpty()");
-
+
// test operation signature conformance matching
helper.createPostcondition(
"Apple.allInstances()->collect(a | self^^setColor(a, Color::red))->notEmpty()");
-
+
// test operation signature conformance matching with null object type
helper.createPostcondition(
"Apple.allInstances()->collect(a | self^^setColor(null, Color::red))->notEmpty()");
-
+
// test operation signature conformance matching with null data type
helper.createPostcondition(
"Apple.allInstances()->collect(a | self^^setColor(a, null))->notEmpty()");
@@ -201,17 +201,17 @@
fail("Failed to parse: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the parsing of OclMessage expressions for operations.
*/
public void test_message_access_operation() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
// test type conformance
helper.createPostcondition(
- "let msgs : Sequence(OclMessage) = self^^preferredColor() in " +
+ "let msgs : Sequence(OclMessage) = self^^preferredColor() in " +
"msgs->forAll(m | m.hasReturned() and m.isOperationCall() and not m.isSignalSent())");
// test non-query operation calls without any arguments
@@ -221,55 +221,55 @@
// interesting expression as the target
helper.createPostcondition(
"Apple.allInstances()->any(true)^^ripen(Color::yellow)->notEmpty()");
-
+
// types of the OclMessage properties are determined by the actual
// operation type, not by the MessageExp arguments
helper.createPostcondition(
- "let msgs : Collection(OclMessage) = Fruit.allInstances()->collect(f | self^^setColor(?, ?)) in " +
+ "let msgs : Collection(OclMessage) = Fruit.allInstances()->collect(f | self^^setColor(?, ?)) in " +
"msgs->forAll(m | m.fruit.color = Color::black implies m.newColor = Color::black)");
-
+
// return values
helper.createPostcondition(
- "let msgs : Collection(OclMessage) = Fruit.allInstances()->collect(f | self^^newFruit()) in " +
+ "let msgs : Collection(OclMessage) = Fruit.allInstances()->collect(f | self^^newFruit()) in " +
"msgs->forAll(m | m.hasReturned() implies m.result().color = Color::green)");
} catch (Exception e) {
fail("Failed to parse: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the validation of the setMessages ("^^") expression for operations.
*/
public void test_sentMessages_operation_validation() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
// non-existent operation
helper.createPostcondition("self^^label('foo')->notEmpty()");
-
+
fail("Should have failed to parse unknown operation");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
try {
// non-conformant argument
helper.createPostcondition("self^^setColor(self, 'red')->notEmpty()");
-
+
fail("Should have failed to parse non-conformant arg");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the parsing of the hasSent ("^") expression for signals.
*/
public void test_hasSent_signal() {
helper.setOperationContext(apple, fruit_ripen);
-
+
try {
helper.createPostcondition("self^Drop(3, self.stem)");
@@ -281,50 +281,50 @@
helper.createPostcondition(
"Apple.allInstances()->any(true)^Drop(3, stem)");
-
+
helper.createPostcondition(
"Apple.allInstances()->exists(a | a^Drop(3, stem))");
-
+
helper.createPostcondition(
"Fruit.allInstances()->forAll(f | f^Drop(?, ?) implies self^Drop(?, ?))");
} catch (Exception e) {
fail("Failed to parse: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the validation of the hasSent ("^") expression for signals.
*/
public void test_hasSent_signal_validation() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
// non-existent signal
helper.createPostcondition("self^Rot(3, stem)");
-
+
fail("Should have failed to parse unknown signal");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
try {
// non-conformant argument
helper.createPostcondition("self^Drop('red', ?)");
-
+
fail("Should have failed to parse non-conformant arg");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the parsing of the sentMessages ("^^") expression for signals.
*/
public void test_sentMessages_signal() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
helper.createPostcondition(
"self^^Drop(3, self.oclAsType(Apple).stem)->notEmpty()");
@@ -333,82 +333,82 @@
helper.createPostcondition(
"Apple.allInstances()->any(true)^^Drop(3, ?)->notEmpty()");
-
+
helper.createPostcondition(
"Apple.allInstances()->collect(a | self^^Drop(null, ? : Stem))->notEmpty()");
-
+
helper.createPostcondition(
"Apple.allInstances()->collect(a | self^^Drop(3, null))->notEmpty()");
} catch (Exception e) {
fail("Failed to parse: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the parsing of OclMessage expressions for signals.
*/
public void test_message_access_signal() {
helper.setOperationContext(apple, fruit_ripen);
-
+
try {
helper.createPostcondition(
- "let msgs : Sequence(OclMessage) = self^^Drop(?, ?) in " +
+ "let msgs : Sequence(OclMessage) = self^^Drop(?, ?) in " +
"msgs->forAll(m | m.isSignalSent() and not m.isOperationCall())");
helper.createPostcondition("self^^Drop(?, ?)->first().oclIsKindOf(OclMessage)");
helper.createPostcondition(
- "let msgs : Collection(OclMessage) = Fruit.allInstances()->collect(f | self^^Drop(?, ?)) in " +
+ "let msgs : Collection(OclMessage) = Fruit.allInstances()->collect(f | self^^Drop(?, ?)) in " +
"msgs->forAll(m | m.delay > 0 and stem <> self.stem)");
} catch (Exception e) {
fail("Failed to parse: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the validation of the setMessages ("^^") expression for signals.
*/
public void test_sentMessages_signal_validation() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
// non-existent signal
helper.createPostcondition("self^^Rot('now')->notEmpty()");
-
+
fail("Should have failed to parse unknown signal");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
try {
// non-conformant argument
helper.createPostcondition("self^^Drop(self, ?)->notEmpty()");
-
+
fail("Should have failed to parse non-conformant arg");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the presentation of operation call choices.
*/
public void test_contentAssist_operations() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.POSTCONDITION,
+ ConstraintKind.POSTCONDITION,
"self^");
assertNotNull(choices);
assertChoice(choices, ChoiceKind.OPERATION, "newFruit");
assertChoice(choices, ChoiceKind.OPERATION, "setColor");
assertNotChoice(choices, ChoiceKind.OPERATION, "oclIsKindOf");
-
+
choices = helper.getSyntaxHelp(
- ConstraintKind.POSTCONDITION, "self^^");
+ ConstraintKind.POSTCONDITION, "self^^");
assertNotNull(choices);
assertChoice(choices, ChoiceKind.OPERATION, "newFruit");
assertChoice(choices, ChoiceKind.OPERATION, "setColor");
@@ -416,21 +416,21 @@
// doesn't parse
choices = helper.getSyntaxHelp(
- ConstraintKind.POSTCONDITION, "self^^^");
+ ConstraintKind.POSTCONDITION, "self^^^");
assertNotNull(choices);
assertChoice(choices, ChoiceKind.VARIABLE, "color");
choices = helper.getSyntaxHelp(
- ConstraintKind.POSTCONDITION,
+ ConstraintKind.POSTCONDITION,
"Apple.allInstances()->any(true)^");
assertNotNull(choices);
assertChoice(choices, ChoiceKind.OPERATION, "newFruit");
assertChoice(choices, ChoiceKind.OPERATION, "setColor");
assertChoice(choices, ChoiceKind.OPERATION, "label");
assertNotChoice(choices, ChoiceKind.OPERATION, "oclIsKindOf");
-
+
choices = helper.getSyntaxHelp(
- ConstraintKind.POSTCONDITION,
+ ConstraintKind.POSTCONDITION,
"Apple.allInstances()->collect(a : Apple | a^^");
assertNotNull(choices);
assertChoice(choices, ChoiceKind.OPERATION, "newFruit");
@@ -441,39 +441,39 @@
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the presentation of signal send choices.
*/
public void test_contentAssist_signals() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.POSTCONDITION,
+ ConstraintKind.POSTCONDITION,
"self^");
assertNotNull(choices);
assertChoice(choices, ChoiceKind.SIGNAL, "Drop");
choices = helper.getSyntaxHelp(
- ConstraintKind.POSTCONDITION, "self^^");
+ ConstraintKind.POSTCONDITION, "self^^");
assertNotNull(choices);
assertChoice(choices, ChoiceKind.SIGNAL, "Drop");
// doesn't parse
choices = helper.getSyntaxHelp(
- ConstraintKind.POSTCONDITION, "self^^^");
+ ConstraintKind.POSTCONDITION, "self^^^");
assertNotNull(choices);
assertChoice(choices, ChoiceKind.VARIABLE, "color");
choices = helper.getSyntaxHelp(
- ConstraintKind.POSTCONDITION,
+ ConstraintKind.POSTCONDITION,
"Apple.allInstances()->any(true)^");
assertNotNull(choices);
assertChoice(choices, ChoiceKind.SIGNAL, "Drop");
-
+
choices = helper.getSyntaxHelp(
- ConstraintKind.POSTCONDITION,
+ ConstraintKind.POSTCONDITION,
"Apple.allInstances()->collect(a : Apple | a^^");
assertNotNull(choices);
assertChoice(choices, ChoiceKind.SIGNAL, "Drop");
@@ -481,68 +481,68 @@
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
//
// Test framework
//
-
+
@Override
protected OCL createOCL() {
return OCL.newInstance(new MessagingFruitEnvironmentFactory(this));
}
-
+
@Override
- public void setUp() {
+ public void setUp() {
super.setUp();
expectModified = true;
}
-
+
public static class MessagingFruitEnvironmentFactory extends EcoreEnvironmentFactory {
protected final AbstractTestSuite suite;
-
+
public MessagingFruitEnvironmentFactory(AbstractTestSuite suite) {
this.suite = suite;
}
-
+
@Override
- public EcoreEnvironment createEnvironment() {
+ public EcoreEnvironment createEnvironment() {
return new MessagingFruitEnvironment(this, suite);
}
@Override
- public EcoreEnvironment createEnvironment(
+ public EcoreEnvironment createEnvironment(
Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent) {
return new MessagingFruitEnvironment(parent, suite);
}
}
-
+
private static class MessagingFruitEnvironment extends EcoreEnvironment implements InitEnvironment {
protected final AbstractTestSuite suite;
private EClass dropSignal;
-
+
private EList<EClassifier> signals = new BasicEList<EClassifier>();
-
+
public MessagingFruitEnvironment(MessagingFruitEnvironmentFactory factory, AbstractTestSuite suite) {
super(factory, null);
this.suite = suite;
setContextPackage(suite.fruitPackage);
-// init();
+ // init();
}
-
+
public MessagingFruitEnvironment(
Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent, AbstractTestSuite suite) {
super(parent);
this.suite = suite;
-
+
init();
}
-
+
public void init() {
dropSignal = EcoreFactory.eINSTANCE.createEClass();
dropSignal.setName("Drop");
-
+
EStructuralFeature property = EcoreFactory.eINSTANCE.createEAttribute();
property.setName("delay");
property.setEType(getOCLStandardLibrary().getReal());
@@ -551,24 +551,24 @@
property.setName("stem");
property.setEType(suite.stem);
dropSignal.getEStructuralFeatures().add(property);
-
+
signals.add(dropSignal);
-
+
suite.fruitPackage.getEClassifiers().add(dropSignal);
}
-
- @Override
- public UMLReflection<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint> getUMLReflection() {
- return new UMLReflectionImpl() {
- @Override
- public List<EClassifier> getSignals(EClassifier owner) {
- if (owner == suite.fruit || owner == suite.apple) {
- return signals;
- }
-
- return super.getSignals(owner);
- }};
- }
+
+ @Override
+ public UMLReflection<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint> getUMLReflection() {
+ return new UMLReflectionImpl() {
+ @Override
+ public List<EClassifier> getSignals(EClassifier owner) {
+ if (owner == suite.fruit || owner == suite.apple) {
+ return signals;
+ }
+
+ return super.getSignals(owner);
+ }};
+ }
}
}
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/OCLDocumentTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/OCLDocumentTest.java
index 1a8bc6f..024ff5b 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/OCLDocumentTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/OCLDocumentTest.java
@@ -44,42 +44,42 @@
public class OCLDocumentTest extends AbstractTestSuite {
Map<String, Constraint> constraints;
-
+
public void test_multipleInvariants() {
Constraint notBlack = getConstraint("not_black");
Constraint notFoo = getConstraint("not_foo");
-
+
assertMatchingContextVariables(fruit, notBlack);
assertMatchingContextVariables(fruit, notFoo);
-
+
EObject anApple = fruitFactory.create(apple);
anApple.eSet(fruit_color, color_black);
anApple.eSet(apple_label, "Foo");
-
+
// this constraint actually uses the derivation of the Fruit::name
// property, defined in the Apple context :-)
assertFalse(ocl.check(anApple, notFoo));
assertFalse(ocl.check(anApple, notBlack));
-
+
anApple.eSet(fruit_color, color_red);
anApple.eSet(apple_label, "Bar");
-
+
assertTrue(ocl.check(anApple, notFoo));
assertTrue(ocl.check(anApple, notBlack));
}
-
+
public void test_multipleDefExpressions() {
assertMatchingContextVariables(fruit, getConstraint("property_helper"));
assertMatchingContextVariables(fruit, getConstraint("operation_helper"));
-
+
EObject anApple = fruitFactory.create(apple);
anApple.eSet(fruit_color, color_black);
anApple.eSet(apple_label, "Foo");
-
+
EObject anotherApple = fruitFactory.create(apple);
anotherApple.eSet(fruit_color, color_red);
anotherApple.eSet(apple_label, "Bar");
-
+
Set<EObject> apples = new java.util.HashSet<EObject>();
apples.add(anApple);
apples.add(anotherApple);
@@ -87,15 +87,15 @@
extentMap.put(apple, apples);
extentMap.put(fruit, apples);
ocl.setExtentMap(extentMap);
-
+
helper = ocl.createOCLHelper();
helper.setContext(apple);
-
+
try {
// test the additional property
Object value = evaluate(helper, anApple, "self.otherFruits");
assertEquals(Collections.singleton(anotherApple), value);
-
+
// test the additional operation
value = evaluate(helper, anotherApple, "self.getOtherFruits(false)");
assertEquals(Collections.singleton(anApple), value);
@@ -103,38 +103,38 @@
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
public void test_multipleInvariantsAndDefExpressions() {
Constraint notBlack = getConstraint("not_black1");
Constraint notFoo = getConstraint("not_foo1");
-
+
assertMatchingContextVariables(fruit, notBlack);
assertMatchingContextVariables(fruit, notFoo);
assertMatchingContextVariables(fruit, getConstraint("property_helper"));
assertMatchingContextVariables(fruit, getConstraint("operation_helper"));
-
+
EObject anApple = fruitFactory.create(apple);
anApple.eSet(fruit_color, color_black);
anApple.eSet(apple_label, "Foo");
-
+
// this constraint actually uses the derivation of the Fruit::name
// property, defined in the Apple context :-)
assertFalse(ocl.check(anApple, notFoo));
assertFalse(ocl.check(anApple, notBlack));
-
+
anApple.eSet(fruit_color, color_red);
anApple.eSet(apple_label, "Bar");
-
+
assertTrue(ocl.check(anApple, notFoo));
assertTrue(ocl.check(anApple, notBlack));
-
+
anApple.eSet(fruit_color, color_black);
anApple.eSet(apple_label, "Foo");
-
+
EObject anotherApple = fruitFactory.create(apple);
anotherApple.eSet(fruit_color, color_red);
anotherApple.eSet(apple_label, "Bar");
-
+
Set<EObject> apples = new java.util.HashSet<EObject>();
apples.add(anApple);
apples.add(anotherApple);
@@ -142,15 +142,15 @@
extentMap.put(apple, apples);
extentMap.put(fruit, apples);
ocl.setExtentMap(extentMap);
-
+
helper = ocl.createOCLHelper();
helper.setContext(apple);
-
+
try {
// test the additional property
Object value = evaluate(helper, anApple, "self.otherFruits1");
assertEquals(Collections.singleton(anotherApple), value);
-
+
// test the additional operation
value = evaluate(helper, anotherApple, "self.getOtherFruits1(false)");
assertEquals(Collections.singleton(anApple), value);
@@ -158,145 +158,145 @@
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
public void test_multipleMixedOperationConstraints() {
Constraint textNotNull = getConstraint("text_not_null");
Constraint textNotLabel = getConstraint("text_not_label");
Constraint computeLabel = getConstraint("compute_label");
Constraint labelIsChanged = getConstraint("label_is_changed");
Constraint labelIsSet = getConstraint("label_is_set");
-
+
assertEquals(1, textNotNull.getConstrainedElements().size());
EOperation oper = (EOperation) textNotNull.getConstrainedElements().get(0);
assertNotNull(oper);
assertEquals(UMLReflection.PRECONDITION, textNotNull.getStereotype());
assertNotNull(textNotNull.getSpecification().getBodyExpression());
assertMatchingContextVariables(oper, textNotNull);
-
+
assertEquals(1, textNotLabel.getConstrainedElements().size());
assertSame(oper, textNotLabel.getConstrainedElements().get(0));
assertEquals(UMLReflection.PRECONDITION, textNotLabel.getStereotype());
assertNotNull(textNotLabel.getSpecification().getBodyExpression());
assertMatchingContextVariables(oper, textNotLabel);
-
+
assertEquals(1, computeLabel.getConstrainedElements().size());
assertSame(oper, computeLabel.getConstrainedElements().get(0));
assertEquals(UMLReflection.BODY, computeLabel.getStereotype());
assertNotNull(computeLabel.getSpecification().getBodyExpression());
assertMatchingContextVariables(oper, computeLabel);
-
+
assertEquals(1, labelIsChanged.getConstrainedElements().size());
assertSame(oper, labelIsChanged.getConstrainedElements().get(0));
assertEquals(UMLReflection.POSTCONDITION, labelIsChanged.getStereotype());
assertNotNull(labelIsChanged.getSpecification().getBodyExpression());
assertMatchingContextVariables(oper, labelIsChanged);
-
+
assertEquals(1, labelIsSet.getConstrainedElements().size());
assertSame(oper, labelIsSet.getConstrainedElements().get(0));
assertEquals(UMLReflection.POSTCONDITION, labelIsSet.getStereotype());
assertNotNull(labelIsSet.getSpecification().getBodyExpression());
assertMatchingContextVariables(oper, labelIsSet);
}
-
+
public void test_initAndDerConstraints() {
helper.setContext(apple);
-
+
try {
EObject anApple = fruitFactory.create(apple);
anApple.eSet(apple_label, "Foo");
-
+
assertEquals("Foo", evaluate(helper, anApple, "self.name"));
-
+
anApple.eUnset(apple_label);
-
+
assertEquals("", evaluate(helper, anApple, "self.name"));
} catch (ParserException e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
- /**
- * Tests that we get a proper ParserException from parsing an operation
- * context declaration that is missing the classifier (qualified) name.
- */
- public void test_operationContextWithoutClassifierName_182286() {
- try {
- ocl.parse(new OCLInput(
- "context label(s : String) : \n" +
- " pre: true"
- ));
- } catch (ParserException e) {
- // success
- System.out.println("Got expected exception: " + e.getLocalizedMessage());
- } catch (RuntimeException e) {
- fail("Got runtime exception: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * Tests that a constraint can reference an operation defined in a package
- * context earlier in the OCL document.
- */
- public void test_dependenciesOnDefExpressions_packageContext_176109() {
- try {
- ocl.parse(new OCLInput(
- "package ecore context EClassifier \n" +
- "def: isHappy() : Boolean = true \n" +
- "endpackage \n" +
- "package ecore context ETypedElement \n" +
- "inv: eType <> null implies eType.isHappy() \n" +
- "endpackage \n"
- ));
- } catch (ParserException e) {
- fail("Should not have failed to parse: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * Tests that a constraint can reference an operation defined in a classifier
- * context earlier in the OCL document.
- */
- public void test_dependenciesOnDefExpressions_classifierContext_176109() {
- try {
- ocl.parse(new OCLInput(
- "package ecore \n" +
- "context EClassifier \n" +
- "def: isHappy() : Boolean = true \n" +
- "context ETypedElement \n" +
- "inv: eType <> null implies eType.isHappy() \n" +
- "endpackage \n"
- ));
- } catch (ParserException e) {
- fail("Should not have failed to parse: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * Tests that a constraint can reference an operation defined ahead of it in
- * the same classifier context.
- */
- public void test_dependenciesOnDefExpressions_withinClassifierContext_176109() {
- try {
- ocl.parse(new OCLInput(
- "package ecore \n" +
- "context EClassifier \n" +
- "def: isHappy() : Boolean = true \n" +
- "inv: self.isHappy() \n" +
- "endpackage \n"
- ));
- } catch (ParserException e) {
- fail("Should not have failed to parse: " + e.getLocalizedMessage());
- }
- }
-
+
+ /**
+ * Tests that we get a proper ParserException from parsing an operation
+ * context declaration that is missing the classifier (qualified) name.
+ */
+ public void test_operationContextWithoutClassifierName_182286() {
+ try {
+ ocl.parse(new OCLInput(
+ "context label(s : String) : \n" +
+ " pre: true"
+ ));
+ } catch (ParserException e) {
+ // success
+ debugPrintln("Got expected exception: " + e.getLocalizedMessage());
+ } catch (RuntimeException e) {
+ fail("Got runtime exception: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests that a constraint can reference an operation defined in a package
+ * context earlier in the OCL document.
+ */
+ public void test_dependenciesOnDefExpressions_packageContext_176109() {
+ try {
+ ocl.parse(new OCLInput(
+ "package ecore context EClassifier \n" +
+ "def: isHappy() : Boolean = true \n" +
+ "endpackage \n" +
+ "package ecore context ETypedElement \n" +
+ "inv: eType <> null implies eType.isHappy() \n" +
+ "endpackage \n"
+ ));
+ } catch (ParserException e) {
+ fail("Should not have failed to parse: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests that a constraint can reference an operation defined in a classifier
+ * context earlier in the OCL document.
+ */
+ public void test_dependenciesOnDefExpressions_classifierContext_176109() {
+ try {
+ ocl.parse(new OCLInput(
+ "package ecore \n" +
+ "context EClassifier \n" +
+ "def: isHappy() : Boolean = true \n" +
+ "context ETypedElement \n" +
+ "inv: eType <> null implies eType.isHappy() \n" +
+ "endpackage \n"
+ ));
+ } catch (ParserException e) {
+ fail("Should not have failed to parse: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests that a constraint can reference an operation defined ahead of it in
+ * the same classifier context.
+ */
+ public void test_dependenciesOnDefExpressions_withinClassifierContext_176109() {
+ try {
+ ocl.parse(new OCLInput(
+ "package ecore \n" +
+ "context EClassifier \n" +
+ "def: isHappy() : Boolean = true \n" +
+ "inv: self.isHappy() \n" +
+ "endpackage \n"
+ ));
+ } catch (ParserException e) {
+ fail("Should not have failed to parse: " + e.getLocalizedMessage());
+ }
+ }
+
//
// Framework methods
//
-
+
@Override
protected void setUp() {
super.setUp();
-
+
constraints = new java.util.HashMap<String, Constraint>();
URI uri = getTestModelURI("/model/test_constraints.ocl");
try {
@@ -306,58 +306,58 @@
is.close();
for (Constraint ct : parsed) {
- validate(ct);
+ validate(ct);
constraints.put(ct.getName(), ct);
}
} catch (Exception e) {
fail("Failed to parse " + uri + " : " + e.getMessage());
- }
+ }
}
-
+
Constraint getConstraint(String name) {
Constraint result = constraints.get(name);
assertNotNull("Did not find constraint " + name, result);
return result;
}
-
+
void assertMatchingContextVariables(EClassifier context, Constraint constraint) {
ExpressionInOCL spec = (ExpressionInOCL) constraint.getSpecification();
EcoreEnvironment env = (EcoreEnvironment) ocl.getEnvironment();
-
+
Variable<EClassifier, EParameter> selfVar = spec.getContextVariable();
assertNotNull(selfVar);
assertEquals(Environment.SELF_VARIABLE_NAME, selfVar.getName());
assertEquals(selfVar.getType(), env.getUMLReflection().getOCLType(context));
}
-
+
void assertMatchingContextVariables(EOperation operation, Constraint constraint) {
ExpressionInOCL spec = (ExpressionInOCL) constraint.getSpecification();
EcoreEnvironment env = (EcoreEnvironment) ocl.getEnvironment();
-
+
if (operation.getEContainingClass() != null) {
Variable<EClassifier, EParameter> selfVar = spec.getContextVariable();
assertNotNull(selfVar);
assertEquals(Environment.SELF_VARIABLE_NAME, selfVar.getName());
assertEquals(selfVar.getType(), env.getUMLReflection().getOCLType(operation.getEContainingClass()));
}
-
+
if ((operation.getEType() != null)
&& !UMLReflection.PRECONDITION.equals(constraint.getStereotype())) {
-
+
Variable<EClassifier, EParameter> resultVar = spec.getResultVariable();
assertNotNull(resultVar);
assertEquals(Environment.RESULT_VARIABLE_NAME, resultVar.getName());
assertEquals(resultVar.getType(), env.getUMLReflection().getOCLType(operation));
}
-
+
EList<EParameter> parms = operation.getEParameters();
EList<Variable<EClassifier, EParameter>> vars = spec.getParameterVariable();
-
+
assertEquals(parms.size(), vars.size());
for (int i = 0; i < parms.size(); i++) {
Variable<EClassifier, EParameter> var = vars.get(i);
EParameter parm = parms.get(i);
-
+
assertEquals(var.getType(), env.getUMLReflection().getOCLType(parm));
}
}
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/OperationConstraintsTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/OperationConstraintsTest.java
index 7d21ed1..3e29b48 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/OperationConstraintsTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/OperationConstraintsTest.java
@@ -16,8 +16,6 @@
import java.util.Collections;
import java.util.Iterator;
-import junit.framework.AssertionFailedError;
-
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
@@ -34,6 +32,8 @@
import org.eclipse.ocl.expressions.PropertyCallExp;
import org.eclipse.ocl.expressions.VariableExp;
+import junit.framework.AssertionFailedError;
+
/**
* Tests support for operation constraints (pre/post/body).
@@ -42,17 +42,17 @@
*/
@SuppressWarnings("nls")
public class OperationConstraintsTest extends AbstractTestSuite {
-
+
/**
* Tests a very simple precondition, with a package and operation context.
*/
public void test_simplePrecondition() {
parseConstraint(
"package ocltest context Fruit::ripen(color : Color) : Boolean " +
- "pre: color <> Color::black " +
- "endpackage");
+ "pre: color <> Color::black " +
+ "endpackage");
}
-
+
/**
* Tests a very simple postcondition, with a package and operation context
* and using the "self" variable to disambiguate the name "color".
@@ -60,60 +60,60 @@
public void test_simplePostcondition() {
parseConstraint(
"package ocltest context Fruit::ripen(color : Color) : Boolean " +
- "post: self.color = color " +
- "endpackage");
+ "post: self.color = color " +
+ "endpackage");
}
-
- /**
- * Now that body expressions can be specified as OCL intended, we can use
- * them to evaluate operations at run-time.
- */
- public void test_passingOclInvalidToOperation() {
- parseConstraint(
- "package ocltest context Fruit::ripen(color : Color) : Boolean " +
- "body: color.oclIsInvalid() " +
- "endpackage");
-
- OCLExpression<EClassifier> query = parse(
- "package ocltest context Apple " +
- "inv: self.ripen(if 1.3 / 0 > 1.3 then Color::black else Color::red endif) " +
- "endpackage");
-
- EObject anApple = fruitFactory.create(apple);
- anApple.eSet(fruit_color, color_black);
- assertTrue((Boolean) evaluate(query, anApple));
- }
- /**
+ /**
+ * Now that body expressions can be specified as OCL intended, we can use
+ * them to evaluate operations at run-time.
+ */
+ public void test_passingOclInvalidToOperation() {
+ parseConstraint(
+ "package ocltest context Fruit::ripen(color : Color) : Boolean " +
+ "body: color.oclIsInvalid() " +
+ "endpackage");
+
+ OCLExpression<EClassifier> query = parse(
+ "package ocltest context Apple " +
+ "inv: self.ripen(if 1.3 / 0 > 1.3 then Color::black else Color::red endif) " +
+ "endpackage");
+
+ EObject anApple = fruitFactory.create(apple);
+ anApple.eSet(fruit_color, color_black);
+ assertTrue((Boolean) evaluate(query, anApple));
+ }
+
+ /**
* Tests a postcondition containing the "@ pre" construct.
*/
public void test_postcondition_atPre() {
parseConstraint(
"package ocltest context Fruit::ripen(c : Color) : Boolean " +
- "post: color <> color@ pre implies color = c " +
- "endpackage");
+ "post: color <> color@ pre implies color = c " +
+ "endpackage");
}
-
+
/**
* Tests a postcondition containing the "@pre" construct on an operation call.
*/
public void test_postcondition_atPre_operation() {
parseConstraint(
"package ocltest context Fruit::ripen(c : Color) : Boolean " +
- "post: preferredColor() <> preferredColor@pre() implies color = c " +
- "endpackage");
+ "post: preferredColor() <> preferredColor@pre() implies color = c " +
+ "endpackage");
}
-
+
/**
* Tests availability of the special "result" variable in postconditions.
*/
public void test_postcondition_result() {
parseConstraint(
"package ocltest context Fruit::ripen(c : Color) : Boolean " +
- "post: result implies color <> color@pre " +
- "endpackage");
+ "post: result implies color <> color@pre " +
+ "endpackage");
}
-
+
/**
* Tests that in case of multiple constraints, each defines its own namespace
* for local variables (we don't get errors on multiple declarations).
@@ -121,179 +121,179 @@
public void test_namespaces() {
parseConstraint(
"package ocltest context Fruit::ripen(c : Color) : Boolean " +
- "pre notBlack: let ok : Boolean = c <> Color::black in " +
- " ok " +
- "pre different: let ok : Boolean = c <> color in " +
- " ok " +
- "body: let b : Boolean = c <> color in " +
- " b implies color <> Color::black " +
- "post worked: result implies color <> color@pre " +
- "endpackage");
+ "pre notBlack: let ok : Boolean = c <> Color::black in " +
+ " ok " +
+ "pre different: let ok : Boolean = c <> color in " +
+ " ok " +
+ "body: let b : Boolean = c <> color in " +
+ " b implies color <> Color::black " +
+ "post worked: result implies color <> color@pre " +
+ "endpackage");
}
-
+
/**
* Checks that we correctly reject illegal use of "@pre" in precondition
* constraints.
*/
public void test_illegalUseOfAtPre_precondition() {
AssertionFailedError err = null;
-
+
try {
parseConstraint(
"package ocltest context Fruit::ripen(c : Color) : Boolean " +
- "pre: c <> color@pre " +
- "endpackage");
+ "pre: c <> color@pre " +
+ "endpackage");
} catch (AssertionFailedError e) {
// success
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
assertNotNull("Should not have succeeded in validating illegal @pre", err);
}
-
+
/**
* Checks that we correctly reject illegal use of "@pre" in invariant
* constraints.
*/
public void test_illegalUseOfAtPre_invariant() {
AssertionFailedError err = null;
-
+
try {
parseConstraint(
"package ocltest context Fruit " +
- "inv: color@pre <> Color::black " +
- "endpackage");
+ "inv: color@pre <> Color::black " +
+ "endpackage");
} catch (AssertionFailedError e) {
// success
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
assertNotNull("Should not have succeeded in validating illegal @pre", err);
}
-
+
/**
* Checks that we correctly reject illegal use of "@pre" in postcondition
* constraints (where the "@pre" is not used on a model property expression).
*/
public void test_illegalUseOfAtPre_postcondition() {
AssertionFailedError err = null;
-
+
try {
parseConstraint(
"package ocltest context Fruit::ripen(c : Color) : Boolean " +
- "post: let oldColor : Color = color in c <> oldColor@pre " +
- "endpackage");
+ "post: let oldColor : Color = color in c <> oldColor@pre " +
+ "endpackage");
} catch (AssertionFailedError e) {
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
assertNotNull("Should not have succeeded in validating illegal @pre", err);
}
-
+
/**
* Tests that local variables correctly hide attributes of the context
- * classifier.
+ * classifier.
*/
public void test_variablesHidingAttributes() {
parseConstraint(
"package ocltest context Fruit::ripen(c : Color) : Boolean " +
- "pre: let color : Boolean = (c = self.color) in " +
- " color implies c <> Color::black " +
- "endpackage");
+ "pre: let color : Boolean = (c = self.color) in " +
+ " color implies c <> Color::black " +
+ "endpackage");
}
-
+
/**
* Tests that parameters are in the same scope as local variables (cannot
- * use same names).
+ * use same names).
*/
public void test_parametersAreLocalVariables() {
AssertionFailedError err = null;
-
+
try {
parseConstraint(
"package ocltest context Fruit::ripen(c : Color) : Boolean " +
- "pre: color : Boolean = (c = self.color) in " +
- " color implies c <> Color::black " +
- "endpackage");
+ "pre: color : Boolean = (c = self.color) in " +
+ " color implies c <> Color::black " +
+ "endpackage");
} catch (AssertionFailedError e) {
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
assertNotNull(err);
}
-
+
/**
* Tests that body conditions are correctly checked for conformance to the
- * operation type.
+ * operation type.
*/
public void test_bodyConditionConformance() {
AssertionFailedError err = null;
-
+
try {
// try a scenario with no common supertype
parseConstraint(
"package ocltest context Fruit::preferredColor() : Color " +
- "body: result = (if true then 'red' else 'brown' endif) " +
- "endpackage");
+ "body: result = (if true then 'red' else 'brown' endif) " +
+ "endpackage");
} catch (AssertionFailedError e) {
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
assertNotNull(err);
err = null;
-
+
try {
// try a scenario with a common supertype
parseConstraint(
"package ocltest context Apple::newApple() : Apple " +
- "body: result = self.newFruit() " +
- "endpackage");
+ "body: result = self.newFruit() " +
+ "endpackage");
} catch (AssertionFailedError e) {
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
assertNotNull(err);
err = null;
-
+
try {
// this scenario is OK
parseConstraint(
"package ocltest context Apple::newFruit() : Fruit " +
- "body: result = self.newApple() " +
- "endpackage");
+ "body: result = self.newApple() " +
+ "endpackage");
} catch (AssertionFailedError e) {
err = e;
System.err.println("Got unexpected error: " + e.getLocalizedMessage());
}
-
+
assertNull(err);
}
-
+
/**
- * Tests that body conditions are not allowed for void operations.
+ * Tests that body conditions are not allowed for void operations.
*/
public void test_bodyConditionVoidOperation() {
AssertionFailedError err = null;
-
+
try {
parseConstraint(
"package ocltest context Apple::label(newLabel : String) : " +
- "body: result = (if true then 'Spy' else 'Spartan' endif) " +
- "endpackage");
+ "body: result = (if true then 'Spy' else 'Spartan' endif) " +
+ "endpackage");
} catch (AssertionFailedError e) {
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
assertNotNull(err);
}
-
+
/**
* Tests that when a parameter name (or any other local variable, for that
* matter) coincides with an attribute name, we correctly distinguish
@@ -313,13 +313,13 @@
myStr.setName("str");
myStr.setEType(EcorePackage.Literals.ESTRING);
apple.getEStructuralFeatures().add(myStr);
-
+
try {
OCLExpression<EClassifier> expr = parseConstraint(
"package ocltest context Apple::foo(str : String) : String " +
- "body: result = (if str = self.str then '' else str endif) " +
- "endpackage");
-
+ "body: result = (if str = self.str then '' else str endif) " +
+ "endpackage");
+
int propertyCalls = 0;
int variableCalls = 0;
for (Iterator<?> iter = EcoreUtil.getAllContents(Collections.singleton(expr)); iter.hasNext();) {
@@ -327,22 +327,22 @@
if (next instanceof PropertyCallExp<?, ?>) {
@SuppressWarnings("unchecked")
PropertyCallExp<EClassifier, EStructuralFeature> pc =
- (PropertyCallExp<EClassifier, EStructuralFeature>) next;
-
+ (PropertyCallExp<EClassifier, EStructuralFeature>) next;
+
if ("str".equals(pc.getReferredProperty().getName())) {
propertyCalls++;
}
} else if (next instanceof VariableExp<?, ?>) {
@SuppressWarnings("unchecked")
VariableExp<EClassifier, EParameter> v =
- (VariableExp<EClassifier, EParameter>) next;
-
+ (VariableExp<EClassifier, EParameter>) next;
+
if ("str".equals(v.getReferredVariable().getName())) {
variableCalls++;
}
}
}
-
+
assertEquals("property calls", 1, propertyCalls);
assertEquals("variable calls", 2, variableCalls);
} finally {
@@ -350,7 +350,7 @@
apple.getEStructuralFeatures().remove(myStr);
}
}
-
+
/**
* Tests that an expression resolves the implicit source of a property call
* correctly when the environment has additional variable names such as
@@ -360,44 +360,44 @@
public void test_implicitPropertySourceLookup_raw_151234() {
OCLExpression<EClassifier> expr = parseConstraint(
"package ocltest context Apple::setColor(fruit : Fruit, newColor : Color) : " +
- "pre: color <> newColor " +
- "endpackage");
+ "pre: color <> newColor " +
+ "endpackage");
assertTrue(expr instanceof OperationCallExp<?, ?>);
OperationCallExp<EClassifier, EOperation> notEquals =
- (OperationCallExp<EClassifier, EOperation>) expr;
+ (OperationCallExp<EClassifier, EOperation>) expr;
assertTrue(notEquals.getSource() instanceof PropertyCallExp<?, ?>);
PropertyCallExp<EClassifier, EStructuralFeature> propertyCall =
- (PropertyCallExp<EClassifier, EStructuralFeature>) notEquals.getSource();
-
+ (PropertyCallExp<EClassifier, EStructuralFeature>) notEquals.getSource();
+
assertTrue(propertyCall.getSource() instanceof VariableExp<?, ?>);
VariableExp<EClassifier, EParameter> var =
- (VariableExp<EClassifier, EParameter>) propertyCall.getSource();
-
+ (VariableExp<EClassifier, EParameter>) propertyCall.getSource();
+
// we did not resolve against "fruit", which also has a color property
assertEquals("self", var.getReferredVariable().getName());
-
+
// now check the resolution of implicit iterator variables as sources
expr = parseConstraint(
- "package ocltest context Apple::setColor(fruit : Fruit, newColor : Color) : " +
- "pre: Fruit.allInstances()->forAll(color <> newColor) " +
+ "package ocltest context Apple::setColor(fruit : Fruit, newColor : Color) : " +
+ "pre: Fruit.allInstances()->forAll(color <> newColor) " +
"endpackage");
assertTrue(expr instanceof IteratorExp<?, ?>);
IteratorExp<EClassifier, EParameter> forAll =
- (IteratorExp<EClassifier, EParameter>) expr;
+ (IteratorExp<EClassifier, EParameter>) expr;
assertTrue(forAll.getBody() instanceof OperationCallExp<?, ?>);
notEquals = (OperationCallExp<EClassifier, EOperation>) forAll.getBody();
assertTrue(notEquals.getSource() instanceof PropertyCallExp<?, ?>);
propertyCall = (PropertyCallExp<EClassifier, EStructuralFeature>) notEquals.getSource();
-
+
assertTrue(propertyCall.getSource() instanceof VariableExp<?, ?>);
var = (VariableExp<EClassifier, EParameter>) propertyCall.getSource();
-
+
// we did not resolve against "fruit", which also has a color property
assertTrue(var.getReferredVariable().getName().startsWith("temp"));
}
-
+
/**
* Tests that an expression resolves the implicit source of a property call
* correctly when the environment has additional variable names such as
@@ -408,43 +408,43 @@
try {
helper.setOperationContext(fruit, fruit_setColor);
OCLExpression<EClassifier> expr =
- helper.createPrecondition("color <> newColor").getSpecification().getBodyExpression();
-
+ helper.createPrecondition("color <> newColor").getSpecification().getBodyExpression();
+
assertTrue(expr instanceof OperationCallExp<?, ?>);
OperationCallExp<EClassifier, EOperation> notEquals =
- (OperationCallExp<EClassifier, EOperation>) expr;
+ (OperationCallExp<EClassifier, EOperation>) expr;
assertTrue(notEquals.getSource() instanceof PropertyCallExp<?, ?>);
PropertyCallExp<EClassifier, EStructuralFeature> propertyCall =
- (PropertyCallExp<EClassifier, EStructuralFeature>) notEquals.getSource();
-
+ (PropertyCallExp<EClassifier, EStructuralFeature>) notEquals.getSource();
+
assertTrue(propertyCall.getSource() instanceof VariableExp<?, ?>);
VariableExp<EClassifier, EParameter> var =
- (VariableExp<EClassifier, EParameter>) propertyCall.getSource();
-
+ (VariableExp<EClassifier, EParameter>) propertyCall.getSource();
+
// we did not resolve against "fruit", which also has a color property
assertEquals("self", var.getReferredVariable().getName());
-
+
// now check the resolution of implicit iterator variables as sources
expr = helper.createPrecondition(
"Fruit.allInstances()->forAll(color <> newColor)").getSpecification().getBodyExpression();
-
+
assertTrue(expr instanceof IteratorExp<?, ?>);
IteratorExp<EClassifier, EParameter> forAll = (IteratorExp<EClassifier, EParameter>) expr;
assertTrue(forAll.getBody() instanceof OperationCallExp<?, ?>);
notEquals = (OperationCallExp<EClassifier, EOperation>) forAll.getBody();
assertTrue(notEquals.getSource() instanceof PropertyCallExp<?, ?>);
propertyCall = (PropertyCallExp<EClassifier, EStructuralFeature>) notEquals.getSource();
-
+
assertTrue(propertyCall.getSource() instanceof VariableExp<?, ?>);
var = (VariableExp<EClassifier, EParameter>) propertyCall.getSource();
-
+
// we did not resolve against "fruit", which also has a color property
assertTrue(var.getReferredVariable().getName().startsWith("temp"));
} catch (ParserException e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests that an expression resolves the implicit source of an operation call
* correctly when the environment has additional variable names such as
@@ -454,27 +454,27 @@
public void test_implicitOperationSourceLookup_raw_151234() {
OCLExpression<EClassifier> expr = parseConstraint(
"package ocltest context Apple::setColor(fruit : Fruit, newColor : Color) : " +
- "pre: preferredColor() <> newColor " +
- "endpackage");
+ "pre: preferredColor() <> newColor " +
+ "endpackage");
assertTrue(expr instanceof OperationCallExp<?, ?>);
OperationCallExp<EClassifier, EOperation> notEquals =
- (OperationCallExp<EClassifier, EOperation>) expr;
+ (OperationCallExp<EClassifier, EOperation>) expr;
assertTrue(notEquals.getSource() instanceof OperationCallExp<?, ?>);
OperationCallExp<EClassifier, EOperation> operationCall =
- (OperationCallExp<EClassifier, EOperation>) notEquals.getSource();
-
+ (OperationCallExp<EClassifier, EOperation>) notEquals.getSource();
+
assertTrue(operationCall.getSource() instanceof VariableExp<?, ?>);
VariableExp<EClassifier, EParameter> var =
- (VariableExp<EClassifier, EParameter>) operationCall.getSource();
-
+ (VariableExp<EClassifier, EParameter>) operationCall.getSource();
+
// we did not resolve against "fruit", which also has a color property
assertEquals("self", var.getReferredVariable().getName());
-
+
// now check the resolution of implicit iterator variables as sources
expr = parseConstraint(
- "package ocltest context Apple::setColor(fruit : Fruit, newColor : Color) : " +
- "pre: Fruit.allInstances()->forAll(preferredColor() <> newColor) " +
+ "package ocltest context Apple::setColor(fruit : Fruit, newColor : Color) : " +
+ "pre: Fruit.allInstances()->forAll(preferredColor() <> newColor) " +
"endpackage");
assertTrue(expr instanceof IteratorExp<?, ?>);
@@ -483,14 +483,14 @@
notEquals = (OperationCallExp<EClassifier, EOperation>) forAll.getBody();
assertTrue(notEquals.getSource() instanceof OperationCallExp<?, ?>);
operationCall = (OperationCallExp<EClassifier, EOperation>) notEquals.getSource();
-
+
assertTrue(operationCall.getSource() instanceof VariableExp<?, ?>);
var = (VariableExp<EClassifier, EParameter>) operationCall.getSource();
-
+
// we did not resolve against "fruit", which also has a color property
assertTrue(var.getReferredVariable().getName().startsWith("temp"));
}
-
+
/**
* Tests that an expression resolves the implicit source of an operation call
* correctly when the environment has additional variable names such as
@@ -502,143 +502,143 @@
helper.setOperationContext(fruit, fruit_setColor);
OCLExpression<EClassifier> expr = helper.createPrecondition(
"preferredColor() <> newColor").getSpecification().getBodyExpression();
-
+
assertTrue(expr instanceof OperationCallExp<?, ?>);
OperationCallExp<EClassifier, EOperation> notEquals =
- (OperationCallExp<EClassifier, EOperation>) expr;
+ (OperationCallExp<EClassifier, EOperation>) expr;
assertTrue(notEquals.getSource() instanceof OperationCallExp<?, ?>);
OperationCallExp<EClassifier, EOperation> operationCall =
- (OperationCallExp<EClassifier, EOperation>) notEquals.getSource();
-
+ (OperationCallExp<EClassifier, EOperation>) notEquals.getSource();
+
assertTrue(operationCall.getSource() instanceof VariableExp<?, ?>);
VariableExp<EClassifier, EParameter> var =
- (VariableExp<EClassifier, EParameter>) operationCall.getSource();
-
+ (VariableExp<EClassifier, EParameter>) operationCall.getSource();
+
// we did not resolve against "fruit", which also has a color property
assertEquals("self", var.getReferredVariable().getName());
-
+
// now check the resolution of implicit iterator variables as sources
expr = helper.createPrecondition(
"Fruit.allInstances()->forAll(preferredColor() <> newColor)").getSpecification().getBodyExpression();
-
+
assertTrue(expr instanceof IteratorExp<?, ?>);
IteratorExp<EClassifier, EParameter> forAll =
- (IteratorExp<EClassifier, EParameter>) expr;
+ (IteratorExp<EClassifier, EParameter>) expr;
assertTrue(forAll.getBody() instanceof OperationCallExp<?, ?>);
notEquals = (OperationCallExp<EClassifier, EOperation>) forAll.getBody();
assertTrue(notEquals.getSource() instanceof OperationCallExp<?, ?>);
operationCall = (OperationCallExp<EClassifier, EOperation>) notEquals.getSource();
-
+
assertTrue(operationCall.getSource() instanceof VariableExp<?, ?>);
var = (VariableExp<EClassifier, EParameter>) operationCall.getSource();
-
+
// we did not resolve against "fruit", which also has a color property
assertTrue(var.getReferredVariable().getName().startsWith("temp"));
} catch (ParserException e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
- /**
- * Tests that body conditions are correctly checked for conformance to the
- * operation type when they are specified as OCL body expressions, not as
- * UML body constraints.
- */
- public void test_bodyExpressionConformance_185345() {
- AssertionFailedError err = null;
-
- try {
- // try a scenario with no common supertype
- parseConstraint(
- "package ocltest context Fruit::preferredColor() : Color " +
- "body: if true then 'red' else 'brown' endif " +
- "endpackage");
- } catch (AssertionFailedError e) {
- err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
- }
-
- assertNotNull(err);
- err = null;
-
- try {
- // try a scenario with a common supertype
- parseConstraint(
- "package ocltest context Apple::newApple() : Apple " +
- "body: self.newFruit() " +
- "endpackage");
- } catch (AssertionFailedError e) {
- err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
- }
-
- assertNotNull(err);
- err = null;
-
- try {
- // this scenario is OK
- parseConstraint(
- "package ocltest context Apple::newFruit() : Fruit " +
- "body: self.newApple() " +
- "endpackage");
- } catch (AssertionFailedError e) {
- err = e;
- System.err.println("Got unexpected error: " + e.getLocalizedMessage());
- }
-
- assertNull(err);
- }
-
- /**
- * Tests that OCL body expressions cannot reference the result of the
- * operation.
- */
- public void test_bodyExpressionResultUsage_185345() {
- AssertionFailedError err = null;
-
- try {
- // not allowed to reference the result variable
- parseConstraint(
- "package ocltest context Apple::preferredLabel(text : String) : String " +
- "body: if true then text else result endif " +
- "endpackage");
- } catch (AssertionFailedError e) {
- err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
- }
-
- assertNotNull(err);
- err = null;
-
- // unless, of course, 'result' is a parameter name
- parseConstraint(
- "package ocltest context Apple::preferredLabel(result : String) : String " +
- "body: if true then 'me' else result endif " +
- "endpackage");
- }
-
- /**
- * Now that body expressions can be specified as OCL intended, we can use
- * them to evaluate operations at run-time.
- */
- public void test_bodyExpressionEvaluation_185345() {
- parseConstraint(
- "package ocltest context Fruit::preferredColor() : Color " +
- "body: if color = Color::black then Color::red else Color::black endif " +
- "endpackage");
-
- OCLExpression<EClassifier> query = parse(
- "package ocltest context Apple " +
- "inv: self.preferredColor() " +
- "endpackage");
-
- EObject anApple = fruitFactory.create(apple);
- anApple.eSet(fruit_color, color_black);
-
- assertSame(color_red, evaluate(query, anApple));
-
- anApple.eSet(fruit_color, color_green);
-
- assertSame(color_black, evaluate(query, anApple));
- }
+
+ /**
+ * Tests that body conditions are correctly checked for conformance to the
+ * operation type when they are specified as OCL body expressions, not as
+ * UML body constraints.
+ */
+ public void test_bodyExpressionConformance_185345() {
+ AssertionFailedError err = null;
+
+ try {
+ // try a scenario with no common supertype
+ parseConstraint(
+ "package ocltest context Fruit::preferredColor() : Color " +
+ "body: if true then 'red' else 'brown' endif " +
+ "endpackage");
+ } catch (AssertionFailedError e) {
+ err = e;
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
+ }
+
+ assertNotNull(err);
+ err = null;
+
+ try {
+ // try a scenario with a common supertype
+ parseConstraint(
+ "package ocltest context Apple::newApple() : Apple " +
+ "body: self.newFruit() " +
+ "endpackage");
+ } catch (AssertionFailedError e) {
+ err = e;
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
+ }
+
+ assertNotNull(err);
+ err = null;
+
+ try {
+ // this scenario is OK
+ parseConstraint(
+ "package ocltest context Apple::newFruit() : Fruit " +
+ "body: self.newApple() " +
+ "endpackage");
+ } catch (AssertionFailedError e) {
+ err = e;
+ System.err.println("Got unexpected error: " + e.getLocalizedMessage());
+ }
+
+ assertNull(err);
+ }
+
+ /**
+ * Tests that OCL body expressions cannot reference the result of the
+ * operation.
+ */
+ public void test_bodyExpressionResultUsage_185345() {
+ AssertionFailedError err = null;
+
+ try {
+ // not allowed to reference the result variable
+ parseConstraint(
+ "package ocltest context Apple::preferredLabel(text : String) : String " +
+ "body: if true then text else result endif " +
+ "endpackage");
+ } catch (AssertionFailedError e) {
+ err = e;
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
+ }
+
+ assertNotNull(err);
+ err = null;
+
+ // unless, of course, 'result' is a parameter name
+ parseConstraint(
+ "package ocltest context Apple::preferredLabel(result : String) : String " +
+ "body: if true then 'me' else result endif " +
+ "endpackage");
+ }
+
+ /**
+ * Now that body expressions can be specified as OCL intended, we can use
+ * them to evaluate operations at run-time.
+ */
+ public void test_bodyExpressionEvaluation_185345() {
+ parseConstraint(
+ "package ocltest context Fruit::preferredColor() : Color " +
+ "body: if color = Color::black then Color::red else Color::black endif " +
+ "endpackage");
+
+ OCLExpression<EClassifier> query = parse(
+ "package ocltest context Apple " +
+ "inv: self.preferredColor() " +
+ "endpackage");
+
+ EObject anApple = fruitFactory.create(apple);
+ anApple.eSet(fruit_color, color_black);
+
+ assertSame(color_red, evaluate(query, anApple));
+
+ anApple.eSet(fruit_color, color_green);
+
+ assertSame(color_black, evaluate(query, anApple));
+ }
}
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ParsingOptionsTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ParsingOptionsTest.java
index 4cca455..1a0b903 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ParsingOptionsTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ParsingOptionsTest.java
@@ -35,12 +35,12 @@
/**
* Tests for parsing options.
- *
+ *
* @author Christian W. Damus (cdamus)
*/
@SuppressWarnings("nls")
public class ParsingOptionsTest
- extends AbstractTestSuite {
+extends AbstractTestSuite {
/**
* Tests the implicit root class option for access to operations.
@@ -55,8 +55,7 @@
fail("Should not have successfully parsed.");
} catch (ParserException e) {
// success
- System.out
- .println("Got expected exception: " + e.getLocalizedMessage());
+ debugPrintln("Got expected exception: " + e.getLocalizedMessage());
}
ParsingOptions.setOption(ocl.getEnvironment(), ParsingOptions
@@ -93,13 +92,12 @@
fail("Should not have successfully parsed.");
} catch (ParserException e) {
// success
- System.out
- .println("Got expected exception: " + e.getLocalizedMessage());
+ debugPrintln("Got expected exception: " + e.getLocalizedMessage());
}
ParsingOptions.setOption(ocl.getEnvironment(), ParsingOptions
.implicitRootClass(ocl.getEnvironment()), apple); // don't try this
- // at home!
+ // at home!
// parse with the option
try {
@@ -148,19 +146,19 @@
assertEquals(UMLReflection.STRICT_SUBTYPE, TypeUtil.getRelationship(ocl
.getEnvironment(), apple, EcorePackage.Literals.EOBJECT));
}
-
+
public void test_implicitRootClass_option_get_380755() {
Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> env = ocl.getEnvironment();
Option<EClassifier> implicitRootClass = ParsingOptions.implicitRootClass(env);
-
+
ParsingOptions.setOption(env, implicitRootClass, EcorePackage.Literals.EOBJECT);
EClassifier value = ParsingOptions.getValue(env, implicitRootClass);
assertSame(EcorePackage.Literals.EOBJECT, value);
-
+
ParsingOptions.setOption(env, implicitRootClass, null);
value = ParsingOptions.getValue(env, implicitRootClass);
assertSame(null, value);
-
+
ParsingOptions.setOption(env, implicitRootClass, EcorePackage.Literals.ECLASS);
value = ParsingOptions.getValue(env, implicitRootClass);
assertSame(EcorePackage.Literals.ECLASS, value);
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ProblemOptionTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ProblemOptionTest.java
index bf5ad35..28f23a3 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ProblemOptionTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ProblemOptionTest.java
@@ -28,12 +28,12 @@
/**
* Tests for problem-reporting options.
- *
+ *
* @author Christian W. Damus (cdamus)
*/
@SuppressWarnings("nls")
public class ProblemOptionTest
- extends AbstractTestSuite {
+extends AbstractTestSuite {
private static class EclipseSupport
{
public static void removePreference(PreferenceableOption<?> option, IScopeContext context) {
@@ -45,7 +45,7 @@
e.printStackTrace();
}
}
-
+
public static <T> void setPreference(PreferenceableOption<T> option, IScopeContext context, T value) {
try {
IEclipsePreferences preferences = context.getNode(option.getPluginId());
@@ -57,146 +57,146 @@
}
}
- /**
- * Tests the severity option for the <tt>toLower()</tt> and <tt>toUpper()</tt>
- * operations on strings.
- */
- public void test_stringCaseConversion_option() {
- helper.setContext(EcorePackage.Literals.ESTRING);
+ /**
+ * Tests the severity option for the <tt>toLower()</tt> and <tt>toUpper()</tt>
+ * operations on strings.
+ */
+ public void test_stringCaseConversion_option() {
+ helper.setContext(EcorePackage.Literals.ESTRING);
- BasicEnvironment benv = OCLUtil.getAdapter(ocl.getEnvironment(), BasicEnvironment.class);
-
- // default severity is warning
- assertWarning("self.toUpper()");
- assertWarning("self.toLower()");
-
- // ignore the operation
- benv.setOption(ProblemOption.STRING_CASE_CONVERSION, ProblemHandler.Severity.OK);
- assertOK("self.toUpper()");
- assertOK("self.toLower()");
-
- // the operation fails to parse
- benv.setOption(ProblemOption.STRING_CASE_CONVERSION, ProblemHandler.Severity.ERROR);
- assertError("self.toUpper()");
- assertError("self.toLower()");
+ BasicEnvironment benv = OCLUtil.getAdapter(ocl.getEnvironment(), BasicEnvironment.class);
- if (EcorePlugin.IS_ECLIPSE_RUNNING) {
- benv.removeOption(ProblemOption.STRING_CASE_CONVERSION);
- EclipseSupport.setPreference(ProblemOption.STRING_CASE_CONVERSION, ConfigurationScope.INSTANCE, Severity.WARNING);
- assertWarning("self.toUpper()");
- benv.removeOption(ProblemOption.STRING_CASE_CONVERSION);
- EclipseSupport.setPreference(ProblemOption.STRING_CASE_CONVERSION, ConfigurationScope.INSTANCE, Severity.OK);
- assertOK("self.toUpper()");
- benv.removeOption(ProblemOption.STRING_CASE_CONVERSION);
- EclipseSupport.setPreference(ProblemOption.STRING_CASE_CONVERSION, ConfigurationScope.INSTANCE, Severity.ERROR);
- assertError("self.toUpper()");
- EclipseSupport.removePreference(ProblemOption.STRING_CASE_CONVERSION, ConfigurationScope.INSTANCE);
- }
- }
+ // default severity is warning
+ assertWarning("self.toUpper()");
+ assertWarning("self.toLower()");
- /**
- * Tests the severity option for the closure() iterator.
- */
- public void test_closure_option() {
- helper.setContext(EcorePackage.Literals.EPACKAGE);
+ // ignore the operation
+ benv.setOption(ProblemOption.STRING_CASE_CONVERSION, ProblemHandler.Severity.OK);
+ assertOK("self.toUpper()");
+ assertOK("self.toLower()");
- BasicEnvironment benv = OCLUtil.getAdapter(ocl.getEnvironment(), BasicEnvironment.class);
-
- // default severity is OK
- assertOK("self->closure(eSuperPackage)");
-
- // ignore the closure iterator
- benv.setOption(ProblemOption.CLOSURE_ITERATOR, ProblemHandler.Severity.WARNING);
- assertWarning("self->closure(eSuperPackage)");
-
- // ignore the closure iterator
- benv.setOption(ProblemOption.CLOSURE_ITERATOR, ProblemHandler.Severity.OK);
- assertOK("self->closure(eSuperPackage)");
-
- // the closure iterator fails to parse
- benv.setOption(ProblemOption.CLOSURE_ITERATOR, ProblemHandler.Severity.ERROR);
- assertError("self->closure(eSuperPackage)");
- }
+ // the operation fails to parse
+ benv.setOption(ProblemOption.STRING_CASE_CONVERSION, ProblemHandler.Severity.ERROR);
+ assertError("self.toUpper()");
+ assertError("self.toLower()");
- /**
- * Tests the severity option for the <tt>''</tt> escape in strings.
- */
- public void test_singleQuoteEscape_option() {
- helper.setContext(EcorePackage.Literals.ESTRING);
+ if (EcorePlugin.IS_ECLIPSE_RUNNING) {
+ benv.removeOption(ProblemOption.STRING_CASE_CONVERSION);
+ EclipseSupport.setPreference(ProblemOption.STRING_CASE_CONVERSION, ConfigurationScope.INSTANCE, Severity.WARNING);
+ assertWarning("self.toUpper()");
+ benv.removeOption(ProblemOption.STRING_CASE_CONVERSION);
+ EclipseSupport.setPreference(ProblemOption.STRING_CASE_CONVERSION, ConfigurationScope.INSTANCE, Severity.OK);
+ assertOK("self.toUpper()");
+ benv.removeOption(ProblemOption.STRING_CASE_CONVERSION);
+ EclipseSupport.setPreference(ProblemOption.STRING_CASE_CONVERSION, ConfigurationScope.INSTANCE, Severity.ERROR);
+ assertError("self.toUpper()");
+ EclipseSupport.removePreference(ProblemOption.STRING_CASE_CONVERSION, ConfigurationScope.INSTANCE);
+ }
+ }
- BasicEnvironment benv = OCLUtil.getAdapter(ocl.getEnvironment(), BasicEnvironment.class);
-
- // default severity is warning
-// assertWarning("'this isn''t a nice string'");
-
- // ignore the single-quote
- benv.setOption(ProblemOption.STRING_SINGLE_QUOTE_ESCAPE, ProblemHandler.Severity.OK);
-
- assertOK("'this isn''t a nice string'");
-
- // the single-quote escape fails to parse
- benv.setOption(ProblemOption.STRING_SINGLE_QUOTE_ESCAPE, ProblemHandler.Severity.ERROR);
-// assertError("'this isn''t a nice string'");
- }
+ /**
+ * Tests the severity option for the closure() iterator.
+ */
+ public void test_closure_option() {
+ helper.setContext(EcorePackage.Literals.EPACKAGE);
- /**
- * Tests the severity option for the <tt>"..."</tt> escape for element names.
- */
- public void test_doubleQuoteElementName_option() {
- helper.setContext(EcorePackage.Literals.EPACKAGE);
+ BasicEnvironment benv = OCLUtil.getAdapter(ocl.getEnvironment(), BasicEnvironment.class);
- BasicEnvironment benv = OCLUtil.getAdapter(ocl.getEnvironment(), BasicEnvironment.class);
-
- // default severity is warning
- assertWarning("self.\"eClassifiers\"");
-
- // ignore the double-quote
- benv.setOption(ProblemOption.ELEMENT_NAME_QUOTE_ESCAPE, ProblemHandler.Severity.OK);
-
- assertOK("self.\"eClassifiers\"");
-
- // the double-quote escape fails to parse
- benv.setOption(ProblemOption.ELEMENT_NAME_QUOTE_ESCAPE, ProblemHandler.Severity.ERROR);
- assertError("self.\"eClassifiers\"");
- }
-
- //
- // Framework methods
- //
-
- void assertOK(String oclQuery) {
- try {
- helper.createQuery(oclQuery);
-
- Diagnostic problem = helper.getProblems();
- assertNull(problem);
- } catch (Exception e) {
- fail("Failed to parse: " + e.getLocalizedMessage());
- }
- }
-
- void assertWarning(String oclQuery) {
- try {
- helper.createQuery(oclQuery);
-
- Diagnostic problem = helper.getProblems();
- assertNotNull(problem);
- assertEquals(Diagnostic.WARNING, problem.getSeverity());
- } catch (Exception e) {
- fail("Failed to parse: " + e.getLocalizedMessage());
- }
- }
-
- void assertError(String oclQuery) {
- try {
- helper.createQuery(oclQuery);
-
- fail("Should have failed to parse");
- } catch (ParserException e) {
- // success
- System.out.println("Got expected exception: " + e.getLocalizedMessage());
- } catch (Exception e) {
- fail("Failed to parse for unexpected reason: " + e.getLocalizedMessage());
- }
- }
+ // default severity is OK
+ assertOK("self->closure(eSuperPackage)");
+
+ // ignore the closure iterator
+ benv.setOption(ProblemOption.CLOSURE_ITERATOR, ProblemHandler.Severity.WARNING);
+ assertWarning("self->closure(eSuperPackage)");
+
+ // ignore the closure iterator
+ benv.setOption(ProblemOption.CLOSURE_ITERATOR, ProblemHandler.Severity.OK);
+ assertOK("self->closure(eSuperPackage)");
+
+ // the closure iterator fails to parse
+ benv.setOption(ProblemOption.CLOSURE_ITERATOR, ProblemHandler.Severity.ERROR);
+ assertError("self->closure(eSuperPackage)");
+ }
+
+ /**
+ * Tests the severity option for the <tt>''</tt> escape in strings.
+ */
+ public void test_singleQuoteEscape_option() {
+ helper.setContext(EcorePackage.Literals.ESTRING);
+
+ BasicEnvironment benv = OCLUtil.getAdapter(ocl.getEnvironment(), BasicEnvironment.class);
+
+ // default severity is warning
+ // assertWarning("'this isn''t a nice string'");
+
+ // ignore the single-quote
+ benv.setOption(ProblemOption.STRING_SINGLE_QUOTE_ESCAPE, ProblemHandler.Severity.OK);
+
+ assertOK("'this isn''t a nice string'");
+
+ // the single-quote escape fails to parse
+ benv.setOption(ProblemOption.STRING_SINGLE_QUOTE_ESCAPE, ProblemHandler.Severity.ERROR);
+ // assertError("'this isn''t a nice string'");
+ }
+
+ /**
+ * Tests the severity option for the <tt>"..."</tt> escape for element names.
+ */
+ public void test_doubleQuoteElementName_option() {
+ helper.setContext(EcorePackage.Literals.EPACKAGE);
+
+ BasicEnvironment benv = OCLUtil.getAdapter(ocl.getEnvironment(), BasicEnvironment.class);
+
+ // default severity is warning
+ assertWarning("self.\"eClassifiers\"");
+
+ // ignore the double-quote
+ benv.setOption(ProblemOption.ELEMENT_NAME_QUOTE_ESCAPE, ProblemHandler.Severity.OK);
+
+ assertOK("self.\"eClassifiers\"");
+
+ // the double-quote escape fails to parse
+ benv.setOption(ProblemOption.ELEMENT_NAME_QUOTE_ESCAPE, ProblemHandler.Severity.ERROR);
+ assertError("self.\"eClassifiers\"");
+ }
+
+ //
+ // Framework methods
+ //
+
+ void assertOK(String oclQuery) {
+ try {
+ helper.createQuery(oclQuery);
+
+ Diagnostic problem = helper.getProblems();
+ assertNull(problem);
+ } catch (Exception e) {
+ fail("Failed to parse: " + e.getLocalizedMessage());
+ }
+ }
+
+ void assertWarning(String oclQuery) {
+ try {
+ helper.createQuery(oclQuery);
+
+ Diagnostic problem = helper.getProblems();
+ assertNotNull(problem);
+ assertEquals(Diagnostic.WARNING, problem.getSeverity());
+ } catch (Exception e) {
+ fail("Failed to parse: " + e.getLocalizedMessage());
+ }
+ }
+
+ void assertError(String oclQuery) {
+ try {
+ helper.createQuery(oclQuery);
+
+ fail("Should have failed to parse");
+ } catch (ParserException e) {
+ // success
+ debugPrintln("Got expected exception: " + e.getLocalizedMessage());
+ } catch (Exception e) {
+ fail("Failed to parse for unexpected reason: " + e.getLocalizedMessage());
+ }
+ }
}
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/RegressionTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/RegressionTest.java
index 10ba053..0e6fd2f 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/RegressionTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/RegressionTest.java
@@ -19,8 +19,6 @@
import java.util.Map;
import java.util.Set;
-import junit.framework.AssertionFailedError;
-
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EAttribute;
@@ -63,6 +61,8 @@
import org.eclipse.ocl.util.TypeUtil;
import org.eclipse.ocl.utilities.UMLReflection;
+import junit.framework.AssertionFailedError;
+
/**
* Regression tests for specific RATLC defects.
*
@@ -70,8 +70,8 @@
*/
@SuppressWarnings("nls")
public class RegressionTest
- extends AbstractTestSuite {
-
+extends AbstractTestSuite {
+
/**
* Tests the "..." escape syntax for reserved words. Regression test for
* RATLC00527506.
@@ -82,11 +82,11 @@
epackage.setNsPrefix("mypkg");
epackage.setNsURI("http:///mypkg.ecore");
resourceSet.getPackageRegistry().put(epackage.getNsURI(), epackage);
-
+
EClass eclass = EcoreFactory.eINSTANCE.createEClass();
eclass.setName("MyType");
epackage.getEClassifiers().add(eclass);
-
+
// "context" is an OCL reserved word
EAttribute eattr = EcoreFactory.eINSTANCE.createEAttribute();
eattr.setName("context");
@@ -94,10 +94,10 @@
eclass.getEStructuralFeatures().add(eattr);
parseConstraint(
"package mypkg context MyType " +
- "inv: self.\"context\"->notEmpty() " +
- "endpackage");
+ "inv: self.\"context\"->notEmpty() " +
+ "endpackage");
}
-
+
/**
* Tests the "..." escape syntax for whitespace. Regression test for
* RATLC00527509.
@@ -108,21 +108,21 @@
epackage.setNsPrefix("mypkg");
epackage.setNsURI("http:///mypkg.ecore");
resourceSet.getPackageRegistry().put(epackage.getNsURI(), epackage);
-
+
EClass eclass = EcoreFactory.eINSTANCE.createEClass();
eclass.setName("MyType");
epackage.getEClassifiers().add(eclass);
-
+
EAttribute eattr = EcoreFactory.eINSTANCE.createEAttribute();
eattr.setName("an attribute");
eattr.setEType(EcorePackage.eINSTANCE.getEString());
eclass.getEStructuralFeatures().add(eattr);
parseConstraint(
"package mypkg context MyType " +
- "inv: self.\"an attribute\"->notEmpty() " +
- "endpackage");
+ "inv: self.\"an attribute\"->notEmpty() " +
+ "endpackage");
}
-
+
/**
* Tests the \" escape syntax for double-quotes. Regression test for
* RATLC00527509.
@@ -133,11 +133,11 @@
epackage.setNsPrefix("mypkg");
epackage.setNsURI("http:///mypkg.ecore");
resourceSet.getPackageRegistry().put(epackage.getNsURI(), epackage);
-
+
EClass eclass = EcoreFactory.eINSTANCE.createEClass();
eclass.setName("MyType");
epackage.getEClassifiers().add(eclass);
-
+
EAttribute eattr = EcoreFactory.eINSTANCE.createEAttribute();
eattr.setName("an\"attribute");
eattr.setEType(EcorePackage.eINSTANCE.getEString());
@@ -145,27 +145,27 @@
// try first to parse within surrounding double-quotes
parseConstraint(
"package mypkg context MyType " +
- "inv: self.\"an\\\"attribute\"->notEmpty() " +
- "endpackage");
+ "inv: self.\"an\\\"attribute\"->notEmpty() " +
+ "endpackage");
AssertionFailedError err = null;
-
+
try {
// also try to parse without the surrounding double-quotes.
// This is not allowed
parseConstraint(
"package ecore context EClass " +
- "inv: self.an\\\"attribute->notEmpty() " +
- "endpackage");
+ "inv: self.an\\\"attribute->notEmpty() " +
+ "endpackage");
} catch (AssertionFailedError e) {
// success
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
assertNotNull("Should not have parsed.", err);
}
-
+
/**
* Tests the support for international characters. Regression test for
* RATLC01080816.
@@ -176,11 +176,11 @@
epackage.setNsPrefix("mypkg");
epackage.setNsURI("http:///mypkg.ecore");
resourceSet.getPackageRegistry().put(epackage.getNsURI(), epackage);
-
+
EClass eclass = EcoreFactory.eINSTANCE.createEClass();
eclass.setName("MyType");
epackage.getEClassifiers().add(eclass);
-
+
EAttribute eattr = EcoreFactory.eINSTANCE.createEAttribute();
// try some extended latin, cyrillic, and arabic
eattr.setName("\u0160\u01d6\u0429\u0639");
@@ -189,10 +189,10 @@
// try these characters in the attribute name and string literal
parseConstraint(
"package mypkg context MyType " +
- "inv: self.\u0160\u01d6\u0429\u0639 <> '\u0160\u01d6\u0429\u0639' " +
- "endpackage");
+ "inv: self.\u0160\u01d6\u0429\u0639 <> '\u0160\u01d6\u0429\u0639' " +
+ "endpackage");
}
-
+
/**
* Tests support for oclIsKindOf() and oclAsType() to cast between
* classifiers that are not related, but where their subtypes may be
@@ -204,49 +204,49 @@
epackage.setNsPrefix("mypkg");
epackage.setNsURI("http:///mypkg.ecore");
resourceSet.getPackageRegistry().put(epackage.getNsURI(), epackage);
-
+
// create three classes. A and B are unrelated, but C extends
// both. Therefore, it is possible to cast a variable of type
// A to type B where the run-time type is C
EClass a = EcoreFactory.eINSTANCE.createEClass();
a.setName("A");
epackage.getEClassifiers().add(a);
-
+
EClass b = EcoreFactory.eINSTANCE.createEClass();
b.setName("B");
epackage.getEClassifiers().add(b);
-
+
EClass c = EcoreFactory.eINSTANCE.createEClass();
c.setName("C");
epackage.getEClassifiers().add(c);
c.getESuperTypes().add(a);
c.getESuperTypes().add(b);
-
+
EAttribute attrA = EcoreFactory.eINSTANCE.createEAttribute();
attrA.setName("a");
attrA.setEType(EcorePackage.eINSTANCE.getEBoolean());
a.getEStructuralFeatures().add(attrA);
-
+
EAttribute attrB = EcoreFactory.eINSTANCE.createEAttribute();
attrB.setName("b");
attrB.setEType(EcorePackage.eINSTANCE.getEBoolean());
b.getEStructuralFeatures().add(attrB);
OCLExpression<EClassifier> constraint = parseConstraint(
"package mypkg context A " +
- "inv: self.oclIsKindOf(B) implies (self.oclAsType(B).b <> self.a) " +
- "endpackage");
-
+ "inv: self.oclIsKindOf(B) implies (self.oclAsType(B).b <> self.a) " +
+ "endpackage");
+
EObject eobj = epackage.getEFactoryInstance().create(c);
eobj.eSet(attrA, Boolean.TRUE);
eobj.eSet(attrB, Boolean.TRUE);
-
+
assertFalse("Should have failed the check", check(constraint, eobj));
-
+
eobj.eSet(attrB, Boolean.FALSE);
-
+
assertTrue("Should not have failed the check", check(constraint, eobj));
}
-
+
/**
* Tests support for short-circuiting AND operator.
*/
@@ -256,51 +256,51 @@
epackage.setNsPrefix("mypkg");
epackage.setNsURI("http:///mypkg.ecore");
resourceSet.getPackageRegistry().put(epackage.getNsURI(), epackage);
-
+
EClass a = EcoreFactory.eINSTANCE.createEClass();
a.setName("A");
epackage.getEClassifiers().add(a);
-
+
EClass b = EcoreFactory.eINSTANCE.createEClass();
b.setName("B");
epackage.getEClassifiers().add(b);
b.getESuperTypes().add(a);
-
+
EAttribute attrA = EcoreFactory.eINSTANCE.createEAttribute();
attrA.setName("a");
attrA.setEType(EcorePackage.eINSTANCE.getEBoolean());
a.getEStructuralFeatures().add(attrA);
-
+
EAttribute attrB = EcoreFactory.eINSTANCE.createEAttribute();
attrB.setName("b");
attrB.setEType(EcorePackage.eINSTANCE.getEBoolean());
b.getEStructuralFeatures().add(attrB);
-
+
try {
OCLExpression<EClassifier> constraint = parseConstraint(
"package mypkg context A " +
- "inv: self.oclIsKindOf(B) and self.oclAsType(B).b " +
- "endpackage");
-
+ "inv: self.oclIsKindOf(B) and self.oclAsType(B).b " +
+ "endpackage");
+
// create an A
EObject eobj = epackage.getEFactoryInstance().create(a);
eobj.eSet(attrA, Boolean.TRUE);
-
+
// this would fail with an NPE on the access to '.b' when
// 'self.oclAsType(B)' evaluates to null, if we didn't short-circuit
assertFalse("Should have failed the check", check(constraint, eobj));
-
+
// create a B this time
eobj = epackage.getEFactoryInstance().create(b);
eobj.eSet(attrA, Boolean.TRUE);
eobj.eSet(attrB, Boolean.TRUE);
-
+
assertTrue("Should not have failed the check", check(constraint, eobj));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests support for short-circuiting OR operator.
*/
@@ -310,51 +310,51 @@
epackage.setNsPrefix("mypkg");
epackage.setNsURI("http:///mypkg.ecore");
resourceSet.getPackageRegistry().put(epackage.getNsURI(), epackage);
-
+
EClass a = EcoreFactory.eINSTANCE.createEClass();
a.setName("A");
epackage.getEClassifiers().add(a);
-
+
EClass b = EcoreFactory.eINSTANCE.createEClass();
b.setName("B");
epackage.getEClassifiers().add(b);
b.getESuperTypes().add(a);
-
+
EAttribute attrA = EcoreFactory.eINSTANCE.createEAttribute();
attrA.setName("a");
attrA.setEType(EcorePackage.eINSTANCE.getEBoolean());
a.getEStructuralFeatures().add(attrA);
-
+
EAttribute attrB = EcoreFactory.eINSTANCE.createEAttribute();
attrB.setName("b");
attrB.setEType(EcorePackage.eINSTANCE.getEBoolean());
b.getEStructuralFeatures().add(attrB);
-
+
try {
OCLExpression<EClassifier> constraint = parseConstraint(
"package mypkg context A " +
- "inv: (not self.oclIsKindOf(B)) or self.oclAsType(B).b " +
- "endpackage");
-
+ "inv: (not self.oclIsKindOf(B)) or self.oclAsType(B).b " +
+ "endpackage");
+
// create an A
EObject eobj = epackage.getEFactoryInstance().create(a);
eobj.eSet(attrA, Boolean.TRUE);
-
+
// this would fail with an NPE on the access to '.b' when
// 'self.oclAsType(B)' evaluates to null, if we didn't short-circuit
assertTrue("Should not have failed the check", check(constraint, eobj));
-
+
// create a B this time
eobj = epackage.getEFactoryInstance().create(b);
eobj.eSet(attrA, Boolean.TRUE);
eobj.eSet(attrB, Boolean.TRUE);
-
+
assertTrue("Should not have failed the check", check(constraint, eobj));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests support for short-circuiting IMPLIES operator.
*/
@@ -364,51 +364,51 @@
epackage.setNsPrefix("mypkg");
epackage.setNsURI("http:///mypkg.ecore");
resourceSet.getPackageRegistry().put(epackage.getNsURI(), epackage);
-
+
EClass a = EcoreFactory.eINSTANCE.createEClass();
a.setName("A");
epackage.getEClassifiers().add(a);
-
+
EClass b = EcoreFactory.eINSTANCE.createEClass();
b.setName("B");
epackage.getEClassifiers().add(b);
b.getESuperTypes().add(a);
-
+
EAttribute attrA = EcoreFactory.eINSTANCE.createEAttribute();
attrA.setName("a");
attrA.setEType(EcorePackage.eINSTANCE.getEBoolean());
a.getEStructuralFeatures().add(attrA);
-
+
EAttribute attrB = EcoreFactory.eINSTANCE.createEAttribute();
attrB.setName("b");
attrB.setEType(EcorePackage.eINSTANCE.getEBoolean());
b.getEStructuralFeatures().add(attrB);
-
+
try {
OCLExpression<EClassifier> constraint = parseConstraint(
"package mypkg context A " +
- "inv: self.oclIsKindOf(B) implies self.oclAsType(B).b " +
- "endpackage ");
-
+ "inv: self.oclIsKindOf(B) implies self.oclAsType(B).b " +
+ "endpackage ");
+
// create an A
EObject eobj = epackage.getEFactoryInstance().create(a);
eobj.eSet(attrA, Boolean.TRUE);
-
+
// this would fail with an NPE on the access to '.b' when
// 'self.oclAsType(B)' evaluates to null, if we didn't short-circuit
assertTrue("Should not have failed the check", check(constraint, eobj));
-
+
// create a B this time
eobj = epackage.getEFactoryInstance().create(b);
eobj.eSet(attrA, Boolean.TRUE);
eobj.eSet(attrB, Boolean.FALSE);
-
+
assertFalse("Should have failed the check", check(constraint, eobj));
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests that we correctly parse the <tt>oclIsNew</tt> operation in
* invariant constraints, but that validation reports a suitable error.
@@ -416,22 +416,22 @@
public void test_oclIsNew_invariant_RATLC00529981() {
OCLExpression<EClassifier> constraint = parseConstraintUnvalidated(
"package ocltest context Fruit " +
- "inv: color.oclIsNew() " +
- "endpackage");
-
+ "inv: color.oclIsNew() " +
+ "endpackage");
+
AssertionFailedError err = null;
-
+
try {
validate(constraint);
} catch (AssertionFailedError e) {
// success
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
assertNotNull("Should not have succeeded in validating illegal oclIsNew", err);
}
-
+
/**
* Tests that we correctly parse the <tt>oclIsNew</tt> operation in
* precondition constraints, but that validation reports a suitable error.
@@ -439,22 +439,22 @@
public void test_oclIsNew_precondition_RATLC00529981() {
OCLExpression<EClassifier> constraint = parseConstraintUnvalidated(
"package ocltest context Fruit::ripen(c : Color) : Boolean " +
- "pre: c.oclIsNew() implies c <> Color::black " +
- "endpackage");
-
+ "pre: c.oclIsNew() implies c <> Color::black " +
+ "endpackage");
+
AssertionFailedError err = null;
-
+
try {
validate(constraint);
} catch (AssertionFailedError e) {
// success
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
assertNotNull("Should not have succeeded in validating illegal oclIsNew", err);
}
-
+
/**
* Tests that we correctly parse the <tt>oclIsNew</tt> operation in
* postcondition constraints, and that validation reports no errors.
@@ -462,10 +462,10 @@
public void test_oclIsNew_postcondition_RATLC00529981() {
parseConstraint(
"package ocltest context Fruit::ripen(c : Color) : Boolean " +
- "post: color.oclIsNew() implies color <> Color::black " +
- "endpackage");
+ "post: color.oclIsNew() implies color <> Color::black " +
+ "endpackage");
}
-
+
/**
* Tests that we correctly parse and evaluate the <tt>toLower</tt> operation
* on OCL string values.
@@ -473,14 +473,14 @@
public void test_toLower_RATLC00529981() {
OCLExpression<EClassifier> expr = parse(
"package ocltest context Fruit " +
- "inv: 'AlPHaBet'.toLower() " +
- "endpackage");
-
+ "inv: 'AlPHaBet'.toLower() " +
+ "endpackage");
+
Object value = evaluate(expr);
-
+
assertEquals("alphabet", value);
}
-
+
/**
* Tests that we correctly parse and evaluate the <tt>toUpper</tt> operation
* on OCL string values.
@@ -488,14 +488,14 @@
public void test_toUpper_RATLC00529981() {
OCLExpression<EClassifier> expr = parse(
"package ocltest context Fruit " +
- "inv: 'AlPHaBet'.toUpper() " +
- "endpackage");
-
+ "inv: 'AlPHaBet'.toUpper() " +
+ "endpackage");
+
Object value = evaluate(expr);
-
+
assertEquals("ALPHABET", value);
}
-
+
/**
* Tests that references that have multiplicity, are unique, and
* are ordered are rendered as OCL sets.
@@ -503,15 +503,15 @@
public void test_referenceMultiplicity_orderedSet_RATLC00538035() {
OCLExpression<EClassifier> expr = parse(
"package ocltest context FruitUtil " +
- "inv: self.orderedSet" +
- " endpackage");
-
+ "inv: self.orderedSet" +
+ " endpackage");
+
// check that the result type is an ordered set type
assertTrue(
"Not an ordered set type",
expr.getType() instanceof OrderedSetType);
}
-
+
/**
* Tests that references that have multiplicity, are unique, and
* are unordered are rendered as OCL sets.
@@ -519,16 +519,16 @@
public void test_referenceMultiplicity_set_RATLC00538035() {
OCLExpression<EClassifier> expr = parse(
"package ocltest context FruitUtil " +
- "inv: self.set" +
- " endpackage");
-
+ "inv: self.set" +
+ " endpackage");
+
// check that the result type is a set type
assertTrue(
"Not a set type",
(expr.getType() instanceof SetType)
- && !(expr.getType() instanceof OrderedSetType));
+ && !(expr.getType() instanceof OrderedSetType));
}
-
+
/**
* Tests that references that have multiplicity, are non-unique, and
* are ordered are rendered as OCL sequences.
@@ -536,15 +536,15 @@
public void test_referenceMultiplicity_sequence_RATLC00538035() {
OCLExpression<EClassifier> expr = parse(
"package ocltest context FruitUtil " +
- "inv: self.sequence" +
- " endpackage");
-
+ "inv: self.sequence" +
+ " endpackage");
+
// check that the result type is a sequence set type
assertTrue(
"Not a sequence type",
expr.getType() instanceof SequenceType);
}
-
+
/**
* Tests that references that have multiplicity, are non-unique, and
* are unordered are rendered as OCL bags.
@@ -552,15 +552,15 @@
public void test_referenceMultiplicity_bag_RATLC00538035() {
OCLExpression<EClassifier> expr = parse(
"package ocltest context FruitUtil " +
- "inv: self.bag" +
- " endpackage");
-
+ "inv: self.bag" +
+ " endpackage");
+
// check that the result type is a bag set type
assertTrue(
"Not a bag type",
expr.getType() instanceof BagType);
}
-
+
/**
* Tests that operation parameters that have multiplicity, are unique, and
* are ordered are rendered as OCL sets.
@@ -568,15 +568,15 @@
public void test_parameterMultiplicity_orderedSet_RATLC00538035() {
OCLExpression<EClassifier> expr = parse(
"package ocltest context FruitUtil " +
- "inv: self.processOrderedSet(self.orderedSet)" +
- " endpackage");
-
+ "inv: self.processOrderedSet(self.orderedSet)" +
+ " endpackage");
+
// now also check that the result type is an ordered set type
assertTrue(
"Not an ordered set type",
expr.getType() instanceof OrderedSetType);
}
-
+
/**
* Tests that operation parameters that have multiplicity, are unique, and
* are unordered are rendered as OCL sets.
@@ -584,16 +584,16 @@
public void test_parameterMultiplicity_set_RATLC00538035() {
OCLExpression<EClassifier> expr = parse(
"package ocltest context FruitUtil " +
- "inv: self.processSet(self.set)" +
- " endpackage");
-
+ "inv: self.processSet(self.set)" +
+ " endpackage");
+
// now also check that the result type is a set type
assertTrue(
"Not a set type",
(expr.getType() instanceof SetType)
- && !(expr.getType() instanceof OrderedSetType));
+ && !(expr.getType() instanceof OrderedSetType));
}
-
+
/**
* Tests that operation parameters that have multiplicity, are non-unique, and
* are ordered are rendered as OCL sequences.
@@ -601,15 +601,15 @@
public void test_parameterMultiplicity_sequence_RATLC00538035() {
OCLExpression<EClassifier> expr = parse(
"package ocltest context FruitUtil " +
- "inv: self.processSequence(self.sequence)" +
- " endpackage");
-
+ "inv: self.processSequence(self.sequence)" +
+ " endpackage");
+
// now also check that the result type is a sequence type
assertTrue(
"Not a sequence type",
expr.getType() instanceof SequenceType);
}
-
+
/**
* Tests that operation parameters that have multiplicity, are non-unique, and
* are unordered are rendered as OCL bags.
@@ -617,15 +617,15 @@
public void test_parameterMultiplicity_bag_RATLC00538035() {
OCLExpression<EClassifier> expr = parse(
"package ocltest context FruitUtil " +
- "inv: self.processBag(self.bag)" +
- " endpackage");
-
+ "inv: self.processBag(self.bag)" +
+ " endpackage");
+
// now also check that the result type is a bag type
assertTrue(
"Not a bag type",
expr.getType() instanceof BagType);
}
-
+
/**
* Tests that operations that have multiplicity, are unique, and
* are ordered are rendered as OCL sets.
@@ -633,15 +633,15 @@
public void test_operationMultiplicity_orderedSet_RATLC00538035() {
OCLExpression<EClassifier> expr = parse(
"package ocltest context FruitUtil " +
- "inv: self.processOrderedSet(self.processOrderedSet(self.orderedSet))" +
- " endpackage");
-
+ "inv: self.processOrderedSet(self.processOrderedSet(self.orderedSet))" +
+ " endpackage");
+
// now also check that the result type is an ordered set type
assertTrue(
"Not an ordered set type",
expr.getType() instanceof OrderedSetType);
}
-
+
/**
* Tests that operations that have multiplicity, are unique, and
* are unordered are rendered as OCL sets.
@@ -649,16 +649,16 @@
public void test_operationMultiplicity_set_RATLC00538035() {
OCLExpression<EClassifier> expr = parse(
"package ocltest context FruitUtil " +
- "inv: self.processSet(self.processSet(self.set))" +
- " endpackage");
-
+ "inv: self.processSet(self.processSet(self.set))" +
+ " endpackage");
+
// now also check that the result type is a set type
assertTrue(
"Not a set type",
(expr.getType() instanceof SetType)
- && !(expr.getType() instanceof OrderedSetType));
+ && !(expr.getType() instanceof OrderedSetType));
}
-
+
/**
* Tests that operations that have multiplicity, are non-unique, and
* are ordered are rendered as OCL sequences.
@@ -666,15 +666,15 @@
public void test_operationMultiplicity_sequence_RATLC00538035() {
OCLExpression<EClassifier> expr = parse(
"package ocltest context FruitUtil " +
- "inv: self.processSequence(self.processSequence(self.sequence))" +
- " endpackage");
-
+ "inv: self.processSequence(self.processSequence(self.sequence))" +
+ " endpackage");
+
// now also check that the result type is a sequence type
assertTrue(
"Not a sequence type",
expr.getType() instanceof SequenceType);
}
-
+
/**
* Tests that operations that have multiplicity, are non-unique, and
* are unordered are rendered as OCL bags.
@@ -682,131 +682,131 @@
public void test_operationMultiplicity_bag_RATLC00538035() {
OCLExpression<EClassifier> expr = parse(
"package ocltest context FruitUtil " +
- "inv: self.processBag(self.processBag(self.bag))" +
- " endpackage");
-
+ "inv: self.processBag(self.processBag(self.bag))" +
+ " endpackage");
+
// now also check that the result type is a bag type
assertTrue(
"Not a bag type",
expr.getType() instanceof BagType);
}
-
+
/**
* Tests that the operation context parsing matches ordered set types
* correctly in the parameters, result type, and body expression type.
*/
public void test_operationContext_orderedSet_RATLC00538035() {
AssertionFailedError err = null;
-
+
// this should not work
try {
parse(
"package ocltest context " +
- "FruitUtil::processOrderedSet(x : Fruit) : Fruit " +
- "body: result = x" +
- " endpackage");
+ "FruitUtil::processOrderedSet(x : Fruit) : Fruit " +
+ "body: result = x" +
+ " endpackage");
} catch (AssertionFailedError e) {
// this is expected (success case)
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
assertNotNull("Parse should have failed", err);
-
+
// this should work
parse(
"package ocltest context " +
- "FruitUtil::processOrderedSet(x : OrderedSet(Fruit)) : OrderedSet(Fruit) " +
- "body: result = x" +
- " endpackage");
+ "FruitUtil::processOrderedSet(x : OrderedSet(Fruit)) : OrderedSet(Fruit) " +
+ "body: result = x" +
+ " endpackage");
}
-
+
/**
* Tests that the operation context parsing matches set types
* correctly in the parameters, result type, and body expression type.
*/
public void test_operationContext_set_RATLC00538035() {
AssertionFailedError err = null;
-
+
// this should not work
try {
parse(
"package ocltest context " +
- "FruitUtil::processSet(x : Fruit) : Fruit " +
- "body: result = x" +
- " endpackage");
+ "FruitUtil::processSet(x : Fruit) : Fruit " +
+ "body: result = x" +
+ " endpackage");
} catch (AssertionFailedError e) {
// this is expected (success case)
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
assertNotNull("Parse should have failed", err);
-
+
// this should work
parse(
"package ocltest context " +
- "FruitUtil::processSet(x : Set(Fruit)) : Set(Fruit) " +
- "body: result = x" +
- " endpackage");
+ "FruitUtil::processSet(x : Set(Fruit)) : Set(Fruit) " +
+ "body: result = x" +
+ " endpackage");
}
-
+
/**
* Tests that the operation context parsing matches sequence types
* correctly in the parameters, result type, and body expression type.
*/
public void test_operationContext_sequence_RATLC00538035() {
AssertionFailedError err = null;
-
+
// this should not work
try {
parse(
"package ocltest context " +
- "FruitUtil::processSequence(x : Fruit) : Fruit " +
- "body: result = x" +
- " endpackage");
+ "FruitUtil::processSequence(x : Fruit) : Fruit " +
+ "body: result = x" +
+ " endpackage");
} catch (AssertionFailedError e) {
// this is expected (success case)
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
assertNotNull("Parse should have failed", err);
-
+
// this should work
parse(
"package ocltest context " +
- "FruitUtil::processSequence(x : Sequence(Fruit)) : Sequence(Fruit) " +
- "body: result = x" +
- " endpackage");
+ "FruitUtil::processSequence(x : Sequence(Fruit)) : Sequence(Fruit) " +
+ "body: result = x" +
+ " endpackage");
}
-
+
/**
* Tests that the operation context parsing matches bag types
* correctly in the parameters, result type, and body expression type.
*/
public void test_operationContext_bag_RATLC00538035() {
AssertionFailedError err = null;
-
+
// this should not work
try {
parse(
"package ocltest context " +
- "FruitUtil::processBag(x : Fruit) : Fruit " +
- "body: result = x" +
- " endpackage");
+ "FruitUtil::processBag(x : Fruit) : Fruit " +
+ "body: result = x" +
+ " endpackage");
} catch (AssertionFailedError e) {
// this is expected (success case)
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
assertNotNull("Parse should have failed", err);
-
+
// this should work
parse(
"package ocltest context " +
- "FruitUtil::processBag(x : Bag(Fruit)) : Bag(Fruit) " +
- "body: result = x" +
- " endpackage");
+ "FruitUtil::processBag(x : Bag(Fruit)) : Bag(Fruit) " +
+ "body: result = x" +
+ " endpackage");
}
-
+
/**
* Regression test to check that <code>allInstances()</code> works as
* expected on enumerations.
@@ -814,15 +814,15 @@
public void test_allInstances_enumeration_RATLC00538079() {
Object result = evaluate(parse(
"package ocltest context Fruit " +
- "inv: Color.allInstances() " +
- " endpackage"));
-
+ "inv: Color.allInstances() " +
+ " endpackage"));
+
Set<EEnumLiteral> expected = new java.util.HashSet<EEnumLiteral>(
color.getELiterals());
-
+
assertEquals(expected, result);
}
-
+
/**
* Regression test to check that <code>allInstances()</code> works as
* expected on the <code>OclVoid</code> type.
@@ -830,15 +830,15 @@
public void test_allInstances_voidType_RATLC00538079() {
Object result = evaluate(parse(
"package ocltest context Fruit " +
- "inv: OclVoid.allInstances() " +
- " endpackage"));
-
+ "inv: OclVoid.allInstances() " +
+ " endpackage"));
+
Set<Object> expected = new java.util.HashSet<Object>();
expected.add(null);
-
+
assertEquals(expected, result);
}
-
+
public void test_bagIterationWithNullOccurrences() {
Bag<Object> bag = CollectionUtil.createNewBag();
bag.add(3);
@@ -864,7 +864,7 @@
i.next();
assertFalse(i.hasNext());
}
-
+
/**
* Regression test to check that <code>allInstances()</code> works as
* expected on primitive types.
@@ -872,12 +872,12 @@
public void test_allInstances_primitive_RATLC00538079() {
Object result = evaluate(parse(
"package ocltest context Fruit " +
- "inv: ecore::EMap.allInstances() " +
- " endpackage"));
-
+ "inv: ecore::EMap.allInstances() " +
+ " endpackage"));
+
assertEquals(Collections.EMPTY_SET, result);
}
-
+
/**
* Regression test for the problem of extra closing parentheses allowing
* garbage expressions to appear to parse correctly. This test tests
@@ -885,21 +885,21 @@
*/
public void test_closingParentheses_core() {
AssertionFailedError err = null;
-
+
// this should not work
try {
parse(
"package ocltest context Fruit " +
- "inv: self)garbage " +
- " endpackage");
+ "inv: self)garbage " +
+ " endpackage");
} catch (AssertionFailedError e) {
// this is expected (success case)
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
assertNotNull("Parse should have failed", err);
}
-
+
/**
* Regression test for the problem of extra closing parentheses allowing
* garbage expressions to appear to parse correctly. This test tests
@@ -907,18 +907,18 @@
*/
public void test_closingParentheses_helper() {
helper.setContext(fruit);
-
+
try {
// this should not work
helper.createInvariant("self)garbage");
-
+
fail("Parse should have failed");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
}
-
+
/**
* Regression test for the problem of extra closing parentheses allowing
* garbage expressions to appear to parse correctly. This test tests
@@ -926,72 +926,72 @@
*/
public void test_closingParentheses_helper_precondition() {
helper.setOperationContext(fruit, fruit_ripen);
-
+
try {
// this should not work
helper.createPrecondition("self)garbage");
-
+
fail("Parse should have failed");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
}
-
+
public void test_operationBodyBoolean_116251() {
AssertionFailedError err = null;
-
+
// this should work
parseConstraint(
"package ocltest context " +
- "FruitUtil::processBag(x : Bag(Fruit)) : Bag(Fruit) " +
- "body: result = x->asSet()->asBag()" +
- " endpackage");
-
+ "FruitUtil::processBag(x : Bag(Fruit)) : Bag(Fruit) " +
+ "body: result = x->asSet()->asBag()" +
+ " endpackage");
+
// as should this
parseConstraint(
"package ocltest context " +
- "FruitUtil::processBag(x : Bag(Fruit)) : Bag(Fruit) " +
- "body: x->asSet()->asBag() = result" +
- " endpackage");
-
+ "FruitUtil::processBag(x : Bag(Fruit)) : Bag(Fruit) " +
+ "body: x->asSet()->asBag() = result" +
+ " endpackage");
+
// and this (allow any number of lets to wrap the expression)
parseConstraint(
"package ocltest context " +
- "FruitUtil::processBag(x : Bag(Fruit)) : Bag(Fruit) " +
- "body: let set : Set(Fruit) = x->asSet() in" +
- " let bag : Bag(Fruit) = set->asBag() in" +
- " result = bag" +
- " endpackage");
-
+ "FruitUtil::processBag(x : Bag(Fruit)) : Bag(Fruit) " +
+ "body: let set : Set(Fruit) = x->asSet() in" +
+ " let bag : Bag(Fruit) = set->asBag() in" +
+ " result = bag" +
+ " endpackage");
+
// this should not work, however, because it has the result in the
// body expression part of the constraint
err = null;
try {
parseConstraint(
"package ocltest context " +
- "FruitUtil::processBag(x : Bag(Fruit)) : Bag(Fruit) " +
- "body: result = result->asSet()->union(x)->asBag()" +
- " endpackage");
+ "FruitUtil::processBag(x : Bag(Fruit)) : Bag(Fruit) " +
+ "body: result = result->asSet()->union(x)->asBag()" +
+ " endpackage");
} catch (AssertionFailedError e) {
// this is expected (success case)
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
assertNotNull("Parse should have failed", err);
}
-
+
public void test_ifWithNullConditionMustBeInvalid_342644() {
EObject apple = fruitFactory.create(this.apple);
Object result = evaluate(parse(
"package ocltest context Fruit " +
- "inv: let b:Boolean=null in (if b then 1 else 2 endif).oclIsInvalid()" +
- " endpackage"), apple);
-
+ "inv: let b:Boolean=null in (if b then 1 else 2 endif).oclIsInvalid()" +
+ " endpackage"), apple);
+
// oclIsInvalid() on an invalid variable value results in TRUE
assertEquals(Boolean.TRUE, result);
}
-
+
/**
* When resolving unqualified property calls in an inner scope (such as in a loop
* expression), the OCL language specification requires that the lookup of the
@@ -1005,7 +1005,7 @@
epackage.setNsPrefix("mypkg");
epackage.setNsURI("http:///mypkg.ecore");
resourceSet.getPackageRegistry().put(epackage.getNsURI(), epackage);
-
+
// Library1
// - Library2
// - Writer1
@@ -1022,12 +1022,12 @@
branchesRef.setUpperBound(ETypedElement.UNBOUNDED_MULTIPLICITY);
branchesRef.setName("branches");
branchesRef.setEType(libraryClass);
-
+
EReference writersRef = EcoreFactory.eINSTANCE.createEReference();
writersRef.setUpperBound(ETypedElement.UNBOUNDED_MULTIPLICITY);
writersRef.setName("writers");
writersRef.setEType(writerClass);
-
+
EAttribute writerName = EcoreFactory.eINSTANCE.createEAttribute();
writerName.setName("name");
writerName.setEType(EcorePackage.eINSTANCE.getEString());
@@ -1037,35 +1037,35 @@
writerClass.getEStructuralFeatures().add(writerName);
EFactory efactory = epackage.getEFactoryInstance();
-
+
// create our test instance
EObject library1 = efactory.create(libraryClass);
EObject library2 = efactory.create(libraryClass);
EObject writer1 = efactory.create(writerClass);
EObject writer2 = efactory.create(writerClass);
-
+
writer1.eSet(writerName, "Joe");
writer2.eSet(writerName, "Jane");
-
+
EList<EObject> branches = new BasicEList<EObject>();
branches.add(library2);
EList<EObject> writers = new BasicEList<EObject>();
writers.add(writer1);
writers.add(writer2);
-
+
library1.eSet(branchesRef, branches);
library2.eSet(writersRef, writers);
-
+
// parse expression
try {
OCLExpression<EClassifier> expr = parse(
- "package mypkg context Library " +
- "inv: branches->collect(writers->collect(w : Writer | w))->flatten()" +
+ "package mypkg context Library " +
+ "inv: branches->collect(writers->collect(w : Writer | w))->flatten()" +
"endpackage");
-
+
@SuppressWarnings("unchecked")
List<EObject> result = (List<EObject>)evaluate(expr, library1);
-
+
assertTrue(result.size() == 2);
assertTrue(result.get(0).eGet(writerName).equals("Joe"));
assertTrue(result.get(1).eGet(writerName).equals("Jane"));
@@ -1073,63 +1073,63 @@
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the collection product() operation.
*/
public void test_product_126336() {
helper.setContext(EcorePackage.Literals.ESTRING);
-
+
Set<Tuple<EOperation, EStructuralFeature>> product = null;
-
+
try {
OCLExpression<EClassifier> expr = helper.createQuery(
"Set{'foo', 'bar'}->product(Sequence{1, 2, 3})");
EClassifier resultType = expr.getType();
assertTrue(resultType instanceof CollectionType);
-
+
EClassifier elementType = ((CollectionType) resultType).getElementType();
-
+
assertTrue(elementType instanceof TupleType);
TupleType tupleType = (TupleType) elementType;
-
+
assertEquals(2, tupleType.getEAttributes().size());
-
+
@SuppressWarnings("unchecked")
Set<Tuple<EOperation, EStructuralFeature>> evalResult =
- (Set<Tuple<EOperation, EStructuralFeature>>) ocl.evaluate("", expr);
+ (Set<Tuple<EOperation, EStructuralFeature>>) ocl.evaluate("", expr);
product = evalResult;
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
}
-
+
assertNotNull(product);
-
+
// got as many product tuples as required (2 x 3)
assertEquals(6, product.size());
-
+
Map<String, Set<Integer>> expectedTuples =
- new java.util.HashMap<String, Set<Integer>>();
+ new java.util.HashMap<String, Set<Integer>>();
Set<Integer> values = new java.util.HashSet<Integer>();
values.add(1);
values.add(2);
values.add(3);
-
+
expectedTuples.put("foo", new java.util.HashSet<Integer>(values));
expectedTuples.put("bar", new java.util.HashSet<Integer>(values));
-
+
for (Tuple<EOperation, EStructuralFeature> tuple : product) {
values = expectedTuples.get(tuple.getValue("first"));
-
+
// every "first" value must hit
assertNotNull(values);
-
+
// every "second" must remove a different mapping
assertTrue(values.remove(tuple.getValue("second")));
}
}
-
+
/**
* Test that the conversion of an expression to string and re-parsing works
* as expected. Use the particular iteration expression described in the
@@ -1146,167 +1146,167 @@
eattr.setEType(EcorePackage.Literals.EINT);
eattr.setUpperBound(1); // not a collection
fake.getEStructuralFeatures().add(eattr);
-
+
EObject aFake = fakePkg.getEFactoryInstance().create(fake);
aFake.eSet(eattr, new Integer(7));
-
+
helper.setContext(fake);
-
+
try {
OCLExpression<EClassifier> expr = helper.createQuery("self.e->sum()");
-
+
// convert to string and re-parse
String toStringResult = expr.toString();
expr = helper.createQuery(toStringResult);
-
+
assertEquals(aFake.eGet(eattr), ocl.evaluate(aFake, expr));
} catch (Exception exc) {
fail("Failed to parse or evaluate: " + exc.getLocalizedMessage());
}
}
-
+
/**
* Test the OclVoid literal 'null'.
*/
public void test_null() {
Object result = evaluate(parse(
- "package ocltest context Fruit " +
- "inv: null.oclIsTypeOf(OclVoid) " +
+ "package ocltest context Fruit " +
+ "inv: null.oclIsTypeOf(OclVoid) " +
" endpackage"));
-
+
assertEquals(Boolean.TRUE, result);
-
+
result = evaluate(parse(
- "package ocltest context Fruit " +
- "inv: null.oclIsUndefined() " +
+ "package ocltest context Fruit " +
+ "inv: null.oclIsUndefined() " +
" endpackage"));
-
+
assertEquals(Boolean.TRUE, result);
-
+
result = evaluate(parse(
- "package ocltest context Fruit " +
- "inv: null.oclIsInvalid() " +
+ "package ocltest context Fruit " +
+ "inv: null.oclIsInvalid() " +
" endpackage"));
-
+
assertEquals(Boolean.FALSE, result);
-
+
result = evaluate(parse(
- "package ocltest context Fruit " +
- "inv: null.oclAsType(Integer) " +
+ "package ocltest context Fruit " +
+ "inv: null.oclAsType(Integer) " +
" endpackage"));
-
+
assertNull(result);
}
-
+
/**
* Test the OclInvalid type and its literal 'invalid'.
*/
public void test_oclInvalid() {
Object result = evaluate(parse(
"package ocltest context Fruit " +
- "inv: invalid.oclIsTypeOf(OclInvalid) " +
- " endpackage"));
-
- assertEquals(Boolean.TRUE, result);
-
- result = evaluate(parse(
- "package ocltest context Fruit " +
- "inv: invalid.oclIsUndefined() " +
+ "inv: invalid.oclIsTypeOf(OclInvalid) " +
" endpackage"));
-
+
assertEquals(Boolean.TRUE, result);
-
+
result = evaluate(parse(
- "package ocltest context Fruit " +
- "inv: invalid.oclIsInvalid() " +
+ "package ocltest context Fruit " +
+ "inv: invalid.oclIsUndefined() " +
" endpackage"));
-
+
assertEquals(Boolean.TRUE, result);
-
+
result = evaluate(parse(
- "package ocltest context Fruit " +
- "inv: invalid.oclAsType(Integer) " +
+ "package ocltest context Fruit " +
+ "inv: invalid.oclIsInvalid() " +
" endpackage"));
-
+
+ assertEquals(Boolean.TRUE, result);
+
+ result = evaluate(parse(
+ "package ocltest context Fruit " +
+ "inv: invalid.oclAsType(Integer) " +
+ " endpackage"));
+
assertInvalid(result);
-
+
result = evaluate(parse(
- "package ocltest context Fruit " +
- "inv: null.oclAsType(Apple).color " +
+ "package ocltest context Fruit " +
+ "inv: null.oclAsType(Apple).color " +
" endpackage"));
-
+
// feature calls on null result in invalid
assertInvalid(result);
-
+
result = evaluate(parse(
- "package ocltest context Fruit " +
- "inv: null.oclAsType(Apple).stem " +
+ "package ocltest context Fruit " +
+ "inv: null.oclAsType(Apple).stem " +
" endpackage"));
-
+
// feature calls on null result in invalid
assertInvalid(result);
-
+
result = evaluate(parse(
- "package ocltest context Fruit " +
- "inv: null.oclAsType(Apple).preferredLabel('foo') " +
+ "package ocltest context Fruit " +
+ "inv: null.oclAsType(Apple).preferredLabel('foo') " +
" endpackage"));
-
+
// feature calls on null result in invalid
assertInvalid(result);
}
-
+
public void test_oclInvalidInIterateAccumulator_342644() {
EObject apple = fruitFactory.create(this.apple);
Object result = evaluate(parse(
"package ocltest context Fruit " +
- "inv: self->iterate(i; acc:Integer='123a'.toInteger() | if acc.oclIsInvalid() then 0 else acc+1 endif)" +
- " endpackage"), apple);
-
+ "inv: self->iterate(i; acc:Integer='123a'.toInteger() | if acc.oclIsInvalid() then 0 else acc+1 endif)" +
+ " endpackage"), apple);
+
// oclIsInvalid() on an invalid variable value results in TRUE
assertEquals(0, result);
}
-
+
public void test_oclIsInvalidOnInvalidLetVariable_342644() {
Object result = evaluate(parse(
"package ocltest context Fruit " +
- "inv: let a:Integer = '123a'.toInteger() in a.oclIsInvalid() " +
- " endpackage"));
-
+ "inv: let a:Integer = '123a'.toInteger() in a.oclIsInvalid() " +
+ " endpackage"));
+
// oclIsInvalid() on an invalid variable value results in TRUE
assertEquals(Boolean.TRUE, result);
}
-
+
public void test_oclIsInvalidOnInvalidOperationResult_342561() {
Object result = evaluate(parse(
"package ocltest context Fruit " +
- "inv: '123a'.toInteger().oclIsInvalid() " +
- " endpackage"));
-
+ "inv: '123a'.toInteger().oclIsInvalid() " +
+ " endpackage"));
+
// oclIsInvalid() on an invalid OperationCallExp results in TRUE
assertEquals(Boolean.TRUE, result);
}
-
+
/**
* Tests that we report an error on failing to find an operation matching
* a call. Moreover, the error is in parsing, not in validating.
*/
public void test_operationNotFound() {
AssertionFailedError err = null;
-
+
// this should not work (failure in parse, not validation)
try {
parseUnvalidated(
"package ocltest context FruitUtil " +
- "inv: self.processOrderedSet(1) = 0 " +
- " endpackage");
+ "inv: self.processOrderedSet(1) = 0 " +
+ " endpackage");
} catch (AssertionFailedError e) {
// this is expected (success case)
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
assertNotNull("Parse should have failed", err);
}
-
+
/**
* Tests that matching operations finds the first match, but that
* casting via oclAsType() can direct the parser to the best match.
@@ -1324,7 +1324,7 @@
c.setName("C");
c.getESuperTypes().add(b);
pkg.getEClassifiers().add(c);
-
+
EReference ref = EcoreFactory.eINSTANCE.createEReference();
ref.setEType(b);
ref.setName("b");
@@ -1333,7 +1333,7 @@
ref.setEType(c);
ref.setName("c");
a.getEStructuralFeatures().add(ref);
-
+
EOperation foo1 = EcoreFactory.eINSTANCE.createEOperation();
foo1.setName("foo");
foo1.setEType(EcorePackage.Literals.EBOOLEAN);
@@ -1341,7 +1341,7 @@
param.setEType(c);
foo1.getEParameters().add(param);
a.getEOperations().add(foo1);
-
+
EOperation foo2 = EcoreFactory.eINSTANCE.createEOperation();
foo2.setName("foo");
foo2.setEType(EcorePackage.Literals.EBOOLEAN);
@@ -1349,40 +1349,40 @@
param.setEType(b);
foo2.getEParameters().add(param);
a.getEOperations().add(foo2);
-
+
helper.setContext(a);
-
+
try {
OCLExpression<EClassifier> expr = helper.createQuery("self.foo(c)");
-
+
assertTrue(expr instanceof OperationCallExp<?, ?>);
OperationCallExp<EClassifier, EOperation> oc =
- (OperationCallExp<EClassifier, EOperation>) expr;
-
+ (OperationCallExp<EClassifier, EOperation>) expr;
+
// foo1's parameter type is c
assertSame(foo1, oc.getReferredOperation());
-
+
expr = helper.createQuery("self.foo(b)");
-
+
assertTrue(expr instanceof OperationCallExp<?, ?>);
oc = (OperationCallExp<EClassifier, EOperation>) expr;
-
+
// we matched foo1 because it was the first operation matching b
// (we skipped the foo having parameter type c)
assertSame(foo2, oc.getReferredOperation());
-
+
expr = helper.createQuery("self.foo(b.oclAsType(C))");
-
+
assertTrue(expr instanceof OperationCallExp<?, ?>);
oc = (OperationCallExp<EClassifier, EOperation>) expr;
-
+
// coerced the arg to type C to find the correct foo
assertSame(foo1, oc.getReferredOperation());
} catch (Exception e) {
fail("Failed to parse: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests that looking up an operation call on an implicit source works
* and fails gracefully when it doesn't. Test the case where the implicit
@@ -1390,33 +1390,33 @@
*/
public void test_operationImplicitSource() {
AssertionFailedError err = null;
-
+
// this should not work
try {
parse(
"package ocltest context Fruit " +
- "inv: Apple.allInstances()->collect(preferredLabel())" +
- " endpackage");
+ "inv: Apple.allInstances()->collect(preferredLabel())" +
+ " endpackage");
} catch (AssertionFailedError e) {
// this is expected (success case)
err = e;
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
assertNotNull("Parse should have failed", err);
-
+
// this should work
parse(
"package ocltest context Fruit " +
- "inv: Apple.allInstances()->collect(preferredLabel('foo'))" +
- " endpackage");
-
+ "inv: Apple.allInstances()->collect(preferredLabel('foo'))" +
+ " endpackage");
+
// and this
parse(
"package ocltest context Apple " +
- "inv: preferredLabel('foo')" +
- " endpackage");
+ "inv: preferredLabel('foo')" +
+ " endpackage");
}
-
+
/**
* Tests resolution of nested packages where the root package has a
* namespace prefix that differs from the name (in particular, by being
@@ -1427,54 +1427,54 @@
rootPackage.setName("foo");
rootPackage.setNsPrefix("a.b.c.foo");
rootPackage.setNsURI("http:///foo.ecore");
-
+
EClass a = EcoreFactory.eINSTANCE.createEClass();
a.setName("A");
rootPackage.getEClassifiers().add(a);
-
+
EPackage nestedPackage = EcoreFactory.eINSTANCE.createEPackage();
nestedPackage.setName("bar");
nestedPackage.setNsPrefix("a.b.c.foo.bar");
nestedPackage.setNsURI("http:///foo/bar.ecore");
-
+
rootPackage.getESubpackages().add(nestedPackage);
-
+
EClass b = EcoreFactory.eINSTANCE.createEClass();
b.setName("B");
nestedPackage.getEClassifiers().add(b);
-
+
EPackage.Registry reg = new EPackageRegistryImpl(resourceSet.getPackageRegistry());
reg.put(rootPackage.getNsURI(), rootPackage);
reg.put(nestedPackage.getNsURI(), nestedPackage);
EcoreEnvironmentFactory ef = new EcoreEnvironmentFactory(reg);
-
+
ocl.dispose();
ocl = OCL.newInstance(ef);
helper = ocl.createOCLHelper();
helper.setContext(b);
-
+
try {
// look up by name
helper.createInvariant("not self.oclIsKindOf(foo::A)");
-
+
// for compatibility, NS prefix also works
helper.createInvariant("not self.oclIsKindOf(a::b::c::foo::A)");
-
+
helper.setContext(a);
-
+
// look-up relative to context package
helper.createInvariant("not self.oclIsKindOf(bar::B)");
-
+
// absolute look-up by name
helper.createInvariant("not self.oclIsKindOf(foo::bar::B)");
-
+
// and by NS prefix
helper.createInvariant("not self.oclIsKindOf(a::b::c::foo::bar::B)");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests that EClassifier sameness is tested using equality rather than
* identity, on the understanding that usually EClasses implement equality
@@ -1484,33 +1484,33 @@
public void test_typeEquality_126145() {
class EqualsEClass extends EClassImpl {
private int key;
-
+
EqualsEClass(int key) {
this.key = key;
}
-
+
@Override
- public boolean equals(Object o) {
+ public boolean equals(Object o) {
return (o instanceof EqualsEClass)
- && (key == ((EqualsEClass) o).key);
+ && (key == ((EqualsEClass) o).key);
}
}
-
+
EPackage epackage = EcoreFactory.eINSTANCE.createEPackage();
epackage.setName("foo");
-
+
EClass a = new EqualsEClass(1);
a.setName("A");
epackage.getEClassifiers().add(a);
-
+
EClass b = new EqualsEClass(1); // same key as a, so b.equals(a)
b.setName("B");
epackage.getEClassifiers().add(b);
-
+
EClass c = new EqualsEClass(2);
c.setName("C");
epackage.getEClassifiers().add(b);
-
+
EReference ref = EcoreFactory.eINSTANCE.createEReference();
ref.setName("a");
ref.setUpperBound(ETypedElement.UNBOUNDED_MULTIPLICITY);
@@ -1525,34 +1525,34 @@
ref.setUnique(true);
ref.setEType(b);
c.getEStructuralFeatures().add(ref);
-
+
helper.setContext(c);
OCLExpression<EClassifier> expr = null;
-
+
try {
expr = helper.createQuery("a->union(b)");
} catch (Exception e) {
fail("Parse failed: " + e.getLocalizedMessage());
}
-
+
assertNotNull(expr);
-
+
EClassifier type = expr.getType();
-
+
assertTrue(type instanceof CollectionType);
-
+
type = ((CollectionType) type).getElementType();
-
+
// verify that the common supertype is a/b, which are considered by
// OCL to be the same type
assertEquals(a, type);
assertEquals(b, type);
-
+
EcoreEnvironment env = (EcoreEnvironment) ocl.getEnvironment();
-
+
assertEquals(UMLReflection.SAME_TYPE, TypeUtil.getRelationship(env, a, b));
assertEquals(UMLReflection.SAME_TYPE, TypeUtil.getRelationship(env, b, a));
-
+
try {
assertEquals(a, TypeUtil.commonSuperType(env, a, b));
assertEquals(b, TypeUtil.commonSuperType(env, a, b));
@@ -1562,10 +1562,10 @@
fail("No common super type: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests referencing an element in an enclosing package using an unqualified name.
- *
+ *
* <ul>
* <li>EPackage level1<ul>
* <li>EEnum Enum1<ul>
@@ -1573,7 +1573,7 @@
* <li>EPackage level2<ul>
* <li>EClass Class1<ul>
* <li>EAttribute attr1 : Enum1</li></ul></li></ul></li></ul></li>
- * </ul>
+ * </ul>
* <pre>
* context: Class1
* expression: attr1 = Enum1::Enum1Literal1
@@ -1584,17 +1584,17 @@
level1.setName("level1");
EPackage level2 = EcoreFactory.eINSTANCE.createEPackage();
level2.setName("level2");
-
+
level1.getESubpackages().add(level2);
-
+
EEnum enum1 = EcoreFactory.eINSTANCE.createEEnum();
enum1.setName("Enum1");
-
+
EEnumLiteral enum1Literal1 = EcoreFactory.eINSTANCE.createEEnumLiteral();
enum1Literal1.setName("Enum1Literal1");
-
+
enum1.getELiterals().add(enum1Literal1);
-
+
EClass class1 = EcoreFactory.eINSTANCE.createEClass();
class1.setName("Class1");
@@ -1603,282 +1603,282 @@
attr1.setEType(enum1);
class1.getEStructuralFeatures().add(attr1);
-
+
level1.getEClassifiers().add(enum1);
level2.getEClassifiers().add(class1);
-
+
helper.setContext(class1);
-
+
try {
helper.createInvariant("attr1 = Enum1::Enum1Literal1");
} catch (Exception e) {
fail("Failed to parse: " + e.getLocalizedMessage());
}
}
-
+
/**
* The Hebrew (Israel) locale on SuSe Linux likes to use character 0xB4
* (acute accent) as a single quotation mark. Should also, then, support
* the back-quote (grave accent), as well.
*/
public void test_hebrew_singleQuote_135321() {
-// checkForUTF8Encoding();
-
+ // checkForUTF8Encoding();
+
parse(
- // English locale style
- "package ocltest context Apple " +
- "inv: preferredLabel('foo')" +
+ // English locale style
+ "package ocltest context Apple " +
+ "inv: preferredLabel('foo')" +
" endpackage");
-
-/* parse( FIXME Bug 291310 rewrite for OCL 2.3 and reintroduce when build is UTF-8.
+
+ /* parse( FIXME Bug 291310 rewrite for OCL 2.3 and reintroduce when build is UTF-8.
// SuSe Linux in Hebrew Local
"package ocltest context Apple " +
"inv: preferredLabel(´foo´)" +
" endpackage");
-
+
parse(
// I've seen this before (esp. in text export from MS Word)
"package ocltest context Apple " +
"inv: preferredLabel(`foo´)" +
" endpackage"); */
}
-
+
/**
* Test that we don't get a <code>null</code> string from an OCL expression
* that contains a reference to a variable that has no name.
*/
public void test_nullVariableName_143386() {
org.eclipse.ocl.ecore.Variable var =
- (org.eclipse.ocl.ecore.Variable) oclFactory.<EClassifier, EParameter>createVariable();
-
+ (org.eclipse.ocl.ecore.Variable) oclFactory.<EClassifier, EParameter>createVariable();
+
assertEquals("\"<null>\"", var.toString());
-
+
VariableExp<EClassifier, EParameter> exp =
- oclFactory.createVariableExp();
+ oclFactory.createVariableExp();
exp.setReferredVariable(var);
-
+
assertEquals("\"<null>\"", exp.toString());
-
+
var.setName("foo");
-
+
assertEquals("foo", var.toString());
assertEquals("foo", exp.toString());
-
+
var.setEType(getOCLStandardLibrary().getString());
-
+
assertEquals("foo : String", var.toString());
assertEquals("foo", exp.toString());
}
-
- /**
- * Regression test for the case of Let expression declaring multiple
- * variables that is well-formed.
- */
- @SuppressWarnings("unchecked")
+
+ /**
+ * Regression test for the case of Let expression declaring multiple
+ * variables that is well-formed.
+ */
+ @SuppressWarnings("unchecked")
public void test_letWithMultipleVariables_bug164503() {
- OCLExpression<EClassifier> expr = parse(
- "package ocltest context Fruit " +
- " inv: let s : String = '', i : Set(Integer) = Set{1}, n : UnlimitedNatural = * in true" +
- " endpackage");
-
- // verify the structure of the nested let expression
-
- // first level let is the String variable
- assertTrue(expr instanceof LetExp<?, ?>);
- LetExp<EClassifier, ?> letExp = (LetExp<EClassifier, ?>) expr;
- Variable<EClassifier, ?> var = letExp.getVariable();
- assertEquals("s", var.getName());
- assertSame(getOCLStandardLibrary().getString(), var.getType());
-
- // second level is the Set(Integer)
- assertTrue(letExp.getIn() instanceof LetExp<?, ?>);
- letExp = (LetExp<EClassifier, ?>) letExp.getIn();
- var = letExp.getVariable();
- assertEquals("i", var.getName());
- assertTrue(var.getType() instanceof SetType);
-
- // third level is the UnlimitedNatural
- assertTrue(letExp.getIn() instanceof LetExp<?, ?>);
- letExp = (LetExp<EClassifier, ?>) letExp.getIn();
- var = letExp.getVariable();
- assertEquals("n", var.getName());
- assertSame(getOCLStandardLibrary().getUnlimitedNatural(), var.getType());
-
- // now we have a real "in"
- assertTrue(letExp.getIn() instanceof BooleanLiteralExp<?>);
- }
-
- /**
- * Regression test for the case of Let expression declaring multiple
- * variables that is ill-formed, that we don't fail parsing with a runtime
- * exception.
- */
- public void test_letWithMultipleVariables_illFormed_bug164503() {
-
- try {
- parse(
- "package ocltest context Fruit " +
- " inv: let s : String = '', i : Set(Integer) in true" +
- " endpackage");
-
- fail("Should have failed to parse or validate");
- } catch (AssertionFailedError e) {
- // success
- System.out.println("Got the expected exception: " + e.getLocalizedMessage());
- } catch (Exception e) {
- fail("Parse failed with run-time exception: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * Tests that, where a path name includes two or more components
- * having the same name, the PathNameCS does not remove duplicates.
- */
- public void test_repeatedNamesInPath_176308() {
- EPackage rootpkg = EcoreFactory.eINSTANCE.createEPackage();
- rootpkg.setName("rootpkg");
- EPackage first = EcoreFactory.eINSTANCE.createEPackage();
- first.setName("repeated");
- EPackage second = EcoreFactory.eINSTANCE.createEPackage();
- second.setName("repeated");
-
- rootpkg.getESubpackages().add(first);
- first.getESubpackages().add(second);
-
- EEnum enum1 = EcoreFactory.eINSTANCE.createEEnum();
- enum1.setName("Enum1");
-
- EEnumLiteral enum1Literal1 = EcoreFactory.eINSTANCE.createEEnumLiteral();
- enum1Literal1.setName("Enum1Literal1");
-
- enum1.getELiterals().add(enum1Literal1);
-
- second.getEClassifiers().add(enum1);
-
- EClass dummy = EcoreFactory.eINSTANCE.createEClass();
- dummy.setName("Dummy");
- rootpkg.getEClassifiers().add(dummy);
-
- EAttribute attr1 = EcoreFactory.eINSTANCE.createEAttribute();
- attr1.setName("attr1");
- attr1.setEType(enum1);
- dummy.getEStructuralFeatures().add(attr1);
-
- helper.setContext(dummy);
-
- try {
- // should not attempt to look up "repeated::Enum1"
- helper.createInvariant(
- "attr1 = repeated::repeated::Enum1::Enum1Literal1");
- } catch (Exception e) {
- fail("Failed to parse: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * Tests that dollar signs are supported in string literals and in
- * element names.
- */
- public void test_dollarSignInStrings_163542() {
- EPackage rootpkg = EcoreFactory.eINSTANCE.createEPackage();
- rootpkg.setName("rootpkg");
- rootpkg.setNsURI("http:///rootpkg.ecore");
-
- EClass superclass = EcoreFactory.eINSTANCE.createEClass();
- superclass.setName("Superclass");
- EClass subclass = EcoreFactory.eINSTANCE.createEClass();
- subclass.setName("Sub$Class");
- subclass.getESuperTypes().add(superclass);
-
- rootpkg.getEClassifiers().add(superclass);
- rootpkg.getEClassifiers().add(subclass);
-
- EAttribute attr1 = EcoreFactory.eINSTANCE.createEAttribute();
- attr1.setName("attr$1");
- attr1.setEType(EcorePackage.Literals.ESTRING);
- superclass.getEStructuralFeatures().add(attr1);
-
- resourceSet.getPackageRegistry().put(rootpkg.getNsURI(), rootpkg);
-
- try {
- // parse dollar sign in comments, element names, and string literals
- ocl.parse(new OCLInput(
- "package rootpkg context Superclass\n" +
- "-- this comment has a $ in it\n" +
- "inv: attr$1 = 'dollar$sign' implies self.oclIsKindOf(Sub$Class)\n" +
- "endpackage"));
- } catch (Exception e) {
- fail("Failed to parse: " + e.getLocalizedMessage());
- }
- }
-
- /**
- * Tests that we don't get NPEs from getting the names of collection types
- * that do not (yet) have element types.
- */
- public void test_nameOfCollectionTypeWithoutElementType() {
- org.eclipse.ocl.types.CollectionType<?, ?> collType = oclFactory.createCollectionType(
- CollectionKind.BAG_LITERAL, null);
-
- collType.getName();
- }
-
- /**
- * Ensure that variable expressions' names are set as they were in the
- * 1.1 release.
- */
- public void test_variableExpName_243526() {
+ OCLExpression<EClassifier> expr = parse(
+ "package ocltest context Fruit " +
+ " inv: let s : String = '', i : Set(Integer) = Set{1}, n : UnlimitedNatural = * in true" +
+ " endpackage");
+
+ // verify the structure of the nested let expression
+
+ // first level let is the String variable
+ assertTrue(expr instanceof LetExp<?, ?>);
+ LetExp<EClassifier, ?> letExp = (LetExp<EClassifier, ?>) expr;
+ Variable<EClassifier, ?> var = letExp.getVariable();
+ assertEquals("s", var.getName());
+ assertSame(getOCLStandardLibrary().getString(), var.getType());
+
+ // second level is the Set(Integer)
+ assertTrue(letExp.getIn() instanceof LetExp<?, ?>);
+ letExp = (LetExp<EClassifier, ?>) letExp.getIn();
+ var = letExp.getVariable();
+ assertEquals("i", var.getName());
+ assertTrue(var.getType() instanceof SetType);
+
+ // third level is the UnlimitedNatural
+ assertTrue(letExp.getIn() instanceof LetExp<?, ?>);
+ letExp = (LetExp<EClassifier, ?>) letExp.getIn();
+ var = letExp.getVariable();
+ assertEquals("n", var.getName());
+ assertSame(getOCLStandardLibrary().getUnlimitedNatural(), var.getType());
+
+ // now we have a real "in"
+ assertTrue(letExp.getIn() instanceof BooleanLiteralExp<?>);
+ }
+
+ /**
+ * Regression test for the case of Let expression declaring multiple
+ * variables that is ill-formed, that we don't fail parsing with a runtime
+ * exception.
+ */
+ public void test_letWithMultipleVariables_illFormed_bug164503() {
+
+ try {
+ parse(
+ "package ocltest context Fruit " +
+ " inv: let s : String = '', i : Set(Integer) in true" +
+ " endpackage");
+
+ fail("Should have failed to parse or validate");
+ } catch (AssertionFailedError e) {
+ // success
+ debugPrintln("Got the expected exception: " + e.getLocalizedMessage());
+ } catch (Exception e) {
+ fail("Parse failed with run-time exception: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests that, where a path name includes two or more components
+ * having the same name, the PathNameCS does not remove duplicates.
+ */
+ public void test_repeatedNamesInPath_176308() {
+ EPackage rootpkg = EcoreFactory.eINSTANCE.createEPackage();
+ rootpkg.setName("rootpkg");
+ EPackage first = EcoreFactory.eINSTANCE.createEPackage();
+ first.setName("repeated");
+ EPackage second = EcoreFactory.eINSTANCE.createEPackage();
+ second.setName("repeated");
+
+ rootpkg.getESubpackages().add(first);
+ first.getESubpackages().add(second);
+
+ EEnum enum1 = EcoreFactory.eINSTANCE.createEEnum();
+ enum1.setName("Enum1");
+
+ EEnumLiteral enum1Literal1 = EcoreFactory.eINSTANCE.createEEnumLiteral();
+ enum1Literal1.setName("Enum1Literal1");
+
+ enum1.getELiterals().add(enum1Literal1);
+
+ second.getEClassifiers().add(enum1);
+
+ EClass dummy = EcoreFactory.eINSTANCE.createEClass();
+ dummy.setName("Dummy");
+ rootpkg.getEClassifiers().add(dummy);
+
+ EAttribute attr1 = EcoreFactory.eINSTANCE.createEAttribute();
+ attr1.setName("attr1");
+ attr1.setEType(enum1);
+ dummy.getEStructuralFeatures().add(attr1);
+
+ helper.setContext(dummy);
+
+ try {
+ // should not attempt to look up "repeated::Enum1"
+ helper.createInvariant(
+ "attr1 = repeated::repeated::Enum1::Enum1Literal1");
+ } catch (Exception e) {
+ fail("Failed to parse: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests that dollar signs are supported in string literals and in
+ * element names.
+ */
+ public void test_dollarSignInStrings_163542() {
+ EPackage rootpkg = EcoreFactory.eINSTANCE.createEPackage();
+ rootpkg.setName("rootpkg");
+ rootpkg.setNsURI("http:///rootpkg.ecore");
+
+ EClass superclass = EcoreFactory.eINSTANCE.createEClass();
+ superclass.setName("Superclass");
+ EClass subclass = EcoreFactory.eINSTANCE.createEClass();
+ subclass.setName("Sub$Class");
+ subclass.getESuperTypes().add(superclass);
+
+ rootpkg.getEClassifiers().add(superclass);
+ rootpkg.getEClassifiers().add(subclass);
+
+ EAttribute attr1 = EcoreFactory.eINSTANCE.createEAttribute();
+ attr1.setName("attr$1");
+ attr1.setEType(EcorePackage.Literals.ESTRING);
+ superclass.getEStructuralFeatures().add(attr1);
+
+ resourceSet.getPackageRegistry().put(rootpkg.getNsURI(), rootpkg);
+
+ try {
+ // parse dollar sign in comments, element names, and string literals
+ ocl.parse(new OCLInput(
+ "package rootpkg context Superclass\n" +
+ "-- this comment has a $ in it\n" +
+ "inv: attr$1 = 'dollar$sign' implies self.oclIsKindOf(Sub$Class)\n" +
+ "endpackage"));
+ } catch (Exception e) {
+ fail("Failed to parse: " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Tests that we don't get NPEs from getting the names of collection types
+ * that do not (yet) have element types.
+ */
+ public void test_nameOfCollectionTypeWithoutElementType() {
+ org.eclipse.ocl.types.CollectionType<?, ?> collType = oclFactory.createCollectionType(
+ CollectionKind.BAG_LITERAL, null);
+
+ collType.getName();
+ }
+
+ /**
+ * Ensure that variable expressions' names are set as they were in the
+ * 1.1 release.
+ */
+ public void test_variableExpName_243526() {
OCLExpression<EClassifier> constraint = parseConstraintUnvalidated(
"package ocltest context Fruit::ripen(c : Color) : Boolean " +
- "pre: c.oclIsUndefined() implies Fruit.allInstances()->forAll(color <> self.color) " +
- "endpackage");
-
+ "pre: c.oclIsUndefined() implies Fruit.allInstances()->forAll(color <> self.color) " +
+ "endpackage");
+
for (Iterator<EObject> iter = constraint.eAllContents(); iter.hasNext();) {
EObject next = iter.next();
-
+
if (next instanceof VariableExp<?, ?>) {
VariableExp<?, ?> ve = (VariableExp<?, ?>) next;
assertNotNull(ve.getReferredVariable());
assertEquals(ve.getReferredVariable().getName(), ve.getName());
}
}
- }
-
- /**
- * Ensures that we can reference the UnlimitedNatural type by name.
- */
- public void test_refToUnlimitedNaturalType_259740() {
+ }
+
+ /**
+ * Ensures that we can reference the UnlimitedNatural type by name.
+ */
+ public void test_refToUnlimitedNaturalType_259740() {
parse(
"package ocltest context Apple " +
- "inv: let u : UnlimitedNatural = * in u.abs()" +
- " endpackage");
+ "inv: let u : UnlimitedNatural = * in u.abs()" +
+ " endpackage");
parse(
"package ocltest context Apple " +
- "inv: let i : Integer = -1 in not i.oclIsKindOf(UnlimitedNatural)" +
- " endpackage");
- }
-
- /**
- * Tests that a package declaration for an unresolved package fails to
- * parse (as it should).
- */
- public void test_nullPackageEnvironment_259818() {
- try {
- parse(
- "package NOSUCHPACKAGE context ocltest::Fruit " +
- " inv: true" +
- " endpackage");
-
- fail("Should have failed to parse or validate");
- } catch (AssertionFailedError e) {
- // success
- System.out.println("Got the expected exception: " + e.getLocalizedMessage());
- } catch (Exception e) {
- fail("Parse failed with run-time exception: " + e.getLocalizedMessage());
- }
- }
-
+ "inv: let i : Integer = -1 in not i.oclIsKindOf(UnlimitedNatural)" +
+ " endpackage");
+ }
+
+ /**
+ * Tests that a package declaration for an unresolved package fails to
+ * parse (as it should).
+ */
+ public void test_nullPackageEnvironment_259818() {
+ try {
+ parse(
+ "package NOSUCHPACKAGE context ocltest::Fruit " +
+ " inv: true" +
+ " endpackage");
+
+ fail("Should have failed to parse or validate");
+ } catch (AssertionFailedError e) {
+ // success
+ debugPrintln("Got the expected exception: " + e.getLocalizedMessage());
+ } catch (Exception e) {
+ fail("Parse failed with run-time exception: " + e.getLocalizedMessage());
+ }
+ }
+
/**
* Tests support for Properties with OclVoid, Collection(OclVoid) type..
*/
@@ -1888,49 +1888,49 @@
epackage.setNsPrefix("mypkg");
epackage.setNsURI("http:///mypkg.ecore");
resourceSet.getPackageRegistry().put(epackage.getNsURI(), epackage);
-
+
EClass a = EcoreFactory.eINSTANCE.createEClass();
a.setName("A");
epackage.getEClassifiers().add(a);
-
+
EClassifier voidType = ocl.getEnvironment().getOCLStandardLibrary().getOclVoid();
-
+
EAttribute attrA = EcoreFactory.eINSTANCE.createEAttribute();
attrA.setName("void");
attrA.setEType(voidType);
a.getEStructuralFeatures().add(attrA);
-
+
EAttribute attrB = EcoreFactory.eINSTANCE.createEAttribute();
attrB.setName("voids");
attrB.setEType(voidType);
attrB.setUpperBound(-1);
a.getEStructuralFeatures().add(attrB);
-
+
try {
OCLExpression<EClassifier> constraint = parseConstraint(
"package mypkg context A " +
- "inv: self.voids = OrderedSet{} " +
- "endpackage");
-
+ "inv: self.voids = OrderedSet{} " +
+ "endpackage");
+
// create an A
EObject eobj = epackage.getEFactoryInstance().create(a);
assertTrue("Should not have failed the check", check(constraint, eobj));
constraint = parseConstraint(
"package mypkg context A " +
- "inv: self.voids = Set{} " +
- "endpackage");
+ "inv: self.voids = Set{} " +
+ "endpackage");
assertFalse("Should have failed the check", check(constraint, eobj)); // Check that we are checking
constraint = parseConstraint(
"package mypkg context A " +
- "inv: self.void = null " +
- "endpackage");
+ "inv: self.void = null " +
+ "endpackage");
assertTrue("Should have failed the check", check(constraint, eobj));
@SuppressWarnings("unchecked")List<Object> voids = (List<Object>) eobj.eGet(attrB);
voids.add(null);
constraint = parseConstraint(
"package mypkg context A " +
- "inv: self.voids = OrderedSet{null} " +
- "endpackage");
+ "inv: self.voids = OrderedSet{null} " +
+ "endpackage");
assertTrue("Should have failed the check", check(constraint, eobj)); // Check that we are checking
} catch (Exception e) {
fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/StatesTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/StatesTest.java
index bcc984c..2d22bad 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/StatesTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/StatesTest.java
@@ -44,14 +44,14 @@
*/
@SuppressWarnings("nls")
public class StatesTest
- extends AbstractTestSuite {
-
+extends AbstractTestSuite {
+
/**
* Tests the parsing of the oclIsInState() expression.
*/
public void test_isInState() {
helper.setContext(fruit);
-
+
try {
// test implicit and explicit source
helper.createInvariant(
@@ -59,115 +59,115 @@
// test source of different type than context (and also implicit)
helper.createInvariant(
- "Apple.allInstances()->forAll(not oclIsInState(Bad::Rotten))");
+ "Apple.allInstances()->forAll(not oclIsInState(Bad::Rotten))");
} catch (Exception e) {
fail("Failed to parse: " + e.getLocalizedMessage());
}
-
+
try {
// just to make sure that the second test, above, wasn't a fluke.
// Fruit doesn't have this state
helper.createInvariant(
- "Fruit.allInstances()->forAll(not oclIsInState(Bad::Rotten))");
-
+ "Fruit.allInstances()->forAll(not oclIsInState(Bad::Rotten))");
+
fail("Should have failed to parse non-existent state");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests some validation of the oclIsInState() expression.
*/
public void test_isInState_validation() {
helper.setContext(fruit);
-
+
try {
// not enough arguments
helper.createInvariant(
- "self.oclIsInState()");
-
+ "self.oclIsInState()");
+
fail("Should have failed to parse empty arglist");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
try {
// too many arguments
helper.createInvariant(
- "Apple.allInstances()->forAll(oclIsInState(Bad, Rotten))");
-
+ "Apple.allInstances()->forAll(oclIsInState(Bad, Rotten))");
+
fail("Should have failed to parse overabundant arglist");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
try {
// wrong kind of argument
helper.createInvariant(
- "self.oclIsInState(color <> Color::black)");
-
+ "self.oclIsInState(color <> Color::black)");
+
fail("Should have failed to parse arg of wrong type");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
-
+
try {
// another kind of wrong kind of argument
helper.createInvariant(
- "self.oclIsInState(OclTest::Fruit)");
-
+ "self.oclIsInState(OclTest::Fruit)");
+
fail("Should have failed to parse arg of wrong type");
} catch (Exception e) {
// success
- System.out.println("Got expected error: " + e.getLocalizedMessage());
+ debugPrintln("Got expected error: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests the content-assist for states.
*/
public void test_stateContentAssist() {
helper.setContext(fruit);
-
+
try {
// simplest case of first path name part completion
List<Choice> choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "self.oclIsInState(");
+ ConstraintKind.INVARIANT, "self.oclIsInState(");
assertNotNull(choices);
assertChoice(choices, ChoiceKind.STATE, "Ripe");
assertChoice(choices, ChoiceKind.STATE, "Bad");
// case of no more completions (path is already complete)
choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT, "self.oclIsInState(Ripe::");
+ ConstraintKind.INVARIANT, "self.oclIsInState(Ripe::");
assertNotNull(choices);
assertTrue(choices.isEmpty());
-
+
// explicit source of non-self type
choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT,
- "Apple.allInstances()->forAll(a : Apple | a.oclIsInState(");
+ ConstraintKind.INVARIANT,
+ "Apple.allInstances()->forAll(a : Apple | a.oclIsInState(");
assertNotNull(choices);
assertChoice(choices, ChoiceKind.STATE, "Ripe");
assertChoice(choices, ChoiceKind.STATE, "Bad");
-
+
// implicit source of non-self type
-// choices = helper.getSyntaxHelp(
-// ConstraintType.INVARIANT,
-// "Apple.allInstances()->forAll(oclIsInState(");
-// assertNotNull(choices);
-// assertChoice(choices, ChoiceType.STRUCTURAL_FEATURE, "Ripe");
-// assertChoice(choices, ChoiceType.STRUCTURAL_FEATURE, "Bad");
-
+ // choices = helper.getSyntaxHelp(
+ // ConstraintType.INVARIANT,
+ // "Apple.allInstances()->forAll(oclIsInState(");
+ // assertNotNull(choices);
+ // assertChoice(choices, ChoiceType.STRUCTURAL_FEATURE, "Ripe");
+ // assertChoice(choices, ChoiceType.STRUCTURAL_FEATURE, "Bad");
+
// available second-level completions
choices = helper.getSyntaxHelp(
- ConstraintKind.INVARIANT,
- "Apple.allInstances()->forAll(a : Apple | a.oclIsInState(Bad::");
+ ConstraintKind.INVARIANT,
+ "Apple.allInstances()->forAll(a : Apple | a.oclIsInState(Bad::");
assertNotNull(choices);
assertChoice(choices, ChoiceKind.STATE, "Bruised");
assertChoice(choices, ChoiceKind.STATE, "Rotten");
@@ -175,78 +175,78 @@
fail("Parse failed: " + e.getLocalizedMessage());
}
}
-
+
//
// Test framework
//
-
+
@Override
protected OCL createOCL() {
return OCL.newInstance(new StatefulFruitEnvironmentFactory(this));
}
-
+
private static final List<String> FRUIT_BAD = Arrays.asList(new String[] {"Bad"});
-
+
public static class StatefulFruitEnvironmentFactory extends EcoreEnvironmentFactory {
protected final AbstractTestSuite suite;
-
+
public StatefulFruitEnvironmentFactory(AbstractTestSuite suite) {
this.suite = suite;
}
-
+
@Override
- public EcoreEnvironment createEnvironment() {
+ public EcoreEnvironment createEnvironment() {
return new StatefulFruitEnvironment(this, suite);
}
@Override
- public EcoreEnvironment createEnvironment(
+ public EcoreEnvironment createEnvironment(
Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent) {
return new StatefulFruitEnvironment(this, parent, suite);
}
}
-
+
private static class StatefulFruitEnvironment extends EcoreEnvironment {
protected final AbstractTestSuite suite;
private EObject fruitRipe;
private EObject fruitBad;
private EObject appleBruised;
private EObject appleRotten;
-
+
public StatefulFruitEnvironment(StatefulFruitEnvironmentFactory factory, AbstractTestSuite suite) {
super(factory, null);
this.suite = suite;
setContextPackage(suite.fruitPackage);
-
+
initStates();
}
-
+
public StatefulFruitEnvironment(
StatefulFruitEnvironmentFactory factory,
Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent, AbstractTestSuite suite) {
super(parent);
this.suite = suite;
-
+
initStates();
}
-
+
private void initStates() {
fruitRipe = EcoreFactory.eINSTANCE.createEObject();
((InternalEObject) fruitRipe).eSetClass(
- (EClass) getOCLStandardLibrary().getState());
+ (EClass) getOCLStandardLibrary().getState());
fruitBad = EcoreFactory.eINSTANCE.createEObject();
((InternalEObject) fruitBad).eSetClass(
- (EClass) getOCLStandardLibrary().getState());
+ (EClass) getOCLStandardLibrary().getState());
appleBruised = EcoreFactory.eINSTANCE.createEObject();
((InternalEObject) appleBruised).eSetClass(
- (EClass) getOCLStandardLibrary().getState());
+ (EClass) getOCLStandardLibrary().getState());
appleRotten = EcoreFactory.eINSTANCE.createEObject();
((InternalEObject) appleRotten).eSetClass(
- (EClass) getOCLStandardLibrary().getState());
+ (EClass) getOCLStandardLibrary().getState());
}
@Override
- protected void collectStates(EClassifier owner, List<String> pathPrefix, List<EObject> states) {
+ protected void collectStates(EClassifier owner, List<String> pathPrefix, List<EObject> states) {
if (owner == suite.fruit) {
if (pathPrefix.isEmpty()) {
states.add(fruitRipe);
@@ -261,25 +261,25 @@
}
}
}
-
-
- @Override
- public UMLReflection<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint> getUMLReflection() {
- return new UMLReflectionImpl() {
- @Override
- public String getName(Object namedElement) {
- if (namedElement == fruitRipe) {
- return "Ripe";
- } else if (namedElement == fruitBad) {
- return "Bad";
- } else if (namedElement == appleBruised) {
- return "Bruised";
- } else if (namedElement == appleRotten) {
- return "Rotten";
- } else {
- return super.getName(namedElement);
- }
- }};
- }
+
+
+ @Override
+ public UMLReflection<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint> getUMLReflection() {
+ return new UMLReflectionImpl() {
+ @Override
+ public String getName(Object namedElement) {
+ if (namedElement == fruitRipe) {
+ return "Ripe";
+ } else if (namedElement == fruitBad) {
+ return "Bad";
+ } else if (namedElement == appleBruised) {
+ return "Bruised";
+ } else if (namedElement == appleRotten) {
+ return "Rotten";
+ } else {
+ return super.getName(namedElement);
+ }
+ }};
+ }
}
}
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/TypesValidatorTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/TypesValidatorTest.java
index f142624..08cf804 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/TypesValidatorTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/TypesValidatorTest.java
@@ -40,92 +40,92 @@
public class TypesValidatorTest extends AbstractTestSuite {
private final EcoreFactory factory = EcoreFactory.eINSTANCE;
-
+
public void test_CollectionType_checkCollectionTypeName() {
CollectionType type = factory.createCollectionType();
type.setElementType(fruit);
-
+
assertOK(type, TypesValidator.COLLECTION_TYPE__COLLECTION_TYPE_NAME);
-
+
type.setName("Collection(Integer)");
-
+
assertProblem(type, TypesValidator.COLLECTION_TYPE__COLLECTION_TYPE_NAME);
-
+
type.setName("Sequence(Fruit)");
-
+
assertProblem(type, TypesValidator.COLLECTION_TYPE__COLLECTION_TYPE_NAME);
-
+
assertOK(getOCLStandardLibrary().getCollection(), TypesValidator.COLLECTION_TYPE__COLLECTION_TYPE_NAME);
}
-
+
public void test_BagType_checkCollectionTypeName() {
CollectionType type = factory.createBagType();
type.setElementType(fruit);
-
+
assertOK(type, TypesValidator.BAG_TYPE__COLLECTION_TYPE_NAME);
-
+
type.setName("Bag(Integer)");
-
+
assertProblem(type, TypesValidator.BAG_TYPE__COLLECTION_TYPE_NAME);
-
+
type.setName("Collection(Fruit)");
-
+
assertProblem(type, TypesValidator.BAG_TYPE__COLLECTION_TYPE_NAME);
-
+
assertOK(getOCLStandardLibrary().getBag(), TypesValidator.BAG_TYPE__COLLECTION_TYPE_NAME);
}
-
+
public void test_SetType_checkCollectionTypeName() {
CollectionType type = factory.createSetType();
type.setElementType(fruit);
-
+
assertOK(type, TypesValidator.SET_TYPE__COLLECTION_TYPE_NAME);
-
+
type.setName("Set(Integer)");
-
+
assertProblem(type, TypesValidator.SET_TYPE__COLLECTION_TYPE_NAME);
-
+
type.setName("Collection(Fruit)");
-
+
assertProblem(type, TypesValidator.SET_TYPE__COLLECTION_TYPE_NAME);
-
+
assertOK(getOCLStandardLibrary().getSet(), TypesValidator.SET_TYPE__COLLECTION_TYPE_NAME);
}
-
+
public void test_SequenceType_checkCollectionTypeName() {
CollectionType type = factory.createSequenceType();
type.setElementType(fruit);
-
+
assertOK(type, TypesValidator.SEQUENCE_TYPE__COLLECTION_TYPE_NAME);
-
+
type.setName("Sequence(Integer)");
-
+
assertProblem(type, TypesValidator.SEQUENCE_TYPE__COLLECTION_TYPE_NAME);
-
+
type.setName("Collection(Fruit)");
-
+
assertProblem(type, TypesValidator.SEQUENCE_TYPE__COLLECTION_TYPE_NAME);
-
+
assertOK(getOCLStandardLibrary().getSequence(), TypesValidator.SEQUENCE_TYPE__COLLECTION_TYPE_NAME);
}
-
+
public void test_OrderedSetType_checkCollectionTypeName() {
CollectionType type = factory.createOrderedSetType();
type.setElementType(fruit);
-
+
assertOK(type, TypesValidator.ORDERED_SET_TYPE__COLLECTION_TYPE_NAME);
-
+
type.setName("OrderedSet(Integer)");
-
+
assertProblem(type, TypesValidator.ORDERED_SET_TYPE__COLLECTION_TYPE_NAME);
-
+
type.setName("Collection(Fruit)");
-
+
assertProblem(type, TypesValidator.ORDERED_SET_TYPE__COLLECTION_TYPE_NAME);
-
+
assertOK(getOCLStandardLibrary().getOrderedSet(), TypesValidator.ORDERED_SET_TYPE__COLLECTION_TYPE_NAME);
}
-
+
/**
* Test that the default name of the collection type of an empty collection
* shows <tt>OclVoid</tt> as the element type.
@@ -135,17 +135,17 @@
URI uri = getTestModelURI("/model/VoidCollectionTypes.ecore");
Resource res = resourceSet.getResource(uri, true);
EPackage epackage = (EPackage) res.getContents().get(0);
-
+
// this one is ill-named
CollectionType setType = (CollectionType) epackage.getEClassifier("Set(T)");
assertSame(getOCLStandardLibrary().getOclVoid(), setType.getElementType());
assertProblem(setType, TypesValidator.SET_TYPE__COLLECTION_TYPE_NAME);
-
+
// this one is well-named
CollectionType bagType = (CollectionType) epackage.getEClassifier("Bag(OclVoid)");
assertSame(getOCLStandardLibrary().getOclVoid(), bagType.getElementType());
assertOK(setType, TypesValidator.BAG_TYPE__COLLECTION_TYPE_NAME);
-
+
// create a new void collection type
CollectionType collectionType = factory.createCollectionType();
collectionType.setElementType(getOCLStandardLibrary().getOclVoid());
@@ -163,7 +163,7 @@
sequenceType.setElementType(getOCLStandardLibrary().getOclVoid());
assertOK(sequenceType, TypesValidator.SEQUENCE_TYPE__COLLECTION_TYPE_NAME);
}
-
+
/**
* Tests that the well-formed name constraint from Ecore is
* disinherited for OCL types.
@@ -185,12 +185,12 @@
assertWellFormedName(oclFactory.createOperationMessageType(fruit_ripen));
assertWellFormedName(oclFactory.createTypeType(fruit));
}
-
+
private void assertWellFormedName(EObject type) {
assertOK(type, EcoreValidator.WELL_FORMED_NAME,
EcoreValidator.DIAGNOSTIC_SOURCE);
}
-
+
/**
* Tests that the well-formed instance type name constraint from Ecore is
* disinherited for OCL types.
@@ -211,7 +211,7 @@
assertWellFormedInstanceTypeName(oclFactory.createOperationMessageType(fruit_ripen));
assertWellFormedInstanceTypeName(oclFactory.createTypeType(fruit));
}
-
+
private void assertWellFormedInstanceTypeName(EObject type) {
assertOK(type, EcoreValidator.WELL_FORMED_INSTANCE_TYPE_NAME,
EcoreValidator.DIAGNOSTIC_SOURCE);
@@ -220,91 +220,91 @@
//
// Fixture methods
//
-
+
protected Diagnostic validate(EObject target) {
Map<Object, Object> ctx = new java.util.HashMap<Object, Object>();
ctx.put(Environment.class, ocl.getEnvironment());
return Diagnostician.INSTANCE.validate(target, ctx);
}
-
+
protected void assertProblem(EObject target, int code) {
assertProblem(validate(target), target, code);
}
-
+
protected void assertProblem(Diagnostic diagnostic, EObject target, int code) {
Diagnostic problem = findProblem(diagnostic, target, code);
assertNotNull("Problem not found", problem);
- System.out.println("Found expected problem: " + problem.getMessage());
+ debugPrintln("Found expected problem: " + problem.getMessage());
}
-
+
protected Diagnostic findProblem(Diagnostic diagnostic, EObject target,
int code, String source) {
-
+
if (source.equals(diagnostic
- .getSource())
+ .getSource())
&& (diagnostic.getSeverity() != Diagnostic.OK)
&& diagnostic.getData().contains(target)
&& (diagnostic.getCode() == code)) {
return diagnostic;
}
-
+
for (Diagnostic child : diagnostic.getChildren()) {
Diagnostic result = findProblem(child, target, code, source);
-
+
if (result != null) {
return result;
}
}
-
+
return null;
}
-
+
protected Diagnostic findProblem(Diagnostic diagnostic, EObject target, int code) {
return findProblem(diagnostic, target, code, TypesValidator.DIAGNOSTIC_SOURCE);
}
-
+
protected Diagnostic findProblem(Diagnostic diagnostic, EObject target) {
if (TypesValidator.DIAGNOSTIC_SOURCE.equals(diagnostic
- .getSource())
+ .getSource())
&& (diagnostic.getSeverity() != Diagnostic.OK)
&& diagnostic.getData().contains(target)) {
return diagnostic;
}
-
+
for (Diagnostic child : diagnostic.getChildren()) {
Diagnostic result = findProblem(child, target);
-
+
if (result != null) {
return result;
}
}
-
+
return null;
}
-
+
protected void assertOK(EObject target, int code) {
assertOK(validate(target), target, code);
}
-
+
protected void assertOK(EObject target, int code, String source) {
assertOK(validate(target), target, code, source);
}
-
+
protected void assertOK(Diagnostic diagnostic, EObject target, int code) {
assertNull("Problem found", findProblem(diagnostic, target, code));
}
-
+
protected void assertOK(Diagnostic diagnostic, EObject target, int code,
String source) {
-
+
assertNull(
"Problem found", findProblem(diagnostic, target, code, source));
}
-
+
protected void assertOK(EObject target) {
assertOK(validate(target), target);
}
-
+
protected void assertOK(Diagnostic diagnostic, EObject target) {
assertNull("Problem found", findProblem(diagnostic, target));
}
diff --git a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ValidationTest.java b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ValidationTest.java
index ece4e19..f013f7f 100644
--- a/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ValidationTest.java
+++ b/tests/org.eclipse.ocl.ecore.tests/src/org/eclipse/ocl/ecore/tests/ValidationTest.java
@@ -41,46 +41,46 @@
*/
@SuppressWarnings("nls")
public class ValidationTest extends AbstractTestSuite {
-
+
/**
- * Tests that operation calls may only invoke query operations.
+ * Tests that operation calls may only invoke query operations.
*/
public void test_callNonQueryOperation_136778() {
// newApple() is not a query operation
OCLExpression<EClassifier> expr = parseConstraintUnvalidated(
- "package ocltest context Apple " +
- "inv: Apple.allInstances()->includes(self.newApple()) " +
+ "package ocltest context Apple " +
+ "inv: Apple.allInstances()->includes(self.newApple()) " +
"endpackage");
-
+
try {
ocl.validate(expr);
fail("Should not have successfully validated");
} catch (SemanticException e) {
// success
- System.out.println("Got expected exception: " + e.getLocalizedMessage());
+ debugPrintln("Got expected exception: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests that only one problem is reported for a sequence of call
* expressions on an unrecognized variable (<tt>simpleNameCS</tt>).
*/
public void test_callExpOnUnrecognizedVariable_226083() {
helper.setContext(apple);
-
+
try {
helper.createInvariant(
- "noSuchVariable.noSuchProperty->includes(self.noSuchOperation())");
+ "noSuchVariable.noSuchProperty->includes(self.noSuchOperation())");
fail("Should not have successfully parsed");
} catch (SemanticException e) {
// success: semantic parse failed (not concrete parse)
Diagnostic diagnostic = e.getDiagnostic();
assertNotNull(diagnostic);
assertEquals(Diagnostic.ERROR, diagnostic.getSeverity());
-
+
// the problem reported is the unrecognized 'noSuchVariable'
assertTrue(diagnostic.getMessage().contains("noSuchVariable"));
-
+
// there is no complaint about the 'noSuchProperty' but there
// is a complaint about 'noSuchOperation'
boolean found = false;
@@ -92,27 +92,27 @@
fail("Wrong kind of parse failure: " + e.getLocalizedMessage());
}
}
-
+
/**
* Tests that only one problem is reported for an iterator expression
* on an unparseable source expression.
*/
public void test_bodyOfUnrcognizableIteratorSource_226083() {
helper.setContext(apple);
-
+
try {
helper.createInvariant(
- "Set{noSuchVariable}->forAll(e | e.noSuchOperation())");
+ "Set{noSuchVariable}->forAll(e | e.noSuchOperation())");
fail("Should not have successfully parsed");
} catch (SemanticException e) {
// success: semantic parse failed (not concrete parse)
Diagnostic diagnostic = e.getDiagnostic();
assertNotNull(diagnostic);
assertEquals(Diagnostic.ERROR, diagnostic.getSeverity());
-
+
// the problem reported is the unrecognized 'noSuchVariable'
assertTrue(diagnostic.getMessage().contains("noSuchVariable"));
-
+
// only one problem was reported, not two (the noSuchOperation
// operation was not attempted)
assertEquals(0, diagnostic.getChildren().size());
@@ -124,13 +124,13 @@
//
// Fixture methods
//
-
+
@Override
protected OCL createOCL() {
return OCL.newInstance(new CustomFruitEnvironmentFactory());
}
-
+
private class CustomFruitEnvironmentFactory extends EcoreEnvironmentFactory {
public CustomFruitEnvironmentFactory() {
@@ -138,37 +138,37 @@
}
@Override
- public EcoreEnvironment createEnvironment() {
+ public EcoreEnvironment createEnvironment() {
return new CustomFruitEnvironment(this);
}
@Override
- public EcoreEnvironment createEnvironment(
+ public EcoreEnvironment createEnvironment(
Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent) {
return new CustomFruitEnvironment(this, parent);
}
}
-
+
private class CustomFruitEnvironment extends EcoreEnvironment {
public CustomFruitEnvironment(CustomFruitEnvironmentFactory factory) {
super(factory, null);
setContextPackage(fruitPackage);
}
-
+
public CustomFruitEnvironment(
CustomFruitEnvironmentFactory factory,
Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> parent) {
super(parent);
}
-
-
- @Override
- public UMLReflection<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint> getUMLReflection() {
- return new UMLReflectionImpl() {
- @Override
- public boolean isQuery(EOperation operation) {
- return operation != apple_newApple;
- }};
- }
+
+
+ @Override
+ public UMLReflection<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint> getUMLReflection() {
+ return new UMLReflectionImpl() {
+ @Override
+ public boolean isQuery(EOperation operation) {
+ return operation != apple_newApple;
+ }};
+ }
}
}